<template>
  <WidgetShell :title="`YTD depreciation by book (${year})`" icon="mdi-chart-bar" :loading="loading" :editing="editing" @refresh="load" @remove="$emit('remove')">
    <div v-if="rows.length" style="height:200px"><Bar :data="chartData" :options="opts" /></div>
    <div v-else-if="!loading" class="quiet text-body-2">No depreciation booked this year.</div>
  </WidgetShell>
</template>
<script>
import WidgetShell from './WidgetShell.vue';
import { Bar } from 'vue-chartjs';
import '../../utils/charts';
import { apiRequest } from '../../services/api';
export default {
  components: { WidgetShell, Bar },
  props: { token: { type: String, required: true }, editing: { type: Boolean, default: false }, config: { type: Object, default: () => ({}) } },
  emits: ['remove'],
  data() { return { loading: false, rows: [], year: new Date().getFullYear(), 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.book), datasets: [{ data: this.rows.map((r) => r.ytd), backgroundColor: '#2457a6' }] }; } },
  mounted() { this.load(); },
  methods: {
    async load() {
      this.loading = true;
      try { const d = await (await apiRequest('/api/dashboard/depreciation', this.token)).json(); this.year = d.year; this.rows = d.byBook.filter((r) => r.ytd); }
      catch { this.rows = []; } finally { this.loading = false; }
    }
  }
};
</script>
