// admin-finance.jsx — Full financial system: dashboard, transactions, expenses, invoices, P&L, tax

const fmtAED = (n) => (n < 0 ? '−' : '') + 'AED ' + Math.abs(Math.round(n)).toLocaleString();
const fmtCompact = (n) => {
  const a = Math.abs(n);
  if (a >= 1000) return (n / 1000).toFixed(1) + 'K';
  return String(n);
};

// ─── Finance Dashboard ──────────────────────────────────────
function FinanceDashboard({ lang }) {
  const t = (ar, en) => lang === 'ar' ? ar : en;
  const revSum = FINANCE_30D.revenue.reduce((a, b) => a + b, 0);
  const expSum = FINANCE_30D.expenses.reduce((a, b) => a + b, 0);
  const netProfit = revSum - expSum;
  const margin = (netProfit / revSum * 100).toFixed(1);
  const revMax = Math.max(...FINANCE_30D.revenue);
  const cashOnHand = 184320;
  const acctsRecv = INVOICES.filter(i => i.status !== 'paid').reduce((s, i) => s + i.total, 0);
  const pendingPay = TRANSACTIONS.filter(t => t.status === 'pending').reduce((s, t) => s + Math.abs(t.amount), 0);

  const kpis = [
    { lbl: t('الإيرادات · 30 يوم', 'Revenue · 30d'), val: fmtAED(revSum), delta: '+18.2%', up: true,  icon: <I.income />,  tone: '#6B7050' },
    { lbl: t('المصاريف · 30 يوم', 'Expenses · 30d'), val: fmtAED(expSum), delta: '+8.4%',  up: false, icon: <I.expense />, tone: '#C97B5E' },
    { lbl: t('صافي الربح',         'Net profit'),     val: fmtAED(netProfit), delta: '+24.6%', up: true,  icon: <I.wallet />,  tone: '#2A1F18' },
    { lbl: t('هامش الربح',         'Profit margin'),  val: margin + '%',     delta: '+2.1pt', up: true,  icon: <I.chart />,   tone: '#8C4A2B' },
  ];

  // Combined area chart paths
  const W = 600, H = 200;
  const xs = FINANCE_30D.revenue.map((_, i) => (i / 29) * W);
  const maxY = revMax * 1.1;
  const yRev = FINANCE_30D.revenue.map(v => H - (v / maxY) * H);
  const yExp = FINANCE_30D.expenses.map(v => H - (v / maxY) * H);

  const buildArea = (ys) => {
    let d = `M0 ${H} `;
    ys.forEach((y, i) => d += `L${xs[i]} ${y} `);
    d += `L${W} ${H} Z`;
    return d;
  };
  const buildLine = (ys) => ys.map((y, i) => `${i ? 'L' : 'M'}${xs[i]} ${y}`).join(' ');

  return (
    <>
      <div className="admin-head">
        <div>
          <div className="eyebrow">{t('المالية · 01', 'Finance · 01')}</div>
          <h1 className="h-display">{t('لوحة الإيرادات', 'Financial Overview')}</h1>
          <div className="sub">{t('آخر ٣٠ يوماً · جميع المبالغ بالدرهم الإماراتي', 'Last 30 days · all amounts in AED')}</div>
        </div>
        <div className="actions">
          <select className="btn ghost" style={{ padding: '0 18px' }}>
            <option>{t('آخر ٣٠ يوم', 'Last 30 days')}</option>
            <option>{t('هذا الشهر', 'This month')}</option>
            <option>{t('هذا الربع', 'This quarter')}</option>
            <option>{t('هذه السنة', 'This year')}</option>
          </select>
          <button className="btn ghost"><I.download /> {t('تصدير', 'Export')}</button>
        </div>
      </div>

      <div className="fin-kpis">
        {kpis.map((k, i) => (
          <div key={i} className="fin-kpi">
            <div className="kpi-icon" style={{ background: `color-mix(in oklab, ${k.tone} 14%, var(--bg-2))`, color: k.tone }}>{k.icon}</div>
            <div className="kpi-body">
              <div className="lbl">{k.lbl}</div>
              <div className="val">{k.val}</div>
              <div className={'delta ' + (k.up ? 'up' : 'down')}>
                {k.up ? <I.trendUp /> : <I.trendDown />} {k.delta} {t('vs الفترة السابقة', 'vs prev')}
              </div>
            </div>
          </div>
        ))}
      </div>

      {/* Cash position strip */}
      <div className="fin-cash-strip">
        <div className="cash-item">
          <div className="lbl"><I.cash /> {t('السيولة المتاحة', 'Cash on hand')}</div>
          <div className="val">{fmtAED(cashOnHand)}</div>
          <div className="sub">{t('عبر ٣ حسابات بنكية', 'across 3 bank accounts')}</div>
        </div>
        <div className="cash-item">
          <div className="lbl"><I.invoice /> {t('ذمم مدينة', 'Accounts receivable')}</div>
          <div className="val">{fmtAED(acctsRecv)}</div>
          <div className="sub">{INVOICES.filter(i => i.status !== 'paid').length} {t('فاتورة معلّقة', 'unpaid invoices')}</div>
        </div>
        <div className="cash-item">
          <div className="lbl"><I.expense /> {t('مدفوعات معلّقة', 'Pending payments')}</div>
          <div className="val">{fmtAED(pendingPay)}</div>
          <div className="sub">{t('للمورّدين', 'to suppliers')}</div>
        </div>
        <div className="cash-item highlight">
          <div className="lbl"><I.tax /> {t('ضريبة القيمة المضافة', 'VAT payable')}</div>
          <div className="val">{fmtAED(Math.round(revSum * 0.05))}</div>
          <div className="sub">{t('Q2 · يستحق ٣٠ يونيو', 'Q2 · due Jun 30')}</div>
        </div>
      </div>

      {/* Main chart: revenue vs expenses */}
      <div className="chart-card" style={{ marginTop: 16 }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 8 }}>
          <h3>{t('الإيرادات مقابل المصاريف · آخر ٣٠ يوماً', 'Revenue vs Expenses · 30 days')}</h3>
          <div style={{ display: 'flex', gap: 16, fontSize: 11 }}>
            <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}>
              <span style={{ width: 10, height: 10, borderRadius: 2, background: '#6B7050' }} />
              {t('إيرادات', 'Revenue')}
            </span>
            <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}>
              <span style={{ width: 10, height: 10, borderRadius: 2, background: '#C97B5E' }} />
              {t('مصاريف', 'Expenses')}
            </span>
          </div>
        </div>
        <div className="fin-area-chart">
          <svg viewBox={`0 0 ${W} ${H + 24}`} preserveAspectRatio="none" width="100%" height="240">
            <defs>
              <linearGradient id="gradRev" x1="0" x2="0" y1="0" y2="1">
                <stop offset="0%" stopColor="#6B7050" stopOpacity="0.35" />
                <stop offset="100%" stopColor="#6B7050" stopOpacity="0.02" />
              </linearGradient>
              <linearGradient id="gradExp" x1="0" x2="0" y1="0" y2="1">
                <stop offset="0%" stopColor="#C97B5E" stopOpacity="0.28" />
                <stop offset="100%" stopColor="#C97B5E" stopOpacity="0.02" />
              </linearGradient>
            </defs>
            {/* gridlines */}
            {[0, 0.25, 0.5, 0.75, 1].map((g, i) => (
              <line key={i} x1="0" x2={W} y1={H * g} y2={H * g} stroke="var(--line-2)" strokeWidth="0.5" />
            ))}
            <path d={buildArea(yRev)} fill="url(#gradRev)" />
            <path d={buildArea(yExp)} fill="url(#gradExp)" />
            <path d={buildLine(yRev)} fill="none" stroke="#6B7050" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
            <path d={buildLine(yExp)} fill="none" stroke="#C97B5E" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
            {/* dots on last point */}
            <circle cx={xs[xs.length - 1]} cy={yRev[yRev.length - 1]} r="4" fill="#6B7050" />
            <circle cx={xs[xs.length - 1]} cy={yExp[yExp.length - 1]} r="4" fill="#C97B5E" />
            {/* x labels */}
            <text x="0" y={H + 16} fontSize="10" fill="var(--ink-3)" fontFamily="var(--f-en-body)">Apr 19</text>
            <text x={W / 2 - 16} y={H + 16} fontSize="10" fill="var(--ink-3)" fontFamily="var(--f-en-body)">May 4</text>
            <text x={W - 36} y={H + 16} fontSize="10" fill="var(--ink-3)" fontFamily="var(--f-en-body)">May 18</text>
          </svg>
        </div>
      </div>

      {/* Two-up: expense breakdown + payment methods */}
      <div className="chart-grid" style={{ marginTop: 16 }}>
        <div className="chart-card">
          <h3>{t('توزيع المصاريف', 'Expense breakdown')}</h3>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 14, marginTop: 4 }}>
            {EXPENSE_CATEGORIES.map(c => (
              <div key={c.id} className="exp-row">
                <div className="exp-row-head">
                  <span style={{ display: 'inline-flex', alignItems: 'center', gap: 10 }}>
                    <span style={{ width: 10, height: 10, borderRadius: 2, background: c.color }} />
                    {lang === 'ar' ? c.ar : c.en}
                  </span>
                  <span className="serif-en" style={{ fontSize: 15 }}>{fmtAED(Math.round(expSum * c.pct / 100))}</span>
                </div>
                <div className="exp-bar">
                  <div className="exp-bar-fill" style={{ width: `${c.pct}%`, background: c.color }} />
                </div>
                <div className="exp-row-foot">
                  <span>{c.pct}% {t('من الإجمالي', 'of total')}</span>
                </div>
              </div>
            ))}
          </div>
        </div>

        <div className="chart-card">
          <h3>{t('طرق الدفع', 'Payment methods')}</h3>
          <div className="pm-list">
            {PAYMENT_SPLIT.map(p => (
              <div key={p.id} className="pm-row">
                <span style={{ width: 28, height: 28, borderRadius: 4, background: `color-mix(in oklab, ${p.color} 18%, var(--bg-2))`, display: 'inline-flex', alignItems: 'center', justifyContent: 'center', color: p.color }}>
                  {p.id === 'cash' ? <I.cash /> : p.id === 'bank' ? <I.bank /> : <I.wallet />}
                </span>
                <div style={{ flex: 1 }}>
                  <div style={{ fontSize: 13, fontWeight: 500 }}>{lang === 'ar' ? p.ar : p.en}</div>
                  <div className="pm-track"><div className="pm-fill" style={{ width: `${p.pct}%`, background: p.color }} /></div>
                </div>
                <div className="pm-pct">{p.pct}%</div>
              </div>
            ))}
          </div>
        </div>
      </div>

      {/* Recent transactions teaser */}
      <div className="chart-card" style={{ marginTop: 16 }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 12 }}>
          <h3>{t('أحدث المعاملات', 'Recent transactions')}</h3>
          <span className="eyebrow" style={{ fontSize: 10 }}>{t('انتقل إلى المعاملات لعرض الكل', 'Go to Transactions to see all')}</span>
        </div>
        <div className="tx-mini-list">
          {TRANSACTIONS.slice(0, 6).map(tx => (
            <div key={tx.id} className="tx-mini">
              <span className={'tx-dot ' + tx.type} />
              <div style={{ flex: 1, minWidth: 0 }}>
                <div className="tx-desc">{lang === 'ar' ? tx.desc_ar : tx.desc_en}</div>
                <div className="tx-meta">{tx.date} · <span className="mono">{tx.id}</span></div>
              </div>
              <div className={'tx-amount ' + (tx.amount > 0 ? 'pos' : 'neg')}>{fmtAED(tx.amount)}</div>
            </div>
          ))}
        </div>
      </div>
    </>
  );
}

