'use client';

import React, { useState, useMemo } from 'react';
import AppLayout from '@/components/AppLayout';
import { TrendingUp, DollarSign, Download, ChevronDown, ChevronUp, BarChart3, CreditCard, Smartphone, Landmark, Wallet, Building2, ArrowUpRight, ArrowDownRight, FileText, Calendar, CalendarDays } from 'lucide-react';
import { BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, Line, PieChart, Pie, Cell, Legend, ComposedChart } from 'recharts';

// ─── Types ────────────────────────────────────────────────────────────────────

interface BranchPL {
  branch: string;
  revenue: number;
  cogs: number;
  grossProfit: number;
  grossMargin: number;
  opex: number;
  netProfit: number;
  netMargin: number;
  prevRevenue: number;
  prevNetProfit: number;
}

interface PaymentBreakdown {
  method: string;
  amount: number;
  transactions: number;
  share: number;
  icon: React.ComponentType<{ size?: number; className?: string }>;
  color: string;
}

interface CashFlowMonth {
  month: string;
  inflow: number;
  outflow: number;
  net: number;
  prevNet: number;
}

interface DrillRow {
  category: string;
  amount: number;
  prev: number;
  type: 'income' | 'expense';
}

interface DailyBranchReport {
  branch: string;
  date: string;
  openingBalance: number;
  totalSales: number;
  cashSales: number;
  mpesaSales: number;
  cardSales: number;
  transactions: number;
  refunds: number;
  netRevenue: number;
  topProduct: string;
}

// ─── Mock Data ────────────────────────────────────────────────────────────────

const BRANCHES = ['All Branches', 'Westlands', 'CBD', 'Eastlands', 'Karen'];
const PERIODS = ['This Month', 'This Year', 'Last Year', 'Custom Range'];

const PL_DATA: Record<string, BranchPL[]> = {
  'All Branches': [
    { branch: 'Westlands', revenue: 1248500, cogs: 748000, grossProfit: 500500, grossMargin: 40.1, opex: 180000, netProfit: 320500, netMargin: 25.7, prevRevenue: 1102000, prevNetProfit: 278000 },
    { branch: 'CBD', revenue: 987200, cogs: 592000, grossProfit: 395200, grossMargin: 40.0, opex: 145000, netProfit: 250200, netMargin: 25.3, prevRevenue: 921000, prevNetProfit: 231000 },
    { branch: 'Eastlands', revenue: 642800, cogs: 398000, grossProfit: 244800, grossMargin: 38.1, opex: 98000, netProfit: 146800, netMargin: 22.8, prevRevenue: 598000, prevNetProfit: 132000 },
    { branch: 'Karen', revenue: 1105600, cogs: 651000, grossProfit: 454600, grossMargin: 41.1, opex: 162000, netProfit: 292600, netMargin: 26.5, prevRevenue: 1034000, prevNetProfit: 268000 },
  ],
  'Westlands': [
    { branch: 'Westlands', revenue: 1248500, cogs: 748000, grossProfit: 500500, grossMargin: 40.1, opex: 180000, netProfit: 320500, netMargin: 25.7, prevRevenue: 1102000, prevNetProfit: 278000 },
  ],
  'CBD': [
    { branch: 'CBD', revenue: 987200, cogs: 592000, grossProfit: 395200, grossMargin: 40.0, opex: 145000, netProfit: 250200, netMargin: 25.3, prevRevenue: 921000, prevNetProfit: 231000 },
  ],
  'Eastlands': [
    { branch: 'Eastlands', revenue: 642800, cogs: 398000, grossProfit: 244800, grossMargin: 38.1, opex: 98000, netProfit: 146800, netMargin: 22.8, prevRevenue: 598000, prevNetProfit: 132000 },
  ],
  'Karen': [
    { branch: 'Karen', revenue: 1105600, cogs: 651000, grossProfit: 454600, grossMargin: 41.1, opex: 162000, netProfit: 292600, netMargin: 26.5, prevRevenue: 1034000, prevNetProfit: 268000 },
  ],
};

const PAYMENT_METHODS: PaymentBreakdown[] = [
  { method: 'Cash', amount: 1482600, transactions: 2841, share: 37.2, icon: Wallet, color: '#22c55e' },
  { method: 'M-Pesa', amount: 1624800, transactions: 3102, share: 40.8, icon: Smartphone, color: '#3b82f6' },
  { method: 'Card', amount: 621400, transactions: 892, share: 15.6, icon: CreditCard, color: '#a855f7' },
  { method: 'Bank Transfer', amount: 255300, transactions: 124, share: 6.4, icon: Landmark, color: '#f59e0b' },
];

const CASHFLOW_DATA: CashFlowMonth[] = [
  { month: 'Jan', inflow: 3240000, outflow: 2180000, net: 1060000, prevNet: 920000 },
  { month: 'Feb', inflow: 2980000, outflow: 2050000, net: 930000, prevNet: 860000 },
  { month: 'Mar', inflow: 3560000, outflow: 2310000, net: 1250000, prevNet: 1080000 },
  { month: 'Apr', inflow: 3120000, outflow: 2240000, net: 880000, prevNet: 950000 },
  { month: 'May', inflow: 3780000, outflow: 2480000, net: 1300000, prevNet: 1120000 },
  { month: 'Jun', inflow: 3984100, outflow: 2600000, net: 1384100, prevNet: 1210000 },
];

const DRILL_ROWS: Record<string, DrillRow[]> = {
  'Westlands': [
    { category: 'Grocery Sales', amount: 682000, prev: 598000, type: 'income' },
    { category: 'Household Items', amount: 312500, prev: 278000, type: 'income' },
    { category: 'Beverages', amount: 254000, prev: 226000, type: 'income' },
    { category: 'Cost of Goods', amount: 748000, prev: 662000, type: 'expense' },
    { category: 'Staff Wages', amount: 98000, prev: 94000, type: 'expense' },
    { category: 'Rent & Utilities', amount: 52000, prev: 52000, type: 'expense' },
    { category: 'Logistics', amount: 30000, prev: 28000, type: 'expense' },
  ],
  'CBD': [
    { category: 'Grocery Sales', amount: 541000, prev: 502000, type: 'income' },
    { category: 'Household Items', amount: 248200, prev: 221000, type: 'income' },
    { category: 'Beverages', amount: 198000, prev: 198000, type: 'income' },
    { category: 'Cost of Goods', amount: 592000, prev: 551000, type: 'expense' },
    { category: 'Staff Wages', amount: 78000, prev: 74000, type: 'expense' },
    { category: 'Rent & Utilities', amount: 42000, prev: 42000, type: 'expense' },
    { category: 'Logistics', amount: 25000, prev: 23000, type: 'expense' },
  ],
  'Eastlands': [
    { category: 'Grocery Sales', amount: 352000, prev: 328000, type: 'income' },
    { category: 'Household Items', amount: 162800, prev: 148000, type: 'income' },
    { category: 'Beverages', amount: 128000, prev: 122000, type: 'income' },
    { category: 'Cost of Goods', amount: 398000, prev: 371000, type: 'expense' },
    { category: 'Staff Wages', amount: 54000, prev: 52000, type: 'expense' },
    { category: 'Rent & Utilities', amount: 28000, prev: 28000, type: 'expense' },
    { category: 'Logistics', amount: 16000, prev: 15000, type: 'expense' },
  ],
  'Karen': [
    { category: 'Grocery Sales', amount: 604000, prev: 566000, type: 'income' },
    { category: 'Household Items', amount: 288600, prev: 268000, type: 'income' },
    { category: 'Beverages', amount: 213000, prev: 200000, type: 'income' },
    { category: 'Cost of Goods', amount: 651000, prev: 610000, type: 'expense' },
    { category: 'Staff Wages', amount: 88000, prev: 84000, type: 'expense' },
    { category: 'Rent & Utilities', amount: 46000, prev: 46000, type: 'expense' },
    { category: 'Logistics', amount: 28000, prev: 26000, type: 'expense' },
  ],
};

