// ============ REPORTS ============
const { Icon: Ico, formatBaht: fbR, formatNumber: fnR, StatCard: SCR, RevenueChart: RCR, Donut: DnR, Ring: RgR } = window.UI;
const Mr = window.MOCK;
const APIr = window.API;

function Reports() {
  const [period, setPeriod] = React.useState('30 ມື້');
  const [income, setIncome] = React.useState(Mr.income);
  const [expenses, setExpenses] = React.useState(Mr.expenses);
  const [employees, setEmployees] = React.useState(Mr.employees);
  const [monthlyProfit, setMonthlyProfit] = React.useState(Mr.monthlyProfit);

  React.useEffect(() => {
    Promise.all([
      APIr.income.list().catch(() => null),
      APIr.expenses.list().catch(() => null),
      APIr.employees.list().catch(() => null),
      APIr.monthlyProfit.list().catch(() => null),
    ]).then(([inc, exp, emp, mp]) => {
      if (inc) setIncome(inc);
      if (exp) setExpenses(exp);
      if (emp) setEmployees(emp);
      if (mp)  setMonthlyProfit(mp);
    });
  }, []);

  const totalRev = income.reduce((s, x) => s + x.amount, 0);
  const totalExp = expenses.reduce((s, x) => s + x.amount, 0);
  const totalSal = employees.reduce((s, e) => s + e.base + e.bonus, 0);
  const profit = totalRev - totalExp - totalSal;
  const margin = totalRev ? ((profit / totalRev) * 100).toFixed(1) : '0.0';

  // Tech performance
  const techStats = employees.map(e => {
    const jobs = income.filter(j => j.tech === e.id);
    const revenue = jobs.reduce((s, j) => s + j.amount, 0);
    return { ...e, jobs: jobs.length, revenue };
  }).sort((a, b) => b.revenue - a.revenue);
  const maxTechRev = Math.max(...techStats.map(t => t.revenue), 1);

  return (
    <div className="page">
      <div className="stat-grid" style={{ gridTemplateColumns: 'repeat(4, 1fr)' }}>
        <SCR label="ລາຍຮັບລວມ" value={totalRev} color="purple" icon={<Ico.Coin/>} isCurrency
          trend={{ dir: 'up', value: `${income.length} ບິນ`, label: '' }}/>
        <SCR label="ລາຍຈ່າຍ + ເງິນເດືອນ" value={totalExp + totalSal} color="cyan" icon={<Ico.Card/>} isCurrency
          trend={{ dir: 'up', value: fbR(totalSal), label: 'ຈາກ ເງິນເດືອນ' }}/>
        <SCR label="ກຳໄລສຸດທິ" value={profit} color="green" icon={<Ico.Trend/>} isCurrency
          trend={{ dir: 'up', value: `${margin}%`, label: 'ອັດຕາກຳໄລສຸດທິ' }}/>
        <SCR label="ມູນຄ່າຕໍ່ບິນສະເລ່ຍ" value={Math.round(income.length ? totalRev / income.length : 0)} color="amber" icon={<Ico.Wrench/>} isCurrency
          trend={{ dir: 'up', value: '+8%', label: 'ທຽບເດືອນກ່ອນ' }}/>
      </div>

      <div className="card" style={{ marginBottom: 16 }}>
        <div className="card-h">
          <div>
            <h3>ວິເຄາະລາຍຮັບ vs ຕົ້ນທຶນ (ລາຍຈ່າຍ + ເງິນເດືອນ)</h3>
            <div className="sub">ປຽບທຽບລາຍວັນ · ພຶດສະພາ 2026</div>
          </div>
          <div className="tabs">
            {['7 ມື້', '14 ມື້', '30 ມື້', 'ປີນີ້'].map(p => (
              <div key={p} className={`tab ${period === p ? 'active' : ''}`} onClick={() => setPeriod(p)}>{p}</div>
            ))}
          </div>
        </div>
        <RCR data={Mr.dailyTrend} height={280}/>
      </div>

      <MonthlyProfit
        monthlyProfit={monthlyProfit}
        currentRev={totalRev}
        currentExp={totalExp}
        currentSal={totalSal}
      />

      <div className="grid-2" style={{ marginBottom: 16 }}>
        <div className="card">
          <div className="card-h">
            <h3>ປະສິດທິພາບຊ່າງ</h3>
            <span className="chip cyan"><span className="dot"></span>ເດືອນນີ້</span>
          </div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 16, marginTop: 8 }}>
            {techStats.map((t, i) => (
              <div key={t.id}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 8 }}>
                  <div style={{
                    width: 22, height: 22, borderRadius: 6,
                    background: i === 0 ? 'var(--grad-pc)' : 'rgba(255,255,255,0.04)',
                    color: i === 0 ? 'white' : 'var(--ink-2)',
                    display: 'grid', placeItems: 'center',
                    fontSize: 11, fontWeight: 700,
                    border: '1px solid var(--line)'
                  }}>{i + 1}</div>
                  <div className={`emp-av ${t.avatar}`}>{t.initials}</div>
                  <div style={{ flex: 1 }}>
                    <div style={{ fontWeight: 500, fontSize: 13 }}>{t.name}</div>
                    <div style={{ fontSize: 11, color: 'var(--ink-3)' }}>{t.role}</div>
                  </div>
                  <div style={{ textAlign: 'right' }}>
                    <div className="mono" style={{ fontWeight: 700, color: '#a78bfa' }}>{fbR(t.revenue)}</div>
                    <div style={{ fontSize: 11, color: 'var(--ink-3)' }}>{t.jobs} ວຽກ</div>
                  </div>
                </div>
                <div className="progress">
                  <span style={{ width: `${(t.revenue / maxTechRev) * 100}%` }}></span>
                </div>
              </div>
            ))}
          </div>
        </div>

        <div className="card">
          <div className="card-h">
            <h3>ສະຫຼຸບກຳໄລ / ຂາດທຶນ</h3>
            <span className="chip green"><span className="dot"></span>ມີກຳໄລ</span>
          </div>
          <div style={{ marginTop: 8 }}>
            <div className="summary-row">
              <span className="label">ລາຍຮັບຈາກວຽກສ້ອມ</span>
              <span className="val" style={{ color: '#a78bfa' }}>+{fbR(totalRev)}</span>
            </div>
            <div className="summary-row">
              <span className="label">ຫັກ ຄ່າອາໄຫຼ່ແລະວັດສະດຸ</span>
              <span className="val" style={{ color: '#22d3ee' }}>−{fbR(expenses.filter(e => e.category === 'ອາໄຫຼ່').reduce((s,x)=>s+x.amount,0))}</span>
            </div>
            <div className="summary-row">
              <span className="label">ຫັກ ຄ່າໃຊ້ຈ່າຍຮ້ານ</span>
              <span className="val" style={{ color: '#22d3ee' }}>−{fbR(expenses.filter(e => e.category === 'ຄ່າໃຊ້ຈ່າຍຮ້ານ').reduce((s,x)=>s+x.amount,0))}</span>
            </div>
            <div className="summary-row">
              <span className="label">ຫັກ ການຕະຫຼາດ/ອຸປະກອນ</span>
              <span className="val" style={{ color: '#22d3ee' }}>−{fbR(expenses.filter(e => !['ອາໄຫຼ່','ຄ່າໃຊ້ຈ່າຍຮ້ານ'].includes(e.category)).reduce((s,x)=>s+x.amount,0))}</span>
            </div>
            <div className="summary-row">
              <span className="label">ຫັກ ເງິນເດືອນພະນັກງານ</span>
              <span className="val" style={{ color: '#22d3ee' }}>−{fbR(totalSal)}</span>
            </div>
            <div style={{
              marginTop: 18,
              padding: 16,
              borderRadius: 12,
              background: 'linear-gradient(135deg, rgba(16,185,129,0.10), rgba(124,58,237,0.06))',
              border: '1px solid rgba(16,185,129,0.20)',
              display: 'flex', alignItems: 'center', justifyContent: 'space-between'
            }}>
              <div>
                <div style={{ fontSize: 11.5, color: 'var(--ink-2)', letterSpacing: '0.08em', textTransform: 'uppercase' }}>ກຳໄລສຸດທິ</div>
                <div style={{ fontSize: 11.5, color: 'var(--ink-3)', marginTop: 2 }}>Net Profit Margin {margin}%</div>
              </div>
              <div className="mono" style={{ fontSize: 26, fontWeight: 800, color: '#34d399' }}>{fbR(profit)}</div>
            </div>
          </div>
        </div>
      </div>

      <div className="grid-2">
        <div className="card">
          <div className="card-h">
            <h3>ສັດສ່ວນປະເພດວຽກສ້ອມ</h3>
            <span className="chip purple"><span className="dot"></span>{income.length} ວຽກ</span>
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 24 }}>
            <div style={{ position: 'relative' }}>
              <DnR data={Mr.categoryMix} size={180}/>
              <div style={{ position: 'absolute', inset: 0, display: 'grid', placeItems: 'center', textAlign: 'center' }}>
                <div>
                  <div className="mono" style={{ fontSize: 24, fontWeight: 700, color: '#a78bfa' }}>{Mr.categoryMix[0].value}%</div>
                  <div style={{ fontSize: 10.5, color: 'var(--ink-2)' }}>{Mr.categoryMix[0].name}</div>
                </div>
              </div>
            </div>
            <div style={{ flex: 1, display: 'flex', flexDirection: 'column', gap: 10 }}>
              {Mr.categoryMix.map(c => (
                <div key={c.name} style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', fontSize: 12.5 }}>
                  <span style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                    <span style={{ width: 10, height: 10, borderRadius: 3, background: c.color }}></span>
                    {c.name}
                  </span>
                  <span className="mono" style={{ fontWeight: 600 }}>{c.value}%</span>
                </div>
              ))}
            </div>
          </div>
        </div>

        <div className="card">
          <div className="card-h">
            <h3>ລູກຄ້າໃຊ້ບໍລິການຫຼາຍສຸດ</h3>
            <span className="chip cyan"><span className="dot"></span>Top 5</span>
          </div>
          <table>
            <thead><tr><th>ລູກຄ້າ</th><th>ວຽກ</th><th style={{textAlign:'right'}}>ມູນຄ່າລວມ</th></tr></thead>
            <tbody>
              {(() => {
                const byCust = {};
                income.forEach(j => {
                  if (!byCust[j.customer]) byCust[j.customer] = { jobs: 0, amount: 0 };
                  byCust[j.customer].jobs += 1;
                  byCust[j.customer].amount += j.amount;
                });
                return Object.entries(byCust)
                  .map(([name, v]) => ({ name, ...v }))
                  .sort((a, b) => b.amount - a.amount)
                  .slice(0, 5);
              })().map((c, i) => (
                <tr key={c.name}>
                  <td>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                      <div style={{ width: 28, height: 28, borderRadius: '50%', background: `hsl(${260 - i*30}, 70%, 55%)`, display: 'grid', placeItems: 'center', fontSize: 10.5, fontWeight: 700 }}>{c.name.split(' ')[0].replace(/ທ້າວ|ນາງ|ຄຸນ/g,'').slice(0,2)}</div>
                      <span style={{ fontWeight: 500 }}>{c.name}</span>
                    </div>
                  </td>
                  <td><span className="chip purple"><span className="dot"></span>{c.jobs} ຄັ້ງ</span></td>
                  <td className="mono" style={{ textAlign: 'right', fontWeight: 600 }}>{fbR(c.amount)}</td>
                </tr>
              ))}
              {income.length === 0 && (
                <tr><td colSpan="3" style={{ textAlign: 'center', padding: '24px', color: 'var(--ink-3)' }}>ບໍ່ມີຂໍ້ມູນ</td></tr>
              )}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
}

