<template>
  <WidgetShell title="Assets by status" icon="mdi-chart-donut" :loading="loading" :editing="editing" @refresh="load" @remove="$emit('remove')">
    <div v-if="rows.length" style="height:200px"><Doughnut :data="chartData" :options="opts" /></div>
    <div v-else-if="!loading" class="quiet text-body-2">No assets yet.</div>
  </WidgetShell>
</template>
<script>
import WidgetShell from './WidgetShell.vue';
import { Doughnut } from 'vue-chartjs';
import '../../utils/charts';
import { apiRequest } from '../../services/api';
const COLORS = ['#2457a6', '#3f9d5a', '#c9892f', '#9b59b6', '#b00020', '#5b7083'];
export default {
  components: { WidgetShell, Doughnut },
  props: { token: { type: String, required: true }, editing: { type: Boolean, default: false }, config: { type: Object, default: () => ({}) } },
  emits: ['remove'],
  data() { return { loading: false, rows: [], opts: { responsive: true, maintainAspectRatio: false, plugins: { legend: { position: 'right', labels: { boxWidth: 12, font: { size: 11 } } } } } }; },
  computed: {
    chartData() {
      return { labels: this.rows.map((r) => this.label(r.status)), datasets: [{ data: this.rows.map((r) => r.count), backgroundColor: this.rows.map((_, i) => COLORS[i % COLORS.length]) }] };
    }
  },
  mounted() { this.load(); },
  methods: {
    label(s) { return String(s || '').replace(/_/g, ' '); },
    async load() {
      this.loading = true;
      try { this.rows = (await (await apiRequest('/api/dashboard', this.token)).json()).byStatus; }
      catch { this.rows = []; } finally { this.loading = false; }
    }
  }
};
</script>