// Daily report mock data per branch
const DAILY_REPORTS: DailyBranchReport[] = [
  { branch: 'Westlands', date: '2026-08-07', openingBalance: 50000, totalSales: 142800, cashSales: 52400, mpesaSales: 68200, cardSales: 22200, transactions: 284, refunds: 3200, netRevenue: 139600, topProduct: 'Cooking Oil 2L' },
  { branch: 'CBD', date: '2026-08-07', openingBalance: 40000, totalSales: 118600, cashSales: 41200, mpesaSales: 58800, cardSales: 18600, transactions: 231, refunds: 1800, netRevenue: 116800, topProduct: 'Unga Pembe 2kg' },
  { branch: 'Eastlands', date: '2026-08-07', openingBalance: 30000, totalSales: 76400, cashSales: 32100, mpesaSales: 34800, cardSales: 9500, transactions: 168, refunds: 900, netRevenue: 75500, topProduct: 'Sugar 1kg' },
  { branch: 'Karen', date: '2026-08-07', openingBalance: 45000, totalSales: 128200, cashSales: 44600, mpesaSales: 62400, cardSales: 21200, transactions: 256, refunds: 2400, netRevenue: 125800, topProduct: 'Milk 500ml' },
];

// ─── Helpers ──────────────────────────────────────────────────────────────────

function fmt(n: number) {
  if (n >= 1_000_000) return `KES ${(n / 1_000_000).toFixed(2)}M`;
  if (n >= 1_000) return `KES ${(n / 1_000).toFixed(0)}K`;
  return `KES ${n.toLocaleString()}`;
}

function pct(current: number, prev: number) {
  if (prev === 0) return 0;
  return ((current - prev) / prev) * 100;
}

const PIE_COLORS = ['#22c55e', '#3b82f6', '#a855f7', '#f59e0b'];

const MONTHS = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];

// ─── Export Helpers ───────────────────────────────────────────────────────────

async function exportReportToPDF(
  plRows: BranchPL[],
  paymentMethods: PaymentBreakdown[],
  cashflow: CashFlowMonth[],
  period: string,
  branch: string,
  activeTab: string
) {
  const { default: jsPDF } = await import('jspdf');
  const { default: autoTable } = await import('jspdf-autotable');

  const doc = new jsPDF({ orientation: 'landscape' });

  doc.setFontSize(16);
  doc.setFont('helvetica', 'bold');
  doc.text('Financial Reports', 14, 18);

  doc.setFontSize(10);
  doc.setFont('helvetica', 'normal');
  doc.text(`Period: ${period}  |  Branch: ${branch}  |  Generated: ${new Date().toLocaleString()}`, 14, 26);

  if (activeTab === 'pl' || activeTab === 'all') {
    doc.setFontSize(12);
    doc.setFont('helvetica', 'bold');
    doc.text('P&L Summary', 14, 36);

    autoTable(doc, {
      startY: 40,
      head: [['Branch', 'Revenue', 'COGS', 'Gross Profit', 'GM%', 'OpEx', 'Net Profit', 'NM%']],
      body: plRows.map((r) => [
        r.branch,
        `KES ${(r.revenue / 1000).toFixed(0)}K`,
        `KES ${(r.cogs / 1000).toFixed(0)}K`,
        `KES ${(r.grossProfit / 1000).toFixed(0)}K`,
        `${r.grossMargin.toFixed(1)}%`,
        `KES ${(r.opex / 1000).toFixed(0)}K`,
        `KES ${(r.netProfit / 1000).toFixed(0)}K`,
        `${r.netMargin.toFixed(1)}%`,
      ]),
      styles: { fontSize: 9, cellPadding: 3 },
      headStyles: { fillColor: [59, 130, 246], textColor: 255, fontStyle: 'bold' },
    });
  }

  if (activeTab === 'payment' || activeTab === 'all') {
    const startY = (doc as any).lastAutoTable?.finalY ? (doc as any).lastAutoTable.finalY + 12 : 40;
    doc.setFontSize(12);
    doc.setFont('helvetica', 'bold');
    doc.text('Payment Methods', 14, startY);

    autoTable(doc, {
      startY: startY + 4,
      head: [['Method', 'Amount (KES)', 'Transactions', 'Share %']],
      body: paymentMethods.map((pm) => [pm.method, pm.amount.toLocaleString(), pm.transactions.toLocaleString(), `${pm.share}%`]),
      styles: { fontSize: 9, cellPadding: 3 },
      headStyles: { fillColor: [59, 130, 246], textColor: 255, fontStyle: 'bold' },
    });
  }

  if (activeTab === 'cashflow' || activeTab === 'all') {
    const startY = (doc as any).lastAutoTable?.finalY ? (doc as any).lastAutoTable.finalY + 12 : 40;
    doc.setFontSize(12);
    doc.setFont('helvetica', 'bold');
    doc.text('Cash Flow', 14, startY);

    autoTable(doc, {
      startY: startY + 4,
      head: [['Month', 'Inflow (KES)', 'Outflow (KES)', 'Net (KES)', 'Prev Net (KES)', 'MoM Change']],
      body: cashflow.map((row) => {
        const change = row.prevNet > 0 ? (((row.net - row.prevNet) / row.prevNet) * 100).toFixed(1) : '0.0';
        return [row.month, row.inflow.toLocaleString(), row.outflow.toLocaleString(), row.net.toLocaleString(), row.prevNet.toLocaleString(), `${change}%`];
      }),
      styles: { fontSize: 9, cellPadding: 3 },
      headStyles: { fillColor: [59, 130, 246], textColor: 255, fontStyle: 'bold' },
    });
  }

  doc.save(`financial-report-${period.replace(/\s+/g, '-').toLowerCase()}-${branch.replace(/\s+/g, '-').toLowerCase()}.pdf`);
}

