// Main app: dashboard for Ciga elt ลาว
const { useState, useEffect, useMemo, useRef, useContext } = React;

// ===== Aggregation helpers =====
function inRange(date, range) {
  return date >= range.start && date <= range.end;
}
function getRange(period, end) {
  const e = new Date(end); e.setHours(23, 59, 59, 999);
  const s = new Date(end);
  if (period === 'day') s.setDate(s.getDate() - 0);
  else if (period === 'week') s.setDate(s.getDate() - 6);
  else if (period === 'month') s.setDate(s.getDate() - 29);
  else if (period === 'quarter') s.setDate(s.getDate() - 89);
  else if (period === 'year') s.setDate(s.getDate() - 364);
  s.setHours(0, 0, 0, 0);
  return { start: s, end: e };
}
function summarize(txs, range, prevRange) {
  let revenue = 0, cogs = 0, opex = 0, restockCost = 0;
  let unitsSold = { 'pilot-m': 0, 'pilot-g': 0 };
  let revenueByProd = { 'pilot-m': 0, 'pilot-g': 0 };
  let txInRange = [];

  for (const t of txs) {
    if (!inRange(t.date, range)) continue;
    txInRange.push(t);
    if (t.type === 'out' && t.kind === 'sale') {
      revenue += t.amount;
      unitsSold[t.productId] += t.qty;
      revenueByProd[t.productId] += t.amount;
      const p = window.CIGA.PRODUCTS.find(x => x.id === t.productId);
      cogs += t.qty * p.cost;
    } else if (t.type === 'in' && t.kind === 'restock') {
      restockCost += t.amount;
    } else if (t.type === 'expense') {
      opex += t.amount;
    }
  }
  const grossProfit = revenue - cogs;
  const netProfit = grossProfit - opex;

  let prev = null;
  if (prevRange) prev = summarize(txs, prevRange, null);
  return { revenue, cogs, opex, restockCost, grossProfit, netProfit, unitsSold, revenueByProd, txInRange, prev };
}
function dailyBuckets(txs, range, fn = (t) => t.amount) {
  const days = [];
  const start = new Date(range.start);
  start.setHours(0, 0, 0, 0);
  const end = new Date(range.end);
  end.setHours(0, 0, 0, 0);
  const cur = new Date(start);
  while (cur <= end) {
    days.push({ date: new Date(cur), value: 0, label: String(cur.getDate()).padStart(2, '0') + '/' + String(cur.getMonth() + 1).padStart(2, '0') });
    cur.setDate(cur.getDate() + 1);
  }
  for (const t of txs) {
    if (!inRange(t.date, range)) continue;
    const d = new Date(t.date); d.setHours(0, 0, 0, 0);
    const idx = Math.floor((d - start) / 86400000);
    if (idx >= 0 && idx < days.length) days[idx].value += fn(t) || 0;
  }
  return days;
}
function computeStockState(txs) {
  // running stock + average cost
  const state = {};
  for (const p of window.CIGA.PRODUCTS) state[p.id] = { qty: 0, totalCost: 0, totalIn: 0, totalOut: 0 };
  // process oldest first
  const sorted = [...txs].sort((a, b) => a.date - b.date);
  for (const t of sorted) {
    if (!t.productId) continue;
    const s = state[t.productId];
    if (t.type === 'in') {
      s.qty += t.qty;
      s.totalCost += t.amount;
      s.totalIn += t.qty;
    } else if (t.type === 'out') {
      s.qty -= t.qty;
      s.totalOut += t.qty;
    }
  }
  return state;
}

// ===== Top bar =====
function TopBar({ period, setPeriod, onOpenAdd, onOpenSettings }) {
  const periods = [
    { id: 'day', label: 'วันนี้' },
    { id: 'week', label: '7 วัน' },
    { id: 'month', label: '30 วัน' },
    { id: 'quarter', label: '90 วัน' },
    { id: 'year', label: '1 ปี' },
  ];
  return (
    <header className="topbar">
      <div className="topbar-left">
        <div className="brand">
          <div className="brand-mark">
            <svg width="20" height="20" viewBox="0 0 24 24" fill="none">
              <rect x="2" y="9" width="20" height="6" rx="2" fill="#ffb547"/>
              <rect x="18" y="8" width="3" height="8" rx="1.5" fill="#a78bfa"/>
              <rect x="2" y="9" width="3" height="6" fill="rgba(0,0,0,0.3)"/>
            </svg>
          </div>
          <div className="brand-text">
            <div className="brand-title">CIGA <span style={{ color: '#ffb547' }}>·</span> ELT</div>
            <div className="brand-sub">ระบบสรุปบัญชี ลาว</div>
          </div>
        </div>
        <div className="topbar-sep" />
        <LiveClock />
      </div>
      <div className="topbar-right">
        <CurrencyToggle />
        <div className="period-group">
          <Icon name="filter" size={14} />
          {periods.map(p => (
            <Pill key={p.id} active={period === p.id} onClick={() => setPeriod(p.id)}>{p.label}</Pill>
          ))}
        </div>
        <button className="icon-btn" title="ค้นหา"><Icon name="search" size={16}/></button>
        <button className="icon-btn" title="ตั้งค่า" onClick={onOpenSettings}><Icon name="settings" size={16}/></button>
        <button className="icon-btn" title="แจ้งเตือน">
          <Icon name="bell" size={16}/>
          <span className="icon-btn-dot"></span>
        </button>
        <button className="btn-primary" onClick={onOpenAdd}>
          <Icon name="plus" size={14}/> เพิ่มรายการ
        </button>
        <div className="avatar">SP</div>
      </div>
    </header>
  );
}

// ===== Sidebar =====
function Sidebar({ active, setActive }) {
  const items = [
    { id: 'overview', label: 'ภาพรวม', icon: 'dashboard' },
    { id: 'invest', label: 'เงินลงทุน', icon: 'invest' },
    { id: 'pl', label: 'รายรับ-จ่าย', icon: 'wallet' },
    { id: 'shareholders', label: 'แบ่งหุ้น', icon: 'users' },
    { id: 'stock', label: 'สต็อก', icon: 'box' },
    { id: 'flow', label: 'รับเข้า-จ่ายออก', icon: 'arrows' },
    { id: 'report', label: 'รายงาน', icon: 'chart' },
  ];
  return (
    <nav className="sidebar">
      <div className="sidebar-items">
        {items.map(it => (
          <a key={it.id} href={`#${it.id}`} className={`side-item ${active === it.id ? 'active' : ''}`}
            onClick={() => setActive(it.id)}>
            <span className="side-icon"><Icon name={it.icon} size={18}/></span>
            <span className="side-label">{it.label}</span>
            {active === it.id && <span className="side-indicator" />}
          </a>
        ))}
      </div>
      <div className="sidebar-footer">
        <div className="status-led" />
        <div>
          <div style={{ fontSize: 10, color: 'rgba(230,233,240,0.4)', letterSpacing: 1 }}>SYS · LIVE</div>
          <div style={{ fontSize: 11, color: '#22d3a3', fontFamily: "'IBM Plex Mono', monospace" }}>ออนไลน์</div>
        </div>
      </div>
    </nav>
  );
}

// ===== KPI Card =====
function KPI({ label, value, prev, delta, deltaLabel, sparkPoints, color, accent, suffix, prefix, format, big }) {
  const up = delta >= 0;
  const fmt = format || (v => Math.round(v).toLocaleString('en-US'));
  return (
    <Card className="kpi" style={{ '--kpi-accent': accent || '#ffb547' }}>
      <div className="kpi-head">
        <div className="kpi-label">{label}</div>
        {delta !== undefined && delta !== null && (
          <span className={`kpi-delta ${up ? 'pos' : 'neg'}`}>
            <Icon name={up ? 'arrow-up' : 'arrow-down'} size={11}/>
            {Math.abs(delta).toFixed(1)}%
          </span>
        )}
      </div>
      <div className={`kpi-value ${big ? 'big' : ''}`} style={{ color: color || '#e6e9f0' }}>
        {prefix}
        <Counter value={value} format={fmt} />
        {suffix && <span className="kpi-suffix">{suffix}</span>}
      </div>
      <div className="kpi-foot">
        <div className="kpi-prev">{deltaLabel}</div>
        {sparkPoints && <Sparkline points={sparkPoints} color={accent || '#ffb547'} width={120} height={32} />}
      </div>
    </Card>
  );
}