// ─── Transactions ──────────────────────────────────────────
function FinanceTransactions({ lang }) {
  const t = (ar, en) => lang === 'ar' ? ar : en;
  const [filter, setFilter] = React.useState('all');
  const [q, setQ] = React.useState('');

  const filtered = TRANSACTIONS.filter(tx => {
    if (filter !== 'all' && tx.type !== filter) return false;
    if (q && !tx.desc_ar.includes(q) && !tx.desc_en.toLowerCase().includes(q.toLowerCase()) && !tx.id.includes(q)) return false;
    return true;
  });

  const tabs = [
    { id: 'all',     label: t('الكل',       'All'),      count: TRANSACTIONS.length },
    { id: 'sale',    label: t('مبيعات',     'Sales'),    count: TRANSACTIONS.filter(t => t.type === 'sale').length },
    { id: 'expense', label: t('مصاريف',     'Expenses'), count: TRANSACTIONS.filter(t => t.type === 'expense').length },
    { id: 'refund',  label: t('استرداد',    'Refunds'),  count: TRANSACTIONS.filter(t => t.type === 'refund').length },
  ];

  const typeLabel = (type) => ({
    sale: t('بيع', 'Sale'),
    expense: t('مصروف', 'Expense'),
    refund: t('استرداد', 'Refund'),
  })[type];
  const methodLabel = (m) => ({
    card: t('بطاقة', 'Card'),
    apple: 'Apple Pay',
    mada: 'Mada',
    bank: t('حوالة', 'Bank'),
    cash: t('نقد', 'Cash'),
  })[m];

  return (
    <>
      <div className="admin-head">
        <div>
          <div className="eyebrow">{t('المالية · 02', 'Finance · 02')}</div>
          <h1 className="h-display">{t('المعاملات', 'Transactions')}</h1>
          <div className="sub">{TRANSACTIONS.length} {t('معاملة · يُحدّث آنياً', 'transactions · live ledger')}</div>
        </div>
        <div className="actions">
          <div className="search-box">
            <I.search />
            <input placeholder={t('بحث برقم أو وصف…', 'Search by ID or description…')} value={q} onChange={e => setQ(e.target.value)} />
          </div>
          <button className="btn ghost"><I.download /> {t('CSV', 'CSV')}</button>
          <button className="btn"><I.plus /> {t('قيد يدوي', 'New entry')}</button>
        </div>
      </div>

      <div style={{ display: 'flex', gap: 6, marginBottom: 24, borderBottom: '1px solid var(--line)', paddingBottom: 0 }}>
        {tabs.map(tab => (
          <button key={tab.id}
                  className="tab-pill"
                  style={{
                    borderBottom: '2px solid ' + (filter === tab.id ? 'var(--ink)' : 'transparent'),
                    color: filter === tab.id ? 'var(--ink)' : 'var(--ink-3)',
                  }}
                  onClick={() => setFilter(tab.id)}>
            {tab.label} <span className="tab-count">{tab.count}</span>
          </button>
        ))}
      </div>

      <div style={{ overflowX: 'auto' }}>
        <table className="table">
          <thead>
            <tr>
              <th>{t('المعرّف', 'ID')}</th>
              <th>{t('التاريخ', 'Date')}</th>
              <th>{t('النوع', 'Type')}</th>
              <th>{t('الوصف', 'Description')}</th>
              <th>{t('طريقة الدفع', 'Method')}</th>
              <th>{t('المرجع', 'Ref')}</th>
              <th style={{ textAlign: 'end' }}>{t('المبلغ', 'Amount')}</th>
              <th>{t('الحالة', 'Status')}</th>
            </tr>
          </thead>
          <tbody>
            {filtered.map(tx => (
              <tr key={tx.id}>
                <td><span className="mono">{tx.id}</span></td>
                <td className="mono" style={{ color: 'var(--ink-3)' }}>{tx.date}</td>
                <td>
                  <span className={'tx-type-pill ' + tx.type}>
                    <span className="tx-dot-sm" />
                    {typeLabel(tx.type)}
                  </span>
                </td>
                <td>{lang === 'ar' ? tx.desc_ar : tx.desc_en}</td>
                <td><span className="mono" style={{ fontSize: 11, color: 'var(--ink-3)' }}>{methodLabel(tx.method)}</span></td>
                <td><span className="mono" style={{ fontSize: 11, color: 'var(--ink-3)' }}>{tx.ref}</span></td>
                <td style={{ textAlign: 'end' }} className={tx.amount > 0 ? 'tx-amount pos' : 'tx-amount neg'}>{fmtAED(tx.amount)}</td>
                <td>
                  <span className={'status-pill ' + (tx.status === 'completed' ? 'delivered' : 'pending')}>
                    {tx.status === 'completed' ? t('مكتمل', 'Completed') : t('معلّق', 'Pending')}
                  </span>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      {/* footer totals */}
      <div className="tx-totals">
        <div>
          <div className="lbl">{t('إجمالي المبيعات', 'Sales total')}</div>
          <div className="val pos">{fmtAED(filtered.filter(t => t.type === 'sale').reduce((s, t) => s + t.amount, 0))}</div>
        </div>
        <div>
          <div className="lbl">{t('إجمالي المصاريف', 'Expenses total')}</div>
          <div className="val neg">{fmtAED(filtered.filter(t => t.type === 'expense').reduce((s, t) => s + t.amount, 0))}</div>
        </div>
        <div>
          <div className="lbl">{t('استردادات', 'Refunds')}</div>
          <div className="val neg">{fmtAED(filtered.filter(t => t.type === 'refund').reduce((s, t) => s + t.amount, 0))}</div>
        </div>
        <div className="grand">
          <div className="lbl">{t('الصافي', 'Net')}</div>
          <div className="val">{fmtAED(filtered.reduce((s, t) => s + t.amount, 0))}</div>
        </div>
      </div>
    </>
  );
}

// ─── Expenses ──────────────────────────────────────────────
function FinanceExpenses({ lang }) {
  const t = (ar, en) => lang === 'ar' ? ar : en;
  const [adding, setAdding] = React.useState(false);
  const expenses = TRANSACTIONS.filter(t => t.type === 'expense');
  const expSum = expenses.reduce((s, t) => s + Math.abs(t.amount), 0);

  return (
    <>
      <div className="admin-head">
        <div>
          <div className="eyebrow">{t('المالية · 03', 'Finance · 03')}</div>
          <h1 className="h-display">{t('المصاريف', 'Expenses')}</h1>
          <div className="sub">{expenses.length} {t('مصروف هذا الشهر · إجمالي ', 'this month · total ')} {fmtAED(expSum)}</div>
        </div>
        <div className="actions">
          <button className="btn"><I.plus /> {t('مصروف جديد', 'New expense')}</button>
        </div>
      </div>

      {/* Category cards */}
      <div className="exp-cat-grid">
        {EXPENSE_CATEGORIES.map(c => (
          <div key={c.id} className="exp-cat-card" style={{ borderTopColor: c.color }}>
            <div className="lbl">{lang === 'ar' ? c.ar : c.en}</div>
            <div className="val">{fmtAED(Math.round(expSum * c.pct / 100))}</div>
            <div className="exp-bar">
              <div className="exp-bar-fill" style={{ width: `${c.pct}%`, background: c.color }} />
            </div>
            <div className="exp-cat-foot">
              <span>{c.pct}%</span>
              <span>{Math.round(expenses.length * c.pct / 100)} {t('قيد', 'entries')}</span>
            </div>
          </div>
        ))}
      </div>

      <div style={{ overflowX: 'auto', marginTop: 24 }}>
        <table className="table">
          <thead>
            <tr>
              <th>{t('التاريخ', 'Date')}</th>
              <th>{t('الوصف', 'Description')}</th>
              <th>{t('الفئة', 'Category')}</th>
              <th>{t('طريقة الدفع', 'Method')}</th>
              <th>{t('المرجع', 'Reference')}</th>
              <th style={{ textAlign: 'end' }}>{t('المبلغ', 'Amount')}</th>
              <th>{t('الحالة', 'Status')}</th>
              <th></th>
            </tr>
          </thead>
          <tbody>
            {expenses.map(e => {
              const cat = EXPENSE_CATEGORIES.find(c => c.id === e.cat);
              return (
                <tr key={e.id}>
                  <td className="mono" style={{ color: 'var(--ink-3)' }}>{e.date}</td>
                  <td>{lang === 'ar' ? e.desc_ar : e.desc_en}</td>
                  <td>
                    {cat && (
                      <span style={{ display: 'inline-flex', alignItems: 'center', gap: 8, fontSize: 13 }}>
                        <span style={{ width: 8, height: 8, borderRadius: '50%', background: cat.color }} />
                        {lang === 'ar' ? cat.ar : cat.en}
                      </span>
                    )}
                  </td>
                  <td><span className="mono" style={{ fontSize: 11 }}>{e.method.toUpperCase()}</span></td>
                  <td><span className="mono" style={{ fontSize: 11, color: 'var(--ink-3)' }}>{e.ref}</span></td>
                  <td style={{ textAlign: 'end' }} className="tx-amount neg">{fmtAED(e.amount)}</td>
                  <td><span className={'status-pill ' + (e.status === 'completed' ? 'delivered' : 'pending')}>{e.status === 'completed' ? t('مدفوع', 'Paid') : t('معلّق', 'Pending')}</span></td>
                  <td><div className="actions-cell"><button className="icon-btn-sm"><I.edit /></button></div></td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    </>
  );
}

// ─── Invoices ──────────────────────────────────────────────
function FinanceInvoices({ lang }) {
  const t = (ar, en) => lang === 'ar' ? ar : en;
  const [viewing, setViewing] = React.useState(null);
  const totalPaid = INVOICES.filter(i => i.status === 'paid').reduce((s, i) => s + i.total, 0);
  const totalUnpaid = INVOICES.filter(i => i.status !== 'paid').reduce((s, i) => s + i.total, 0);
  const overdue = INVOICES.filter(i => i.status === 'overdue').length;

  const statusLabel = (s) => ({
    paid:    t('مدفوعة', 'Paid'),
    sent:    t('مرسلة', 'Sent'),
    overdue: t('متأخرة', 'Overdue'),
    draft:   t('مسودة', 'Draft'),
  })[s];

  return (
    <>
      <div className="admin-head">
        <div>
          <div className="eyebrow">{t('المالية · 04', 'Finance · 04')}</div>
          <h1 className="h-display">{t('الفواتير', 'Invoices')}</h1>
          <div className="sub">{INVOICES.length} {t('فاتورة', 'invoices')} · {overdue} {t('متأخرة', 'overdue')}</div>
        </div>
        <div className="actions">
          <button className="btn"><I.plus /> {t('فاتورة جديدة', 'New invoice')}</button>
        </div>
      </div>

      <div className="inv-summary">
        <div className="inv-card">
          <div className="lbl">{t('مدفوعة هذا الشهر', 'Paid this month')}</div>
          <div className="val">{fmtAED(totalPaid)}</div>
          <div className="sub up"><I.trendUp /> {INVOICES.filter(i => i.status === 'paid').length} {t('فواتير', 'invoices')}</div>
        </div>
        <div className="inv-card">
          <div className="lbl">{t('غير مدفوعة', 'Outstanding')}</div>
          <div className="val">{fmtAED(totalUnpaid)}</div>
          <div className="sub">{INVOICES.filter(i => i.status === 'sent').length} {t('مرسلة', 'sent')} · {overdue} {t('متأخرة', 'overdue')}</div>
        </div>
        <div className="inv-card">
          <div className="lbl">{t('متوسط وقت الدفع', 'Avg payment time')}</div>
          <div className="val">18 <span style={{ fontSize: 14, color: 'var(--ink-3)' }}>{t('يوم', 'days')}</span></div>
          <div className="sub up"><I.trendDown /> {t('أسرع بـ ٤ أيام', '4 days faster')}</div>
        </div>
      </div>

      <div style={{ overflowX: 'auto', marginTop: 24 }}>
        <table className="table">
          <thead>
            <tr>
              <th>{t('الفاتورة', 'Invoice')}</th>
              <th>{t('العميل', 'Client')}</th>
              <th>{t('تاريخ الإصدار', 'Issue date')}</th>
              <th>{t('الاستحقاق', 'Due')}</th>
              <th>{t('العناصر', 'Items')}</th>
              <th style={{ textAlign: 'end' }}>{t('المجموع الفرعي', 'Subtotal')}</th>
              <th style={{ textAlign: 'end' }}>{t('ضريبة', 'VAT')}</th>
              <th style={{ textAlign: 'end' }}>{t('الإجمالي', 'Total')}</th>
              <th>{t('الحالة', 'Status')}</th>
              <th></th>
            </tr>
          </thead>
          <tbody>
            {INVOICES.map(inv => (
              <tr key={inv.id} style={{ cursor: 'pointer' }} onClick={() => setViewing(inv)}>
                <td><span className="mono">{inv.id}</span></td>
                <td><div style={{ fontWeight: 500 }}>{lang === 'ar' ? inv.client : inv.client_en}</div></td>
                <td className="mono" style={{ color: 'var(--ink-3)' }}>{inv.date}</td>
                <td className="mono" style={{ color: inv.status === 'overdue' ? 'var(--danger)' : 'var(--ink-3)' }}>{inv.due}</td>
                <td className="tabular">{inv.items}</td>
                <td style={{ textAlign: 'end' }} className="tabular">{inv.subtotal.toLocaleString()}</td>
                <td style={{ textAlign: 'end' }} className="tabular" >{inv.vat.toLocaleString()}</td>
                <td style={{ textAlign: 'end' }} className="serif-en">AED {inv.total.toLocaleString()}</td>
                <td><span className={'status-pill ' + (inv.status === 'paid' ? 'delivered' : inv.status === 'overdue' ? 'cancelled' : 'shipped')}>{statusLabel(inv.status)}</span></td>
                <td><div className="actions-cell"><button className="icon-btn-sm" onClick={(e) => { e.stopPropagation(); setViewing(inv); }}><I.arrow /></button></div></td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      {viewing && <InvoiceViewer invoice={viewing} onClose={() => setViewing(null)} lang={lang} />}
    </>
  );
}

function InvoiceViewer({ invoice, onClose, lang }) {
  const t = (ar, en) => lang === 'ar' ? ar : en;
  return (
    <div className="modal-back" onClick={onClose}>
      <div className="invoice-doc" onClick={e => e.stopPropagation()}>
        <button className="modal-x" onClick={onClose}><I.close /></button>
        <div className="inv-head">
          <div>
            <div className="brand-mark">{t('استبرق', 'ISTABRAQ')}</div>
            <div className="brand-mark-en">{t('Indian perfumery · since 2018', 'Indian perfumery · since 2018')}</div>
            <div style={{ marginTop: 12, fontSize: 12, color: 'var(--ink-3)' }}>
              {t('شارع جميرا، دبي، الإمارات العربية المتحدة', 'Jumeirah St, Dubai, UAE')}<br />
              VAT TRN: 100123456700003<br />
              hello@istabraq.ae
            </div>
          </div>
          <div style={{ textAlign: 'end' }}>
            <div className="eyebrow" style={{ fontSize: 13, letterSpacing: '0.3em' }}>{t('فاتورة', 'INVOICE')}</div>
            <div className="serif-en" style={{ fontSize: 28, marginTop: 4 }}>{invoice.id}</div>
            <div style={{ marginTop: 12, fontSize: 12 }}>
              <div><span style={{ color: 'var(--ink-3)' }}>{t('تاريخ:', 'Issued:')}</span> <span className="mono">{invoice.date}</span></div>
              <div><span style={{ color: 'var(--ink-3)' }}>{t('استحقاق:', 'Due:')}</span> <span className="mono">{invoice.due}</span></div>
              <div style={{ marginTop: 6 }}>
                <span className={'status-pill ' + (invoice.status === 'paid' ? 'delivered' : invoice.status === 'overdue' ? 'cancelled' : 'shipped')}>
                  {invoice.status === 'paid' ? t('مدفوعة', 'Paid') : invoice.status === 'overdue' ? t('متأخرة', 'Overdue') : t('مرسلة', 'Sent')}
                </span>
              </div>
            </div>
          </div>
        </div>

        <hr className="fine" />

        <div className="inv-parties">
          <div>
            <div className="eyebrow">{t('من', 'From')}</div>
            <div style={{ fontWeight: 500, marginTop: 6 }}>{t('استبرق للعطور ذ.م.م', 'Istabraq Perfumery LLC')}</div>
            <div style={{ fontSize: 12, color: 'var(--ink-3)' }}>Dubai · UAE</div>
          </div>
          <div>
            <div className="eyebrow">{t('إلى', 'Bill to')}</div>
            <div style={{ fontWeight: 500, marginTop: 6 }}>{lang === 'ar' ? invoice.client : invoice.client_en}</div>
            <div style={{ fontSize: 12, color: 'var(--ink-3)' }}>{t('عميل تجزئة بالجملة', 'Wholesale account')}</div>
          </div>
        </div>

        <table className="inv-items">
          <thead>
            <tr>
              <th>{t('الوصف', 'Description')}</th>
              <th style={{ textAlign: 'center' }}>{t('الكمية', 'Qty')}</th>
              <th style={{ textAlign: 'end' }}>{t('السعر', 'Unit')}</th>
              <th style={{ textAlign: 'end' }}>{t('المجموع', 'Amount')}</th>
            </tr>
          </thead>
          <tbody>
            {[0, 6, 4].map((i, idx) => {
              const p = PRODUCTS[i];
              const qty = [6, 4, 8][idx];
              return (
                <tr key={i}>
                  <td>
                    <div style={{ fontWeight: 500 }}>{lang === 'ar' ? p.name_ar : p.name_en}</div>
                    <div style={{ fontSize: 11, color: 'var(--ink-3)' }}>{p.concentration} · 50ml · {p.origin}</div>
                  </td>
                  <td style={{ textAlign: 'center' }} className="tabular">{qty}</td>
                  <td style={{ textAlign: 'end' }} className="tabular">{p.price.toLocaleString()}</td>
                  <td style={{ textAlign: 'end' }} className="serif-en">AED {(p.price * qty).toLocaleString()}</td>
                </tr>
              );
            })}
          </tbody>
        </table>

        <div className="inv-totals">
          <div className="row"><span>{t('المجموع الفرعي', 'Subtotal')}</span><span className="tabular">AED {invoice.subtotal.toLocaleString()}</span></div>
          <div className="row"><span>{t('ضريبة القيمة المضافة (٥٪)', 'VAT (5%)')}</span><span className="tabular">AED {invoice.vat.toLocaleString()}</span></div>
          <div className="row total"><span>{t('الإجمالي المستحق', 'Total due')}</span><span className="serif-en">AED {invoice.total.toLocaleString()}</span></div>
        </div>

        <div className="inv-foot">
          <div className="eyebrow">{t('شروط الدفع', 'Payment terms')}</div>
          <div style={{ fontSize: 12, color: 'var(--ink-2)', marginTop: 6, maxWidth: '60ch' }}>
            {t('الدفع خلال ٣٠ يوماً من تاريخ الإصدار. تحويل بنكي إلى Emirates NBD · AE12 0260 0010 1234 5678 901.',
               'Payment due within 30 days. Bank transfer to Emirates NBD · AE12 0260 0010 1234 5678 901.')}
          </div>
        </div>

        <div style={{ display: 'flex', gap: 8, marginTop: 32, justifyContent: 'flex-end' }}>
          <button className="btn ghost"><I.print /> {t('طباعة', 'Print')}</button>
          <button className="btn ghost"><I.download /> {t('PDF', 'PDF')}</button>
          {invoice.status !== 'paid' && <button className="btn"><I.check /> {t('تسجيل الدفع', 'Mark paid')}</button>}
        </div>
      </div>
    </div>
  );
}

// ─── P&L ───────────────────────────────────────────────────
function FinancePnL({ lang }) {
  const t = (ar, en) => lang === 'ar' ? ar : en;
  const max = Math.max(...PNL_MONTHLY.map(m => m.rev));

  const totRev = PNL_MONTHLY.reduce((s, m) => s + m.rev, 0);
  const totExp = PNL_MONTHLY.reduce((s, m) => s + m.exp, 0);
  const totNet = totRev - totExp;

  // P&L line items
  const breakdown = [
    { label_ar: 'مبيعات تجزئة',          label_en: 'Retail sales',           amount: 892400, kind: 'rev' },
    { label_ar: 'مبيعات الجملة (B2B)',  label_en: 'Wholesale (B2B)',        amount: 274200, kind: 'rev' },
    { label_ar: 'العينات',                label_en: 'Sample sales',           amount: 18400,  kind: 'rev' },
    { label_ar: 'أخرى',                    label_en: 'Other revenue',          amount: 6800,   kind: 'rev' },
    { label_ar: 'تكلفة البضاعة المباعة', label_en: 'Cost of goods sold',     amount: -284600,kind: 'cogs' },
    { label_ar: 'الرواتب',                label_en: 'Salaries & wages',       amount: -92400, kind: 'opex' },
    { label_ar: 'الإيجار والمرافق',      label_en: 'Rent & utilities',        amount: -48200, kind: 'opex' },
    { label_ar: 'التسويق والإعلان',      label_en: 'Marketing & ads',         amount: -38400, kind: 'opex' },
    { label_ar: 'الشحن والخدمات',         label_en: 'Shipping & fulfilment',  amount: -52800, kind: 'opex' },
    { label_ar: 'متفرقات',                label_en: 'Misc & admin',            amount: -19600, kind: 'opex' },
  ];
  const totalRev = breakdown.filter(b => b.kind === 'rev').reduce((s, b) => s + b.amount, 0);
  const totalCOGS = Math.abs(breakdown.filter(b => b.kind === 'cogs').reduce((s, b) => s + b.amount, 0));
  const totalOpex = Math.abs(breakdown.filter(b => b.kind === 'opex').reduce((s, b) => s + b.amount, 0));
  const grossProfit = totalRev - totalCOGS;
  const netIncome = grossProfit - totalOpex;

  return (
    <>
      <div className="admin-head">
        <div>
          <div className="eyebrow">{t('المالية · 05', 'Finance · 05')}</div>
          <h1 className="h-display">{t('الأرباح والخسائر', 'Profit & Loss')}</h1>
          <div className="sub">{t('آخر ٦ أشهر · ديسمبر إلى مايو', 'Last 6 months · Dec → May')}</div>
        </div>
        <div className="actions">
          <button className="btn ghost"><I.print /> {t('طباعة', 'Print')}</button>
          <button className="btn ghost"><I.download /> {t('PDF', 'PDF')}</button>
        </div>
      </div>

      {/* 6-month chart */}
      <div className="chart-card">
        <h3>{t('الإيرادات والمصاريف وصافي الربح', 'Revenue, expenses, net profit')}</h3>
        <div className="pnl-chart">
          {PNL_MONTHLY.map((m, i) => (
            <div key={i} className="pnl-month">
              <div className="pnl-bars">
                <div className="pnl-bar rev" style={{ height: `${(m.rev / max) * 100}%` }} title={'Rev ' + fmtAED(m.rev)} />
                <div className="pnl-bar exp" style={{ height: `${(m.exp / max) * 100}%` }} title={'Exp ' + fmtAED(m.exp)} />
                <div className="pnl-bar net" style={{ height: `${(m.net / max) * 100}%` }} title={'Net ' + fmtAED(m.net)} />
              </div>
              <div className="pnl-label">{lang === 'ar' ? m.m_ar : m.m_en}</div>
            </div>
          ))}
        </div>
        <div style={{ display: 'flex', gap: 18, marginTop: 16, fontSize: 11 }}>
          <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}><span style={{ width: 12, height: 8, background: '#6B7050', borderRadius: 2 }} />{t('إيرادات', 'Revenue')}</span>
          <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}><span style={{ width: 12, height: 8, background: '#C97B5E', borderRadius: 2 }} />{t('مصاريف', 'Expenses')}</span>
          <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}><span style={{ width: 12, height: 8, background: 'var(--ink)', borderRadius: 2 }} />{t('صافي الربح', 'Net profit')}</span>
          <span style={{ marginInlineStart: 'auto', color: 'var(--ink-3)' }}>
            {t('الإجمالي:', 'Total:')} <span className="serif-en" style={{ fontSize: 14 }}>{fmtAED(totRev)}</span> · {fmtAED(totExp)} · <span style={{ color: 'var(--accent-2)', fontWeight: 500 }}>{fmtAED(totNet)}</span>
          </span>
        </div>
      </div>

      {/* P&L statement */}
      <div className="chart-card" style={{ marginTop: 16 }}>
        <h3>{t('بيان الدخل · مايو ٢٠٢٦', 'Income statement · May 2026')}</h3>
        <table className="pnl-table">
          <tbody>
            <tr className="pnl-section"><td colSpan="2">{t('الإيرادات', 'Revenue')}</td></tr>
            {breakdown.filter(b => b.kind === 'rev').map((b, i) => (
              <tr key={i}>
                <td>{lang === 'ar' ? b.label_ar : b.label_en}</td>
                <td className="serif-en">AED {b.amount.toLocaleString()}</td>
              </tr>
            ))}
            <tr className="pnl-subtotal">
              <td>{t('إجمالي الإيرادات', 'Total revenue')}</td>
              <td className="serif-en">AED {totalRev.toLocaleString()}</td>
            </tr>

            <tr className="pnl-section"><td colSpan="2">{t('تكلفة البضائع', 'Cost of goods sold')}</td></tr>
            {breakdown.filter(b => b.kind === 'cogs').map((b, i) => (
              <tr key={i}>
                <td>{lang === 'ar' ? b.label_ar : b.label_en}</td>
                <td className="serif-en neg">−AED {Math.abs(b.amount).toLocaleString()}</td>
              </tr>
            ))}
            <tr className="pnl-subtotal">
              <td>{t('إجمالي الربح', 'Gross profit')}</td>
              <td className="serif-en">AED {grossProfit.toLocaleString()} <span style={{ color: 'var(--ink-3)', fontSize: 12 }}>({(grossProfit / totalRev * 100).toFixed(1)}%)</span></td>
            </tr>

            <tr className="pnl-section"><td colSpan="2">{t('المصاريف التشغيلية', 'Operating expenses')}</td></tr>
            {breakdown.filter(b => b.kind === 'opex').map((b, i) => (
              <tr key={i}>
                <td>{lang === 'ar' ? b.label_ar : b.label_en}</td>
                <td className="serif-en neg">−AED {Math.abs(b.amount).toLocaleString()}</td>
              </tr>
            ))}
            <tr className="pnl-subtotal">
              <td>{t('إجمالي المصاريف التشغيلية', 'Total operating')}</td>
              <td className="serif-en neg">−AED {totalOpex.toLocaleString()}</td>
            </tr>

            <tr className="pnl-grand">
              <td>{t('صافي الدخل', 'Net income')}</td>
              <td className="serif-en">AED {netIncome.toLocaleString()} <span style={{ fontSize: 13, color: 'var(--accent-2)' }}>({(netIncome / totalRev * 100).toFixed(1)}%)</span></td>
            </tr>
          </tbody>
        </table>
      </div>
    </>
  );
}

// ─── Tax / VAT ─────────────────────────────────────────────
function FinanceTax({ lang }) {
  const t = (ar, en) => lang === 'ar' ? ar : en;
  const Q2_revenue = 671200;
  const Q2_vat_output = Q2_revenue * 0.05;
  const Q2_purchases = 312400;
  const Q2_vat_input = Q2_purchases * 0.05;
  const Q2_payable = Q2_vat_output - Q2_vat_input;

  const quarters = [
    { id: 'Q1-2026', period: t('يناير - مارس ٢٠٢٦', 'Jan - Mar 2026'), rev: 531400, out: 26570, inp: 13420, paid: true },
    { id: 'Q2-2026', period: t('أبريل - يونيو ٢٠٢٦', 'Apr - Jun 2026'), rev: Q2_revenue, out: Q2_vat_output, inp: Q2_vat_input, paid: false },
    { id: 'Q4-2025', period: t('أكتوبر - ديسمبر ٢٠٢٥', 'Oct - Dec 2025'), rev: 482600, out: 24130, inp: 11890, paid: true },
    { id: 'Q3-2025', period: t('يوليو - سبتمبر ٢٠٢٥', 'Jul - Sep 2025'), rev: 418200, out: 20910, inp: 10240, paid: true },
  ];

  return (
    <>
      <div className="admin-head">
        <div>
          <div className="eyebrow">{t('المالية · 06', 'Finance · 06')}</div>
          <h1 className="h-display">{t('ضريبة القيمة المضافة', 'VAT & Tax')}</h1>
          <div className="sub">{t('TRN: 100123456700003 · معدل الضريبة ٥٪', 'TRN: 100123456700003 · 5% rate')}</div>
        </div>
        <div className="actions">
          <button className="btn ghost"><I.download /> {t('تقرير FTA', 'FTA report')}</button>
        </div>
      </div>

      {/* current quarter — featured card */}
      <div className="tax-feature">
        <div className="tax-feat-l">
          <div className="eyebrow" style={{ color: 'rgba(255,255,255,0.55)' }}>{t('الربع الحالي · Q2 ٢٠٢٦', 'Current quarter · Q2 2026')}</div>
          <div className="tax-feat-num">{fmtAED(Q2_payable)}</div>
          <div className="tax-feat-lbl">{t('ضريبة مستحقة', 'VAT payable')}</div>
          <div className="tax-feat-due">
            <I.cash />
            {t('تاريخ الاستحقاق: ٣٠ يونيو ٢٠٢٦', 'Due: 30 June 2026')}
          </div>
          <div className="tax-feat-bar">
            <div className="seg" style={{ width: `${(Q2_vat_input / Q2_vat_output) * 100}%`, background: '#C97B5E' }} />
          </div>
          <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 11, color: 'rgba(255,255,255,0.7)' }}>
            <span>{t('ضريبة المدخلات (قابل للخصم)', 'Input VAT (deductible)')}: {fmtAED(Q2_vat_input)}</span>
            <span>{t('ضريبة المخرجات', 'Output VAT')}: {fmtAED(Q2_vat_output)}</span>
          </div>
        </div>
        <div className="tax-feat-r">
          <div className="tax-feat-row">
            <span>{t('المبيعات الخاضعة للضريبة', 'Taxable sales')}</span>
            <span className="serif-en">{fmtAED(Q2_revenue)}</span>
          </div>
          <div className="tax-feat-row">
            <span>{t('المشتريات الخاضعة للضريبة', 'Taxable purchases')}</span>
            <span className="serif-en">{fmtAED(Q2_purchases)}</span>
          </div>
          <div className="tax-feat-row">
            <span>{t('ضريبة المخرجات', 'Output VAT (5%)')}</span>
            <span className="serif-en">+{fmtAED(Q2_vat_output)}</span>
          </div>
          <div className="tax-feat-row">
            <span>{t('ضريبة المدخلات', 'Input VAT (5%)')}</span>
            <span className="serif-en" style={{ color: '#a8d6b3' }}>−{fmtAED(Q2_vat_input)}</span>
          </div>
          <div className="tax-feat-row total">
            <span>{t('صافي الضريبة المستحقة', 'Net VAT due')}</span>
            <span className="serif-en">{fmtAED(Q2_payable)}</span>
          </div>
          <button className="btn" style={{ marginTop: 16, width: '100%', background: '#fff', color: '#1a1a1a', border: 'none' }}>
            {t('تقديم الإقرار الضريبي', 'File return now')}
          </button>
        </div>
      </div>

      {/* quarters history */}
      <div className="chart-card" style={{ marginTop: 24 }}>
        <h3>{t('سجل الإقرارات الضريبية', 'Tax return history')}</h3>
        <table className="table">
          <thead>
            <tr>
              <th>{t('الفترة', 'Period')}</th>
              <th>{t('المبيعات', 'Sales')}</th>
              <th>{t('ضريبة المخرجات', 'Output VAT')}</th>
              <th>{t('ضريبة المدخلات', 'Input VAT')}</th>
              <th style={{ textAlign: 'end' }}>{t('الصافي', 'Net VAT')}</th>
              <th>{t('الحالة', 'Status')}</th>
            </tr>
          </thead>
          <tbody>
            {quarters.map(q => (
              <tr key={q.id}>
                <td><span className="mono">{q.id}</span><div style={{ fontSize: 11, color: 'var(--ink-3)' }}>{q.period}</div></td>
                <td className="serif-en">AED {q.rev.toLocaleString()}</td>
                <td className="serif-en">AED {Math.round(q.out).toLocaleString()}</td>
                <td className="serif-en neg">−AED {Math.round(q.inp).toLocaleString()}</td>
                <td style={{ textAlign: 'end' }} className="serif-en">AED {Math.round(q.out - q.inp).toLocaleString()}</td>
                <td>
                  <span className={'status-pill ' + (q.paid ? 'delivered' : 'pending')}>
                    {q.paid ? <I.check /> : null} {q.paid ? t('مقدّم ومدفوع', 'Filed & paid') : t('قيد التحضير', 'Due')}
                  </span>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </>
  );
}

window.FinanceDashboard = FinanceDashboard;
window.FinanceTransactions = FinanceTransactions;
window.FinanceExpenses = FinanceExpenses;
window.FinanceInvoices = FinanceInvoices;
window.FinancePnL = FinancePnL;
window.FinanceTax = FinanceTax;
