import { m as Alpine } from './vendor-ui-CflGdlft.js';
import { apiGet, apiPost, money, monthNow } from './app-api.js';

function registerReports() {
  if (window.__ssaReportsRegistered) return;
  window.__ssaReportsRegistered = true;

  Alpine.data('reportsComponent', () => ({
    billingMonth: monthNow(),
    recentReports: [],
    isLoading: false,

    init() {
      this.load();
      this.loadCharts();
    },

    async load() {
      this.isLoading = true;
      try {
        const res = await apiGet(`/reports/owing?billing_month=${encodeURIComponent(this.billingMonth)}`);
        this.recentReports = (res.data || []).map(r => ({
          id: r.invoice_id,
          name: `${r.first_name} ${r.last_name}`.trim(),
          type: r.guardian_name || '—',
          dateRange: r.billing_month,
          generated: r.due_date,
          status: Number(r.balance) <= 0 ? 'paid' : 'owing',
          balance: Number(r.balance || 0),
          phone: r.guardian_phone || '',
          email: r.guardian_email || '',
        }));
      } catch (e) {
        window.AdminApp?.notificationManager?.error(e.message);
      } finally {
        this.isLoading = false;
      }
    },

    charts: {
      revenue: null,
    },

    async loadCharts() {
      try {
        const res = await apiGet('/stats/revenue-trend?months=6');
        this.renderRevenueTrend(res.data || []);
      } catch {
        // non-critical
      }
    },

    renderRevenueTrend(rows) {
      const el = document.getElementById('owingRevenueTrendChart');
      if (!el || typeof ApexCharts === 'undefined') return;

      const categories = rows.map(r => r.billing_month);
      const series = rows.map(r => Number(r.paid || 0));

      const options = {
        series: [{ name: 'Paid', data: series }],
        chart: { type: 'line', height: 260, toolbar: { show: false } },
        stroke: { curve: 'smooth', width: 2 },
        dataLabels: { enabled: false },
        xaxis: { categories },
        yaxis: { labels: { formatter: v => Number(v).toLocaleString() } },
        colors: ['#22c55e'],
      };

      if (this.charts.revenue) {
        this.charts.revenue.updateOptions(options);
      } else {
        this.charts.revenue = new ApexCharts(el, options);
        this.charts.revenue.render();
      }
    },

    async refreshReports() {
      await this.load();
      window.AdminApp?.notificationManager?.success('Refreshed');
    },

    async sendReminder(report, channel) {
      try {
        await apiPost('/notifications/send-owing', {
          billing_month: this.billingMonth,
          invoice_id: report.id,
          channel: channel === 'sms' || channel === 'email' ? 'auto' : channel,
        });
        window.AdminApp?.notificationManager?.success('Reminder sent');
      } catch (e) {
        window.AdminApp?.notificationManager?.error(e.message);
      }
    },

    async sendBulk(channel) {
      try {
        const res = await apiPost('/notifications/send-owing', {
          billing_month: this.billingMonth,
          channel: channel === 'sms' || channel === 'email' ? 'auto' : channel,
        });
        window.AdminApp?.notificationManager?.success(`Sent: ${res.sent || 0}, Failed: ${res.failed || 0}`);
      } catch (e) {
        window.AdminApp?.notificationManager?.error(e.message);
      }
    },

    money(v) {
      return money(v);
    },

    updateDateRange() {},
    updateReportType() {},
    applyFilters() {
      this.load();
    },
    scheduleReport() {},
    generateReport() {},
    exportData() {},
    downloadReport() {},
    shareReport() {},
    duplicateReport() {},
    deleteReport() {},

    kpis: {
      revenue: 0,
      revenueChange: 0,
      orders: 0,
      ordersChange: 0,
      customers: 0,
      customersChange: 0,
      conversionRate: 0,
      conversionChange: 0,
    },

    topProducts: [],
    chartsInitialized: true,
    initCharts() {},
  }));
}

document.addEventListener('alpine:init', registerReports);

try {
  registerReports();
} catch {
  // noop
}
