// ============ Phase 2: Stock Management ============

// --- engine: คำนวณ balance จาก movements ---
function stockComputeBalance(db, stockItemId) {
  let onHand = 0;
  // ใช้ balance ที่บันทึกไว้ (ถ้ามี) เป็นจุดเริ่มต้น
  const saved = (db.stockBalances || []).find(b => b.stockItemId === stockItemId);
  if (saved) {
    onHand = Number(saved.onHand) || 0;
  } else {
    // คำนวณจาก movements ทั้งหมด
    (db.stockMovements || [])
      .filter(m => m.stockItemId === stockItemId)
      .forEach(m => { onHand += Number(m.qty) || 0; }); // qty+ = เข้า, qty- = ออก
  }
  return onHand;
}

function stockBuildItems(db) {
  const items = db.stockItems || [];
  return items.map(item => {
    const onHand = stockComputeBalance(db, item.id);
    const reorderPoint = Number(item.reorderPoint) || 0;
    const lowAlert = reorderPoint > 0 && onHand <= reorderPoint;
    const emptyAlert = onHand <= 0;
    return { ...item, onHand, reorderPoint, lowAlert, emptyAlert };
  });
}

function stockNewItem(db, refType, refId) {
  const id = nextCode(db.stockItems || [], 'STK');
  const ref =
    refType === 'ingredient' ? (db.ingredients || []).find(i => i.id === refId) :
    refType === 'package'    ? (db.packages    || []).find(p => p.id === refId) :
    null;
  return {
    id,
    refType: refType || 'ingredient',
    refId: refId || '',
    name: ref?.name || '',
    unit: ref?.unit || '',
    reorderPoint: 0,
    status: 'active',
  };
}

function stockApplyMovement(db, stockItemId, qty, movementType, note, refType, refId, atIso) {
  const mvId = nextCode(db.stockMovements || [], 'MOV');
  const mv = {
    id: mvId,
    stockItemId,
    movementType,
    qty: Number(qty),
    unit: (db.stockItems || []).find(s => s.id === stockItemId)?.unit || '',
    refType: refType || movementType,
    refId: refId || '',
    note: note || '',
    createdAt: atIso || new Date().toISOString(), // รองรับบิลย้อนหลัง: ใช้วันที่บนบิลถ้ามี
  };
  // อัปเดต balance
  const balances = (db.stockBalances || []).filter(b => b.stockItemId !== stockItemId);
  const current = (db.stockBalances || []).find(b => b.stockItemId === stockItemId);
  const newOnHand = (Number(current?.onHand) || 0) + Number(qty);
  balances.push({ stockItemId, onHand: newOnHand, lastUpdatedAt: new Date().toISOString() });
  return {
    stockMovements: [...(db.stockMovements || []), mv],
    stockBalances: balances,
  };
}

// --- helpers ---
function mvTypeLabel(type, qty) {
  if (type === 'receive') return 'รับเข้า';
  if (type === 'waste') return 'ตัดออก';
  if (type === 'adjust') return 'ปรับยอด';
  if (type === 'production') return 'ผลิต';
  if (type === 'sale') return 'ขาย';
  return qty >= 0 ? 'รับเข้า' : 'ตัดออก';
}
function mvTypeTone(type, qty) {
  if (type === 'receive') return 'green';
  if (type === 'waste') return 'red';
  if (type === 'adjust') return 'blue';
  if (type === 'production') return 'purple';
  if (type === 'sale') return 'orange';
  return qty >= 0 ? 'green' : 'red';
}
function fmtDateShort(iso) {
  if (!iso) return '-';
  const d = new Date(iso);
  return d.toLocaleDateString('th-TH', { day: '2-digit', month: 'short' }) + ' ' + d.toLocaleTimeString('th-TH', { hour: '2-digit', minute: '2-digit' });
}

