// admin-finance.jsx — real financial system driven by the API (no mock data)

const fmtAED = (n) => (n < 0 ? '−' : '') + 'AED ' + Math.abs(Math.round(n)).toLocaleString();

const EXP_LABELS = {
  inventory: ['مخزون وعطور خام', 'Inventory & raw materials'],
  shipping:  ['شحن وتوصيل', 'Shipping & logistics'],
  salaries:  ['رواتب', 'Salaries'],
  rent:      ['إيجار وفواتير', 'Rent & utilities'],
  marketing: ['تسويق', 'Marketing'],
  misc:      ['متفرقات', 'Other'],
};
const PAY_LABELS = {
  card:  ['بطاقة ائتمان', 'Credit card'], apple: ['Apple Pay', 'Apple Pay'],
  mada:  ['مدى', 'Mada'], bank: ['حوالة بنكية', 'Bank transfer'],
  cod:   ['عند الاستلام', 'Cash on delivery'], cash: ['نقداً', 'Cash'],
};

function FinLoading() {
  return <div style={{ padding: 60, textAlign: 'center', color: 'var(--ink-3)' }}>
    <div className="boot-bar" style={{ margin: '0 auto' }}><span /></div>
  </div>;
}
function FinEmpty({ lang, label }) {
  return <div style={{ padding: '60px 0', textAlign: 'center', color: 'var(--ink-3)' }}>
    <div className="serif-en" style={{ fontSize: 26 }}>{lang === 'ar' ? 'لا توجد بيانات بعد' : 'No data yet'}</div>
    <div style={{ marginTop: 6, fontSize: 13 }}>{label}</div>
  </div>;
}

// ── reusable: add a ledger entry (expense / manual) ──
function EntryModal({ lang, onClose, onSaved, defaultType }) {
  const t = (ar, en) => lang === 'ar' ? ar : en;
  const [f, setF] = React.useState({ type: defaultType || 'expense', desc_ar: '', amount: '', cat: 'inventory', method: 'bank', date: new Date().toISOString().slice(0, 10) });
  const upd = (k, v) => setF({ ...f, [k]: v });
  const [busy, setBusy] = React.useState(false);
  const save = async () => {
    if (!f.desc_ar || !f.amount) return;
    setBusy(true);
    await apiPost('transactions', { ...f, desc_en: f.desc_ar, amount: Number(f.amount) });
    onSaved();
  };
  return (
    <div className="modal-back" onClick={onClose}>
      <div className="modal" style={{ gridTemplateColumns: '1fr', maxWidth: 480 }} onClick={e => e.stopPropagation()}>
        <div className="modal-r" style={{ padding: 32 }}>
          <button className="modal-x" onClick={onClose}><I.close /></button>
          <div className="eyebrow">{t('قيد جديد', 'New entry')}</div>
          <h2 className="h-display" style={{ fontSize: 28, margin: '4px 0 20px' }}>{t('إضافة معاملة', 'Add transaction')}</h2>
          <div className="co-grid">
            <div className="field"><label>{t('النوع', 'Type')}</label>
              <select value={f.type} onChange={e => upd('type', e.target.value)}>
                <option value="expense">{t('مصروف', 'Expense')}</option>
                <option value="sale">{t('بيع/إيراد', 'Sale / income')}</option>
                <option value="refund">{t('استرداد', 'Refund')}</option>
              </select>
            </div>
            <div className="field"><label>{t('المبلغ (AED)', 'Amount (AED)')}</label><input type="number" value={f.amount} onChange={e => upd('amount', e.target.value)} /></div>
            <div className="field span-2"><label>{t('الوصف', 'Description')}</label><input value={f.desc_ar} onChange={e => upd('desc_ar', e.target.value)} /></div>
            {f.type === 'expense' && (
              <div className="field"><label>{t('الفئة', 'Category')}</label>
                <select value={f.cat} onChange={e => upd('cat', e.target.value)}>
                  {Object.entries(EXP_LABELS).map(([k, v]) => <option key={k} value={k}>{lang === 'ar' ? v[0] : v[1]}</option>)}
                </select>
              </div>
            )}
            <div className="field"><label>{t('طريقة الدفع', 'Method')}</label>
              <select value={f.method} onChange={e => upd('method', e.target.value)}>
                <option value="bank">{t('حوالة', 'Bank')}</option><option value="card">{t('بطاقة', 'Card')}</option><option value="cash">{t('نقد', 'Cash')}</option>
              </select>
            </div>
            <div className="field"><label>{t('التاريخ', 'Date')}</label><input type="date" value={f.date} onChange={e => upd('date', e.target.value)} /></div>
          </div>
          <div style={{ display: 'flex', gap: 8, marginTop: 24, justifyContent: 'flex-end' }}>
            <button className="btn ghost" onClick={onClose}>{t('إلغاء', 'Cancel')}</button>
            <button className="btn" onClick={save} disabled={busy}>{busy ? '…' : t('حفظ', 'Save')}</button>
          </div>
        </div>
      </div>
    </div>
  );
}