// ============ MONTHLY PROFIT ============
function MonthlyProfit({ monthlyProfit, currentRev, currentExp, currentSal }) {
  const rows = monthlyProfit.map(m => {
    if (m.current) {
      const rev = currentRev, exp = currentExp, sal = currentSal;
      return { ...m, revenue: rev, expenses: exp, salary: sal, profit: rev - exp - sal };
    }
    return { ...m, profit: m.revenue - m.expenses - m.salary };
  });
  const maxAbs = Math.max(...rows.map(r => Math.abs(r.profit)), 1);
  const best = rows.reduce((b, r) => (r.profit > b.profit ? r : b), rows[0]);
  const worst = rows.reduce((w, r) => (r.profit < w.profit ? r : w), rows[0]);
  const avg = rows.reduce((s, r) => s + r.profit, 0) / (rows.length || 1);
  const sumProfit = rows.reduce((s, r) => s + r.profit, 0);

  return (
    <div className="card" style={{ marginBottom: 16 }}>
      <div className="card-h">
        <div>
          <h3>ກຳໄລສຸດທິລາຍເດືອນ</h3>
          <div className="sub">ປຽບທຽບກຳໄລ 6 ເດືອນຫຼ້າສຸດ · ລາຍຮັບ − ລາຍຈ່າຍ − ເງິນເດືອນ</div>
        </div>
        <span className="chip green"><span className="dot"></span>ສະເລ່ຍ {fbR(Math.round(avg))} / ເດືອນ</span>
      </div>

      <table>
        <thead>
          <tr>
            <th>ເດືອນ</th>
            <th style={{ textAlign: 'right' }}>ລາຍຮັບ</th>
            <th style={{ textAlign: 'right' }}>ລາຍຈ່າຍ</th>
            <th style={{ textAlign: 'right' }}>ເງິນເດືອນ</th>
            <th style={{ textAlign: 'right' }}>ກຳໄລສຸດທິ</th>
            <th style={{ width: 220 }}>ທຽບສັດສ່ວນ</th>
          </tr>
        </thead>
        <tbody>
          {rows.map(r => {
            const isProfit = r.profit >= 0;
            const pct = (Math.abs(r.profit) / maxAbs) * 100;
            const margin = r.revenue ? ((r.profit / r.revenue) * 100).toFixed(1) : '0.0';
            return (
              <tr key={r.key} style={r.current ? { background: 'rgba(124,58,237,0.06)' } : {}}>
                <td>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                    <div style={{
                      width: 36, height: 36, borderRadius: 10,
                      background: r.current ? 'var(--grad-pc)' : 'rgba(255,255,255,0.04)',
                      color: r.current ? 'white' : 'var(--ink-2)',
                      display: 'grid', placeItems: 'center',
                      fontSize: 11, fontWeight: 700, letterSpacing: '0.05em',
                      border: '1px solid var(--line)'
                    }}>{r.label.split(' ')[0].slice(0, 3)}</div>
                    <div>
                      <div style={{ fontWeight: 500 }}>{r.label}</div>
                      <div style={{ fontSize: 11, color: 'var(--ink-3)' }}>
                        {r.current ? 'ເດືອນປັດຈຸບັນ' : `Margin ${margin}%`}
                        {r === best && !r.current ? ' · 🏆 ສູງສຸດ' : ''}
                        {r === worst && !r.current ? ' · ຕ່ຳສຸດ' : ''}
                      </div>
                    </div>
                  </div>
                </td>
                <td className="mono" style={{ textAlign: 'right', color: '#a78bfa' }}>{fbR(r.revenue)}</td>
                <td className="mono" style={{ textAlign: 'right', color: '#22d3ee' }}>−{fbR(r.expenses)}</td>
                <td className="mono" style={{ textAlign: 'right', color: '#fbbf24' }}>−{fbR(r.salary)}</td>
                <td className="mono" style={{ textAlign: 'right', fontWeight: 700, color: isProfit ? '#34d399' : '#fb7185', fontSize: 14 }}>
                  {isProfit ? '+' : ''}{fbR(r.profit)}
                </td>
                <td>
                  <div className="progress">
                    <span style={{
                      width: `${pct}%`,
                      background: isProfit
                        ? 'linear-gradient(90deg, #10b981, #34d399)'
                        : 'linear-gradient(90deg, #f43f5e, #fb7185)'
                    }}></span>
                  </div>
                  <div style={{ fontSize: 10.5, color: 'var(--ink-3)', marginTop: 4, textAlign: 'right' }}>
                    {isProfit ? 'ກຳໄລ' : 'ຂາດທຶນ'} {Math.round(pct)}% ຂອງເດືອນທີ່ດີທີ່ສຸດ
                  </div>
                </td>
              </tr>
            );
          })}
        </tbody>
        <tfoot>
          <tr style={{ background: 'rgba(16,185,129,0.05)' }}>
            <td style={{ padding: '14px 18px', fontWeight: 700 }} colSpan="4">
              ລວມ {rows.length} ເດືອນ · ກຳໄລສະສົມ
            </td>
            <td className="mono" style={{ textAlign: 'right', padding: '14px 18px', fontWeight: 800, fontSize: 15, color: sumProfit >= 0 ? '#34d399' : '#fb7185' }}>
              {sumProfit >= 0 ? '+' : ''}{fbR(sumProfit)}
            </td>
            <td></td>
          </tr>
        </tfoot>
      </table>
    </div>
  );
}