async function exportReportToExcel(
  plRows: BranchPL[],
  paymentMethods: PaymentBreakdown[],
  cashflow: CashFlowMonth[],
  period: string,
  branch: string
) {
  const XLSX = await import('xlsx');
  const wb = XLSX.utils.book_new();

  const plSheet = XLSX.utils.json_to_sheet(plRows.map((r) => ({
    Branch: r.branch, Revenue: r.revenue, COGS: r.cogs, 'Gross Profit': r.grossProfit,
    'GM%': r.grossMargin, OpEx: r.opex, 'Net Profit': r.netProfit, 'NM%': r.netMargin,
    'Prev Revenue': r.prevRevenue, 'Prev Net Profit': r.prevNetProfit,
  })));
  XLSX.utils.book_append_sheet(wb, plSheet, 'P&L Summary');

  const pmSheet = XLSX.utils.json_to_sheet(paymentMethods.map((pm) => ({
    Method: pm.method, 'Amount (KES)': pm.amount, Transactions: pm.transactions, 'Share %': pm.share,
  })));
  XLSX.utils.book_append_sheet(wb, pmSheet, 'Payment Methods');

  const cfSheet = XLSX.utils.json_to_sheet(cashflow.map((row) => ({
    Month: row.month, 'Inflow (KES)': row.inflow, 'Outflow (KES)': row.outflow,
    'Net (KES)': row.net, 'Prev Net (KES)': row.prevNet,
    'MoM Change %': row.prevNet > 0 ? (((row.net - row.prevNet) / row.prevNet) * 100).toFixed(1) : '0.0',
  })));
  XLSX.utils.book_append_sheet(wb, cfSheet, 'Cash Flow');

  XLSX.writeFile(wb, `financial-report-${period.replace(/\s+/g, '-').toLowerCase()}-${branch.replace(/\s+/g, '-').toLowerCase()}.xlsx`);
}

async function exportDailyReportToPDF(report: DailyBranchReport, periodLabel: string) {
  const { default: jsPDF } = await import('jspdf');
  const { default: autoTable } = await import('jspdf-autotable');

  const doc = new jsPDF();

  doc.setFontSize(18);
  doc.setFont('helvetica', 'bold');
  doc.text('Daily Sales Report', 14, 20);

  doc.setFontSize(11);
  doc.setFont('helvetica', 'normal');
  doc.text(`Branch: ${report.branch}`, 14, 30);
  doc.text(`Period: ${periodLabel}`, 14, 37);
  doc.text(`Generated: ${new Date().toLocaleString()}`, 14, 44);

  autoTable(doc, {
    startY: 52,
    head: [['Metric', 'Value']],
    body: [
      ['Opening Balance', `KES ${report.openingBalance.toLocaleString()}`],
      ['Total Sales', `KES ${report.totalSales.toLocaleString()}`],
      ['Cash Sales', `KES ${report.cashSales.toLocaleString()}`],
      ['M-Pesa Sales', `KES ${report.mpesaSales.toLocaleString()}`],
      ['Card Sales', `KES ${report.cardSales.toLocaleString()}`],
      ['Total Transactions', report.transactions.toString()],
      ['Refunds', `KES ${report.refunds.toLocaleString()}`],
      ['Net Revenue', `KES ${report.netRevenue.toLocaleString()}`],
      ['Top Product', report.topProduct],
    ],
    styles: { fontSize: 10, cellPadding: 4 },
    headStyles: { fillColor: [59, 130, 246], textColor: 255, fontStyle: 'bold' },
    columnStyles: { 0: { fontStyle: 'bold', cellWidth: 70 } },
  });

  doc.save(`daily-report-${report.branch.replace(/\s+/g, '-').toLowerCase()}-${periodLabel.replace(/\s+/g, '-').toLowerCase()}.pdf`);
}

// ─── Sub-components ───────────────────────────────────────────────────────────

function DrillDownPanel({ branch, onClose }: { branch: string; onClose: () => void }) {
  const rows = DRILL_ROWS[branch] ?? [];
  const income = rows.filter((r) => r.type === 'income');
  const expenses = rows.filter((r) => r.type === 'expense');

  return (
    <div className="card-elevated rounded-xl overflow-hidden border border-primary/20">
      <div className="flex items-center justify-between px-5 py-4 bg-primary/5 border-b border-border">
        <div className="flex items-center gap-2">
          <Building2 size={16} className="text-primary" />
          <h4 className="text-sm font-700 text-foreground">{branch} — P&amp;L Breakdown</h4>
        </div>
        <button onClick={onClose} className="text-xs text-muted-foreground hover:text-foreground transition-colors px-2 py-1 rounded hover:bg-muted">
          Close ✕
        </button>
      </div>
      <div className="grid grid-cols-1 md:grid-cols-2 divide-y md:divide-y-0 md:divide-x divide-border">
        <div className="p-4">
          <p className="text-xs font-700 uppercase tracking-widest text-success mb-3">Revenue Streams</p>
          <div className="space-y-2">
            {income.map((r) => {
              const change = pct(r.amount, r.prev);
              return (
                <div key={r.category} className="flex items-center justify-between py-1.5 border-b border-border/50 last:border-0">
                  <span className="text-sm text-foreground">{r.category}</span>
                  <div className="flex items-center gap-3">
                    <span className={`text-xs font-600 flex items-center gap-0.5 ${change >= 0 ? 'text-success' : 'text-danger'}`}>
                      {change >= 0 ? <ArrowUpRight size={12} /> : <ArrowDownRight size={12} />}
                      {Math.abs(change).toFixed(1)}%
                    </span>
                    <span className="text-sm font-700 text-foreground font-tabular w-24 text-right">{fmt(r.amount)}</span>
                  </div>
                </div>
              );
            })}
          </div>
        </div>
        <div className="p-4">
          <p className="text-xs font-700 uppercase tracking-widest text-danger mb-3">Cost & Expenses</p>
          <div className="space-y-2">
            {expenses.map((r) => {
              const change = pct(r.amount, r.prev);
              return (
                <div key={r.category} className="flex items-center justify-between py-1.5 border-b border-border/50 last:border-0">
                  <span className="text-sm text-foreground">{r.category}</span>
                  <div className="flex items-center gap-3">
                    <span className={`text-xs font-600 flex items-center gap-0.5 ${change <= 0 ? 'text-success' : 'text-danger'}`}>
                      {change >= 0 ? <ArrowUpRight size={12} /> : <ArrowDownRight size={12} />}
                      {Math.abs(change).toFixed(1)}%
                    </span>
                    <span className="text-sm font-700 text-foreground font-tabular w-24 text-right">{fmt(r.amount)}</span>
                  </div>
                </div>
              );
            })}
          </div>
        </div>
      </div>
    </div>
  );
}

// ─── Custom Date Range Picker ─────────────────────────────────────────────────

type DateMode = 'specific' | 'month-year';

interface CustomRange {
  mode: DateMode;
  specificDate: string;
  month: string;
  year: string;
}

