<template>
  <WidgetShell title="Depreciation to date by category" icon="mdi-chart-line" :loading="loading" :editing="editing" @refresh="load" @remove="$emit('remove')">
    <div v-if="rows.length" style="height:200px"><Line :data="chartData" :options="opts" /></div>
    <div v-else-if="!loading" class="quiet text-body-2">No depreciation by category yet.</div>
  </WidgetShell>
</template>
<script>
import WidgetShell from './WidgetShell.vue';
import { Line } from 'vue-chartjs';
import '../../utils/charts';
import { apiRequest } from '../../services/api';
export default {
  components: { WidgetShell, Line },
  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: { display: false } }, scales: { y: { beginAtZero: true, ticks: { callback: (v) => '$' + Number(v).toLocaleString() } } } } }; },
  computed: {
    chartData() {
      return { labels: this.rows.map((r) => r.category), datasets: [{ data: this.rows.map((r) => r.accumulated), borderColor: '#9b59b6', backgroundColor: 'rgba(155,89,182,.15)', fill: true, tension: 0.25, pointRadius: 3 }] };
    }
  },
  mounted() { this.load(); },
  methods: {
    async load() {
      this.loading = true;
      try { this.rows = (await (await apiRequest('/api/dashboard/depreciation', this.token)).json()).byCategory.filter((r) => r.accumulated); }
      catch { this.rows = []; } finally { this.loading = false; }
    }
  }
};
</script>