// ============ STOCK ============
function Stock() {
  const [filter, setFilter] = React.useState('ທັງໝົດ');
  const [inventory, setInventory] = React.useState(Mr.inventory);
  const [editItem, setEditItem] = React.useState(null);
  const [addOpen, setAddOpen] = React.useState(false);
  const [removing, setRemoving] = React.useState(null);

  React.useEffect(() => {
    APIr.inventory.list().then(setInventory).catch(() => {});
  }, []);

  const cats = ['ທັງໝົດ', ...new Set(inventory.map(i => i.cat))];
  const filtered = filter === 'ທັງໝົດ' ? inventory : inventory.filter(x => x.cat === filter);
  const totalStock = inventory.reduce((s, x) => s + x.stock, 0);
  const totalValue = inventory.reduce((s, x) => s + x.stock * x.cost, 0);
  const lowStock = inventory.filter(x => x.stock <= x.min).length;

  const handleSave = async (item) => {
    if (item.sku) {
      // UPDATE
      const payload = { name: item.name, cat: item.cat, cost: item.cost, price: item.price, stock: item.stock, min: item.min };
      try {
        const updated = await APIr.inventory.update(item.sku, payload);
        setInventory(inventory.map(x => x.sku === item.sku ? updated : x));
      } catch (e) {
        setInventory(inventory.map(x => x.sku === item.sku ? item : x));
      }
    } else {
      // CREATE
      try {
        const created = await APIr.inventory.create(item);
        setInventory([...inventory, created]);
      } catch (e) {
        const seq = (inventory.length + 1).toString().padStart(3, '0');
        setInventory([...inventory, { ...item, sku: `SKU-LOCAL-${seq}` }]);
      }
    }
    setEditItem(null);
    setAddOpen(false);
  };

  const handleDelete = async (sku) => {
    if (!window.confirm('ຢືນຢັນລົບອາໄຫຼ່ນີ້?')) return;
    setRemoving(sku);
    try { await APIr.inventory.remove(sku); } catch (e) { console.warn(e); }
    setTimeout(() => {
      setInventory(prev => prev.filter(x => x.sku !== sku));
      setRemoving(null);
    }, 240);
  };

  return (
    <div className="page">
      <div className="stat-grid" style={{ gridTemplateColumns: 'repeat(4, 1fr)' }}>
        <SCR label="SKU ທັງໝົດ" value={inventory.length} color="purple" icon={<Ico.Box/>}
          trend={{ dir: 'up', value: `${cats.length - 1} ໝວດ`, label: '' }}/>
        <SCR label="ອັນໃນສະຕັອກ" value={totalStock} color="cyan" icon={<Ico.Stock/>}
          trend={{ dir: 'up', value: 'ທຸກໝວດ', label: 'ນັບລວມ' }}/>
        <SCR label="ມູນຄ່າສະຕັອກ (ຕົ້ນທຶນ)" value={totalValue} color="green" icon={<Ico.Coin/>} isCurrency
          trend={{ dir: 'up', value: 'ອັບເດດ', label: 'ລາຄາທຶນປັດຈຸບັນ' }}/>
        <SCR label="ແຈ້ງເຕືອນໃກ້ໝົດ" value={lowStock} color="amber" icon={<Ico.Alert/>}
          trend={{ dir: 'up', value: 'ຮີບສັ່ງຊື້', label: '' }}/>
      </div>

      <div className="card">
        <div className="card-h">
          <div className="tabs">
            {cats.map(c => <div key={c} className={`tab ${filter === c ? 'active' : ''}`} onClick={() => setFilter(c)}>{c}</div>)}
          </div>
          <div style={{ display: 'flex', gap: 10 }}>
            <button className="btn"><Ico.Download/> Export</button>
            <button className="btn btn-primary" onClick={() => setAddOpen(true)}><Ico.Plus/> ເພີ່ມອາໄຫຼ່</button>
          </div>
        </div>
        <table>
          <thead>
            <tr>
              <th>SKU</th><th>ຊື່ອາໄຫຼ່</th><th>ໝວດ</th><th style={{textAlign:'right'}}>ຕົ້ນທຶນ</th><th style={{textAlign:'right'}}>ລາຄາຂາຍ</th><th style={{textAlign:'right'}}>ກຳໄລ/ອັນ</th><th>ຄົງເຫຼືອ</th><th>ລະດັບສະຕັອກ</th><th style={{ textAlign: 'right', width: 150 }}>ການຈັດການ</th>
            </tr>
          </thead>
          <tbody>
            {filtered.map(item => {
              const margin = item.price - item.cost;
              const pct = Math.min(100, (item.stock / (item.min * 2)) * 100);
              const isLow = item.stock <= item.min;
              return (
                <tr key={item.sku} className={removing === item.sku ? 'removing' : ''}>
                  <td className="mono" style={{ fontSize: 12, color: 'var(--ink-2)' }}>{item.sku}</td>
                  <td style={{ fontWeight: 500 }}>{item.name}</td>
                  <td><span className="chip purple"><span className="dot"></span>{item.cat}</span></td>
                  <td className="mono" style={{ textAlign: 'right', color: 'var(--ink-2)' }}>{fbR(item.cost)}</td>
                  <td className="mono" style={{ textAlign: 'right', fontWeight: 600 }}>{fbR(item.price)}</td>
                  <td className="mono" style={{ textAlign: 'right', color: '#34d399', fontWeight: 600 }}>+{fbR(margin)}</td>
                  <td>
                    <span className={`chip ${isLow ? 'red' : 'green'}`}>
                      <span className="dot"></span>
                      <span className="mono">{item.stock}</span> ອັນ
                    </span>
                  </td>
                  <td style={{ width: 160 }}>
                    <div className="progress">
                      <span style={{
                        width: `${pct}%`,
                        background: isLow ? 'linear-gradient(90deg, #f43f5e, #f59e0b)' : 'var(--grad-pc)'
                      }}></span>
                    </div>
                    <div style={{ fontSize: 10.5, color: 'var(--ink-3)', marginTop: 4 }}>ຂັ້ນຕ່ຳ <span className="mono">{item.min}</span></div>
                  </td>
                  <td style={{ textAlign: 'right' }}>
                    <div style={{ display: 'flex', gap: 6, justifyContent: 'flex-end' }}>
                      <button className="btn" style={{ fontSize: 12 }} onClick={() => setEditItem(item)}>ແກ້ໄຂ</button>
                      <button className="icon-btn danger" title="ລົບອາໄຫຼ່" onClick={() => handleDelete(item.sku)}>
                        <Ico.Trash/>
                      </button>
                    </div>
                  </td>
                </tr>
              );
            })}
            {filtered.length === 0 && (
              <tr><td colSpan="9" style={{ textAlign: 'center', padding: '32px', color: 'var(--ink-3)' }}>ບໍ່ມີອາໄຫຼ່ໃນໝວດນີ້ — ກົດປຸ່ມ "ເພີ່ມອາໄຫຼ່" ເພື່ອເລີ່ມຕົ້ນ</td></tr>
            )}
          </tbody>
        </table>
      </div>

      {(addOpen || editItem) && (
        <InventoryModal
          item={editItem}
          onClose={() => { setAddOpen(false); setEditItem(null); }}
          onSave={handleSave}
        />
      )}
    </div>
  );
}