function CustomRangePicker({ value, onChange }: { value: CustomRange; onChange: (v: CustomRange) => void }) {
  const currentYear = 2026;
  const years = Array.from({ length: 5 }, (_, i) => String(currentYear - i));

  return (
    <div className="flex flex-wrap items-center gap-3 p-3 bg-primary/5 border border-primary/20 rounded-lg">
      <div className="flex items-center gap-2">
        <span className="text-xs font-600 text-muted-foreground">Mode:</span>
        <div className="flex gap-1">
          <button
            onClick={() => onChange({ ...value, mode: 'specific' })}
            className={`px-3 py-1 rounded text-xs font-600 transition-colors ${value.mode === 'specific' ? 'bg-primary text-white' : 'bg-card border border-border text-muted-foreground hover:text-foreground'}`}
          >
            Specific Date
          </button>
          <button
            onClick={() => onChange({ ...value, mode: 'month-year' })}
            className={`px-3 py-1 rounded text-xs font-600 transition-colors ${value.mode === 'month-year' ? 'bg-primary text-white' : 'bg-card border border-border text-muted-foreground hover:text-foreground'}`}
          >
            Month & Year
          </button>
        </div>
      </div>

      {value.mode === 'specific' ? (
        <div className="flex items-center gap-2">
          <Calendar size={14} className="text-primary" />
          <input
            type="date"
            value={value.specificDate}
            onChange={(e) => onChange({ ...value, specificDate: e.target.value })}
            className="h-8 px-2 text-xs bg-card border border-border rounded text-foreground outline-none focus:border-primary"
          />
        </div>
      ) : (
        <div className="flex items-center gap-2">
          <CalendarDays size={14} className="text-primary" />
          <select
            value={value.month}
            onChange={(e) => onChange({ ...value, month: e.target.value })}
            className="h-8 px-2 text-xs bg-card border border-border rounded text-foreground outline-none focus:border-primary"
          >
            {MONTHS.map((m, i) => <option key={m} value={String(i + 1).padStart(2, '0')}>{m}</option>)}
          </select>
          <select
            value={value.year}
            onChange={(e) => onChange({ ...value, year: e.target.value })}
            className="h-8 px-2 text-xs bg-card border border-border rounded text-foreground outline-none focus:border-primary"
          >
            {years.map((y) => <option key={y}>{y}</option>)}
          </select>
        </div>
      )}
    </div>
  );
}

function getCustomRangeLabel(range: CustomRange): string {
  if (range.mode === 'specific' && range.specificDate) {
    return range.specificDate;
  }
  if (range.mode === 'month-year') {
    const monthName = MONTHS[parseInt(range.month, 10) - 1] ?? '';
    return `${monthName} ${range.year}`;
  }
  return 'Custom Range';
}

// ─── Daily Reports Tab ────────────────────────────────────────────────────────