// --- UI ---
function StockPage({ go }) {
  const { fdb: db, settings, setDb, logActivity, flash } = useData();
  const [tab, setTab] = React.useState('list');
  const [search, setSearch] = React.useState('');
  const [editItem, setEditItem] = React.useState(null);
  const [newModal, setNewModal] = React.useState(false);
  const [newForm, setNewForm] = React.useState({ refType: 'ingredient', refId: '', reorderPoint: 0 });
  const [mvModal, setMvModal] = React.useState(null); // null | { item, type:'receive'|'waste'|'adjust' }
  const [mvForm, setMvForm] = React.useState({ qty: 0, rawQty: '', inputUnit: '', note: '', purchaseCost: '', adjustTarget: '' });

  const th = settings?.uiLang !== 'en';
  const items = React.useMemo(() => stockBuildItems(db), [db]);
  const filtered = items.filter(item =>
    item.status !== 'inactive' &&
    (!search || item.name.toLowerCase().includes(search.toLowerCase()))
  );
  const alertItems = filtered.filter(i => i.lowAlert || i.emptyAlert);
  const okItems = filtered.filter(i => !i.lowAlert && !i.emptyAlert);

  // มูลค่าสต็อกรวม — ใช้ costPerUnit ของวัตถุดิบ/แพคเกจที่ ref ไว้
  const stockValue = React.useMemo(() => {
    return items.reduce((sum, item) => {
      let cpu = 0;
      if (item.refType === 'ingredient') {
        const ing = (db.ingredients || []).find(i => i.id === item.refId);
        cpu = Number(ing?.costPerUnit) || 0;
      } else if (item.refType === 'package') {
        const pkg = (db.packages || []).find(p => p.id === item.refId);
        cpu = Number(pkg?.costPerPiece) || 0;
      }
      return sum + item.onHand * cpu;
    }, 0);
  }, [items, db.ingredients, db.packages]);

  // สร้างรายการ ref options
  const ingOptions = (db.ingredients || []).map(i => ({ value: i.id, label: `${i.name} (${i.unit})`, unit: i.unit }));
  const pkgOptions = (db.packages || []).map(p => ({ value: p.id, label: `${p.name} (${p.unit || 'ชิ้น'})`, unit: p.unit || 'ชิ้น' }));
  const refOptions = newForm.refType === 'package' ? pkgOptions : ingOptions;

  const saveNewItem = () => {
    if (!newForm.refId) { flash('กรุณาเลือกวัตถุดิบ/แพคเกจ', 'err'); return; }
    const dup = (db.stockItems || []).find(s => s.refType === newForm.refType && s.refId === newForm.refId);
    if (dup) { flash(`${dup.name} มีในสต็อกแล้ว`, 'err'); return; }
    const item = stockNewItem(db, newForm.refType, newForm.refId);
    item.reorderPoint = Number(newForm.reorderPoint) || 0;
    setDb(prev => ({ ...prev, stockItems: [...(prev.stockItems || []), item] }));
    if (logActivity) logActivity('stock.item_added', { entityType: 'stockItem', entityId: item.id, note: item.name });
    flash(`เพิ่ม ${item.name} ในสต็อกแล้ว`);
    setNewModal(false);
    setNewForm({ refType: 'ingredient', refId: '', reorderPoint: 0 });
  };

  const saveEditItem = () => {
    setDb(prev => ({
      ...prev,
      stockItems: (prev.stockItems || []).map(s => s.id === editItem.id ? { ...s, reorderPoint: Number(editItem.reorderPoint) || 0, status: editItem.status } : s),
    }));
    flash('บันทึกแล้ว');
    setEditItem(null);
  };

  const openMv = (item, type) => {
    setMvModal({ item, type });
    setMvForm({ qty: 0, rawQty: '', inputUnit: item.unit || '', note: '', purchaseCost: '', adjustTarget: String(item.onHand || 0) });
  };

  const saveMv = () => {
    const type = mvModal.type;
    if (type === 'adjust') {
      const target = Number(mvForm.adjustTarget);
      if (isNaN(target) || target < 0) { flash('กรุณาใส่ยอดคงเหลือจริง', 'err'); return; }
      const current = mvModal.item.onHand;
      const diff = target - current;
      const updates = stockApplyMovement(db, mvModal.item.id, diff, 'adjust', mvForm.note || `ปรับยอด: ${current} → ${target}`);
      setDb(prev => ({ ...prev, ...updates }));
      if (logActivity) logActivity('stock.adjust', { entityType: 'stockItem', entityId: mvModal.item.id, note: `ปรับยอด ${current} → ${target} ${mvModal.item.unit}` });
      flash('ปรับยอดสต็อกแล้ว');
    } else {
      const qty = Number(mvForm.qty);
      if (!qty || qty <= 0) { flash('กรุณาใส่จำนวนที่ถูกต้อง', 'err'); return; }
      const signedQty = type === 'waste' ? -qty : qty;
      const updates = stockApplyMovement(db, mvModal.item.id, signedQty, type, mvForm.note);
      // ถ้า receive + ใส่ราคา → สร้าง purchaseEvent
      const purchaseCost = Number(mvForm.purchaseCost);
      const newUpdates = { ...updates };
      if (type === 'receive' && purchaseCost > 0) {
        const peId = nextCode(db.purchaseEvents || [], 'PEV');
        newUpdates.purchaseEvents = [...(db.purchaseEvents || []), {
          id: peId,
          stockItemId: mvModal.item.id,
          qty,
          unitCost: purchaseCost / qty,
          totalCost: purchaseCost,
          supplier: '',
          receivedAt: new Date().toISOString(),
          note: mvForm.note || '',
        }];
      }
      setDb(prev => ({ ...prev, ...newUpdates }));
      const label = type === 'waste' ? 'ตัดออก' : 'รับเข้า';
      if (logActivity) logActivity(`stock.${type}`, { entityType: 'stockItem', entityId: mvModal.item.id, note: `${label} ${qty} ${mvModal.item.unit}` });
      flash(`บันทึก${label}แล้ว`);
    }
    setMvModal(null);
  };

  const movements = React.useMemo(() => {
    return (db.stockMovements || [])
      .slice()
      .sort((a, b) => String(b.createdAt).localeCompare(String(a.createdAt)))
      .slice(0, 100)
      .map(mv => {
        const item = (db.stockItems || []).find(s => s.stockItemId === mv.stockItemId || s.id === mv.stockItemId);
        return { ...mv, itemName: item?.name || mv.stockItemId };
      });
  }, [db.stockMovements, db.stockItems]);

  const toneRow = item => item.emptyAlert ? 'red' : item.lowAlert ? 'orange' : 'green';

  const TabBtn = ({ id, label }) => (
    <button onClick={() => setTab(id)} style={{
      padding: '7px 18px', borderRadius: 999, fontSize: 13.5, fontWeight: 600, cursor: 'pointer', border: 'none',
      background: tab === id ? 'var(--accent)' : 'var(--chip)',
      color: tab === id ? '#fff' : 'var(--ink-2)',
    }}>{label}</button>
  );

  return (
    <div className="view-enter" style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>

      {/* Summary bar */}
      <div className="r-2col" style={{ display: 'grid', gridTemplateColumns: 'repeat(4,1fr)', gap: 12 }}>
        <Card pad={16}>
          <div style={{ fontSize: 12.5, color: 'var(--ink-3)', marginBottom: 4 }}>รายการทั้งหมด</div>
          <div className="tnum" style={{ fontSize: 26, fontWeight: 800, color: 'var(--accent)' }}>{window.fmt(filtered.length)}</div>
        </Card>
        <Card pad={16}>
          <div style={{ fontSize: 12.5, color: 'var(--ink-3)', marginBottom: 4 }}>ใกล้หมด / หมดแล้ว</div>
          <div className="tnum" style={{ fontSize: 26, fontWeight: 800, color: alertItems.length > 0 ? 'var(--red)' : 'var(--green)' }}>{window.fmt(alertItems.length)}</div>
        </Card>
        <Card pad={16}>
          <div style={{ fontSize: 12.5, color: 'var(--ink-3)', marginBottom: 4 }}>มูลค่าสต็อกรวม</div>
          <div className="tnum" style={{ fontSize: 22, fontWeight: 800, color: 'var(--green)' }}>{window.fmtB(stockValue, 0)}</div>
        </Card>
        <Card pad={16}>
          <div style={{ fontSize: 12.5, color: 'var(--ink-3)', marginBottom: 4 }}>บันทึกทั้งหมด</div>
          <div className="tnum" style={{ fontSize: 26, fontWeight: 800, color: 'var(--ink-2)' }}>{window.fmt((db.stockMovements || []).length)}</div>
        </Card>
      </div>

      {/* Tabs + search + add */}
      <Card pad={18}>
        <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', alignItems: 'center', marginBottom: 14 }}>
          <TabBtn id="list" label="รายการสต็อก" />
          <TabBtn id="history" label="ประวัติเคลื่อนไหว" />
          <div style={{ flex: 1 }} />
          {tab === 'list' && (
            <>
              <input value={search} onChange={e => setSearch(e.target.value)} placeholder="ค้นหา..." style={{ padding: '7px 12px', borderRadius: 8, border: '1px solid var(--line)', fontSize: 13, background: 'var(--surface)', color: 'var(--ink)', width: 160 }} />
              <Button icon="plus" size="sm" onClick={() => setNewModal(true)}>เพิ่มรายการ</Button>
            </>
          )}
        </div>

        {tab === 'list' && (
          <>
            {alertItems.length > 0 && (
              <div style={{ marginBottom: 14 }}>
                <div style={{ fontSize: 13, fontWeight: 700, color: 'var(--red)', marginBottom: 8 }}>⚠️ ต้องดำเนินการ ({alertItems.length} รายการ)</div>
                <div style={{ display: 'grid', gap: 8 }}>
                  {alertItems.map(item => <StockRow key={item.id} item={item} onReceive={() => openMv(item, 'receive')} onWaste={() => openMv(item, 'waste')} onAdjust={() => openMv(item, 'adjust')} onEdit={() => setEditItem({ ...item })} />)}
                </div>
              </div>
            )}
            {okItems.length > 0 ? (
              <div style={{ display: 'grid', gap: 8 }}>
                {okItems.map(item => <StockRow key={item.id} item={item} onReceive={() => openMv(item, 'receive')} onWaste={() => openMv(item, 'waste')} onAdjust={() => openMv(item, 'adjust')} onEdit={() => setEditItem({ ...item })} />)}
              </div>
            ) : alertItems.length === 0 && (
              <Empty icon="layers" title="ยังไม่มีรายการสต็อก" sub="กดปุ่ม 'เพิ่มรายการ' เพื่อเริ่มติดตามวัตถุดิบที่ต้องการ" />
            )}
          </>
        )}

        {tab === 'history' && (
          movements.length > 0 ? (
            <div style={{ overflowX: 'auto' }}>
              <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13.5 }}>
                <thead><tr style={{ fontSize: 12, color: 'var(--ink-3)', fontWeight: 700 }}>
                  <th style={{ textAlign: 'left', padding: '8px 12px' }}>วัน/เวลา</th>
                  <th style={{ textAlign: 'left', padding: '8px 10px' }}>รายการ</th>
                  <th style={{ textAlign: 'center', padding: '8px 10px' }}>ประเภท</th>
                  <th style={{ textAlign: 'right', padding: '8px 10px' }}>จำนวน</th>
                  <th style={{ textAlign: 'left', padding: '8px 12px' }}>หมายเหตุ</th>
                </tr></thead>
                <tbody>{movements.map(mv => (
                  <tr key={mv.id} style={{ borderTop: '1px solid var(--line-2)' }}>
                    <td style={{ padding: '10px 12px', fontSize: 12, color: 'var(--ink-3)', whiteSpace: 'nowrap' }}>{fmtDateShort(mv.createdAt)}</td>
                    <td style={{ padding: '10px 10px', fontWeight: 600 }}>{mv.itemName}</td>
                    <td style={{ padding: '10px 10px', textAlign: 'center' }}>
                      <Badge tone={mvTypeTone(mv.movementType, mv.qty)}>{mvTypeLabel(mv.movementType, mv.qty)}</Badge>
                    </td>
                    <td className="tnum" style={{ padding: '10px 10px', textAlign: 'right', fontWeight: 700, color: mv.qty >= 0 ? 'var(--green)' : 'var(--red)' }}>
                      {mv.qty >= 0 ? '+' : ''}{mv.qty} {mv.unit}
                    </td>
                    <td style={{ padding: '10px 12px', color: 'var(--ink-3)', fontSize: 12.5 }}>{mv.note || '-'}</td>
                  </tr>
                ))}</tbody>
              </table>
            </div>
          ) : <Empty icon="doc" title="ยังไม่มีประวัติ" sub="เริ่มบันทึกรับเข้า/ตัดออกจากรายการสต็อก" />
        )}
      </Card>

      {/* Modal: เพิ่มรายการใหม่ */}
      <Modal open={newModal} onClose={() => setNewModal(false)} title="เพิ่มรายการสต็อก" width={480}
        footer={<div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end' }}><Button variant="secondary" onClick={() => setNewModal(false)}>ยกเลิก</Button><Button onClick={saveNewItem}>บันทึก</Button></div>}>
        <div style={{ display: 'grid', gap: 14 }}>
          <Field label="ประเภท">
            <Select value={newForm.refType} onChange={e => setNewForm(f => ({ ...f, refType: e.target.value, refId: '' }))} options={[{ value: 'ingredient', label: 'วัตถุดิบ' }, { value: 'package', label: 'แพคเกจ' }]} />
          </Field>
          <Field label={newForm.refType === 'package' ? 'แพคเกจ' : 'วัตถุดิบ'}>
            <Select value={newForm.refId} onChange={e => setNewForm(f => ({ ...f, refId: e.target.value }))} placeholder="-- เลือก --" options={refOptions} />
          </Field>
          <Field label="จุดสั่งซื้อ (แจ้งเตือนเมื่อคงเหลือถึงระดับนี้)" hint="ใส่ 0 ถ้าไม่ต้องการแจ้งเตือน">
            <Input type="number" min="0" value={newForm.reorderPoint} onChange={e => setNewForm(f => ({ ...f, reorderPoint: e.target.value }))} placeholder="0" />
          </Field>
        </div>
      </Modal>

      {/* Modal: แก้ไขรายการ */}
      <Modal open={!!editItem} onClose={() => setEditItem(null)} title={`แก้ไข: ${editItem?.name || ''}`} width={400}
        footer={<div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end' }}><Button variant="secondary" onClick={() => setEditItem(null)}>ยกเลิก</Button><Button onClick={saveEditItem}>บันทึก</Button></div>}>
        {editItem && (
          <div style={{ display: 'grid', gap: 14 }}>
            <Field label="จุดสั่งซื้อ" hint="แจ้งเตือนเมื่อคงเหลือถึงระดับนี้">
              <Input type="number" min="0" value={editItem.reorderPoint} onChange={e => setEditItem(i => ({ ...i, reorderPoint: e.target.value }))} />
            </Field>
            <Field label="สถานะ">
              <Select value={editItem.status || 'active'} onChange={e => setEditItem(i => ({ ...i, status: e.target.value }))} options={[{ value: 'active', label: 'ใช้งาน' }, { value: 'inactive', label: 'หยุดติดตาม' }]} />
            </Field>
          </div>
        )}
      </Modal>

      {/* Modal: รับเข้า / ตัดออก / ปรับยอด */}
      <Modal open={!!mvModal} onClose={() => setMvModal(null)}
        title={mvModal ? `${mvModal.type === 'waste' ? 'ตัดออก / ของเสีย' : mvModal.type === 'adjust' ? 'ปรับยอดสต็อก' : 'รับเข้า'}: ${mvModal.item.name}` : ''}
        width={440}
        footer={<div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end' }}>
          <Button variant="secondary" onClick={() => setMvModal(null)}>ยกเลิก</Button>
          <Button
            onClick={saveMv}
            style={mvModal?.type === 'waste' ? { background: 'var(--red)', color: '#fff' } : {}}
          >
            {mvModal?.type === 'waste' ? 'บันทึกตัดออก' : mvModal?.type === 'adjust' ? 'ยืนยันปรับยอด' : 'บันทึกรับเข้า'}
          </Button>
        </div>}>
        {mvModal && (
          <div style={{ display: 'grid', gap: 14 }}>
            {/* current balance chip */}
            <div style={{ padding: '10px 14px', borderRadius: 10, background: 'var(--surface-2)', fontSize: 13.5, display: 'flex', justifyContent: 'space-between' }}>
              <span>คงเหลือปัจจุบัน</span>
              <b className="tnum">{mvModal.item.onHand} {mvModal.item.unit}</b>
            </div>

            {mvModal.type === 'adjust' ? (
              <>
                <Field label="ยอดจริงที่นับได้" hint={`ระบบจะปรับจาก ${mvModal.item.onHand} เป็นค่านี้`}>
                  <Input type="number" min="0" step="any"
                    value={mvForm.adjustTarget}
                    onChange={e => setMvForm(f => ({ ...f, adjustTarget: e.target.value }))}
                    placeholder="0"
                  />
                </Field>
                {mvForm.adjustTarget !== '' && !isNaN(Number(mvForm.adjustTarget)) && (
                  <div style={{ padding: '8px 12px', borderRadius: 8, background: Number(mvForm.adjustTarget) >= mvModal.item.onHand ? 'var(--green-soft)' : 'var(--red-soft)', fontSize: 13 }}>
                    ผลต่าง: <b className="tnum" style={{ color: Number(mvForm.adjustTarget) >= mvModal.item.onHand ? 'var(--green)' : 'var(--red)' }}>
                      {Number(mvForm.adjustTarget) >= mvModal.item.onHand ? '+' : ''}{Number(mvForm.adjustTarget) - mvModal.item.onHand} {mvModal.item.unit}
                    </b>
                  </div>
                )}
              </>
            ) : (
              <>
                <UnitQtyInput
                  label={`จำนวน${mvModal.type === 'waste' ? 'ที่ตัดออก' : 'ที่รับเข้า'}`}
                  qty={mvForm.qty}
                  unit={mvModal.item.unit}
                  inputUnit={mvForm.inputUnit}
                  onInputUnitChange={u => setMvForm(f => ({ ...f, inputUnit: u }))}
                  onQtyChange={v => setMvForm(f => ({ ...f, qty: v }))}
                  placeholder="0"
                  min={0}
                />
                {mvModal.type === 'receive' && (
                  <Field label="ราคาที่ซื้อมาครั้งนี้ (฿)" hint="ไม่บังคับ — ใช้คำนวณต้นทุนจริง">
                    <Input type="number" min="0" step="any"
                      value={mvForm.purchaseCost}
                      onChange={e => setMvForm(f => ({ ...f, purchaseCost: e.target.value }))}
                      placeholder="0.00"
                    />
                    {mvForm.purchaseCost && mvForm.qty > 0 && (
                      <div style={{ fontSize: 12, color: 'var(--accent)', marginTop: 4 }}>
                        ต้นทุน/หน่วย: ฿{(Number(mvForm.purchaseCost) / Number(mvForm.qty)).toFixed(3)}
                      </div>
                    )}
                  </Field>
                )}
              </>
            )}

            <Field label="หมายเหตุ (ไม่บังคับ)">
              <Input value={mvForm.note}
                onChange={e => setMvForm(f => ({ ...f, note: e.target.value }))}
                placeholder={mvModal.type === 'waste' ? 'เช่น หมดอายุ, หกหล่น' : mvModal.type === 'adjust' ? 'เช่น นับสต็อกประจำสัปดาห์' : 'เช่น รับจาก supplier'}
              />
            </Field>
          </div>
        )}
      </Modal>

    </div>
  );
}