function InventoryModal({ item, onClose, onSave }) {
  const isEdit = !!item;
  const [name, setName]   = React.useState(item?.name || '');
  const [cat, setCat]     = React.useState(item?.cat || '');
  const [cost, setCost]   = React.useState(item?.cost ?? '');
  const [price, setPrice] = React.useState(item?.price ?? '');
  const [stock, setStock] = React.useState(item?.stock ?? '');
  const [min, setMin]     = React.useState(item?.min ?? '');
  const [error, setError] = React.useState('');
  const [saving, setSaving] = React.useState(false);

  const handleSave = async () => {
    if (!name.trim() || !cat.trim() || cost === '' || price === '' || stock === '' || min === '') {
      setError('ກະລຸນາປ້ອນຂໍ້ມູນໃຫ້ຄົບທຸກຊ່ອງ');
      return;
    }
    const costN  = Number(String(cost).replace(/,/g, ''));
    const priceN = Number(String(price).replace(/,/g, ''));
    const stockN = Number(String(stock).replace(/,/g, ''));
    const minN   = Number(String(min).replace(/,/g, ''));
    if ([costN, priceN, stockN, minN].some(n => isNaN(n) || n < 0)) {
      setError('ຕົວເລກບໍ່ຖືກຕ້ອງ (ຕ້ອງເປັນຈຳນວນບວກ)');
      return;
    }
    setSaving(true);
    await onSave({
      ...(item || {}),
      name: name.trim(),
      cat: cat.trim(),
      cost: costN,
      price: priceN,
      stock: stockN,
      min: minN,
    });
  };

  return (
    <window.UI.Modal
      title={isEdit ? 'ແກ້ໄຂອາໄຫຼ່' : 'ເພີ່ມອາໄຫຼ່ໃໝ່'}
      subtitle={isEdit ? `${item.sku} · ປັບລາຍລະອຽດ / ສະຕັອກ` : 'ປ້ອນຂໍ້ມູນອາໄຫຼ່ໃໝ່'}
      onClose={onClose}
      footer={<>
        {error && <span style={{ color: '#fb7185', fontSize: 12, marginRight: 'auto' }}>{error}</span>}
        <button className="btn" onClick={onClose}>ຍົກເລີກ</button>
        <button className="btn btn-primary" onClick={handleSave} disabled={saving}>
          <Ico.Check/> {saving ? 'ກຳລັງບັນທຶກ...' : (isEdit ? 'ບັນທຶກການແກ້ໄຂ' : 'ເພີ່ມອາໄຫຼ່')}
        </button>
      </>}>
      <div className="form-grid">
        <div className="field full"><label>ຊື່ອາໄຫຼ່</label><input className="input" placeholder="ເຊັ່ນ ໜ້າຈໍ iPhone 14 Pro" value={name} onChange={e => setName(e.target.value)}/></div>
        <div className="field"><label>ໝວດ</label>
          <input className="input" list="cat-list" placeholder="ເລືອກ ຫຼື ພິມໝວດໃໝ່" value={cat} onChange={e => setCat(e.target.value)}/>
          <datalist id="cat-list">
            <option value="ໜ້າຈໍ"/>
            <option value="ແບັດເຕີຣີ"/>
            <option value="ກະຈົກຫຼັງ"/>
            <option value="ພອດສາກ"/>
            <option value="ລຳໂພງ"/>
            <option value="ອຸປະກອນເສີມ"/>
          </datalist>
        </div>
        <div className="field"><label>ຕົ້ນທຶນຕໍ່ອັນ (ກີບ)</label><input className="input mono" placeholder="0" value={cost} onChange={e => setCost(e.target.value)}/></div>
        <div className="field"><label>ລາຄາຂາຍ (ກີບ)</label><input className="input mono" placeholder="0" value={price} onChange={e => setPrice(e.target.value)}/></div>
        <div className="field"><label>ຈຳນວນຄົງເຫຼືອ</label><input className="input mono" placeholder="0" value={stock} onChange={e => setStock(e.target.value)}/></div>
        <div className="field"><label>ຂັ້ນຕ່ຳ (ແຈ້ງເຕືອນ)</label><input className="input mono" placeholder="0" value={min} onChange={e => setMin(e.target.value)}/></div>
      </div>
    </window.UI.Modal>
  );
}

window.PAGES_C = { Reports, Stock };