function DailyReportsTab({ selectedBranch, periodLabel }: { selectedBranch: string; periodLabel: string }) {
  const [exportingBranch, setExportingBranch] = useState<string | null>(null);

  const reports = useMemo(() => {
    if (selectedBranch === 'All Branches') return DAILY_REPORTS;
    return DAILY_REPORTS.filter((r) => r.branch === selectedBranch);
  }, [selectedBranch]);

  const totals = useMemo(() => reports.reduce(
    (acc, r) => ({
      totalSales: acc.totalSales + r.totalSales,
      cashSales: acc.cashSales + r.cashSales,
      mpesaSales: acc.mpesaSales + r.mpesaSales,
      cardSales: acc.cardSales + r.cardSales,
      transactions: acc.transactions + r.transactions,
      refunds: acc.refunds + r.refunds,
      netRevenue: acc.netRevenue + r.netRevenue,
    }),
    { totalSales: 0, cashSales: 0, mpesaSales: 0, cardSales: 0, transactions: 0, refunds: 0, netRevenue: 0 }
  ), [reports]);

  const handleExportBranchPDF = async (report: DailyBranchReport) => {
    setExportingBranch(report.branch);
    try {
      await exportDailyReportToPDF(report, periodLabel);
    } finally {
      setExportingBranch(null);
    }
  };

  return (
    <div className="space-y-5">
      {/* Summary KPI cards */}
      <div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
        {[
          { label: 'Total Sales', value: fmt(totals.totalSales), icon: DollarSign, color: 'text-success', bg: 'bg-success/10' },
          { label: 'M-Pesa', value: fmt(totals.mpesaSales), icon: Smartphone, color: 'text-primary', bg: 'bg-primary/10' },
          { label: 'Cash', value: fmt(totals.cashSales), icon: Wallet, color: 'text-accent', bg: 'bg-accent/10' },
          { label: 'Transactions', value: totals.transactions.toLocaleString(), icon: BarChart3, color: 'text-info', bg: 'bg-info/10' },
        ].map((stat) => {
          const IconComp = stat.icon;
          return (
            <div key={stat.label} className="card-elevated rounded-xl p-4">
              <div className="flex items-center gap-2 mb-2">
                <div className={`w-8 h-8 rounded-lg ${stat.bg} flex items-center justify-center`}>
                  <IconComp size={16} className={stat.color} />
                </div>
                <span className="text-xs text-muted-foreground">{stat.label}</span>
              </div>
              <p className="text-xl font-700 text-foreground">{stat.value}</p>
            </div>
          );
        })}
      </div>

      {/* Per-branch cards with individual PDF export */}
      <div className="grid grid-cols-1 xl:grid-cols-2 gap-4">
        {reports.map((report) => (
          <div key={report.branch} className="card-elevated rounded-xl overflow-hidden">
            {/* Card header */}
            <div className="flex items-center justify-between px-5 py-4 bg-muted/30 border-b border-border">
              <div className="flex items-center gap-2">
                <Building2 size={16} className="text-primary" />
                <span className="text-sm font-700 text-foreground">{report.branch}</span>
                <span className="text-xs text-muted-foreground ml-1">— {periodLabel}</span>
              </div>
              <button
                onClick={() => handleExportBranchPDF(report)}
                disabled={exportingBranch === report.branch}
                className="flex items-center gap-1.5 px-3 py-1.5 rounded-md border border-border text-xs font-600 text-foreground hover:bg-muted transition-colors disabled:opacity-60"
              >
                <FileText size={13} />
                {exportingBranch === report.branch ? 'Exporting…' : 'Export PDF'}
              </button>
            </div>

            {/* Metrics grid */}
            <div className="p-4 grid grid-cols-2 gap-3">
              <div className="space-y-2.5">
                <div className="flex justify-between items-center py-1.5 border-b border-border/50">
                  <span className="text-xs text-muted-foreground">Total Sales</span>
                  <span className="text-sm font-700 text-foreground">{fmt(report.totalSales)}</span>
                </div>
                <div className="flex justify-between items-center py-1.5 border-b border-border/50">
                  <span className="text-xs text-muted-foreground flex items-center gap-1"><Wallet size={11} />Cash</span>
                  <span className="text-sm font-600 text-success">{fmt(report.cashSales)}</span>
                </div>
                <div className="flex justify-between items-center py-1.5 border-b border-border/50">
                  <span className="text-xs text-muted-foreground flex items-center gap-1"><Smartphone size={11} />M-Pesa</span>
                  <span className="text-sm font-600 text-primary">{fmt(report.mpesaSales)}</span>
                </div>
                <div className="flex justify-between items-center py-1.5">
                  <span className="text-xs text-muted-foreground flex items-center gap-1"><CreditCard size={11} />Card</span>
                  <span className="text-sm font-600 text-accent">{fmt(report.cardSales)}</span>
                </div>
              </div>
              <div className="space-y-2.5">
                <div className="flex justify-between items-center py-1.5 border-b border-border/50">
                  <span className="text-xs text-muted-foreground">Net Revenue</span>
                  <span className="text-sm font-700 text-foreground">{fmt(report.netRevenue)}</span>
                </div>
                <div className="flex justify-between items-center py-1.5 border-b border-border/50">
                  <span className="text-xs text-muted-foreground">Transactions</span>
                  <span className="text-sm font-600 text-foreground">{report.transactions}</span>
                </div>
                <div className="flex justify-between items-center py-1.5 border-b border-border/50">
                  <span className="text-xs text-muted-foreground">Refunds</span>
                  <span className="text-sm font-600 text-danger">{fmt(report.refunds)}</span>
                </div>
                <div className="flex justify-between items-center py-1.5">
                  <span className="text-xs text-muted-foreground">Top Product</span>
                  <span className="text-xs font-600 text-foreground truncate max-w-[100px]" title={report.topProduct}>{report.topProduct}</span>
                </div>
              </div>
            </div>

            {/* Payment breakdown bar */}
            <div className="px-4 pb-4">
              <p className="text-xs text-muted-foreground mb-1.5">Payment Mix</p>
              <div className="flex h-2 rounded-full overflow-hidden gap-0.5">
                <div className="bg-success rounded-full transition-all" style={{ width: `${((report.cashSales / report.totalSales) * 100).toFixed(1)}%` }} title={`Cash ${((report.cashSales / report.totalSales) * 100).toFixed(1)}%`} />
                <div className="bg-primary rounded-full transition-all" style={{ width: `${((report.mpesaSales / report.totalSales) * 100).toFixed(1)}%` }} title={`M-Pesa ${((report.mpesaSales / report.totalSales) * 100).toFixed(1)}%`} />
                <div className="bg-accent rounded-full transition-all" style={{ width: `${((report.cardSales / report.totalSales) * 100).toFixed(1)}%` }} title={`Card ${((report.cardSales / report.totalSales) * 100).toFixed(1)}%`} />
              </div>
              <div className="flex gap-3 mt-1.5">
                <span className="text-xs text-muted-foreground flex items-center gap-1"><span className="w-2 h-2 rounded-full bg-success inline-block" />Cash {((report.cashSales / report.totalSales) * 100).toFixed(0)}%</span>
                <span className="text-xs text-muted-foreground flex items-center gap-1"><span className="w-2 h-2 rounded-full bg-primary inline-block" />M-Pesa {((report.mpesaSales / report.totalSales) * 100).toFixed(0)}%</span>
                <span className="text-xs text-muted-foreground flex items-center gap-1"><span className="w-2 h-2 rounded-full bg-accent inline-block" />Card {((report.cardSales / report.totalSales) * 100).toFixed(0)}%</span>
              </div>
            </div>
          </div>
        ))}
      </div>

      {/* Summary table */}
      {reports.length > 1 && (
        <div className="card-elevated rounded-xl overflow-hidden">
          <div className="px-5 py-4 border-b border-border">
            <h3 className="text-sm font-700 text-foreground">Branch Comparison — {periodLabel}</h3>
          </div>
          <div className="overflow-x-auto">
            <table className="w-full text-sm">
              <thead>
                <tr className="bg-muted/50 border-b border-border">
                  {['Branch', 'Total Sales', 'Cash', 'M-Pesa', 'Card', 'Transactions', 'Refunds', 'Net Revenue'].map((h) => (
                    <th key={h} className={`px-4 py-3 text-xs font-600 text-muted-foreground uppercase tracking-wide ${h === 'Branch' ? 'text-left' : 'text-right'}`}>{h}</th>
                  ))}
                </tr>
              </thead>
              <tbody className="divide-y divide-border">
                {reports.map((r) => (
                  <tr key={r.branch} className="hover:bg-muted/30 transition-colors">
                    <td className="px-4 py-3 font-600 text-foreground flex items-center gap-2"><Building2 size={13} className="text-muted-foreground" />{r.branch}</td>
                    <td className="px-4 py-3 text-right font-tabular text-foreground">{fmt(r.totalSales)}</td>
                    <td className="px-4 py-3 text-right font-tabular text-success">{fmt(r.cashSales)}</td>
                    <td className="px-4 py-3 text-right font-tabular text-primary">{fmt(r.mpesaSales)}</td>
                    <td className="px-4 py-3 text-right font-tabular text-accent">{fmt(r.cardSales)}</td>
                    <td className="px-4 py-3 text-right font-tabular text-foreground">{r.transactions}</td>
                    <td className="px-4 py-3 text-right font-tabular text-danger">{fmt(r.refunds)}</td>
                    <td className="px-4 py-3 text-right font-tabular font-700 text-foreground">{fmt(r.netRevenue)}</td>
                  </tr>
                ))}
                <tr className="bg-muted/50 font-700">
                  <td className="px-4 py-3 font-700 text-foreground">Total</td>
                  <td className="px-4 py-3 text-right font-tabular text-foreground">{fmt(totals.totalSales)}</td>
                  <td className="px-4 py-3 text-right font-tabular text-success">{fmt(totals.cashSales)}</td>
                  <td className="px-4 py-3 text-right font-tabular text-primary">{fmt(totals.mpesaSales)}</td>
                  <td className="px-4 py-3 text-right font-tabular text-accent">{fmt(totals.cardSales)}</td>
                  <td className="px-4 py-3 text-right font-tabular text-foreground">{totals.transactions}</td>
                  <td className="px-4 py-3 text-right font-tabular text-danger">{fmt(totals.refunds)}</td>
                  <td className="px-4 py-3 text-right font-tabular font-700 text-foreground">{fmt(totals.netRevenue)}</td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>
      )}
    </div>
  );
}

// ─── Main Page ────────────────────────────────────────────────────────────────