// ── reusable: create invoice ──
function InvoiceModal({ lang, onClose, onSaved }) {
  const t = (ar, en) => lang === 'ar' ? ar : en;
  const [f, setF] = React.useState({ client: '', items: 1, subtotal: '', due: new Date(Date.now() + 30 * 864e5).toISOString().slice(0, 10), date: new Date().toISOString().slice(0, 10), status: 'sent' });
  const upd = (k, v) => setF({ ...f, [k]: v });
  const [busy, setBusy] = React.useState(false);
  const vat = Math.round((Number(f.subtotal) || 0) * 0.05);
  const save = async () => {
    if (!f.client || !f.subtotal) return;
    setBusy(true);
    await apiPost('invoices', { ...f, client_en: f.client, subtotal: Number(f.subtotal), vat });
    onSaved();
  };
  return (
    <div className="modal-back" onClick={onClose}>
      <div className="modal" style={{ gridTemplateColumns: '1fr', maxWidth: 480 }} onClick={e => e.stopPropagation()}>
        <div className="modal-r" style={{ padding: 32 }}>
          <button className="modal-x" onClick={onClose}><I.close /></button>
          <div className="eyebrow">{t('فاتورة جديدة', 'New invoice')}</div>
          <h2 className="h-display" style={{ fontSize: 28, margin: '4px 0 20px' }}>{t('إصدار فاتورة', 'Issue invoice')}</h2>
          <div className="co-grid">
            <div className="field span-2"><label>{t('العميل', 'Client')}</label><input value={f.client} onChange={e => upd('client', e.target.value)} /></div>
            <div className="field"><label>{t('عدد العناصر', 'Items')}</label><input type="number" value={f.items} onChange={e => upd('items', e.target.value)} /></div>
            <div className="field"><label>{t('المجموع الفرعي', 'Subtotal')}</label><input type="number" value={f.subtotal} onChange={e => upd('subtotal', e.target.value)} /></div>
            <div className="field"><label>{t('الاستحقاق', 'Due date')}</label><input type="date" value={f.due} onChange={e => upd('due', e.target.value)} /></div>
            <div className="field"><label>{t('الحالة', 'Status')}</label>
              <select value={f.status} onChange={e => upd('status', e.target.value)}>
                <option value="sent">{t('مرسلة', 'Sent')}</option><option value="draft">{t('مسودة', 'Draft')}</option><option value="paid">{t('مدفوعة', 'Paid')}</option>
              </select>
            </div>
            <div className="field span-2" style={{ color: 'var(--ink-3)', fontSize: 12 }}>{t('الضريبة (٥٪): ', 'VAT (5%): ')}AED {vat.toLocaleString()} · {t('الإجمالي: ', 'Total: ')}AED {((Number(f.subtotal) || 0) + vat).toLocaleString()}</div>
          </div>
          <div style={{ display: 'flex', gap: 8, marginTop: 24, justifyContent: 'flex-end' }}>
            <button className="btn ghost" onClick={onClose}>{t('إلغاء', 'Cancel')}</button>
            <button className="btn" onClick={save} disabled={busy}>{busy ? '…' : t('إصدار', 'Issue')}</button>
          </div>
        </div>
      </div>
    </div>
  );
}