function StockRow({ item, onReceive, onWaste, onAdjust, onEdit }) {
  const tone = item.emptyAlert ? 'red' : item.lowAlert ? 'orange' : 'green';
  return (
    <div style={{ display: 'grid', gridTemplateColumns: '1fr auto auto auto auto', gap: 10, alignItems: 'center', padding: '10px 14px', border: '1px solid var(--line-2)', borderRadius: 12, background: item.emptyAlert ? 'var(--red-soft)' : item.lowAlert ? 'var(--orange-soft)' : 'var(--surface)' }}>
      <div>
        <div style={{ fontWeight: 700, fontSize: 14 }}>{item.name}</div>
        <div style={{ fontSize: 12, color: 'var(--ink-3)', marginTop: 2 }}>{item.refType === 'package' ? 'แพคเกจ' : 'วัตถุดิบ'}{item.reorderPoint > 0 ? ` · จุดสั่งซื้อ: ${item.reorderPoint} ${item.unit}` : ''}</div>
      </div>
      <div style={{ textAlign: 'right' }}>
        <div className="tnum" style={{ fontSize: 20, fontWeight: 800, color: `var(--${tone === 'red' ? 'red' : tone === 'orange' ? 'orange' : 'green'})` }}>{item.onHand}</div>
        <div style={{ fontSize: 11.5, color: 'var(--ink-3)' }}>{item.unit}</div>
      </div>
      <Badge tone={tone}>{item.emptyAlert ? 'หมดแล้ว' : item.lowAlert ? 'ใกล้หมด' : 'พอ'}</Badge>
      <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
        <Button variant="secondary" size="sm" onClick={onReceive}>+รับเข้า</Button>
        <Button variant="ghost" size="sm" onClick={onWaste} style={{ color: 'var(--red)' }}>−ตัด</Button>
        <Button variant="ghost" size="sm" onClick={onAdjust} style={{ color: 'var(--accent)', fontSize: 12 }}>ปรับยอด</Button>
      </div>
      <IconBtn name="edit" onClick={onEdit} title="แก้ไข" />
    </div>
  );
}

Object.assign(window, { StockPage, stockBuildItems, stockApplyMovement, stockComputeBalance });
