// ============ Waste Log — บันทึกของเสีย ตัดสต็อกอัตโนมัติ ============

const { useState: useStateW, useEffect: useEffectW, useRef: useRefW } = React;


const WASTE_REASONS = [
  { value: 'expired',   label: '🗓 หมดอายุ' },
  { value: 'damaged',   label: '💥 เสียหาย/แตก' },
  { value: 'cooking',   label: '🔥 ไหม้/ทำผิด' },
  { value: 'spilled',   label: '💧 หกเสีย' },
  { value: 'quality',   label: '❌ คุณภาพไม่ผ่าน' },
  { value: 'other',     label: '📝 อื่นๆ' },
];

function wasteReasonLabel(v) {
  return (WASTE_REASONS.find(r => r.value === v) || {}).label || v || '—';
}

// ประเภทของเสีย: ขนม (shopStock) | วัตถุดิบ (ingredient stockItem) | อุปกรณ์ (package stockItem)
const WASTE_CATS = [
  { id: 'bakery',     label: '🍞 ขนม',     hint: 'สินค้าขนมสำเร็จรูปหน้าร้าน' },
  { id: 'ingredient', label: '🥛 วัตถุดิบ', hint: 'วัตถุดิบในการผลิตเครื่องดื่ม/ขนม' },
  { id: 'package',    label: '📦 อุปกรณ์',  hint: 'บรรจุภัณฑ์ ถ้วย ฝา หลอด ฯลฯ' },
];