function exportCSV(rows, filename) {
  if (!rows.length) return;
  const keys = Object.keys(rows[0]);
  const csv = [keys.join(','), ...rows.map(r => keys.map(k => `"${String(r[k] ?? '').replace(/"/g, '""')}"`).join(','))].join('\n');
  const blob = new Blob(['﻿' + csv], { type: 'text/csv;charset=utf-8' });
  const a = document.createElement('a');
  a.href = URL.createObjectURL(blob); a.download = filename; a.click();
}

// ─── Finance Dashboard ──────────────────────────────────────
function FinanceDashboard({ lang }) {
  const t = (ar, en) => lang === 'ar' ? ar : en;
  const [fin, setFin] = React.useState(null);
  const [txs, setTxs] = React.useState([]);
  React.useEffect(() => {
    apiGet('finance').then(setFin);
    apiGet('transactions').then(d => setTxs(Array.isArray(d) ? d : []));
  }, []);
  if (!fin) return <FinLoading />;
  const k = fin.kpis, cash = fin.cash;
  const expSum = fin.kpis.expenses;

  const kpis = [
    { lbl: t('الإيرادات · 30 يوم', 'Revenue · 30d'), val: fmtAED(k.revenue), tone: '#6B7050', icon: <I.income /> },
    { lbl: t('المصاريف · 30 يوم', 'Expenses · 30d'), val: fmtAED(k.expenses), tone: '#C97B5E', icon: <I.expense /> },
    { lbl: t('صافي الربح', 'Net profit'), val: fmtAED(k.net), tone: '#2A1F18', icon: <I.wallet /> },
    { lbl: t('هامش الربح', 'Profit margin'), val: k.margin + '%', tone: '#8C4A2B', icon: <I.chart /> },
  ];

  const W = 600, H = 200;
  const rev = fin.series.map(s => s.rev), exp = fin.series.map(s => s.exp);
  const xs = fin.series.map((_, i) => (i / Math.max(1, fin.series.length - 1)) * W);
  const maxY = Math.max(1, ...rev, ...exp) * 1.1;
  const yOf = (v) => H - (v / maxY) * H;
  const buildArea = (arr) => 'M0 ' + H + ' ' + arr.map((v, i) => `L${xs[i]} ${yOf(v)}`).join(' ') + ` L${W} ${H} Z`;
  const buildLine = (arr) => arr.map((v, i) => `${i ? 'L' : 'M'}${xs[i]} ${yOf(v)}`).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">
          <button className="btn ghost" onClick={() => exportCSV(txs, 'transactions.csv')}><I.download /> {t('تصدير', 'Export')}</button>
        </div>
      </div>

      <div className="fin-kpis">
        {kpis.map((c, i) => (
          <div key={i} className="fin-kpi">
            <div className="kpi-icon" style={{ background: `color-mix(in oklab, ${c.tone} 14%, var(--bg-2))`, color: c.tone }}>{c.icon}</div>
            <div className="kpi-body"><div className="lbl">{c.lbl}</div><div className="val">{c.val}</div></div>
          </div>
        ))}
      </div>

      <div className="fin-cash-strip">
        <div className="cash-item"><div className="lbl"><I.cash /> {t('السيولة (صافي)', 'Cash position')}</div><div className="val">{fmtAED(cash.on_hand)}</div><div className="sub">{t('إيرادات − مصاريف', 'income − expenses')}</div></div>
        <div className="cash-item"><div className="lbl"><I.invoice /> {t('ذمم مدينة', 'Receivable')}</div><div className="val">{fmtAED(cash.receivable)}</div><div className="sub">{t('فواتير غير مدفوعة', 'unpaid invoices')}</div></div>
        <div className="cash-item"><div className="lbl"><I.expense /> {t('مدفوعات معلّقة', 'Pending')}</div><div className="val">{fmtAED(cash.pending)}</div><div className="sub">{t('قيود معلّقة', 'pending entries')}</div></div>
        <div className="cash-item highlight"><div className="lbl"><I.tax /> {t('ضريبة محصّلة', 'VAT collected')}</div><div className="val">{fmtAED(cash.vat_payable)}</div><div className="sub">{t('من الطلبات', 'from orders')}</div></div>
      </div>

      <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>
            {[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(rev)} fill="url(#gradRev)" />
            <path d={buildArea(exp)} fill="url(#gradExp)" />
            <path d={buildLine(rev)} fill="none" stroke="#6B7050" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
            <path d={buildLine(exp)} fill="none" stroke="#C97B5E" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
          </svg>
        </div>
      </div>

      <div className="chart-grid" style={{ marginTop: 16 }}>
        <div className="chart-card">
          <h3>{t('توزيع المصاريف', 'Expense breakdown')}</h3>
          {expSum === 0 ? <FinEmpty lang={lang} label={t('سجّل مصاريفك من قسم المصاريف', 'Add expenses to see the breakdown')} /> : (
            <div style={{ display: 'flex', flexDirection: 'column', gap: 14, marginTop: 4 }}>
              {fin.expense_categories.filter(c => c.amount > 0).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' ? EXP_LABELS[c.id][0] : EXP_LABELS[c.id][1]}</span>
                    <span className="serif-en" style={{ fontSize: 15 }}>{fmtAED(c.amount)}</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>
          {fin.payment_split.length === 0 ? <FinEmpty lang={lang} label={t('تظهر بعد أول طلب', 'appears after the first order')} /> : (
            <div className="pm-list">
              {fin.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' || p.id === 'cod' ? <I.cash /> : p.id === 'bank' ? <I.bank /> : <I.wallet />}
                  </span>
                  <div style={{ flex: 1 }}>
                    <div style={{ fontSize: 13, fontWeight: 500 }}>{PAY_LABELS[p.id] ? (lang === 'ar' ? PAY_LABELS[p.id][0] : PAY_LABELS[p.id][1]) : p.id}</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>

      <div className="chart-card" style={{ marginTop: 16 }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 12 }}>
          <h3>{t('أحدث المعاملات', 'Recent transactions')}</h3>
        </div>
        {txs.length === 0 ? <FinEmpty lang={lang} label={t('لا معاملات بعد', 'no transactions yet')} /> : (
          <div className="tx-mini-list">
            {txs.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 [rows, setRows] = React.useState([]);
  const [filter, setFilter] = React.useState('all');
  const [q, setQ] = React.useState('');
  const [adding, setAdding] = React.useState(false);
  const load = () => apiGet('transactions').then(d => setRows(Array.isArray(d) ? d : []));
  React.useEffect(() => { load(); }, []);

  const filtered = rows.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: rows.length },
    { id: 'sale', label: t('مبيعات', 'Sales'), count: rows.filter(r => r.type === 'sale').length },
    { id: 'expense', label: t('مصاريف', 'Expenses'), count: rows.filter(r => r.type === 'expense').length },
    { id: 'refund', label: t('استرداد', 'Refunds'), count: rows.filter(r => r.type === 'refund').length },
  ];
  const typeLabel = (x) => ({ sale: t('بيع', 'Sale'), expense: t('مصروف', 'Expense'), refund: t('استرداد', 'Refund') })[x];
  const methodLabel = (m) => ({ card: t('بطاقة', 'Card'), apple: 'Apple Pay', mada: 'Mada', bank: t('حوالة', 'Bank'), cash: t('نقد', 'Cash'), cod: t('عند الاستلام', 'COD') })[m] || 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">{rows.length} {t('معاملة', 'transactions')}</div>
        </div>
        <div className="actions">
          <div className="search-box"><I.search /><input placeholder={t('بحث…', 'Search…')} value={q} onChange={e => setQ(e.target.value)} /></div>
          <button className="btn ghost" onClick={() => exportCSV(rows, 'transactions.csv')}><I.download /> CSV</button>
          <button className="btn" onClick={() => setAdding(true)}><I.plus /> {t('قيد يدوي', 'New entry')}</button>
        </div>
      </div>

      <div style={{ display: 'flex', gap: 6, marginBottom: 24, borderBottom: '1px solid var(--line)' }}>
        {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>

      {filtered.length === 0 ? <FinEmpty lang={lang} label={t('أضف قيداً يدوياً أو انتظر أول طلب', 'Add a manual entry or wait for the first order')} /> : (
        <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>
      )}

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

      {adding && <EntryModal lang={lang} defaultType="expense" onClose={() => setAdding(false)} onSaved={() => { setAdding(false); load(); }} />}
    </>
  );
}

// ─── Expenses ──────────────────────────────────────────────
function FinanceExpenses({ lang }) {
  const t = (ar, en) => lang === 'ar' ? ar : en;
  const [rows, setRows] = React.useState([]);
  const [fin, setFin] = React.useState(null);
  const [adding, setAdding] = React.useState(false);
  const load = () => { apiGet('transactions').then(d => setRows((d || []).filter(x => x.type === 'expense'))); apiGet('finance').then(setFin); };
  React.useEffect(() => { load(); }, []);
  const expSum = rows.reduce((s, r) => s + Math.abs(r.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">{rows.length} {t('مصروف · إجمالي ', 'expenses · total ')}{fmtAED(expSum)}</div>
        </div>
        <div className="actions"><button className="btn" onClick={() => setAdding(true)}><I.plus /> {t('مصروف جديد', 'New expense')}</button></div>
      </div>

      {fin && expSum > 0 && (
        <div className="exp-cat-grid">
          {fin.expense_categories.filter(c => c.amount > 0).map(c => (
            <div key={c.id} className="exp-cat-card" style={{ borderTopColor: c.color }}>
              <div className="lbl">{lang === 'ar' ? EXP_LABELS[c.id][0] : EXP_LABELS[c.id][1]}</div>
              <div className="val">{fmtAED(c.amount)}</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></div>
            </div>
          ))}
        </div>
      )}

      {rows.length === 0 ? <FinEmpty lang={lang} label={t('سجّل أول مصروف بالضغط على «مصروف جديد»', 'Add your first expense')} /> : (
        <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('المرجع', 'Ref')}</th><th style={{ textAlign: 'end' }}>{t('المبلغ', 'Amount')}</th><th>{t('الحالة', 'Status')}</th></tr></thead>
            <tbody>
              {rows.map(e => (
                <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>{e.cat && EXP_LABELS[e.cat] ? (lang === 'ar' ? EXP_LABELS[e.cat][0] : EXP_LABELS[e.cat][1]) : '—'}</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>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}

      {adding && <EntryModal lang={lang} defaultType="expense" onClose={() => setAdding(false)} onSaved={() => { setAdding(false); load(); }} />}
    </>
  );
}

// ─── Invoices ──────────────────────────────────────────────
function FinanceInvoices({ lang }) {
  const t = (ar, en) => lang === 'ar' ? ar : en;
  const [rows, setRows] = React.useState([]);
  const [viewing, setViewing] = React.useState(null);
  const [adding, setAdding] = React.useState(false);
  const load = () => apiGet('invoices').then(d => setRows(Array.isArray(d) ? d : []));
  React.useEffect(() => { load(); }, []);
  const totalPaid = rows.filter(i => i.status === 'paid').reduce((s, i) => s + i.total, 0);
  const totalUnpaid = rows.filter(i => i.status !== 'paid').reduce((s, i) => s + i.total, 0);
  const overdue = rows.filter(i => i.status === 'overdue').length;
  const statusLabel = (s) => ({ paid: t('مدفوعة', 'Paid'), sent: t('مرسلة', 'Sent'), overdue: t('متأخرة', 'Overdue'), draft: t('مسودة', 'Draft') })[s];
  const markPaid = async (code) => { await apiPut('invoices', code, { status: 'paid' }); setViewing(null); load(); };

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

      <div className="inv-summary">
        <div className="inv-card"><div className="lbl">{t('مدفوعة', 'Paid')}</div><div className="val">{fmtAED(totalPaid)}</div><div className="sub up"><I.trendUp /> {rows.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">{rows.filter(i => i.status === 'sent').length} {t('مرسلة', 'sent')} · {overdue} {t('متأخرة', 'overdue')}</div></div>
        <div className="inv-card"><div className="lbl">{t('عدد الفواتير', 'Total invoices')}</div><div className="val">{rows.length}</div><div className="sub">{t('هذا الشهر', 'this period')}</div></div>
      </div>

      {rows.length === 0 ? <FinEmpty lang={lang} label={t('أصدر أول فاتورة بالضغط على «فاتورة جديدة»', 'Issue your first invoice')} /> : (
        <div style={{ overflowX: 'auto', marginTop: 24 }}>
          <table className="table">
            <thead><tr><th>{t('الفاتورة', 'Invoice')}</th><th>{t('العميل', 'Client')}</th><th>{t('الإصدار', 'Issued')}</th><th>{t('الاستحقاق', 'Due')}</th><th>{t('العناصر', 'Items')}</th><th style={{ textAlign: 'end' }}>{t('الإجمالي', 'Total')}</th><th>{t('الحالة', 'Status')}</th><th></th></tr></thead>
            <tbody>
              {rows.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="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)} onMarkPaid={markPaid} lang={lang} />}
      {adding && <InvoiceModal lang={lang} onClose={() => setAdding(false)} onSaved={() => { setAdding(false); load(); }} />}
    </>
  );
}

function InvoiceViewer({ invoice, onClose, onMarkPaid, 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.store</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>
          </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>
        </div>
        <div className="inv-totals" style={{ marginInlineStart: 'auto' }}>
          <div className="row"><span>{t('المجموع الفرعي', 'Subtotal')}</span><span className="tabular">AED {invoice.subtotal.toLocaleString()}</span></div>
          <div className="row"><span>{t('عدد العناصر', 'Items')}</span><span className="tabular">{invoice.items}</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 style={{ display: 'flex', gap: 8, marginTop: 32, justifyContent: 'flex-end' }}>
          <button className="btn ghost" onClick={() => window.print()}><I.print /> {t('طباعة', 'Print')}</button>
          {invoice.status !== 'paid' && <button className="btn" onClick={() => onMarkPaid(invoice.id)}><I.check /> {t('تسجيل الدفع', 'Mark paid')}</button>}
        </div>
      </div>
    </div>
  );
}

// ─── P&L ───────────────────────────────────────────────────
function FinancePnL({ lang }) {
  const t = (ar, en) => lang === 'ar' ? ar : en;
  const [fin, setFin] = React.useState(null);
  React.useEffect(() => { apiGet('finance').then(setFin); }, []);
  if (!fin) return <FinLoading />;
  const months = fin.pnl_months;
  const max = Math.max(1, ...months.map(m => m.rev));
  const totRev = months.reduce((s, m) => s + m.rev, 0);
  const totExp = months.reduce((s, m) => s + m.exp, 0);
  const totNet = totRev - totExp;
  const monthName = (ym) => { const d = new Date(ym + '-01'); return d.toLocaleString(lang === 'ar' ? 'ar' : 'en', { month: 'short' }); };

  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('محسوب من معاملاتك الفعلية', 'Computed from your real ledger')}</div>
        </div>
        <div className="actions"><button className="btn ghost" onClick={() => window.print()}><I.print /> {t('طباعة', 'Print')}</button></div>
      </div>

      {months.length === 0 ? <FinEmpty lang={lang} label={t('تظهر بعد تسجيل مبيعات/مصاريف', 'appears once you have sales/expenses')} /> : (
        <div className="chart-card">
          <h3>{t('الإيرادات والمصاريف وصافي الربح', 'Revenue, expenses, net profit')}</h3>
          <div className="pnl-chart">
            {months.map((m, i) => (
              <div key={i} className="pnl-month">
                <div className="pnl-bars">
                  <div className="pnl-bar rev" style={{ height: `${(m.rev / max) * 100}%` }} />
                  <div className="pnl-bar exp" style={{ height: `${(m.exp / max) * 100}%` }} />
                  <div className="pnl-bar net" style={{ height: `${(Math.max(0, m.net) / max) * 100}%` }} />
                </div>
                <div className="pnl-label">{monthName(m.ym)}</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')}</span>
          </div>
        </div>
      )}

      <div className="chart-card" style={{ marginTop: 16 }}>
        <h3>{t('بيان الدخل', 'Income statement')}</h3>
        <table className="pnl-table"><tbody>
          <tr className="pnl-section"><td colSpan="2">{t('الإيرادات', 'Revenue')}</td></tr>
          <tr><td>{t('إجمالي المبيعات', 'Total sales')}</td><td className="serif-en">AED {Math.round(totRev).toLocaleString()}</td></tr>
          <tr className="pnl-section"><td colSpan="2">{t('المصاريف', 'Expenses')}</td></tr>
          {fin.expense_categories.filter(c => c.amount > 0).map(c => (
            <tr key={c.id}><td>{lang === 'ar' ? EXP_LABELS[c.id][0] : EXP_LABELS[c.id][1]}</td><td className="serif-en neg">−AED {Math.round(c.amount).toLocaleString()}</td></tr>
          ))}
          <tr className="pnl-subtotal"><td>{t('إجمالي المصاريف', 'Total expenses')}</td><td className="serif-en neg">−AED {Math.round(totExp).toLocaleString()}</td></tr>
          <tr className="pnl-grand"><td>{t('صافي الدخل', 'Net income')}</td><td className="serif-en">AED {Math.round(totNet).toLocaleString()} {totRev > 0 && <span style={{ fontSize: 13, color: 'var(--accent-2)' }}>({(totNet / totRev * 100).toFixed(1)}%)</span>}</td></tr>
        </tbody></table>
      </div>
    </>
  );
}

// ─── Tax / VAT ─────────────────────────────────────────────
function FinanceTax({ lang }) {
  const t = (ar, en) => lang === 'ar' ? ar : en;
  const [fin, setFin] = React.useState(null);
  React.useEffect(() => { apiGet('finance').then(setFin); }, []);
  if (!fin) return <FinLoading />;
  const outputVat = fin.cash.vat_payable;
  const inputVat = Math.round(fin.kpis.expenses * 0.05);
  const payable = outputVat - inputVat;

  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% · from your real data')}</div>
        </div>
      </div>

      <div className="tax-feature">
        <div className="tax-feat-l">
          <div className="eyebrow" style={{ color: 'rgba(255,255,255,0.55)' }}>{t('الفترة الحالية', 'Current period')}</div>
          <div className="tax-feat-num">{fmtAED(payable)}</div>
          <div className="tax-feat-lbl">{t('ضريبة مستحقة', 'VAT payable')}</div>
          <div className="tax-feat-bar"><div className="seg" style={{ width: `${outputVat ? Math.min(100, inputVat / outputVat * 100) : 0}%`, background: '#C97B5E' }} /></div>
          <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 11, color: 'rgba(255,255,255,0.7)' }}>
            <span>{t('ضريبة المدخلات', 'Input VAT')}: {fmtAED(inputVat)}</span>
            <span>{t('ضريبة المخرجات', 'Output VAT')}: {fmtAED(outputVat)}</span>
          </div>
        </div>
        <div className="tax-feat-r">
          <div className="tax-feat-row"><span>{t('المبيعات الخاضعة', 'Taxable sales')}</span><span className="serif-en">{fmtAED(fin.kpis.revenue)}</span></div>
          <div className="tax-feat-row"><span>{t('المصاريف الخاضعة', 'Taxable purchases')}</span><span className="serif-en">{fmtAED(fin.kpis.expenses)}</span></div>
          <div className="tax-feat-row"><span>{t('ضريبة المخرجات', 'Output VAT')}</span><span className="serif-en">+{fmtAED(outputVat)}</span></div>
          <div className="tax-feat-row"><span>{t('ضريبة المدخلات', 'Input VAT')}</span><span className="serif-en" style={{ color: '#a8d6b3' }}>−{fmtAED(inputVat)}</span></div>
          <div className="tax-feat-row total"><span>{t('صافي الضريبة المستحقة', 'Net VAT due')}</span><span className="serif-en">{fmtAED(payable)}</span></div>
        </div>
      </div>
    </>
  );
}

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