<!-- /src/components/financialReports/charts/IncomeByClassChart.vue -->
<!-- Horizontal bar chart ranking classes by received revenue vs. outstanding receivables. -->
<template>
  <div class="chart-wrap" dir="ltr" :style="{ height: computedHeight + 'px' }">
    <Bar v-if="rows.length" :data="chartData" :options="options" />
    <div v-else class="flex align-items-center justify-content-center h-full text-muted text-sm">
      داده‌ای برای نمایش وجود ندارد
    </div>
  </div>
</template>

<script setup>
import { computed } from 'vue';
import { Bar } from 'vue-chartjs';
import { usePersianDate } from '@/composables/usePersianDate';
import { CHART_COLORS } from '@/utils/chartTheme';

const props = defineProps({
  rows: { type: Array, default: () => [] }, // [{ className, actualReceivedRevenue, pendingReceivables }]
  limit: { type: Number, default: 8 }
});

const { toPersianDigits } = usePersianDate();
const formatToman = (v) => `${toPersianDigits(Math.round(v || 0).toLocaleString())} تومان`;

const topRows = computed(() => props.rows.slice(0, props.limit));
const computedHeight = computed(() => Math.max(220, topRows.value.length * 46));

const chartData = computed(() => ({
  labels: topRows.value.map((r) => r.className),
  datasets: [
    {
      label: 'وصول‌شده',
      data: topRows.value.map((r) => r.actualReceivedRevenue),
      backgroundColor: CHART_COLORS.received,
      borderRadius: 5,
      maxBarThickness: 18
    },
    {
      label: 'مطالبات معوق',
      data: topRows.value.map((r) => r.pendingReceivables),
      backgroundColor: CHART_COLORS.outstanding,
      borderRadius: 5,
      maxBarThickness: 18
    }
  ]
}));

const options = computed(() => ({
  indexAxis: 'y',
  responsive: true,
  maintainAspectRatio: false,
  plugins: {
    legend: {
      position: 'top',
      align: 'end',
      labels: { usePointStyle: true, pointStyle: 'circle', boxWidth: 8, boxHeight: 8 }
    },
    tooltip: {
      rtl: true,
      textDirection: 'rtl',
      callbacks: {
        label: (ctx) => `${ctx.dataset.label}: ${formatToman(ctx.parsed.x)}`
      }
    }
  },
  scales: {
    x: {
      stacked: false,
      grid: { color: CHART_COLORS.gridLine, drawBorder: false },
      ticks: { color: CHART_COLORS.muted, callback: (v) => toPersianDigits(Number(v).toLocaleString()) }
    },
    y: {
      grid: { display: false },
      ticks: { color: CHART_COLORS.muted }
    }
  }
}));
</script>

<style scoped>
.chart-wrap {
  width: 100%;
  position: relative;
}
</style>