function WastePage() {
  const { db, setDb, flash, logActivity } = useData();

  const [tab, setTab] = useStateW('log');       // 'log' | 'history' | 'trend'
  const [wcat, setWcat] = useStateW('bakery');  // 'bakery' | 'ingredient' | 'package'
  const [form, setForm] = useStateW({
    itemId: '',   // menuId หรือ stockItemId
    qty: '',
    reason: 'expired',
    note: '',
    wastedAt: new Date().toLocaleDateString('en-CA'),
    photo: '',
  });
  const [saving, setSaving] = useStateW(false);
  const photoRef = useRefW();

  // เปลี่ยนหมวด → reset itemId
  const changeWcat = (c) => { setWcat(c); setForm(f => ({ ...f, itemId: '', qty: '' })); };

  const handlePhoto = (file) => {
    if (!file) return;
    const reader = new FileReader();
    reader.onload = e => setForm(f => ({ ...f, photo: e.target.result }));
    reader.readAsDataURL(file);
  };

  // ---- options per category ----
  const stockItems = (db.stockItems || []).filter(s => s.status !== 'inactive');
  const bakeryMenus = (db.menus || []).filter(m => m.status !== 'inactive' && m.category !== 'Beverage')
    .sort((a, b) => String(a.id).localeCompare(String(b.id)));

  // comboOptions ดึงจาก master list โดยตรง
  // form.itemId เก็บ: menuId (bakery) | ingId (ingredient) | pkgId (package)
  const comboOptions = React.useMemo(() => {
    if (wcat === 'bakery') {
      return bakeryMenus.map(m => {
        const bal = (db.shopStock || []).find(b => b.menuId === m.id);
        return { value: m.id, label: `[${m.id}] ${m.name} · คงเหลือ ${fmt(bal ? Number(bal.onHand) || 0 : 0, 0)} ชิ้น` };
      });
    }
    if (wcat === 'ingredient') {
      return (db.ingredients || []).map(ing => {
        const si = stockItems.find(s => s.refType === 'ingredient' && s.refId === ing.id);
        const bal = si ? stockComputeBalance(db, si.id) : 0;
        return {
          value: ing.id,
          label: `${ing.name}${ing.unit ? ` (${ing.unit})` : ''} · คงเหลือ ${fmt(bal, 2)} ${ing.unit || ''}${!si ? ' ⚠️ ไม่มี stockItem' : ''}`,
        };
      });
    }
    // package
    return (db.packages || []).map(pkg => {
      const si = stockItems.find(s => s.refType === 'package' && s.refId === pkg.id);
      const bal = si ? stockComputeBalance(db, si.id) : 0;
      return {
        value: pkg.id,
        label: `${pkg.name}${pkg.unit ? ` (${pkg.unit})` : ''} · คงเหลือ ${fmt(bal, 2)} ${pkg.unit || ''}${!si ? ' ⚠️ ไม่มี stockItem' : ''}`,
      };
    });
  }, [wcat, db.shopStock, db.stockItems, db.menus, db.ingredients, db.packages, db.stockBalances]);

  // ข้อมูล item ที่เลือก (รวม stockItemId สำหรับตัดยอด)
  const selectedItem = React.useMemo(() => {
    if (!form.itemId) return null;
    if (wcat === 'bakery') {
      const m = bakeryMenus.find(x => x.id === form.itemId);
      const bal = (db.shopStock || []).find(b => b.menuId === form.itemId);
      return m ? { name: `[${m.id}] ${m.name}`, unit: 'ชิ้น', balance: bal ? Number(bal.onHand) || 0 : 0, costPerUnit: 0, stockItemId: null } : null;
    }
    if (wcat === 'ingredient') {
      const ing = (db.ingredients || []).find(i => i.id === form.itemId);
      if (!ing) return null;
      const si = stockItems.find(s => s.refType === 'ingredient' && s.refId === ing.id);
      return { name: ing.name, unit: ing.unit || '', balance: si ? stockComputeBalance(db, si.id) : 0, costPerUnit: Number(ing.costPerUnit) || 0, stockItemId: si?.id || null };
    }
    // package
    const pkg = (db.packages || []).find(p => p.id === form.itemId);
    if (!pkg) return null;
    const si = stockItems.find(s => s.refType === 'package' && s.refId === pkg.id);
    return { name: pkg.name, unit: pkg.unit || '', balance: si ? stockComputeBalance(db, si.id) : 0, costPerUnit: 0, stockItemId: si?.id || null };
  }, [form.itemId, wcat, db.shopStock, db.stockBalances, db.stockItems, db.ingredients, db.packages]);

  // ---- history ----
  const history = [...(db.wasteEvents || [])]
    .sort((a, b) => String(b.wastedAt || b.createdAt || '').localeCompare(String(a.wastedAt || a.createdAt || '')));
  const thisMonth = new Date().toLocaleDateString('en-CA').slice(0, 7);
  const monthWaste = history.filter(e => String(e.wastedAt || e.createdAt || '').startsWith(thisMonth));
  const totalWasteValue = monthWaste.reduce((s, e) => {
    const qty = Math.abs(Number(e.qty) || 0);
    if (!qty) return s;
    if (e.menuId) {
      const cost = typeof computeMenuCost === 'function' ? computeMenuCost(db, e.menuId).total : 0;
      return s + qty * cost;
    }
    if (e.source === 'shop_product') return s;
    const si = stockItems.find(x => x.id === e.stockItemId);
    if (si) {
      let cpu = 0;
      if (si.refType === 'ingredient') { const ing = (db.ingredients || []).find(i => i.id === si.refId); cpu = Number(ing?.costPerUnit) || 0; }
      else if (si.refType === 'package') { const pkg = (db.packages || []).find(p => p.id === si.refId); cpu = Number(pkg?.costPerPiece) || 0; }
      return s + qty * cpu;
    }
    return s;
  }, 0);

  // ---- save ----
  const save = () => {
    if (!form.itemId) { flash('เลือกรายการที่เสียก่อน', 'err'); return; }
    const qty = parseFloat(form.qty);
    if (!qty || qty <= 0) { flash('ใส่จำนวนที่เสีย', 'err'); return; }
    setSaving(true);
    try {
      const id = nextCode(db.wasteEvents || [], 'WST');
      const now = new Date().toISOString();
      const reasonText = `ของเสีย: ${wasteReasonLabel(form.reason)}${form.note ? ' — ' + form.note : ''}`;
      const photos = form.photo ? [form.photo] : [];
      let newDb = { ...db };

      if (wcat === 'bakery') {
        const shopRes = shopStockApply(newDb, form.itemId, (db.branches || ['JE BAR'])[0], -qty, 'waste', reasonText, id);
        newDb = { ...newDb, ...shopRes };
        newDb.wasteEvents = [...(newDb.wasteEvents || []), {
          id, source: 'shop_product', menuId: form.itemId,
          menuName: selectedItem?.name || form.itemId,
          qty: -qty, reason: form.reason, note: form.note.trim(),
          photos, wastedAt: form.wastedAt || now.slice(0, 10), createdAt: now,
        }];
      } else {
        const sid = selectedItem?.stockItemId;
        if (!sid) { flash(`"${selectedItem?.name}" ยังไม่มีข้อมูลสต็อก — กรุณาตั้งค่า stockItem ในหน้าสต็อกก่อน`, 'err'); setSaving(false); return; }
        const upd = stockApplyMovement(newDb, sid, -qty, 'waste', reasonText, 'waste', id, form.wastedAt);
        newDb = { ...newDb, ...upd };
        newDb.wasteEvents = [...(newDb.wasteEvents || []), {
          id, stockItemId: sid,
          refType: wcat, refId: form.itemId,
          itemName: selectedItem?.name || form.itemId,
          qty: -qty, reason: form.reason, note: form.note.trim(),
          photos, wastedAt: form.wastedAt || now.slice(0, 10), createdAt: now,
        }];
      }
      setDb(newDb);
      if (logActivity) logActivity('waste.logged', {
        entityType: wcat, entityId: form.itemId,
        note: `บันทึกของเสีย ${selectedItem?.name || ''} ${qty} ${selectedItem?.unit || ''} — ${wasteReasonLabel(form.reason)}`,
      });
      flash(`บันทึกของเสีย ${selectedItem?.name || ''} ${qty} ${selectedItem?.unit || ''} แล้ว`);
      setForm(f => ({ ...f, itemId: '', qty: '', note: '', reason: 'expired', photo: '' }));
    } catch (e) {
      flash('บันทึกไม่สำเร็จ: ' + (e.message || e), 'err');
    } finally {
      setSaving(false);
    }
  };

  // ---- ลบ (คืนสต็อก) ----
  const deleteWaste = (ev) => {
    if (!window.confirm(`ลบรายการของเสียนี้? สต็อกจะถูกคืน ${Math.abs(ev.qty)} หน่วย`)) return;
    let newDb = { ...db };
    if (ev.source === 'shop_product') {
      const branch = ev.branchId || (db.branches || ['JE BAR'])[0];
      const shopRes = shopStockApply(newDb, ev.menuId, branch, Math.abs(Number(ev.qty) || 0), 'adjust', `ยกเลิกของเสีย #${ev.id}`, ev.id);
      newDb = { ...newDb, ...shopRes };
    } else if (ev.stockItemId) {
      const upd = stockApplyMovement(newDb, ev.stockItemId, Math.abs(Number(ev.qty) || 0), 'adjust', `ยกเลิกของเสีย #${ev.id}`, 'waste', ev.id);
      newDb = { ...newDb, ...upd };
    }
    newDb.wasteEvents = (newDb.wasteEvents || []).filter(e => e.id !== ev.id);
    setDb(newDb);
    flash('ลบรายการของเสียแล้ว');
  };

  const reasonSummary = WASTE_REASONS.map(r => ({
    ...r, count: monthWaste.filter(e => e.reason === r.value).length,
  })).filter(r => r.count > 0).sort((a, b) => b.count - a.count);

  // monthly trend: last 12 months
  const trendData = React.useMemo(() => {
    const months = [];
    const now = new Date();
    for (let i = 11; i >= 0; i--) {
      const d = new Date(now.getFullYear(), now.getMonth() - i, 1);
      const key = d.toLocaleDateString('en-CA').slice(0, 7);
      const label = d.toLocaleDateString('th-TH', { month: 'short', year: '2-digit' });
      const evs = history.filter(e => String(e.wastedAt || e.createdAt || '').startsWith(key));
      const value = evs.reduce((s, e) => {
        const qty = Math.abs(Number(e.qty) || 0);
        if (!qty) return s;
        if (e.menuId) {
          const cost = typeof computeMenuCost === 'function' ? computeMenuCost(db, e.menuId).total : 0;
          return s + qty * cost;
        }
        if (e.source === 'shop_product') return s;
        const si = stockItems.find(x => x.id === e.stockItemId);
        if (si) {
          let cpu = 0;
          if (si.refType === 'ingredient') { const ing = (db.ingredients||[]).find(i=>i.id===si.refId); cpu = Number(ing?.costPerUnit)||0; }
          else if (si.refType === 'package') { const pkg = (db.packages||[]).find(p=>p.id===si.refId); cpu = Number(pkg?.costPerPiece)||0; }
          return s + qty * cpu;
        }
        return s;
      }, 0);
      months.push({ key, label, count: evs.length, value });
    }
    return months;
  }, [history, db, stockItems]);

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

      {/* KPI */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3,1fr)', gap: 14 }} className="r-2col">
        <Stat label="รายการเสียเดือนนี้" value={fmt(monthWaste.length)} icon="trash" tone="var(--red)"
          sub="ทุกประเภท" />
        <Stat label="มูลค่าของเสียเดือนนี้" value={fmtB(totalWasteValue)} icon="wallet" tone="var(--orange)"
          sub="ขนม+วัตถุดิบ+อุปกรณ์" />
        <Stat label="รายการเสียทั้งหมด" value={fmt(history.length)} icon="doc"
          sub="ตั้งแต่เริ่มบันทึก" />
      </div>

      {/* main tabs */}
      <div style={{ display: 'flex', gap: 4, background: 'var(--chip)', borderRadius: 12, padding: 4, width: 'fit-content' }}>
        {[{ id: 'log', label: '📝 บันทึกของเสีย' }, { id: 'history', label: '📋 ประวัติ' }, { id: 'trend', label: '📊 แนวโน้ม' }].map(t => (
          <button key={t.id} onClick={() => setTab(t.id)} style={{
            padding: '8px 18px', borderRadius: 9, border: 'none', cursor: 'pointer', fontSize: 13.5, fontFamily: 'inherit',
            background: tab === t.id ? 'var(--surface)' : 'transparent',
            color: tab === t.id ? 'var(--ink)' : 'var(--ink-2)',
            fontWeight: tab === t.id ? 600 : 400,
            boxShadow: tab === t.id ? 'var(--shadow-sm)' : 'none',
            transition: 'all .15s',
          }}>{t.label}</button>
        ))}
      </div>

      {tab === 'log' && (
        <Card>
          <SectionTitle sub="เลือกประเภท ระบุรายการที่เสีย ตัดสต็อกอัตโนมัติ">บันทึกของเสีย</SectionTitle>

          {/* category tabs */}
          <div style={{ display: 'flex', gap: 8, marginBottom: 18, flexWrap: 'wrap' }}>
            {WASTE_CATS.map(c => (
              <button key={c.id} onClick={() => changeWcat(c.id)} style={{
                padding: '9px 18px', borderRadius: 22, border: '1.5px solid',
                borderColor: wcat === c.id ? 'var(--red)' : 'var(--line)',
                background: wcat === c.id ? 'var(--red-soft)' : 'var(--chip)',
                color: wcat === c.id ? 'var(--red)' : 'var(--ink-2)',
                fontWeight: wcat === c.id ? 700 : 400,
                cursor: 'pointer', fontSize: 14, fontFamily: 'inherit',
                transition: 'all .15s',
              }}>
                {c.label}
              </button>
            ))}
          </div>
          <div style={{ fontSize: 12.5, color: 'var(--ink-3)', marginBottom: 14, marginTop: -10 }}>
            {WASTE_CATS.find(c => c.id === wcat)?.hint}
          </div>

          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }} className="r-2col">

            <Field label={wcat === 'bakery' ? 'เลือกขนมที่เสีย' : wcat === 'ingredient' ? 'เลือกวัตถุดิบที่เสีย' : 'เลือกอุปกรณ์ที่เสีย'}
              style={{ gridColumn: '1 / -1' }}>
              <SearchCombobox
                value={form.itemId}
                onChange={e => setForm(f => ({ ...f, itemId: e.target.value, qty: '' }))}
                placeholder="พิมพ์ชื่อเพื่อค้นหา..."
                options={comboOptions}
              />
            </Field>

            <Field label="จำนวนที่เสีย"
              hint={selectedItem ? `คงเหลือก่อนตัด: ${fmt(selectedItem.balance, 2)} ${selectedItem.unit}` : ''}>
              <Input type="number" min="0" step="any" value={form.qty}
                onChange={e => setForm(f => ({ ...f, qty: e.target.value }))}
                placeholder={`จำนวน${selectedItem ? ` (${selectedItem.unit})` : ''}`} />
            </Field>

            <Field label="วันที่เสีย">
              <Input type="date" value={form.wastedAt}
                onChange={e => setForm(f => ({ ...f, wastedAt: e.target.value }))} />
            </Field>

            <Field label="สาเหตุ" style={{ gridColumn: '1 / -1' }}>
              <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
                {WASTE_REASONS.map(r => (
                  <button key={r.value} onClick={() => setForm(f => ({ ...f, reason: r.value }))} style={{
                    padding: '8px 14px', borderRadius: 20, border: '1.5px solid',
                    borderColor: form.reason === r.value ? 'var(--red)' : 'var(--line)',
                    background: form.reason === r.value ? 'var(--red-soft)' : 'var(--chip)',
                    color: form.reason === r.value ? 'var(--red)' : 'var(--ink-2)',
                    cursor: 'pointer', fontSize: 13, fontFamily: 'inherit',
                    fontWeight: form.reason === r.value ? 600 : 400, transition: 'all .15s',
                  }}>{r.label}</button>
                ))}
              </div>
            </Field>

            {/* รูป */}
            <Field label="รูปภาพ (ไม่บังคับ)" style={{ gridColumn: '1 / -1' }}>
              <input type="file" accept="image/*" ref={photoRef}
                onChange={e => handlePhoto(e.target.files[0])} style={{ display: 'none' }} />
              {!form.photo
                ? <button onClick={() => photoRef.current?.click()} style={{
                    display: 'flex', alignItems: 'center', gap: 10,
                    padding: '10px 16px', borderRadius: 10,
                    border: '1.5px dashed var(--line)', background: 'var(--surface-2)',
                    cursor: 'pointer', color: 'var(--ink-2)', fontSize: 14, fontFamily: 'inherit', width: '100%',
                  }}>
                    <span style={{ fontSize: 22 }}>📷</span><span>ถ่ายรูปหรือเลือกรูปของเสีย</span>
                  </button>
                : <div style={{ position: 'relative', display: 'inline-block' }}>
                    <img src={form.photo} alt="waste"
                      style={{ maxHeight: 140, maxWidth: '100%', borderRadius: 10, border: '1px solid var(--line)', objectFit: 'cover', display: 'block' }} />
                    <button onClick={() => setForm(f => ({ ...f, photo: '' }))} style={{
                      position: 'absolute', top: 6, right: 6, width: 26, height: 26,
                      borderRadius: '50%', background: 'rgba(0,0,0,.55)', color: '#fff',
                      fontSize: 14, border: 'none', cursor: 'pointer', lineHeight: '26px', textAlign: 'center',
                    }}>×</button>
                    <button onClick={() => photoRef.current?.click()} style={{
                      position: 'absolute', bottom: 6, right: 6, padding: '4px 10px', borderRadius: 8,
                      background: 'rgba(0,0,0,.5)', color: '#fff', fontSize: 12, border: 'none',
                      cursor: 'pointer', fontFamily: 'inherit',
                    }}>เปลี่ยนรูป</button>
                  </div>
              }
            </Field>

            <Field label="หมายเหตุ (ไม่บังคับ)" style={{ gridColumn: '1 / -1' }}>
              <Input value={form.note} onChange={e => setForm(f => ({ ...f, note: e.target.value }))}
                placeholder="เช่น นมหมดอายุวันที่ 20 มิ.ย., เค้กหล่นแตก" />
            </Field>
          </div>

          {/* preview cost */}
          {selectedItem && form.qty > 0 && selectedItem.costPerUnit > 0 && (() => {
            const loss = parseFloat(form.qty) * selectedItem.costPerUnit;
            return <div style={{
              marginTop: 8, padding: '10px 14px', borderRadius: 10,
              background: 'var(--red-soft)', border: '1px solid var(--red)',
              fontSize: 13.5, color: 'var(--red)', display: 'flex', justifyContent: 'space-between',
            }}>
              <span>มูลค่าที่สูญเสีย (ประมาณ)</span>
              <span style={{ fontWeight: 700 }}>{fmtB(loss)}</span>
            </div>;
          })()}

          {selectedItem && parseFloat(form.qty) > selectedItem.balance && (
            <Badge tone="orange" style={{ marginTop: 4 }}>
              ⚠️ จำนวนที่บันทึก ({form.qty}) มากกว่าคงเหลือ ({fmt(selectedItem.balance, 2)}) — สต็อกจะติดลบ
            </Badge>
          )}

          <div style={{ marginTop: 18, display: 'flex', justifyContent: 'flex-end' }}>
            <Button icon="check" onClick={save} disabled={saving || !form.itemId || !form.qty}>
              {saving ? 'กำลังบันทึก…' : 'บันทึกของเสีย'}
            </Button>
          </div>
        </Card>
      )}

      {tab === 'history' && (
        <Card>
          <SectionTitle sub={`${history.length} รายการทั้งหมด · เดือนนี้ ${monthWaste.length} รายการ`}>
            ประวัติของเสีย
          </SectionTitle>
          {reasonSummary.length > 0 && (
            <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', marginBottom: 16 }}>
              <span style={{ fontSize: 12.5, color: 'var(--ink-3)', alignSelf: 'center' }}>เดือนนี้:</span>
              {reasonSummary.map(r => (
                <span key={r.value} style={{ fontSize: 12.5, padding: '4px 10px', borderRadius: 16, background: 'var(--red-soft)', color: 'var(--red)' }}>
                  {r.label} ×{r.count}
                </span>
              ))}
            </div>
          )}
          {history.length === 0
            ? <Empty icon="trash" title="ยังไม่มีรายการของเสีย" sub="กด 'บันทึกของเสีย' เพื่อเริ่มบันทึก" />
            : <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
                {history.map(ev => {
                  const isBakery = ev.source === 'shop_product';
                  const si = !isBakery ? stockItems.find(s => s.id === ev.stockItemId) : null;
                  // หาชื่อจาก master data ก่อน ถ้าไม่มีค่อยใช้ stockItem
                  const masterName = ev.itemName || (() => {
                    if (ev.refType === 'ingredient') return (db.ingredients || []).find(i => i.id === ev.refId)?.name;
                    if (ev.refType === 'package') return (db.packages || []).find(p => p.id === ev.refId)?.name;
                    return null;
                  })();
                  const ing = si ? (db.ingredients || []).find(i => i.id === si.refId) : null;
                  const loss = !isBakery ? Math.abs(Number(ev.qty) || 0) * (ing ? Number(ing.costPerUnit) || 0 : 0) : 0;
                  const name = isBakery ? (ev.menuName || ev.menuId) : (masterName || si?.name || ev.stockItemId || '—');
                  const unit = isBakery ? 'ชิ้น' : (si?.unit || ing?.unit || '');
                  const catBadge = isBakery ? '🍞' : (ev.refType === 'package' || si?.refType === 'package') ? '📦' : '🥛';
                  return (
                    <div key={ev.id} style={{
                      display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start',
                      padding: '12px 14px', borderRadius: 12, background: 'var(--surface-2)',
                      gap: 12, flexWrap: 'wrap',
                    }}>
                      <div style={{ display: 'flex', flexDirection: 'column', gap: 3, flex: 1, minWidth: 0 }}>
                        <div style={{ display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap' }}>
                          <span style={{ fontSize: 15 }}>{catBadge}</span>
                          <span style={{ fontWeight: 600, fontSize: 14 }}>{name}</span>
                          <Badge tone="red">{wasteReasonLabel(ev.reason)}</Badge>
                        </div>
                        <div style={{ fontSize: 12.5, color: 'var(--ink-3)' }}>
                          {ev.wastedAt || ev.createdAt?.slice(0, 10) || '—'}
                          {ev.note ? ` · ${ev.note}` : ''}
                        </div>
                        {(ev.photos || []).length > 0 && (
                          <img src={ev.photos[0]} alt="waste"
                            onClick={() => window.open(ev.photos[0], '_blank')}
                            style={{ marginTop: 6, height: 56, borderRadius: 8, border: '1px solid var(--line)', objectFit: 'cover', cursor: 'zoom-in' }} />
                        )}
                      </div>
                      <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-end', gap: 2 }}>
                        <span className="tnum" style={{ fontWeight: 700, color: 'var(--red)', fontSize: 15 }}>
                          -{fmt(Math.abs(Number(ev.qty) || 0), 2)} {unit}
                        </span>
                        {loss > 0 && <span style={{ fontSize: 12, color: 'var(--ink-3)' }}>{fmtB(loss)}</span>}
                      </div>
                      <IconBtn name="trash" danger title="ลบและคืนสต็อก" onClick={() => deleteWaste(ev)} />
                    </div>
                  );
                })}
              </div>}
        </Card>
      )}
      {tab === 'trend' && (() => {
        const maxVal = Math.max(...trendData.map(d => d.value), 1);
        const maxCount = Math.max(...trendData.map(d => d.count), 1);
        const totalVal = trendData.reduce((s,d)=>s+d.value,0);
        const totalCount = trendData.reduce((s,d)=>s+d.count,0);
        const avgVal = totalVal / 12;
        return (
          <Card>
            <SectionTitle sub="ย้อนหลัง 12 เดือน">แนวโน้มของเสียรายเดือน</SectionTitle>
            <div style={{display:'grid',gridTemplateColumns:'repeat(3,1fr)',gap:12,marginBottom:20}} className="r-2col">
              <Stat label="รวม 12 เดือน (รายการ)" value={fmt(totalCount)} icon="trash" tone="var(--red)"/>
              <Stat label="มูลค่าสูญเสียรวม" value={fmtB(totalVal,0)} icon="wallet" tone="var(--orange)"/>
              <Stat label="เฉลี่ย/เดือน" value={fmtB(avgVal,0)} icon="chart" tone="var(--ink-3)"/>
            </div>

            {/* มูลค่าของเสีย bar chart */}
            <div style={{marginBottom:24}}>
              <div style={{fontSize:13,fontWeight:700,color:'var(--ink-2)',marginBottom:12}}>มูลค่าของเสีย (฿)</div>
              <div style={{display:'flex',alignItems:'flex-end',gap:6,height:140,padding:'0 4px'}}>
                {trendData.map(d => {
                  const h = maxVal > 0 ? Math.max(4, (d.value / maxVal) * 120) : 4;
                  const isThis = d.key === thisMonth;
                  return (
                    <div key={d.key} style={{flex:1,display:'flex',flexDirection:'column',alignItems:'center',gap:4}}>
                      {d.value > 0 && <div style={{fontSize:9,color:'var(--ink-3)',textAlign:'center',lineHeight:1.2}}>{fmtB(d.value,0).replace('฿','')}</div>}
                      <div style={{width:'100%',height:h,borderRadius:'4px 4px 0 0',
                        background:isThis?'var(--red)':'var(--accent)',
                        opacity:isThis?1:0.6,transition:'height .3s'}}/>
                      <div style={{fontSize:9,color:isThis?'var(--red)':'var(--ink-3)',fontWeight:isThis?700:400,textAlign:'center',lineHeight:1.2}}>{d.label}</div>
                    </div>
                  );
                })}
              </div>
            </div>

            {/* จำนวนรายการ bar chart */}
            <div>
              <div style={{fontSize:13,fontWeight:700,color:'var(--ink-2)',marginBottom:12}}>จำนวนรายการของเสีย</div>
              <div style={{display:'flex',alignItems:'flex-end',gap:6,height:100,padding:'0 4px'}}>
                {trendData.map(d => {
                  const h = maxCount > 0 ? Math.max(d.count>0?4:0, (d.count / maxCount) * 80) : 0;
                  const isThis = d.key === thisMonth;
                  return (
                    <div key={d.key} style={{flex:1,display:'flex',flexDirection:'column',alignItems:'center',gap:4}}>
                      {d.count > 0 && <div style={{fontSize:9,color:'var(--ink-3)'}}>{d.count}</div>}
                      <div style={{width:'100%',height:h,borderRadius:'4px 4px 0 0',
                        background:isThis?'var(--orange)':'var(--ink-3)',
                        opacity:isThis?1:0.4,transition:'height .3s'}}/>
                      <div style={{fontSize:9,color:isThis?'var(--orange)':'var(--ink-3)',fontWeight:isThis?700:400,textAlign:'center',lineHeight:1.2}}>{d.label}</div>
                    </div>
                  );
                })}
              </div>
            </div>

            {/* table */}
            <div style={{marginTop:20,overflowX:'auto'}}>
              <table style={{width:'100%',borderCollapse:'collapse',fontSize:13}}>
                <thead><tr style={{fontSize:11.5,color:'var(--ink-3)',fontWeight:700}}>
                  <th style={{textAlign:'left',padding:'6px 10px'}}>เดือน</th>
                  <th style={{textAlign:'right',padding:'6px 10px'}}>รายการ</th>
                  <th style={{textAlign:'right',padding:'6px 10px'}}>มูลค่า (฿)</th>
                </tr></thead>
                <tbody>{[...trendData].reverse().map(d=>(
                  <tr key={d.key} style={{borderTop:'1px solid var(--line-2)',background:d.key===thisMonth?'var(--red-soft)':'transparent'}}>
                    <td style={{padding:'8px 10px',fontWeight:d.key===thisMonth?700:400}}>{d.label}{d.key===thisMonth?' (เดือนนี้)':''}</td>
                    <td className="tnum" style={{padding:'8px 10px',textAlign:'right',color:d.count>0?'var(--red)':'var(--ink-3)'}}>{d.count}</td>
                    <td className="tnum" style={{padding:'8px 10px',textAlign:'right',color:d.value>0?'var(--orange)':'var(--ink-3)'}}>{d.value>0?fmtB(d.value,0):'-'}</td>
                  </tr>
                ))}</tbody>
              </table>
            </div>
          </Card>
        );
      })()}
    </div>
  );
}

Object.assign(window, { WastePage });
