<template>
  <WidgetShell title="Category value" icon="mdi-shape-outline" :loading="loading" :editing="editing" @refresh="load" @remove="$emit('remove')">
    <div v-if="rows.length" style="height:160px"><Bar :data="chartData" :options="opts" /></div>
    <table v-if="rows.length" class="mini-table mt-2">
      <thead><tr><th>Category</th><th class="r">Assets</th><th class="r">Value</th></tr></thead>
      <tbody><tr v-for="r in rows" :key="r.category"><td>{{ r.category }}</td><td class="r">{{ r.count }}</td><td class="r">{{ currency(r.value) }}</td></tr></tbody>
    </table>
    <div v-if="!rows.length && !loading" class="quiet text-body-2">No assets yet.</div>
  </WidgetShell>
</template>
<script>
import WidgetShell from './WidgetShell.vue';
import { Bar } from 'vue-chartjs';
import '../../utils/charts';
import { apiRequest } from '../../services/api';
import { currency } from '../../utils/format';
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: [], opts: { responsive: true, maintainAspectRatio: false, plugins: { legend: { display: false } }, scales: { y: { ticks: { callback: (v) => '$' + Number(v).toLocaleString() } } } } }; },
  computed: { chartData() { return { labels: this.rows.map((r) => r.category), datasets: [{ data: this.rows.map((r) => r.value), backgroundColor: '#2457a6' }] }; } },
  mounted() { this.load(); },
  methods: {
    currency,
    async load() {
      this.loading = true;
      try { this.rows = (await (await apiRequest('/api/dashboard', this.token)).json()).byCategory; }
      catch { this.rows = []; } finally { this.loading = false; }
    }
  }
};
</script>
<style scoped>
.mini-table { width: 100%; border-collapse: collapse; font-size: .82rem; }
.mini-table th, .mini-table td { padding: 3px 6px; border-bottom: 1px solid rgba(128,128,128,.14); text-align: left; }
.mini-table .r { text-align: right; }
</style>