export default function ReportsPage() {
  const [selectedBranch, setSelectedBranch] = useState('All Branches');
  const [selectedPeriod, setSelectedPeriod] = useState('This Month');
  const [drillBranch, setDrillBranch] = useState<string | null>(null);
  const [activeTab, setActiveTab] = useState<'pl' | 'payment' | 'cashflow' | 'daily'>('pl');
  const [exportLoading, setExportLoading] = useState<'pdf' | 'excel' | null>(null);
  const [customRange, setCustomRange] = useState<CustomRange>({
    mode: 'month-year',
    specificDate: '2026-08-07',
    month: '08',
    year: '2026',
  });

  const plRows = useMemo(() => PL_DATA[selectedBranch] ?? PL_DATA['All Branches'], [selectedBranch]);

  const totals = useMemo(() => plRows.reduce(
    (acc, r) => ({
      revenue: acc.revenue + r.revenue,
      grossProfit: acc.grossProfit + r.grossProfit,
      netProfit: acc.netProfit + r.netProfit,
      prevRevenue: acc.prevRevenue + r.prevRevenue,
      prevNetProfit: acc.prevNetProfit + r.prevNetProfit,
    }),
    { revenue: 0, grossProfit: 0, netProfit: 0, prevRevenue: 0, prevNetProfit: 0 }
  ), [plRows]);

  const revenueChange = pct(totals.revenue, totals.prevRevenue);
  const profitChange = pct(totals.netProfit, totals.prevNetProfit);

  const latestCF = CASHFLOW_DATA[CASHFLOW_DATA.length - 1];
  const momChange = pct(latestCF.net, latestCF.prevNet);

  const periodLabel = selectedPeriod === 'Custom Range' ? getCustomRangeLabel(customRange) : selectedPeriod;

  const tabs = [
    { key: 'pl', label: 'P&L Summary' },
    { key: 'payment', label: 'Payment Methods' },
    { key: 'cashflow', label: 'Cash Flow' },
    { key: 'daily', label: 'Daily Reports' },
  ] as const;

  const handleExportPDF = async () => {
    setExportLoading('pdf');
    try {
      await exportReportToPDF(plRows, PAYMENT_METHODS, CASHFLOW_DATA, periodLabel, selectedBranch, activeTab);
    } finally {
      setExportLoading(null);
    }
  };

  const handleExportExcel = async () => {
    setExportLoading('excel');
    try {
      await exportReportToExcel(plRows, PAYMENT_METHODS, CASHFLOW_DATA, periodLabel, selectedBranch);
    } finally {
      setExportLoading(null);
    }
  };

  return (
    <AppLayout>
      <div className="p-6 xl:p-8 max-w-screen-2xl mx-auto space-y-6">

        {/* Header */}
        <div className="flex flex-col sm:flex-row sm:items-start justify-between gap-4">
          <div>
            <h1 className="text-xl font-700 text-foreground">Financial Reports</h1>
            <p className="text-sm text-muted-foreground mt-0.5">P&amp;L by branch, payment breakdown, cash flow, and daily reports</p>
          </div>
          <div className="flex flex-col gap-3">
            <div className="flex gap-2 flex-wrap">
              <select
                value={selectedBranch}
                onChange={(e) => { setSelectedBranch(e.target.value); setDrillBranch(null); }}
                className="h-9 px-3 text-sm bg-card border border-border rounded-md text-foreground outline-none focus:border-primary"
              >
                {BRANCHES.map((b) => <option key={b}>{b}</option>)}
              </select>
              <select
                value={selectedPeriod}
                onChange={(e) => setSelectedPeriod(e.target.value)}
                className="h-9 px-3 text-sm bg-card border border-border rounded-md text-foreground outline-none focus:border-primary"
              >
                {PERIODS.map((p) => <option key={p}>{p}</option>)}
              </select>
              {activeTab !== 'daily' && (
                <>
                  <button
                    onClick={handleExportPDF}
                    disabled={exportLoading === 'pdf'}
                    className="flex items-center gap-2 px-4 py-2 rounded-md border border-border text-sm font-600 text-foreground hover:bg-muted transition-colors disabled:opacity-60"
                  >
                    <FileText size={15} />
                    {exportLoading === 'pdf' ? 'Exporting…' : 'PDF'}
                  </button>
                  <button
                    onClick={handleExportExcel}
                    disabled={exportLoading === 'excel'}
                    className="flex items-center gap-2 px-4 py-2 rounded-md bg-success/10 border border-success/30 text-sm font-600 text-success hover:bg-success/20 transition-colors disabled:opacity-60"
                  >
                    <Download size={15} />
                    {exportLoading === 'excel' ? 'Exporting…' : 'Excel'}
                  </button>
                </>
              )}
            </div>
            {/* Custom range picker */}
            {selectedPeriod === 'Custom Range' && (
              <CustomRangePicker value={customRange} onChange={setCustomRange} />
            )}
          </div>
        </div>

        {/* KPI Summary Cards */}
        <div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
          {[
            {
              label: 'Total Revenue', value: fmt(totals.revenue), change: revenueChange,
              icon: DollarSign, color: 'text-success', bg: 'bg-success/10',
            },
            {
              label: 'Gross Profit', value: fmt(totals.grossProfit),
              change: pct(totals.grossProfit, totals.prevRevenue * 0.4),
              icon: TrendingUp, color: 'text-primary', bg: 'bg-primary/10',
            },
            {
              label: 'Net Profit', value: fmt(totals.netProfit), change: profitChange,
              icon: BarChart3, color: 'text-info', bg: 'bg-info/10',
            },
            {
              label: 'Cash Flow (Jun)', value: fmt(latestCF.net), change: momChange,
              icon: Wallet, color: 'text-accent', bg: 'bg-accent/10',
            },
          ].map((stat) => {
            const IconComp = stat.icon;
            const up = stat.change >= 0;
            return (
              <div key={stat.label} className="card-elevated rounded-xl p-4">
                <div className="flex items-center justify-between mb-2">
                  <div className={`w-8 h-8 rounded-lg ${stat.bg} flex items-center justify-center`}>
                    <IconComp size={16} className={stat.color} />
                  </div>
                  <span className={`text-xs font-600 flex items-center gap-0.5 ${up ? 'text-success' : 'text-danger'}`}>
                    {up ? <ArrowUpRight size={12} /> : <ArrowDownRight size={12} />}
                    {Math.abs(stat.change).toFixed(1)}%
                  </span>
                </div>
                <p className="text-xl font-700 text-foreground">{stat.value}</p>
                <p className="text-xs text-muted-foreground mt-0.5">{stat.label}</p>
              </div>
            );
          })}
        </div>

        {/* Tab Navigation */}
        <div className="flex gap-1 bg-muted/50 p-1 rounded-lg w-fit flex-wrap">
          {tabs.map((t) => (
            <button
              key={t.key}
              onClick={() => setActiveTab(t.key)}
              className={`px-4 py-1.5 rounded-md text-sm font-600 transition-all ${activeTab === t.key ? 'bg-card text-foreground shadow-sm' : 'text-muted-foreground hover:text-foreground'}`}
            >
              {t.label}
            </button>
          ))}
        </div>

        {/* ── P&L Summary Tab ── */}
        {activeTab === 'pl' && (
          <div className="space-y-4">
            <div className="card-elevated rounded-xl p-5">
              <div className="flex items-center justify-between mb-4">
                <h3 className="text-sm font-700 text-foreground">Revenue vs Net Profit by Branch</h3>
                <span className="text-xs text-muted-foreground">{periodLabel} · KES</span>
              </div>
              <ResponsiveContainer width="100%" height={220}>
                <BarChart data={plRows} barGap={4} barCategoryGap="30%">
                  <CartesianGrid strokeDasharray="3 3" stroke="var(--border)" vertical={false} />
                  <XAxis dataKey="branch" tick={{ fontSize: 11, fill: 'var(--muted-foreground)' }} axisLine={false} tickLine={false} />
                  <YAxis tick={{ fontSize: 11, fill: 'var(--muted-foreground)' }} axisLine={false} tickLine={false} tickFormatter={(v) => `${(v / 1000).toFixed(0)}K`} />
                  <Tooltip
                    formatter={(v: number, name: string) => [fmt(v), name]}
                    contentStyle={{ background: 'var(--card)', border: '1px solid var(--border)', borderRadius: '8px', fontSize: '12px' }}
                  />
                  <Legend wrapperStyle={{ fontSize: '11px', paddingTop: '8px' }} />
                  <Bar dataKey="revenue" name="Revenue" fill="var(--primary)" radius={[4, 4, 0, 0]} />
                  <Bar dataKey="netProfit" name="Net Profit" fill="var(--success, #22c55e)" radius={[4, 4, 0, 0]} />
                </BarChart>
              </ResponsiveContainer>
            </div>

            <div className="card-elevated rounded-xl overflow-hidden">
              <div className="px-5 py-4 border-b border-border flex items-center justify-between">
                <h3 className="text-sm font-700 text-foreground">P&amp;L Summary — {periodLabel}</h3>
                <span className="text-xs text-muted-foreground">Click a row to drill down</span>
              </div>
              <div className="overflow-x-auto">
                <table className="w-full text-sm">
                  <thead>
                    <tr className="bg-muted/50 border-b border-border">
                      {['Branch', 'Revenue', 'COGS', 'Gross Profit', 'GM%', 'OpEx', 'Net Profit', 'NM%', 'vs Prev'].map((h) => (
                        <th key={h} className={`px-4 py-3 text-xs font-600 text-muted-foreground uppercase tracking-wide ${h === 'Branch' ? 'text-left' : 'text-right'}`}>{h}</th>
                      ))}
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-border">
                    {plRows.map((r) => {
                      const revenueChg = pct(r.revenue, r.prevRevenue);
                      const isDrilled = drillBranch === r.branch;
                      return (
                        <React.Fragment key={r.branch}>
                          <tr
                            onClick={() => setDrillBranch(isDrilled ? null : r.branch)}
                            className={`cursor-pointer transition-colors ${isDrilled ? 'bg-primary/5' : 'hover:bg-muted/30'}`}
                          >
                            <td className="px-4 py-3">
                              <div className="flex items-center gap-2">
                                <Building2 size={14} className="text-muted-foreground" />
                                <span className="font-600 text-foreground">{r.branch}</span>
                                {isDrilled ? <ChevronUp size={14} className="text-primary ml-1" /> : <ChevronDown size={14} className="text-muted-foreground ml-1" />}
                              </div>
                            </td>
                            <td className="px-4 py-3 text-right font-tabular text-foreground">{fmt(r.revenue)}</td>
                            <td className="px-4 py-3 text-right font-tabular text-danger">{fmt(r.cogs)}</td>
                            <td className="px-4 py-3 text-right font-tabular font-600 text-foreground">{fmt(r.grossProfit)}</td>
                            <td className="px-4 py-3 text-right font-tabular text-success">{r.grossMargin.toFixed(1)}%</td>
                            <td className="px-4 py-3 text-right font-tabular text-danger">{fmt(r.opex)}</td>
                            <td className="px-4 py-3 text-right font-tabular font-700 text-foreground">{fmt(r.netProfit)}</td>
                            <td className="px-4 py-3 text-right font-tabular text-success">{r.netMargin.toFixed(1)}%</td>
                            <td className="px-4 py-3 text-right">
                              <span className={`text-xs font-600 flex items-center justify-end gap-0.5 ${revenueChg >= 0 ? 'text-success' : 'text-danger'}`}>
                                {revenueChg >= 0 ? <ArrowUpRight size={12} /> : <ArrowDownRight size={12} />}
                                {Math.abs(revenueChg).toFixed(1)}%
                              </span>
                            </td>
                          </tr>
                        </React.Fragment>
                      );
                    })}
                    <tr className="bg-muted/50 font-700">
                      <td className="px-4 py-3 text-sm font-700 text-foreground">Total</td>
                      <td className="px-4 py-3 text-right font-tabular text-foreground">{fmt(totals.revenue)}</td>
                      <td className="px-4 py-3 text-right font-tabular text-danger">{fmt(plRows.reduce((a, r) => a + r.cogs, 0))}</td>
                      <td className="px-4 py-3 text-right font-tabular text-foreground">{fmt(totals.grossProfit)}</td>
                      <td className="px-4 py-3 text-right font-tabular text-success">{totals.revenue > 0 ? ((totals.grossProfit / totals.revenue) * 100).toFixed(1) : 0}%</td>
                      <td className="px-4 py-3 text-right font-tabular text-danger">{fmt(plRows.reduce((a, r) => a + r.opex, 0))}</td>
                      <td className="px-4 py-3 text-right font-tabular text-foreground">{fmt(totals.netProfit)}</td>
                      <td className="px-4 py-3 text-right font-tabular text-success">{totals.revenue > 0 ? ((totals.netProfit / totals.revenue) * 100).toFixed(1) : 0}%</td>
                      <td className="px-4 py-3 text-right">
                        <span className={`text-xs font-600 flex items-center justify-end gap-0.5 ${revenueChange >= 0 ? 'text-success' : 'text-danger'}`}>
                          {revenueChange >= 0 ? <ArrowUpRight size={12} /> : <ArrowDownRight size={12} />}
                          {Math.abs(revenueChange).toFixed(1)}%
                        </span>
                      </td>
                    </tr>
                  </tbody>
                </table>
              </div>
            </div>

            {drillBranch && DRILL_ROWS[drillBranch] && (
              <DrillDownPanel branch={drillBranch} onClose={() => setDrillBranch(null)} />
            )}
          </div>
        )}

        {/* ── Payment Methods Tab ── */}
        {activeTab === 'payment' && (
          <div className="space-y-6">
            <div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
              {PAYMENT_METHODS.map((pm) => {
                const IconComp = pm.icon;
                return (
                  <div key={pm.method} className="card-elevated rounded-xl p-4">
                    <div className="flex items-center gap-2 mb-3">
                      <div className="w-8 h-8 rounded-lg flex items-center justify-center" style={{ background: `${pm.color}20` }}>
                        <IconComp size={16} style={{ color: pm.color }} />
                      </div>
                      <span className="text-sm font-600 text-foreground">{pm.method}</span>
                    </div>
                    <p className="text-xl font-700 text-foreground">{fmt(pm.amount)}</p>
                    <div className="flex items-center justify-between mt-1">
                      <p className="text-xs text-muted-foreground">{pm.transactions.toLocaleString()} txns</p>
                      <span className="text-xs font-700" style={{ color: pm.color }}>{pm.share}%</span>
                    </div>
                    <div className="mt-2 h-1.5 bg-muted rounded-full overflow-hidden">
                      <div className="h-full rounded-full transition-all" style={{ width: `${pm.share}%`, background: pm.color }} />
                    </div>
                  </div>
                );
              })}
            </div>

            <div className="grid grid-cols-1 xl:grid-cols-2 gap-6">
              <div className="card-elevated rounded-xl p-5">
                <h3 className="text-sm font-700 text-foreground mb-4">Revenue Share by Payment Method</h3>
                <ResponsiveContainer width="100%" height={260}>
                  <PieChart>
                    <Pie
                      data={PAYMENT_METHODS}
                      dataKey="amount"
                      nameKey="method"
                      cx="50%"
                      cy="50%"
                      outerRadius={90}
                      innerRadius={50}
                      paddingAngle={3}
                      label={({ method, share }) => `${method} ${share}%`}
                      labelLine={false}
                    >
                      {PAYMENT_METHODS.map((pm, i) => (
                        <Cell key={pm.method} fill={PIE_COLORS[i]} />
                      ))}
                    </Pie>
                    <Tooltip formatter={(v: number) => [fmt(v), 'Amount']} contentStyle={{ background: 'var(--card)', border: '1px solid var(--border)', borderRadius: '8px', fontSize: '12px' }} />
                    <Legend wrapperStyle={{ fontSize: '11px' }} />
                  </PieChart>
                </ResponsiveContainer>
              </div>

              <div className="card-elevated rounded-xl p-5">
                <h3 className="text-sm font-700 text-foreground mb-4">Transaction Volume by Method</h3>
                <ResponsiveContainer width="100%" height={260}>
                  <BarChart data={PAYMENT_METHODS} layout="vertical" barSize={20}>
                    <CartesianGrid strokeDasharray="3 3" stroke="var(--border)" horizontal={false} />
                    <XAxis type="number" tick={{ fontSize: 11, fill: 'var(--muted-foreground)' }} axisLine={false} tickLine={false} />
                    <YAxis dataKey="method" type="category" tick={{ fontSize: 11, fill: 'var(--muted-foreground)' }} axisLine={false} tickLine={false} width={90} />
                    <Tooltip formatter={(v: number) => [v.toLocaleString(), 'Transactions']} contentStyle={{ background: 'var(--card)', border: '1px solid var(--border)', borderRadius: '8px', fontSize: '12px' }} />
                    <Bar dataKey="transactions" radius={[0, 4, 4, 0]}>
                      {PAYMENT_METHODS.map((pm, i) => (
                        <Cell key={pm.method} fill={PIE_COLORS[i]} />
                      ))}
                    </Bar>
                  </BarChart>
                </ResponsiveContainer>
              </div>
            </div>
          </div>
        )}

        {/* ── Cash Flow Tab ── */}
        {activeTab === 'cashflow' && (
          <div className="space-y-6">
            <div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
              {[
                { label: 'Total Inflow (Jun)', value: fmt(latestCF.inflow), change: pct(latestCF.inflow, CASHFLOW_DATA[4].inflow), up: true },
                { label: 'Total Outflow (Jun)', value: fmt(latestCF.outflow), change: pct(latestCF.outflow, CASHFLOW_DATA[4].outflow), up: false },
                { label: 'Net Cash Flow (Jun)', value: fmt(latestCF.net), change: momChange, up: momChange >= 0 },
              ].map((s) => (
                <div key={s.label} className="card-elevated rounded-xl p-4">
                  <p className="text-xs text-muted-foreground mb-1">{s.label}</p>
                  <p className="text-2xl font-700 text-foreground">{s.value}</p>
                  <span className={`text-xs font-600 flex items-center gap-0.5 mt-1 ${s.up ? 'text-success' : 'text-danger'}`}>
                    {s.up ? <ArrowUpRight size={12} /> : <ArrowDownRight size={12} />}
                    {Math.abs(s.change).toFixed(1)}% vs last month
                  </span>
                </div>
              ))}
            </div>

            <div className="card-elevated rounded-xl p-5">
              <div className="flex items-center justify-between mb-4">
                <h3 className="text-sm font-700 text-foreground">Cash Flow Trends — 6 Month View</h3>
                <div className="flex items-center gap-4 text-xs text-muted-foreground">
                  <span className="flex items-center gap-1.5"><span className="w-3 h-0.5 bg-primary rounded inline-block" />Inflow</span>
                  <span className="flex items-center gap-1.5"><span className="w-3 h-0.5 bg-danger rounded inline-block" />Outflow</span>
                  <span className="flex items-center gap-1.5"><span className="w-3 h-0.5 bg-success rounded inline-block" />Net</span>
                </div>
              </div>
              <ResponsiveContainer width="100%" height={280}>
                <ComposedChart data={CASHFLOW_DATA}>
                  <CartesianGrid strokeDasharray="3 3" stroke="var(--border)" vertical={false} />
                  <XAxis dataKey="month" tick={{ fontSize: 11, fill: 'var(--muted-foreground)' }} axisLine={false} tickLine={false} />
                  <YAxis tick={{ fontSize: 11, fill: 'var(--muted-foreground)' }} axisLine={false} tickLine={false} tickFormatter={(v) => `${(v / 1000).toFixed(0)}K`} />
                  <Tooltip
                    formatter={(v: number, name: string) => [fmt(v), name]}
                    contentStyle={{ background: 'var(--card)', border: '1px solid var(--border)', borderRadius: '8px', fontSize: '12px' }}
                  />
                  <Bar dataKey="inflow" name="Inflow" fill="var(--primary)" opacity={0.7} radius={[4, 4, 0, 0]} barSize={18} />
                  <Bar dataKey="outflow" name="Outflow" fill="var(--danger, #ef4444)" opacity={0.7} radius={[4, 4, 0, 0]} barSize={18} />
                  <Line type="monotone" dataKey="net" name="Net" stroke="#22c55e" strokeWidth={2.5} dot={{ fill: '#22c55e', r: 4 }} />
                </ComposedChart>
              </ResponsiveContainer>
            </div>

            <div className="card-elevated rounded-xl overflow-hidden">
              <div className="px-5 py-4 border-b border-border">
                <h3 className="text-sm font-700 text-foreground">Month-over-Month Comparison</h3>
              </div>
              <div className="overflow-x-auto">
                <table className="w-full text-sm">
                  <thead>
                    <tr className="bg-muted/50 border-b border-border">
                      {['Month', 'Inflow', 'Outflow', 'Net Cash Flow', 'Prev Month Net', 'MoM Change'].map((h) => (
                        <th key={h} className={`px-4 py-3 text-xs font-600 text-muted-foreground uppercase tracking-wide ${h === 'Month' ? 'text-left' : 'text-right'}`}>{h}</th>
                      ))}
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-border">
                    {CASHFLOW_DATA.map((row, i) => {
                      const change = pct(row.net, row.prevNet);
                      const isLatest = i === CASHFLOW_DATA.length - 1;
                      return (
                        <tr key={row.month} className={`transition-colors hover:bg-muted/30 ${isLatest ? 'bg-primary/5' : ''}`}>
                          <td className="px-4 py-3 font-600 text-foreground">
                            {row.month} {isLatest && <span className="ml-1 text-xs text-primary font-600">Current</span>}
                          </td>
                          <td className="px-4 py-3 text-right font-tabular text-success">{fmt(row.inflow)}</td>
                          <td className="px-4 py-3 text-right font-tabular text-danger">{fmt(row.outflow)}</td>
                          <td className="px-4 py-3 text-right font-tabular font-700 text-foreground">{fmt(row.net)}</td>
                          <td className="px-4 py-3 text-right font-tabular text-muted-foreground">{fmt(row.prevNet)}</td>
                          <td className="px-4 py-3 text-right">
                            <span className={`text-xs font-600 flex items-center justify-end gap-0.5 ${change >= 0 ? 'text-success' : 'text-danger'}`}>
                              {change >= 0 ? <ArrowUpRight size={12} /> : <ArrowDownRight size={12} />}
                              {Math.abs(change).toFixed(1)}%
                            </span>
                          </td>
                        </tr>
                      );
                    })}
                  </tbody>
                </table>
              </div>
            </div>
          </div>
        )}

        {/* ── Daily Reports Tab ── */}
        {activeTab === 'daily' && (
          <DailyReportsTab selectedBranch={selectedBranch} periodLabel={periodLabel} />
        )}

      </div>
    </AppLayout>
  );
}