// ===== Main app =====
function App() {
  const [period, setPeriod] = useState('month');
  const [active, setActive] = useState('overview');
  const [addOpen, setAddOpen] = useState(false);
  const [detailTx, setDetailTx] = useState(null);
  const [txs, setTxs] = useState(() => window.CIGA.transactions);
  const [invs, setInvs] = useState(() => window.CIGA.investments);
  const [investModal, setInvestModal] = useState(null); // null | { mode: 'add' } | { mode: 'edit', inv }
  const [currency, setCurrencyState] = useState(() => {
    try { return localStorage.getItem('ciga-ccy') || 'LAK'; } catch (e) { return 'LAK'; }
  });
  const setCurrency = (c) => {
    setCurrencyState(c);
    try { localStorage.setItem('ciga-ccy', c); } catch (e) {}
  };
  const [rate, setRateState] = useState(() => loadRate());
  const setRate = (r) => {
    const v = Number(r);
    if (!Number.isFinite(v) || v <= 0) return;
    setRateState(v);
    try { localStorage.setItem('ciga-rate', String(v)); } catch (e) {}
  };
  const [settingsOpen, setSettingsOpen] = useState(false);

  // ---- Shareholders & profit split ----
  const [mgmtFeePct, setMgmtFeePctState] = useState(() => {
    try { const v = parseFloat(localStorage.getItem('ciga-mgmt')); return Number.isFinite(v) ? v : 40; } catch (e) { return 40; }
  });
  const setMgmtFeePct = (v) => {
    const n = Math.max(0, Math.min(100, Number(v) || 0));
    setMgmtFeePctState(n);
    try { localStorage.setItem('ciga-mgmt', String(n)); } catch (e) {}
  };
  const DEFAULT_SHAREHOLDERS = [
    { id: 'sh-1', name: 'Winner',     pct: 20 },
    { id: 'sh-2', name: 'Arty',       pct: 20 },
    { id: 'sh-3', name: 'เสี่ยแบงค์',  pct: 20 },
    { id: 'sh-4', name: 'พี่ป๊อป',     pct: 20 },
    { id: 'sh-5', name: 'พี่แคน',     pct: 10 },
    { id: 'sh-6', name: 'เซอร์ใบ',    pct: 10 },
  ];
  const [shareholders, setShareholdersState] = useState(() => {
    try { const j = localStorage.getItem('ciga-sh'); if (j) return JSON.parse(j); } catch (e) {}
    return DEFAULT_SHAREHOLDERS;
  });
  const setShareholders = (arr) => {
    setShareholdersState(arr);
    try { localStorage.setItem('ciga-sh', JSON.stringify(arr)); } catch (e) {}
  };
  const [shModalOpen, setShModalOpen] = useState(false);

  const ccySym = moneySymbol(currency);
  const M = (v, opts) => fmtMoney(v, currency, opts, rate);
  const Mk = (v) => fmtMoney(v, currency, { compact: true }, rate);

  // ---- Export helpers ----
  function downloadFile(filename, content, mime = 'text/plain') {
    const blob = new Blob([content], { type: mime + ';charset=utf-8' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url; a.download = filename;
    document.body.appendChild(a); a.click();
    document.body.removeChild(a);
    setTimeout(() => URL.revokeObjectURL(url), 1000);
  }
  function exportJSON() {
    const data = {
      meta: {
        exported_at: new Date().toISOString(),
        schema_version: '1.0',
        business: 'Ciga ELT Lao',
      },
      settings: {
        exchange_rate_thb_lak: rate,
        display_currency: currency,
        mgmt_fee_pct: mgmtFeePct,
      },
      products: window.CIGA.PRODUCTS,
      investments: invs.map(i => ({ ...i, date: i.date.toISOString() })),
      shareholders: shareholders.map((s, i) => ({ ...s, display_order: i + 1 })),
      transactions: txs.map(t => ({ ...t, date: t.date.toISOString() })),
    };
    const ts = new Date().toISOString().slice(0, 10);
    downloadFile(`ciga-elt-export-${ts}.json`, JSON.stringify(data, null, 2), 'application/json');
  }
  function exportSQL() {
    const esc = (s) => s == null ? 'NULL' : `'${String(s).replace(/'/g, "''")}'`;
    const num = (n) => n == null ? 'NULL' : String(n);
    const dt = (d) => `'${new Date(d).toISOString().slice(0, 19).replace('T', ' ')}'`;
    const date = (d) => `'${new Date(d).toISOString().slice(0, 10)}'`;
    let sql = '';
    sql += '-- ============================================================\n';
    sql += '-- Ciga · ELT Lao — Data Export\n';
    sql += `-- Generated: ${new Date().toISOString()}\n`;
    sql += '-- Run schema.sql first, then this file.\n';
    sql += '-- ============================================================\n\n';

    sql += '-- ลบข้อมูลเก่า (ถ้ามี) ก่อน import ใหม่\n';
    sql += 'DELETE FROM transactions;\nDELETE FROM investments;\nDELETE FROM shareholders;\nDELETE FROM products;\nDELETE FROM settings;\n\n';

    sql += '-- Products\n';
    for (const p of window.CIGA.PRODUCTS) {
      sql += `INSERT INTO products (id, name, short_code, color, hue, cost, price) VALUES (${esc(p.id)}, ${esc(p.name)}, ${esc(p.short)}, ${esc(p.color)}, ${num(p.hue)}, ${num(p.cost)}, ${num(p.price)});\n`;
    }

    sql += '\n-- Shareholders\n';
    shareholders.forEach((s, i) => {
      sql += `INSERT INTO shareholders (id, name, pct, display_order) VALUES (${esc(s.id)}, ${esc(s.name)}, ${num(s.pct)}, ${i + 1});\n`;
    });

    sql += '\n-- Investments\n';
    for (const inv of invs) {
      sql += `INSERT INTO investments (id, invest_date, amount, source, note) VALUES (${esc(inv.id)}, ${date(inv.date)}, ${num(inv.amount)}, ${esc(inv.source)}, ${esc(inv.note)});\n`;
    }

    sql += '\n-- Transactions\n';
    for (const t of txs) {
      sql += `INSERT INTO transactions (id, tx_date, tx_type, tx_kind, product_id, qty, unit_price, amount, channel, note) VALUES (${esc(t.id)}, ${dt(t.date)}, ${esc(t.type)}, ${esc(t.kind)}, ${esc(t.productId)}, ${num(t.qty)}, ${num(t.unitPrice)}, ${num(t.amount)}, ${esc(t.channel)}, ${esc(t.note)});\n`;
    }

    sql += '\n-- Settings\n';
    const settings = [
      ['exchange_rate_thb_lak', String(rate)],
      ['display_currency', currency],
      ['mgmt_fee_pct', String(mgmtFeePct)],
      ['business_name', 'Ciga ELT Lao'],
      ['schema_version', '1.0'],
    ];
    for (const [k, v] of settings) {
      sql += `INSERT INTO settings (setting_key, setting_value) VALUES (${esc(k)}, ${esc(v)});\n`;
    }
    sql += '\n-- จบไฟล์\n';

    const ts = new Date().toISOString().slice(0, 10);
    downloadFile(`ciga-elt-data-${ts}.sql`, sql, 'application/sql');
  }
  function importJSON(file) {
    const reader = new FileReader();
    reader.onload = (e) => {
      try {
        const data = JSON.parse(e.target.result);
        if (data.transactions) setTxs(data.transactions.map(t => ({ ...t, date: new Date(t.date) })));
        if (data.investments) setInvs(data.investments.map(i => ({ ...i, date: new Date(i.date) })));
        if (data.shareholders) setShareholders(data.shareholders);
        if (data.settings) {
          if (data.settings.exchange_rate_thb_lak) setRate(data.settings.exchange_rate_thb_lak);
          if (data.settings.display_currency) setCurrency(data.settings.display_currency);
          if (data.settings.mgmt_fee_pct != null) setMgmtFeePct(data.settings.mgmt_fee_pct);
        }
        alert('นำเข้าข้อมูลสำเร็จ ✓');
      } catch (err) {
        alert('ไฟล์ JSON ไม่ถูกต้อง: ' + err.message);
      }
    };
    reader.readAsText(file);
  }
  function clearAllData() {
    const ok = confirm(
      '⚠ ล้างข้อมูลทั้งหมด?\n\n' +
      '— ธุรกรรมทั้งหมด ' + txs.length + ' รายการ\n' +
      '— เงินลงทุน ' + invs.length + ' รายการ\n' +
      '— ผู้ถือหุ้น ' + shareholders.length + ' คน\n\n' +
      'การกระทำนี้ไม่สามารถย้อนกลับได้\n(แนะนำให้ Export SQL/JSON ไว้ก่อน)'
    );
    if (!ok) return;
    const ok2 = confirm('ยืนยันอีกครั้ง — ล้างข้อมูลทั้งหมด?');
    if (!ok2) return;
    setTxs([]);
    setInvs([]);
    setShareholders([]);
    setMgmtFeePct(40);
    try {
      ['ciga-sh', 'ciga-mgmt'].forEach(k => localStorage.removeItem(k));
    } catch (e) {}
    setSettingsOpen(false);
    setTimeout(() => alert('ล้างข้อมูลเรียบร้อย ✓ พร้อมเริ่มต้นใหม่'), 100);
  }

  const range = useMemo(() => getRange(period, window.CIGA.END), [period]);
  const prevRange = useMemo(() => {
    const span = range.end - range.start;
    return { start: new Date(range.start.getTime() - span - 1), end: new Date(range.start.getTime() - 1) };
  }, [range]);

  const summary = useMemo(() => summarize(txs, range, prevRange), [txs, range, prevRange]);
  const stockState = useMemo(() => computeStockState(txs), [txs]);
  const totalInvested = useMemo(() => invs.reduce((s, i) => s + i.amount, 0), [invs]);

  // Daily series for charts
  const revSeries = useMemo(() => dailyBuckets(txs, range, t => (t.type === 'out' && t.kind === 'sale') ? t.amount : 0), [txs, range]);
  const expSeries = useMemo(() => dailyBuckets(txs, range, t => {
    if (t.type === 'expense') return t.amount;
    if (t.type === 'in' && t.kind === 'restock') return t.amount;
    return 0;
  }), [txs, range]);
  const stockMoveBars = useMemo(() => {
    const days = [];
    const start = new Date(range.start); start.setHours(0,0,0,0);
    const end = new Date(range.end); end.setHours(0,0,0,0);
    const cur = new Date(start);
    while (cur <= end) {
      days.push({ date: new Date(cur), valueIn: 0, valueOut: 0, label: String(cur.getDate()).padStart(2,'0')+'/'+String(cur.getMonth()+1).padStart(2,'0') });
      cur.setDate(cur.getDate() + 1);
    }
    for (const t of txs) {
      if (!t.productId || !inRange(t.date, range)) continue;
      const d = new Date(t.date); d.setHours(0,0,0,0);
      const idx = Math.floor((d - start) / 86400000);
      if (idx < 0 || idx >= days.length) continue;
      if (t.type === 'in') days[idx].valueIn += t.qty;
      else if (t.type === 'out') days[idx].valueOut += t.qty;
    }
    return days;
  }, [txs, range]);

  // Sparkline points for KPI (last N days)
  function sparkFrom(series) { return series.map(d => d.value); }

  // Deltas vs previous period
  function pctDelta(cur, prev) {
    if (!prev) return 0;
    if (prev === 0) return cur > 0 ? 100 : 0;
    return ((cur - prev) / prev) * 100;
  }

  // ---- Cash position ----
  const cashBalance = useMemo(() => {
    let cash = 0;
    for (const i of invs) cash += i.amount;
    for (const t of txs) {
      if (t.type === 'out' && t.kind === 'sale') cash += t.amount;
      if (t.type === 'in' && t.kind === 'restock') cash -= t.amount;
      if (t.type === 'expense') cash -= t.amount;
    }
    return cash;
  }, [txs, invs]);

  // ---- Ticker items ----
  const tickerItems = [
    { label: 'PILOT·MV', value: M(350000), delta: 2.4 },
    { label: 'PILOT·GR', value: M(380000), delta: 1.1 },
    { label: 'NET·30D', value: Mk(summary.netProfit), delta: pctDelta(summary.netProfit, summary.prev?.netProfit) },
    { label: 'REV·30D', value: Mk(summary.revenue), delta: pctDelta(summary.revenue, summary.prev?.revenue) },
    { label: 'CASH', value: Mk(cashBalance), delta: 8.2 },
    { label: 'UNITS·MV', value: String(stockState['pilot-m']?.qty || 0), delta: -3.2 },
    { label: 'UNITS·GR', value: String(stockState['pilot-g']?.qty || 0), delta: 1.8 },
    { label: 'LAK/USD', value: '21,580', delta: -0.12 },
    { label: 'LAK/THB', value: '615.4', delta: 0.04 },
    { label: 'CCY', value: currency, delta: 0 },
  ];

  // ---- Actions ----
  function addTransaction(tx) {
    setTxs(prev => [tx, ...prev]);
  }
  function deleteTransaction(id) {
    setTxs(prev => prev.filter(t => t.id !== id));
  }
  function saveInvestment(inv) {
    setInvs(prev => {
      const idx = prev.findIndex(x => x.id === inv.id);
      if (idx >= 0) {
        const next = [...prev];
        next[idx] = inv;
        return next;
      }
      return [...prev, inv].sort((a, b) => a.date - b.date);
    });
  }
  function deleteInvestment(id) {
    setInvs(prev => prev.filter(i => i.id !== id));
  }

  return (
    <CurrencyContext.Provider value={{ currency, setCurrency, rate, setRate }}>
    <div className="app">
      <TopBar period={period} setPeriod={setPeriod} onOpenAdd={() => setAddOpen(true)} onOpenSettings={() => setSettingsOpen(true)} />
      <Ticker items={tickerItems} />
      <div className="layout">
        <Sidebar active={active} setActive={setActive} />
        <main className="main">

          {/* HERO KPI */}
          <section id="overview" className="kpi-grid">
            <KPI
              label="เงินลงทุนรวม"
              value={totalInvested}
              format={M}
              accent="#ffb547"
              delta={0}
              deltaLabel={`${invs.length} ครั้งสะสม`}
              sparkPoints={[0,0,50,50,50,50,68,68,68,68,80,80,80]}
            />
            <KPI
              label="รายรับ"
              value={summary.revenue}
              format={M}
              accent="#22d3a3"
              color="#e6e9f0"
              delta={pctDelta(summary.revenue, summary.prev?.revenue)}
              deltaLabel={`เทียบงวดก่อน ${Mk(summary.prev?.revenue || 0)}`}
              sparkPoints={sparkFrom(revSeries)}
            />
            <KPI
              label="รายจ่าย"
              value={summary.opex + summary.restockCost}
              format={M}
              accent="#ff5a78"
              delta={pctDelta(summary.opex + summary.restockCost, (summary.prev?.opex || 0) + (summary.prev?.restockCost || 0))}
              deltaLabel={`รวมต้นทุนสินค้า + opex`}
              sparkPoints={sparkFrom(expSeries)}
            />
            <KPI
              label="กำไรสุทธิ"
              value={summary.netProfit}
              format={M}
              accent="#7c5cff"
              color={summary.netProfit >= 0 ? '#22d3a3' : '#ff5a78'}
              delta={pctDelta(summary.netProfit, summary.prev?.netProfit)}
              deltaLabel={`Margin ${summary.revenue ? ((summary.netProfit / summary.revenue) * 100).toFixed(1) : '0'}%`}
              sparkPoints={revSeries.map((d, i) => d.value - (expSeries[i]?.value || 0))}
            />
            <KPI
              label="เงินสดคงเหลือ"
              value={cashBalance}
              format={M}
              accent="#60a5fa"
              delta={pctDelta(cashBalance, totalInvested)}
              deltaLabel={`จากทุน ${Mk(totalInvested)}`}
              sparkPoints={revSeries.map((_, i) => totalInvested + revSeries.slice(0, i+1).reduce((s, x) => s + x.value, 0) - expSeries.slice(0, i+1).reduce((s, x) => s + x.value, 0))}
            />
          </section>

          {/* ROW 2: Revenue/Expense chart + Product mix */}
          <section className="row-grid two-cols">
            <Card className="panel">
              <div className="panel-head">
                <div>
                  <div className="panel-title">กระแสรายรับ-รายจ่าย</div>
                  <div className="panel-sub">รายวัน · {fmtDate(range.start, 'long')} – {fmtDate(range.end, 'long')}</div>
                </div>
                <div className="legend">
                  <span className="legend-item"><span className="dot" style={{ background: '#22d3a3' }}></span>รายรับ</span>
                  <span className="legend-item"><span className="dot" style={{ background: '#ff5a78' }}></span>รายจ่าย</span>
                  <span className="legend-item"><span className="dot" style={{ background: '#ffb547' }}></span>กำไรสะสม</span>
                </div>
              </div>
              <AreaChart
                height={280}
                labels={revSeries.map((d, i) => i % Math.ceil(revSeries.length / 7) === 0 ? d.label : '')}
                series={[
                  { name: 'รายรับ', color: '#22d3a3', points: revSeries.map(d => d.value) },
                  { name: 'รายจ่าย', color: '#ff5a78', points: expSeries.map(d => d.value) },
                  { name: 'กำไรสะสม', color: '#ffb547', points: revSeries.map((d, i) => Math.max(0, revSeries.slice(0, i+1).reduce((s, x) => s + x.value, 0) - expSeries.slice(0, i+1).reduce((s, x) => s + x.value, 0))) },
                ]}
                yFormat={v => Mk(v)}
              />
            </Card>

            <Card className="panel">
              <div className="panel-head">
                <div>
                  <div className="panel-title">สัดส่วนสินค้า</div>
                  <div className="panel-sub">รายรับจาก Pilot ม่วง vs เขียว</div>
                </div>
              </div>
              <div className="donut-wrap">
                <Donut
                  size={180}
                  thickness={20}
                  centerLabel="รวม"
                  centerValue={Mk(summary.revenue)}
                  segments={[
                    { color: '#a78bfa', value: summary.revenueByProd['pilot-m'] },
                    { color: '#4ade80', value: summary.revenueByProd['pilot-g'] },
                  ]}
                />
                <div className="donut-legend">
                  {window.CIGA.PRODUCTS.map(p => {
                    const v = summary.revenueByProd[p.id];
                    const pct = summary.revenue ? (v / summary.revenue * 100) : 0;
                    const units = summary.unitsSold[p.id];
                    return (
                      <div key={p.id} className="donut-row">
                        <div className="donut-row-head">
                          <span className="dot" style={{ background: p.color }}></span>
                          <span className="donut-row-name">{p.name}</span>
                          <span className="donut-row-pct">{pct.toFixed(1)}%</span>
                        </div>
                        <div className="donut-row-val">{Mk(v)} · {units} ชิ้น</div>
                        <div className="donut-row-bar"><span style={{ width: pct + '%', background: p.color }}></span></div>
                      </div>
                    );
                  })}
                </div>
              </div>
            </Card>
          </section>

          {/* ROW 3: Investment + Cashflow */}
          <section id="invest" className="row-grid two-cols">
            <Card className="panel">
              <div className="panel-head">
                <div>
                  <div className="panel-title">เงินลงทุน</div>
                  <div className="panel-sub">ประวัติการเติมทุน · รวม {Mk(totalInvested)}</div>
                </div>
                <button className="link-btn" onClick={() => setInvestModal({ mode: 'add' })}><Icon name="plus" size={12}/> บันทึกเงินลงทุน</button>
              </div>
              <div className="invest-timeline">
                {invs.map((inv, i) => (
                  <div key={inv.id} className="invest-row">
                    <div className="invest-node">
                      <span className="invest-dot" style={{ background: i === 0 ? '#ffb547' : '#7c5cff' }} />
                      {i < invs.length - 1 && <span className="invest-line" />}
                    </div>
                    <div className="invest-body">
                      <div className="invest-head">
                        <span className="invest-id">{inv.id}</span>
                        <span className="invest-date">{fmtDate(inv.date, 'long')}</span>
                      </div>
                      <div className="invest-title">{inv.note}</div>
                      <div className="invest-meta">
                        <span>{inv.source}</span>
                        <span className="invest-amount">{M(inv.amount, { sign: true })}</span>
                      </div>
                      <div className="invest-actions">
                        <button className="icon-btn-mini neutral" onClick={() => setInvestModal({ mode: 'edit', inv })} title="แก้ไข"><Icon name="edit" size={12}/></button>
                        <button className="icon-btn-mini" onClick={() => { if (confirm('ลบรายการเงินลงทุนนี้?')) deleteInvestment(inv.id); }} title="ลบ"><Icon name="trash" size={12}/></button>
                      </div>
                    </div>
                  </div>
                ))}
              </div>
              <div className="invest-total">
                <div>
                  <div className="muted-label">ผลตอบแทนจากการลงทุน (ROI)</div>
                  <div className="big-stat" style={{ color: '#22d3a3' }}>
                    {((summary.revenue - summary.cogs - summary.opex) / totalInvested * 100).toFixed(2)}%
                  </div>
                </div>
                <div>
                  <div className="muted-label">เงินสด/ทุน</div>
                  <div className="big-stat">{(cashBalance / totalInvested * 100).toFixed(1)}%</div>
                </div>
                <div>
                  <div className="muted-label">สต็อกมูลค่า</div>
                  <div className="big-stat">{Mk(
                    Object.entries(stockState).reduce((s, [id, st]) => {
                      const p = window.CIGA.PRODUCTS.find(x => x.id === id);
                      return s + st.qty * p.cost;
                    }, 0))}</div>
                </div>
              </div>
            </Card>

            <Card id="pl" className="panel">
              <div className="panel-head">
                <div>
                  <div className="panel-title">งบกำไรขาดทุน</div>
                  <div className="panel-sub">P&L สรุปงวดที่เลือก</div>
                </div>
              </div>
              <div className="pl-table">
                <div className="pl-row">
                  <div className="pl-name">รายรับจากการขาย</div>
                  <div className="pl-val pos">{M(summary.revenue)}</div>
                  <div className="pl-bar"><span style={{ width: '100%', background: '#22d3a3' }}></span></div>
                </div>
                <div className="pl-row">
                  <div className="pl-name">ต้นทุนขาย (COGS)</div>
                  <div className="pl-val neg">{M(-summary.cogs)}</div>
                  <div className="pl-bar"><span style={{ width: (summary.revenue ? (summary.cogs/summary.revenue)*100 : 0) + '%', background: '#ff5a78' }}></span></div>
                </div>
                <div className="pl-row sub">
                  <div className="pl-name">กำไรขั้นต้น</div>
                  <div className="pl-val">{M(summary.grossProfit)}</div>
                  <div className="pl-bar"><span style={{ width: (summary.revenue ? (summary.grossProfit/summary.revenue)*100 : 0) + '%', background: '#ffb547' }}></span></div>
                </div>
                <div className="pl-row">
                  <div className="pl-name">ค่าใช้จ่ายดำเนินงาน</div>
                  <div className="pl-val neg">{M(-summary.opex)}</div>
                  <div className="pl-bar"><span style={{ width: (summary.revenue ? (summary.opex/summary.revenue)*100 : 0) + '%', background: '#ff5a78' }}></span></div>
                </div>
                <div className="pl-row total">
                  <div className="pl-name">กำไรสุทธิ</div>
                  <div className="pl-val" style={{ color: summary.netProfit >= 0 ? '#22d3a3' : '#ff5a78' }}>
                    {M(summary.netProfit)}
                  </div>
                  <div className="pl-bar"><span style={{ width: (summary.revenue ? Math.min(100, Math.max(0,(summary.netProfit/summary.revenue)*100)) : 0) + '%', background: summary.netProfit >= 0 ? '#22d3a3' : '#ff5a78' }}></span></div>
                </div>
              </div>
              <div className="margin-stats">
                <div>
                  <div className="muted-label">Gross Margin</div>
                  <div className="big-stat">{summary.revenue ? (summary.grossProfit / summary.revenue * 100).toFixed(1) : '0'}%</div>
                </div>
                <div>
                  <div className="muted-label">Net Margin</div>
                  <div className="big-stat" style={{ color: summary.netProfit >= 0 ? '#22d3a3' : '#ff5a78' }}>
                    {summary.revenue ? (summary.netProfit / summary.revenue * 100).toFixed(1) : '0'}%
                  </div>
                </div>
                <div>
                  <div className="muted-label">COGS Ratio</div>
                  <div className="big-stat">{summary.revenue ? (summary.cogs / summary.revenue * 100).toFixed(1) : '0'}%</div>
                </div>
              </div>
            </Card>
          </section>

          {/* ROW 3.5: Shareholders / Profit split */}
          <section id="shareholders" className="row-grid">
            <Card className="panel" glow>
              <div className="panel-head">
                <div>
                  <div className="panel-title">สรุปแบ่งหุ้นส่วน</div>
                  <div className="panel-sub">หักค่าบริหาร {mgmtFeePct}% ก่อนแบ่งตามสัดส่วนผู้ถือหุ้น · {shareholders.length} คน</div>
                </div>
                <button className="link-btn" onClick={() => setShModalOpen(true)}>
                  <Icon name="edit" size={12}/> จัดการผู้ถือหุ้น
                </button>
              </div>
              {(() => {
                const totalPool = Math.max(0, summary.netProfit);
                const mgmtFee = totalPool * (mgmtFeePct / 100);
                const remainPct = 100 - mgmtFeePct;
                const remaining = totalPool - mgmtFee;
                const totalSharePct = shareholders.reduce((s, x) => s + Number(x.pct || 0), 0);
                const validSum = Math.abs(totalSharePct - 100) < 0.01;
                return (
                  <div className="sh-wrap">
                    <div className="sh-summary">
                      <div className="sh-stat">
                        <div className="muted-label">ยอดคงเหลือทั้งหมด</div>
                        <div className="sh-stat-val" style={{ color: '#ffb547' }}>{M(totalPool)}</div>
                      </div>
                      <div className="sh-arrow">→</div>
                      <div className="sh-stat sh-stat-mgmt">
                        <div className="muted-label">ค่าบริหาร · {mgmtFeePct}%</div>
                        <div className="sh-stat-val" style={{ color: '#ff5a78' }}>{M(mgmtFee)}</div>
                      </div>
                      <div className="sh-arrow">→</div>
                      <div className="sh-stat sh-stat-pool">
                        <div className="muted-label">คงเหลือแบ่งหุ้น · {remainPct}%</div>
                        <div className="sh-stat-val" style={{ color: '#22d3a3' }}>{M(remaining)}</div>
                      </div>
                    </div>
                    <table className="sh-table">
                      <thead>
                        <tr>
                          <th style={{ width: '40%' }}>ผู้ถือหุ้น</th>
                          <th style={{ width: '20%' }}>หุ้น (%)</th>
                          <th style={{ width: '20%' }}>สัดส่วนของยอดเต็ม</th>
                          <th style={{ textAlign: 'right' }}>ยอดที่ได้รับ</th>
                        </tr>
                      </thead>
                      <tbody>
                        <tr className="sh-row sh-row-mgmt">
                          <td>
                            <span className="sh-avatar" style={{ background: 'linear-gradient(135deg, #ff5a78, #b91c4f)' }}>บ</span>
                            <span className="sh-name">บริหาร (Management Fee)</span>
                          </td>
                          <td className="mono">{mgmtFeePct}%</td>
                          <td className="mono muted">{mgmtFeePct}%</td>
                          <td className="mono right" style={{ color: '#ff5a78', fontWeight: 600 }}>{M(mgmtFee)}</td>
                        </tr>
                        {shareholders.map((sh, i) => {
                          const share = remaining * (Number(sh.pct) / 100);
                          const ofTotal = remainPct * (Number(sh.pct) / 100);
                          const palette = ['#a78bfa', '#4ade80', '#60a5fa', '#ffb547', '#22d3a3', '#f472b6', '#fb923c', '#34d399'];
                          const col = palette[i % palette.length];
                          return (
                            <tr key={sh.id} className="sh-row">
                              <td>
                                <span className="sh-avatar" style={{ background: `linear-gradient(135deg, ${col}, ${col}aa)` }}>{(sh.name || '?').trim()[0]}</span>
                                <span className="sh-name">{sh.name}</span>
                              </td>
                              <td className="mono">{Number(sh.pct).toFixed(1)}%</td>
                              <td className="mono muted">{ofTotal.toFixed(1)}%</td>
                              <td className="mono right" style={{ fontWeight: 600 }}>{M(share)}</td>
                            </tr>
                          );
                        })}
                        <tr className="sh-row sh-row-total">
                          <td><strong>รวมหุ้นส่วน</strong></td>
                          <td className="mono" style={{ color: validSum ? '#22d3a3' : '#ff5a78' }}>
                            {totalSharePct.toFixed(1)}%
                            {!validSum && <span className="sh-warn" title="สัดส่วนต้องรวม 100%"> ⚠</span>}
                          </td>
                          <td className="mono muted">{remainPct}%</td>
                          <td className="mono right" style={{ color: '#22d3a3', fontWeight: 700 }}>{M(remaining * totalSharePct / 100)}</td>
                        </tr>
                      </tbody>
                    </table>
                    {!validSum && (
                      <div className="sh-warn-msg">
                        <Icon name="bolt" size={12}/>
                        สัดส่วนการถือหุ้นรวมต้องเท่ากับ 100% (ตอนนี้ {totalSharePct.toFixed(1)}%) · กด "จัดการผู้ถือหุ้น" เพื่อแก้ไข
                      </div>
                    )}
                    {totalPool <= 0 && (
                      <div className="sh-warn-msg" style={{ background: 'rgba(255,181,71,0.06)', borderColor: 'rgba(255,181,71,0.25)', color: '#ffb547' }}>
                        <Icon name="bolt" size={12}/>
                        ยังไม่มีกำไรในงวดนี้ — เปลี่ยนช่วงเวลาให้ครอบคลุมการขาย เพื่อแบ่งหุ้น
                      </div>
                    )}
                  </div>
                );
              })()}
            </Card>
          </section>

          {/* ROW 4: Stock + Movements */}
          <section id="stock" className="row-grid stock-grid">
            {window.CIGA.PRODUCTS.map(p => {
              const st = stockState[p.id] || { qty: 0, totalIn: 0, totalOut: 0 };
              const cap = 400;
              const lowThreshold = 60;
              const low = st.qty < lowThreshold;
              const stockValue = st.qty * p.cost;
              const turnover = st.totalIn > 0 ? (st.totalOut / st.totalIn * 100) : 0;
              return (
                <Card key={p.id} className="stock-card" style={{ '--prod-color': p.color, '--prod-hue': p.hue }}>
                  <div className="stock-head">
                    <div className="stock-prod">
                      <div className="stock-mark" style={{ background: `radial-gradient(circle at 30% 30%, ${p.color}, ${p.color}88)` }}>
                        <svg width="22" height="22" viewBox="0 0 24 24" fill="none">
                          <rect x="3" y="9" width="14" height="6" rx="1.5" fill="#fff" opacity="0.95"/>
                          <rect x="16" y="8" width="4" height="8" rx="1.5" fill="rgba(0,0,0,0.4)"/>
                        </svg>
                      </div>
                      <div>
                        <div className="stock-name">{p.name}</div>
                        <div className="stock-sku">SKU · {p.short}</div>
                      </div>
                    </div>
                    {low && <span className="badge-warn">สต็อกต่ำ</span>}
                  </div>
                  <div className="stock-qty">
                    <div className="stock-qty-num"><Counter value={st.qty} format={v => Math.round(v).toString()} /></div>
                    <div className="stock-qty-unit">ชิ้น</div>
                  </div>
                  <div className="stock-bar">
                    <div className="stock-bar-fill" style={{ width: Math.min(100, st.qty / cap * 100) + '%', background: `linear-gradient(90deg, ${p.color}, ${p.color}aa)` }}></div>
                    <div className="stock-bar-mark" style={{ left: (lowThreshold / cap * 100) + '%' }} title="ระดับเตือนภัย"></div>
                  </div>
                  <div className="stock-meta">
                    <div><span className="muted-label">ต้นทุน/ชิ้น</span><span>{M(p.cost)}</span></div>
                    <div><span className="muted-label">ราคาขาย</span><span>{M(p.price)}</span></div>
                    <div><span className="muted-label">กำไร/ชิ้น</span><span style={{ color: '#22d3a3' }}>{M(p.price - p.cost, { sign: true })}</span></div>
                    <div><span className="muted-label">มูลค่าสต็อก</span><span>{Mk(stockValue)}</span></div>
                  </div>
                  <div className="stock-flow">
                    <div className="flow-stat">
                      <Icon name="arrow-down" size={12}/>
                      <div>
                        <div className="muted-label">รับเข้ารวม</div>
                        <div style={{ fontFamily: "'IBM Plex Mono', monospace" }}>{st.totalIn}</div>
                      </div>
                    </div>
                    <div className="flow-stat">
                      <Icon name="arrow-up" size={12}/>
                      <div>
                        <div className="muted-label">ขายออกรวม</div>
                        <div style={{ fontFamily: "'IBM Plex Mono', monospace" }}>{st.totalOut}</div>
                      </div>
                    </div>
                    <div className="flow-stat">
                      <Icon name="pulse" size={12}/>
                      <div>
                        <div className="muted-label">Turnover</div>
                        <div style={{ fontFamily: "'IBM Plex Mono', monospace", color: '#ffb547' }}>{turnover.toFixed(0)}%</div>
                      </div>
                    </div>
                  </div>
                </Card>
              );
            })}
            <Card id="flow" className="panel stock-move-panel">
              <div className="panel-head">
                <div>
                  <div className="panel-title">การเคลื่อนไหวสต็อก</div>
                  <div className="panel-sub">รับเข้า vs จ่ายออก (ชิ้น/วัน)</div>
                </div>
                <div className="legend">
                  <span className="legend-item"><span className="dot" style={{ background: '#60a5fa' }}></span>รับเข้า</span>
                  <span className="legend-item"><span className="dot" style={{ background: '#ffb547' }}></span>จ่ายออก</span>
                </div>
              </div>
              <BarChart data={stockMoveBars} height={200} palette={{ in: '#60a5fa', out: '#ffb547' }} />
            </Card>
          </section>

          {/* ROW 5: Recent movements + transactions */}
          <section id="report" className="row-grid two-cols">
            <Card className="panel">
              <div className="panel-head">
                <div>
                  <div className="panel-title">รับเข้า-จ่ายออก ล่าสุด</div>
                  <div className="panel-sub">การเคลื่อนไหวของสินค้าในงวด</div>
                </div>
              </div>
              <Table
                rows={summary.txInRange.filter(t => t.productId).slice(0, 12)}
                columns={[
                  { key: 'date', label: 'วันที่', render: t => <span style={{ fontFamily: "'IBM Plex Mono', monospace" }}>{fmtDate(t.date)}<span style={{ color: 'rgba(230,233,240,0.35)' }}> · {fmtTime(t.date)}</span></span> },
                  { key: 'id', label: 'อ้างอิง', render: t => <span style={{ fontFamily: "'IBM Plex Mono', monospace", color: 'rgba(230,233,240,0.55)' }}>{t.id}</span> },
                  { key: 'type', label: 'ทิศทาง', render: t => <span className={`tag tag-${t.type}`}>{t.type === 'in' ? '▼ รับเข้า' : '▲ จ่ายออก'}</span> },
                  { key: 'product', label: 'สินค้า', render: t => {
                      const p = window.CIGA.PRODUCTS.find(x => x.id === t.productId);
                      return <span><span className="dot" style={{ background: p.color, marginRight: 6 }}></span>{p.name}</span>;
                    }},
                  { key: 'qty', label: 'จำนวน', align: 'right', render: t => <span style={{ fontFamily: "'IBM Plex Mono', monospace", color: t.type === 'in' ? '#60a5fa' : '#ffb547' }}>{t.type === 'in' ? '+' : '−'}{t.qty}</span> },
                  { key: 'amount', label: 'มูลค่า', align: 'right', render: t => <span style={{ fontFamily: "'IBM Plex Mono', monospace" }}>{M(t.amount)}</span> },
                ]}
                onClickRow={setDetailTx}
              />
            </Card>

            <Card className="panel">
              <div className="panel-head">
                <div>
                  <div className="panel-title">รายการธุรกรรมล่าสุด</div>
                  <div className="panel-sub">รายรับและรายจ่ายทั้งหมด</div>
                </div>
              </div>
              <Table
                rows={summary.txInRange.slice(0, 12)}
                columns={[
                  { key: 'date', label: 'วันที่', render: t => <span style={{ fontFamily: "'IBM Plex Mono', monospace" }}>{fmtDate(t.date)}</span> },
                  { key: 'kind', label: 'ประเภท', render: t => {
                    const map = { sale: ['ขาย','#22d3a3'], restock: ['รับสินค้า','#60a5fa'], opex: ['ค่าใช้จ่าย','#ff5a78'], rent: ['ค่าเช่า','#ff5a78'] };
                    const [lab, col] = map[t.kind] || ['อื่นๆ','#888'];
                    return <span className="tag" style={{ borderColor: col + '40', color: col }}>{lab}</span>;
                  }},
                  { key: 'note', label: 'รายละเอียด', render: t => <span style={{ color: '#e6e9f0', fontSize: 12 }}>{t.note}<div style={{ color: 'rgba(230,233,240,0.4)', fontSize: 10 }}>{t.channel}</div></span> },
                  { key: 'amount', label: 'จำนวนเงิน', align: 'right', render: t => {
                    const positive = t.type === 'out' && t.kind === 'sale';
                    return <span style={{ fontFamily: "'IBM Plex Mono', monospace", color: positive ? '#22d3a3' : '#ff5a78', fontWeight: 600 }}>
                      {positive ? '+' : '−'}{M(t.amount)}
                    </span>;
                  }},
                  { key: 'actions', label: '', render: t => (
                    <button className="icon-btn-mini" onClick={e => { e.stopPropagation(); deleteTransaction(t.id); }} title="ลบ"><Icon name="trash" size={13}/></button>
                  )},
                ]}
                onClickRow={setDetailTx}
              />
            </Card>
          </section>

          <footer className="footer">
            <span>CIGA · ELT — ระบบสรุปบัญชี ลาว · v1.0</span>
            <span style={{ fontFamily: "'IBM Plex Mono', monospace", color: 'rgba(230,233,240,0.4)' }}>
              อัปเดตล่าสุด {fmtDate(window.CIGA.END, 'long')} · {summary.txInRange.length} รายการในงวด
            </span>
          </footer>
        </main>
      </div>

      {addOpen && <AddTxModal onClose={() => setAddOpen(false)} onSubmit={tx => { addTransaction(tx); setAddOpen(false); }} />}
      {detailTx && <DetailModal tx={detailTx} onClose={() => setDetailTx(null)} onDelete={(id) => { deleteTransaction(id); setDetailTx(null); }} />}
      {investModal && <InvestmentModal
        mode={investModal.mode}
        inv={investModal.inv}
        onClose={() => setInvestModal(null)}
        onSubmit={(inv) => { saveInvestment(inv); setInvestModal(null); }}
        onDelete={(id) => { deleteInvestment(id); setInvestModal(null); }}
      />}
      {settingsOpen && <SettingsModal
        onClose={() => setSettingsOpen(false)}
        onExportJSON={exportJSON}
        onExportSQL={exportSQL}
        onImportJSON={importJSON}
        onClearAll={clearAllData}
        stats={{ txCount: txs.length, invCount: invs.length, shCount: shareholders.length }}
      />}
      {shModalOpen && <ShareholderModal
        shareholders={shareholders}
        mgmtFeePct={mgmtFeePct}
        setShareholders={setShareholders}
        setMgmtFeePct={setMgmtFeePct}
        onClose={() => setShModalOpen(false)}
      />}
    </div>
    </CurrencyContext.Provider>
  );
}

// ===== Table =====
function Table({ rows, columns, onClickRow }) {
  if (!rows.length) {
    return <div className="empty">ไม่มีข้อมูลในงวดนี้</div>;
  }
  return (
    <div className="table-wrap">
      <table className="data-table">
        <thead>
          <tr>{columns.map(c => <th key={c.key} style={{ textAlign: c.align || 'left' }}>{c.label}</th>)}</tr>
        </thead>
        <tbody>
          {rows.map((r, ri) => (
            <tr key={r.id || ri} onClick={() => onClickRow && onClickRow(r)} style={{ cursor: onClickRow ? 'pointer' : 'default' }}>
              {columns.map(c => <td key={c.key} style={{ textAlign: c.align || 'left' }}>{c.render(r)}</td>)}
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}

// ===== Add transaction modal =====
function AddTxModal({ onClose, onSubmit }) {
  const { currency, rate: userRate } = useCurrency();
  const sym = moneySymbol(currency);
  const convRate = currency === 'THB' ? 1 / userRate : 1;
  const M = (v, opts) => fmtMoney(v, currency, opts, userRate);
  // Input values are entered in the selected currency, stored in LAK.
  const [kind, setKind] = useState('sale'); // sale | restock | opex
  const [productId, setProductId] = useState('pilot-m');
  const [qty, setQty] = useState('');
  const [unitPrice, setUnitPrice] = useState('');
  const [amount, setAmount] = useState('');
  const [note, setNote] = useState('');
  const [channel, setChannel] = useState('');

  useEffect(() => {
    if (kind === 'sale') {
      const p = window.CIGA.PRODUCTS.find(x => x.id === productId);
      setUnitPrice(String(Math.round(p.price * convRate)));
      setChannel('ขายปลีก');
    } else if (kind === 'restock') {
      const p = window.CIGA.PRODUCTS.find(x => x.id === productId);
      setUnitPrice(String(Math.round(p.cost * convRate)));
      setChannel('รับจากซัพพลายเออร์');
    } else {
      setUnitPrice(''); setChannel('ค่าใช้จ่ายดำเนินงาน');
    }
  }, [kind, productId, currency, convRate]);

  const totalDisplay = kind === 'opex' ? Number(amount) || 0 : (Number(qty) || 0) * (Number(unitPrice) || 0);
  const total = totalDisplay / convRate; // convert back to LAK for storage

  function submit() {
    const tx = {
      id: 'TX' + Date.now().toString(36).toUpperCase().slice(-5),
      date: new Date(),
      type: kind === 'sale' ? 'out' : kind === 'restock' ? 'in' : 'expense',
      kind,
      productId: kind === 'opex' ? null : productId,
      qty: kind === 'opex' ? null : Number(qty),
      unitPrice: kind === 'opex' ? null : Number(unitPrice),
      amount: total,
      channel: channel || 'อื่นๆ',
      note: note || '—',
    };
    onSubmit(tx);
  }

  return (
    <div className="modal-overlay" onClick={onClose}>
      <div className="modal" onClick={e => e.stopPropagation()}>
        <div className="modal-head">
          <div>
            <div className="modal-title">เพิ่มรายการใหม่</div>
            <div className="modal-sub">บันทึกธุรกรรมเข้าสู่ระบบบัญชี</div>
          </div>
          <button className="icon-btn" onClick={onClose}><Icon name="x"/></button>
        </div>
        <div className="modal-body">
          <div className="field">
            <label>ประเภทรายการ</label>
            <div className="seg">
              {[
                { id: 'sale', label: 'ขายออก', color: '#22d3a3' },
                { id: 'restock', label: 'รับเข้า', color: '#60a5fa' },
                { id: 'opex', label: 'ค่าใช้จ่าย', color: '#ff5a78' },
              ].map(o => (
                <button key={o.id} className={`seg-btn ${kind === o.id ? 'active' : ''}`} onClick={() => setKind(o.id)} style={{ '--seg-color': o.color }}>
                  {o.label}
                </button>
              ))}
            </div>
          </div>
          {kind !== 'opex' && (
            <div className="field">
              <label>สินค้า</label>
              <div className="seg">
                {window.CIGA.PRODUCTS.map(p => (
                  <button key={p.id} className={`seg-btn ${productId === p.id ? 'active' : ''}`} onClick={() => setProductId(p.id)} style={{ '--seg-color': p.color }}>
                    <span className="dot" style={{ background: p.color, marginRight: 8 }}></span>{p.name}
                  </button>
                ))}
              </div>
            </div>
          )}
          <div className="field-row">
            {kind !== 'opex' && (
              <>
                <div className="field">
                  <label>จำนวน (ชิ้น)</label>
                  <input type="number" value={qty} onChange={e => setQty(e.target.value)} placeholder="0" />
                </div>
                <div className="field">
                  <label>ราคา/ชิ้น ({sym})</label>
                  <input type="number" value={unitPrice} onChange={e => setUnitPrice(e.target.value)} />
                </div>
              </>
            )}
            {kind === 'opex' && (
              <div className="field" style={{ flex: 1 }}>
                <label>จำนวนเงิน ({sym})</label>
                <input type="number" value={amount} onChange={e => setAmount(e.target.value)} placeholder="0" />
              </div>
            )}
          </div>
          <div className="field">
            <label>ช่องทาง</label>
            <input type="text" value={channel} onChange={e => setChannel(e.target.value)} />
          </div>
          <div className="field">
            <label>หมายเหตุ / รายละเอียด</label>
            <input type="text" value={note} onChange={e => setNote(e.target.value)} placeholder="เช่น ลูกค้าประจำ คุณเอ" />
          </div>
          <div className="modal-total">
            <span>รวมเป็นเงิน</span>
            <span style={{ fontFamily: "'IBM Plex Mono', monospace", fontSize: 22, fontWeight: 600, color: '#ffb547' }}>{M(total)}</span>
          </div>
        </div>
        <div className="modal-foot">
          <button className="btn-ghost" onClick={onClose}>ยกเลิก</button>
          <button className="btn-primary" onClick={submit} disabled={total <= 0}>
            <Icon name="plus" size={14}/> บันทึก
          </button>
        </div>
      </div>
    </div>
  );
}

// ===== Detail modal =====
function DetailModal({ tx, onClose, onDelete }) {
  const { currency, rate } = useCurrency();
  const M = (v, opts) => fmtMoney(v, currency, opts, rate);
  const p = tx.productId ? window.CIGA.PRODUCTS.find(x => x.id === tx.productId) : null;
  return (
    <div className="modal-overlay" onClick={onClose}>
      <div className="modal" style={{ maxWidth: 480 }} onClick={e => e.stopPropagation()}>
        <div className="modal-head">
          <div>
            <div className="modal-title">{tx.id}</div>
            <div className="modal-sub">{fmtDate(tx.date, 'long')} · {fmtTime(tx.date)}</div>
          </div>
          <button className="icon-btn" onClick={onClose}><Icon name="x"/></button>
        </div>
        <div className="modal-body">
          <div className="detail-row"><span>ประเภท</span><span style={{ color: tx.type === 'out' && tx.kind === 'sale' ? '#22d3a3' : tx.type === 'in' ? '#60a5fa' : '#ff5a78' }}>
            {tx.kind === 'sale' ? 'ขายออก' : tx.kind === 'restock' ? 'รับเข้า' : tx.kind === 'opex' ? 'ค่าใช้จ่าย' : 'ค่าเช่า'}
          </span></div>
          {p && <div className="detail-row"><span>สินค้า</span><span><span className="dot" style={{ background: p.color, marginRight: 6 }}></span>{p.name}</span></div>}
          {tx.qty != null && <div className="detail-row"><span>จำนวน</span><span style={{ fontFamily: "'IBM Plex Mono', monospace" }}>{tx.qty} ชิ้น</span></div>}
          {tx.unitPrice != null && <div className="detail-row"><span>ราคา/ชิ้น</span><span style={{ fontFamily: "'IBM Plex Mono', monospace" }}>{M(tx.unitPrice)}</span></div>}
          <div className="detail-row"><span>ช่องทาง</span><span>{tx.channel}</span></div>
          <div className="detail-row"><span>หมายเหตุ</span><span style={{ color: '#e6e9f0' }}>{tx.note}</span></div>
          <div className="detail-row total"><span>มูลค่ารวม</span><span style={{ fontFamily: "'IBM Plex Mono', monospace", fontSize: 22, color: '#ffb547', fontWeight: 600 }}>{M(tx.amount)}</span></div>
        </div>
        <div className="modal-foot">
          <button className="btn-ghost btn-danger" onClick={() => onDelete(tx.id)}><Icon name="trash" size={13}/> ลบรายการ</button>
          <button className="btn-primary" onClick={onClose}>ปิด</button>
        </div>
      </div>
    </div>
  );
}

// ===== Investment add/edit modal =====
function InvestmentModal({ mode, inv, onClose, onSubmit, onDelete }) {
  const { currency, rate: userRate } = useCurrency();
  const sym = moneySymbol(currency);
  const convRate = currency === 'THB' ? 1 / userRate : 1;
  const M = (v, opts) => fmtMoney(v, currency, opts, userRate);
  const isEdit = mode === 'edit';
  const toLocalISO = (d) => {
    const z = new Date(d);
    z.setMinutes(z.getMinutes() - z.getTimezoneOffset());
    return z.toISOString().slice(0, 10);
  };
  const [amount, setAmount] = useState(() => isEdit ? String(Math.round(inv.amount * convRate)) : '');
  const [source, setSource] = useState(() => isEdit ? inv.source : 'ผู้ก่อตั้ง');
  const [note, setNote] = useState(() => isEdit ? inv.note : '');
  const [date, setDate] = useState(() => isEdit ? toLocalISO(inv.date) : toLocalISO(new Date()));

  const lakAmount = (Number(amount) || 0) / convRate;
  const sources = ['ผู้ก่อตั้ง', 'พาร์ทเนอร์', 'นักลงทุน', 'เงินกู้', 'อื่นๆ'];

  function submit() {
    const next = {
      id: isEdit ? inv.id : 'INV' + String(Date.now()).slice(-6),
      date: new Date(date + 'T12:00:00'),
      amount: lakAmount,
      source,
      note: note || (isEdit ? inv.note : 'เงินลงทุนเพิ่มเติม'),
    };
    onSubmit(next);
  }

  return (
    <div className="modal-overlay" onClick={onClose}>
      <div className="modal" onClick={e => e.stopPropagation()}>
        <div className="modal-head">
          <div>
            <div className="modal-title">{isEdit ? 'แก้ไขเงินลงทุน' : 'บันทึกเงินลงทุนใหม่'}</div>
            <div className="modal-sub">{isEdit ? inv.id : 'เพิ่มทุนเข้าระบบบัญชี'}</div>
          </div>
          <button className="icon-btn" onClick={onClose}><Icon name="x"/></button>
        </div>
        <div className="modal-body">
          <div className="field-row">
            <div className="field" style={{ flex: 1 }}>
              <label>วันที่</label>
              <input type="date" value={date} onChange={e => setDate(e.target.value)} />
            </div>
            <div className="field" style={{ flex: 1.2 }}>
              <label>จำนวนเงิน ({sym})</label>
              <input type="number" value={amount} onChange={e => setAmount(e.target.value)} placeholder="0" autoFocus={!isEdit} />
            </div>
          </div>
          <div className="field">
            <label>แหล่งเงินทุน</label>
            <div className="seg seg-wrap">
              {sources.map(s => (
                <button key={s} className={`seg-btn ${source === s ? 'active' : ''}`} onClick={() => setSource(s)} style={{ '--seg-color': '#ffb547' }}>
                  {s}
                </button>
              ))}
            </div>
          </div>
          <div className="field">
            <label>หมายเหตุ / วัตถุประสงค์</label>
            <input type="text" value={note} onChange={e => setNote(e.target.value)} placeholder="เช่น เพิ่มทุนขยายสต็อก" />
          </div>
          <div className="modal-total">
            <span>บันทึกเป็นเงิน LAK</span>
            <span style={{ fontFamily: "'IBM Plex Mono', monospace", fontSize: 22, fontWeight: 600, color: '#ffb547' }}>
              {fmtMoney(lakAmount, 'LAK')}
            </span>
          </div>
          {currency !== 'LAK' && (
            <div style={{ fontSize: 11, color: 'rgba(230,233,240,0.45)', textAlign: 'right', marginTop: -8 }}>
              ≈ {M(lakAmount)} (สกุลที่แสดง)
            </div>
          )}
        </div>
        <div className="modal-foot">
          {isEdit ? (
            <button className="btn-ghost btn-danger" onClick={() => { if (confirm('ลบรายการเงินลงทุนนี้?')) onDelete(inv.id); }}>
              <Icon name="trash" size={13}/> ลบรายการ
            </button>
          ) : <button className="btn-ghost" onClick={onClose}>ยกเลิก</button>}
          <button className="btn-primary" onClick={submit} disabled={lakAmount <= 0}>
            <Icon name={isEdit ? 'edit' : 'plus'} size={14}/> {isEdit ? 'บันทึกการแก้ไข' : 'บันทึกเงินลงทุน'}
          </button>
        </div>
      </div>
    </div>
  );
}

// ===== Settings modal (currency rate, etc.) =====
function SettingsModal({ onClose, onExportJSON, onExportSQL, onImportJSON, onClearAll, stats }) {
  const { currency, rate, setRate } = useCurrency();
  const [val, setVal] = useState(String(rate));
  const n = parseFloat(val);
  const valid = Number.isFinite(n) && n > 0;
  function save() {
    if (!valid) return;
    setRate(n);
    onClose();
  }
  // Quick-set presets
  const presets = [580, 600, 615, 630, 650];
  return (
    <div className="modal-overlay" onClick={onClose}>
      <div className="modal" style={{ maxWidth: 520 }} onClick={e => e.stopPropagation()}>
        <div className="modal-head">
          <div>
            <div className="modal-title">ตั้งค่า</div>
            <div className="modal-sub">อัตราแลกเปลี่ยนและตัวเลือกระบบ</div>
          </div>
          <button className="icon-btn" onClick={onClose}><Icon name="x"/></button>
        </div>
        <div className="modal-body">
          <div className="settings-section">
            <div className="settings-section-head">
              <Icon name="percent" size={14}/>
              <span>อัตราแลกเปลี่ยน</span>
            </div>
            <div className="field">
              <label>1 บาท (THB) = ? กีบ (LAK)</label>
              <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                <span style={{ fontFamily: "'IBM Plex Mono', monospace", color: 'var(--text-muted)', fontSize: 16 }}>฿1 =</span>
                <input
                  type="number"
                  value={val}
                  onChange={e => setVal(e.target.value)}
                  style={{ flex: 1, fontSize: 16, fontWeight: 600 }}
                  step="0.1"
                  autoFocus
                />
                <span style={{ fontFamily: "'IBM Plex Mono', monospace", color: 'var(--accent)', fontSize: 16, fontWeight: 600 }}>₭{val}</span>
              </div>
            </div>
            <div className="presets">
              <span className="presets-label">ค่าใช้บ่อย:</span>
              {presets.map(p => (
                <button key={p} className={`preset-btn ${parseFloat(val) === p ? 'active' : ''}`} onClick={() => setVal(String(p))}>
                  {p}
                </button>
              ))}
            </div>
            {valid && (
              <div className="rate-preview">
                <div><span className="muted-label">ตัวอย่าง</span></div>
                <div>฿1,000 ≈ ₭{(1000 * n).toLocaleString('en-US')}</div>
                <div>฿10,000 ≈ ₭{(10000 * n).toLocaleString('en-US')}</div>
                <div>₭1,000,000 ≈ ฿{Math.round(1000000 / n).toLocaleString('en-US')}</div>
              </div>
            )}
          </div>
          <div className="settings-section">
            <div className="settings-section-head">
              <Icon name="dot" size={14}/>
              <span>สกุลเงินที่แสดง</span>
            </div>
            <CurrencyToggle />
            <div style={{ fontSize: 11, color: 'var(--text-dim)', marginTop: 8 }}>
              กำลังแสดงผลใน <strong style={{ color: 'var(--accent)' }}>{currency === 'LAK' ? 'กีบ (LAK)' : 'บาท (THB)'}</strong> · ข้อมูลทั้งหมดจัดเก็บภายในเป็นกีบเสมอ
            </div>
          </div>

          <div className="settings-section">
            <div className="settings-section-head">
              <Icon name="box" size={14}/>
              <span>บันทึกข้อมูล / อัพขึ้นฐานข้อมูล</span>
            </div>
            {stats && (
              <div className="db-stats">
                <div><span>ธุรกรรม</span><span>{stats.txCount.toLocaleString('en-US')}</span></div>
                <div><span>เงินลงทุน</span><span>{stats.invCount}</span></div>
                <div><span>ผู้ถือหุ้น</span><span>{stats.shCount}</span></div>
              </div>
            )}
            <div className="export-grid">
              <button className="export-btn" onClick={onExportSQL}>
                <div className="export-btn-icon" style={{ background: 'linear-gradient(135deg, #ffb547, #ffc878)' }}>
                  <svg width="22" height="22" viewBox="0 0 24 24" fill="none"><path d="M21 8v13H3V3h13l5 5z" stroke="#0a0d14" strokeWidth="2" strokeLinejoin="round"/><path d="M14 3v6h6" stroke="#0a0d14" strokeWidth="2"/><text x="7" y="17" font-family="monospace" font-size="6" font-weight="700" fill="#0a0d14">SQL</text></svg>
                </div>
                <div className="export-btn-text">
                  <strong>Export SQL</strong>
                  <span>INSERT statements — อัพขึ้น DB ได้เลย</span>
                </div>
              </button>
              <button className="export-btn" onClick={onExportJSON}>
                <div className="export-btn-icon" style={{ background: 'linear-gradient(135deg, #60a5fa, #3b82f6)' }}>
                  <svg width="22" height="22" viewBox="0 0 24 24" fill="none"><path d="M21 8v13H3V3h13l5 5z" stroke="#0a0d14" strokeWidth="2" strokeLinejoin="round"/><text x="6" y="16" font-family="monospace" font-size="5" font-weight="700" fill="#0a0d14">JSON</text></svg>
                </div>
                <div className="export-btn-text">
                  <strong>Export JSON</strong>
                  <span>สำรองข้อมูลทั้งหมด</span>
                </div>
              </button>
              <label className="export-btn">
                <div className="export-btn-icon" style={{ background: 'linear-gradient(135deg, #22d3a3, #14b88a)' }}>
                  <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="#0a0d14" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M21 15v4a2 2 0 01-2 2H5a2 2 0 01-2-2v-4M17 8l-5-5-5 5M12 3v12"/></svg>
                </div>
                <div className="export-btn-text">
                  <strong>Import JSON</strong>
                  <span>นำเข้าข้อมูลที่ export ไว้</span>
                </div>
                <input type="file" accept=".json,application/json" style={{ display: 'none' }} onChange={e => {
                  if (e.target.files[0]) onImportJSON(e.target.files[0]);
                  e.target.value = '';
                }}/>
              </label>
            </div>
            <div className="db-help">
              <strong>วิธีอัพขึ้น database</strong>
              <ol>
                <li>รัน <code>database/schema.sql</code> ใน phpMyAdmin / Supabase เพื่อสร้างตาราง</li>
                <li>กด <em>Export SQL</em> เพื่อดาวน์โหลดข้อมูลปัจจุบัน</li>
                <li>อัพโหลดไฟล์ขึ้น DB — เสร็จ</li>
              </ol>
            </div>
          </div>

          <div className="settings-section danger-zone">
            <div className="settings-section-head" style={{ color: 'var(--neg)' }}>
              <Icon name="trash" size={14}/>
              <span>ล้างข้อมูลทั้งหมด</span>
            </div>
            <div style={{ fontSize: 11.5, color: 'var(--text-muted)', lineHeight: 1.6 }}>
              ล้างธุรกรรม เงินลงทุน และผู้ถือหุ้นทั้งหมด — เพื่อเริ่มต้นจากศูนย์<br/>
              <strong style={{ color: 'var(--neg)' }}>ไม่สามารถย้อนกลับได้</strong> — แนะนำให้ Export SQL/JSON ไว้ก่อน
            </div>
            <button className="btn-danger-full" onClick={onClearAll}>
              <Icon name="trash" size={14}/> ล้างข้อมูลทั้งหมด
            </button>
          </div>
        </div>
        <div className="modal-foot">
          <button className="btn-ghost" onClick={onClose}>ยกเลิก</button>
          <button className="btn-primary" onClick={save} disabled={!valid}>
            <Icon name="bolt" size={14}/> บันทึก
          </button>
        </div>
      </div>
    </div>
  );
}

// ===== Shareholder management modal =====
function ShareholderModal({ shareholders, mgmtFeePct, setShareholders, setMgmtFeePct, onClose }) {
  const [fee, setFee] = useState(String(mgmtFeePct));
  const [list, setList] = useState(() => shareholders.map(x => ({ ...x })));
  const totalPct = list.reduce((s, x) => s + (Number(x.pct) || 0), 0);
  const valid = Math.abs(totalPct - 100) < 0.01;

  function update(idx, key, value) {
    setList(prev => prev.map((x, i) => i === idx ? { ...x, [key]: value } : x));
  }
  function add() {
    const nextId = 'sh-' + (Date.now().toString(36).slice(-5));
    setList(prev => [...prev, { id: nextId, name: '', pct: 0 }]);
  }
  function remove(idx) {
    setList(prev => prev.filter((_, i) => i !== idx));
  }
  function distributeEvenly() {
    if (list.length === 0) return;
    const each = +(100 / list.length).toFixed(2);
    setList(prev => prev.map((x, i) => ({ ...x, pct: i === prev.length - 1 ? +(100 - each * (prev.length - 1)).toFixed(2) : each })));
  }
  function save() {
    if (!valid) return;
    const f = Math.max(0, Math.min(100, parseFloat(fee) || 0));
    setMgmtFeePct(f);
    setShareholders(list.filter(x => (x.name || '').trim() !== ''));
    onClose();
  }

  return (
    <div className="modal-overlay" onClick={onClose}>
      <div className="modal" style={{ maxWidth: 640 }} onClick={e => e.stopPropagation()}>
        <div className="modal-head">
          <div>
            <div className="modal-title">จัดการผู้ถือหุ้น</div>
            <div className="modal-sub">ปรับสัดส่วนหุ้น (%) และค่าบริหาร · รวมต้อง = 100%</div>
          </div>
          <button className="icon-btn" onClick={onClose}><Icon name="x"/></button>
        </div>
        <div className="modal-body">
          <div className="field">
            <label>ค่าบริหาร (Management Fee) %</label>
            <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
              <input
                type="range" min="0" max="100" step="1"
                value={fee} onChange={e => setFee(e.target.value)}
                style={{ flex: 1 }}
              />
              <div style={{ display: 'flex', alignItems: 'center', gap: 4, width: 90 }}>
                <input type="number" value={fee} onChange={e => setFee(e.target.value)} style={{ width: 60, textAlign: 'right' }} min="0" max="100" />
                <span style={{ fontFamily: "'IBM Plex Mono', monospace", color: 'var(--accent)' }}>%</span>
              </div>
            </div>
            <div style={{ fontSize: 11, color: 'var(--text-dim)' }}>
              หักก่อนแบ่งให้ผู้ถือหุ้น · เหลือ <strong style={{ color: '#22d3a3' }}>{(100 - (parseFloat(fee) || 0)).toFixed(0)}%</strong> สำหรับแบ่งหุ้น
            </div>
          </div>
          <div className="sh-edit-header">
            <span>ผู้ถือหุ้น</span>
            <span className={`sh-edit-total ${valid ? 'ok' : 'bad'}`}>
              รวม {totalPct.toFixed(1)}% / 100%
              {!valid && ' ⚠'}
            </span>
          </div>
          <div className="sh-edit-list">
            {list.map((sh, i) => (
              <div key={sh.id} className="sh-edit-row">
                <input
                  type="text" value={sh.name} placeholder="ชื่อผู้ถือหุ้น"
                  onChange={e => update(i, 'name', e.target.value)}
                  style={{ flex: 1 }}
                />
                <div className="sh-edit-pct">
                  <input
                    type="number" value={sh.pct} step="0.1" min="0" max="100"
                    onChange={e => update(i, 'pct', parseFloat(e.target.value) || 0)}
                    style={{ width: 70, textAlign: 'right' }}
                  />
                  <span style={{ fontFamily: "'IBM Plex Mono', monospace", color: 'var(--text-muted)' }}>%</span>
                </div>
                <button className="icon-btn-mini" onClick={() => remove(i)} title="ลบ"><Icon name="trash" size={12}/></button>
              </div>
            ))}
          </div>
          <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
            <button className="btn-ghost" onClick={add} style={{ fontSize: 11.5 }}><Icon name="plus" size={12}/> เพิ่มผู้ถือหุ้น</button>
            <button className="btn-ghost" onClick={distributeEvenly} style={{ fontSize: 11.5 }}><Icon name="percent" size={12}/> แบ่งเท่าๆ กัน</button>
          </div>
        </div>
        <div className="modal-foot">
          <button className="btn-ghost" onClick={onClose}>ยกเลิก</button>
          <button className="btn-primary" onClick={save} disabled={!valid}>
            <Icon name="bolt" size={14}/> บันทึก
          </button>
        </div>
      </div>
    </div>
  );
}

// Mount
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);
