/* X-REAL Stock System — Audit, History, Settings */

// ─── BATCH EDIT MODAL ──────────────────────────────────────────────────
function BatchEditModal({ stock, product, location, onSave, onClose }) {
  const [lot, setLot] = useState(stock.lot || "");
  const [exp, setExp] = useState(stock.expDate || "");
  const [qty, setQty] = useState(stock.qty);
  if (!stock) return null;
  const submit = () => {
    onSave(stock.id, { lot, expDate: exp, qty: parseInt(qty) || 0 });
    onClose();
  };
  return (
    <div className="xr-modal-overlay" onClick={e => e.target === e.currentTarget && onClose()}>
      <div className="xr-modal" style={{ padding: 22, maxWidth: 440, width: "94vw" }}>
        <div style={{ fontWeight: 700, fontSize: 15, marginBottom: 4 }}>แก้ไข Batch</div>
        <div style={{ fontSize: 12, color: "var(--text-3)", marginBottom: 14 }}>
          <SkuBadge sku={product?.sku || "—"}/> {product?.name} · {location?.name}
        </div>
        <FG label="Lot Number" style={{ marginBottom: 10 }}>
          <input className="xr-input" type="text" value={lot} onChange={e => setLot(e.target.value)}
            placeholder="เช่น LOT-2026-05"
            autoCapitalize="characters" autoCorrect="off" autoComplete="off" spellCheck="false"/>
        </FG>
        <FG label="วันหมดอายุ (dd/mm/yyyy)" style={{ marginBottom: 10 }}>
          <DateInput value={exp} onChange={setExp}/>
        </FG>
        <FG label="จำนวนคงเหลือ" style={{ marginBottom: 14 }}>
          <input className="xr-input" type="number" min="0" value={qty}
            onChange={e => setQty(e.target.value)}
            style={{ fontWeight: 700, textAlign: "center" }}/>
          <div style={{ fontSize: 11, color: "var(--text-3)", marginTop: 4 }}>ตั้งเป็น 0 = ลบ batch นี้ออกจากระบบ</div>
        </FG>
        <div style={{ display: "flex", gap: 8 }}>
          <Btn variant="accent" icon="check" onClick={submit} full>บันทึก</Btn>
          <Btn variant="ghost" onClick={onClose}>ยกเลิก</Btn>
        </div>
      </div>
    </div>
  );
}

// ─── AUDIT ─────────────────────────────────────────────────────────────
function AuditPage({ products, locations, stocks, stores, consLedger, getQty, onSubmit, onEditBatch, onAuditCons, prefill }) {
  const storageLocs = locations.filter(l => l.isStorage);
  // Audit target: either { kind: "stock", locId } or { kind: "cons", storeId, branchId }
  const [target, setTarget] = useState(prefill?.locId
    ? { kind: "stock", locId: prefill.locId }
    : { kind: "stock", locId: storageLocs[0]?.id || "" });
  const [actuals, setActuals] = useState({});
  const [note, setNote] = useState("");
  const [search, setSearch] = useState("");
  const [editBatch, setEditBatch] = useState(null);
  const [showAllBatches, setShowAllBatches] = useState(false);
  const [selConsStore, setSelConsStore] = useState(null);

  const isCons = target.kind === "cons";
  const selLoc = target.kind === "stock" ? target.locId : "";
  const loc = storageLocs.find(l => l.id === selLoc);
  const consStore = isCons ? stores.find(s => s.id === target.storeId) : null;
  const consBranch = consStore?.branches.find(b => b.id === target.branchId);

  // For consignment: compute current ledger balance per SKU at this branch
  const consBalance = (skuId) => isCons ? consLedger
    .filter(e => e.branchId === target.branchId && e.skuId === skuId)
    .reduce((a, e) => a + (e.sentQty || 0) - (e.soldQty || 0) - (e.returnQty || 0) + (e.adjQty || 0), 0) : 0;

  const getSysQty = pid => isCons ? consBalance(pid) : getQty(pid, selLoc);
  const getDiff = pid => { const a = actuals[pid]; if (a === undefined) return 0; return a - getSysQty(pid); };
  const changed = products.filter(p => getDiff(p.id) !== 0);

  // Expiring batches for selected location (only for stock audit)
  const expBatches = !isCons ? stocks.filter(s => s.locId === selLoc && ["warn", "expired", "soon"].includes(expStatus(s.expDate))) : [];
  const allBatches = !isCons ? stocks.filter(s => s.locId === selLoc && (s.lot || s.expDate)) : [];

  const submit = () => {
    const entries = Object.entries(actuals).filter(([, v]) => v !== undefined).map(([pid, v]) => ({ skuId: pid, actual: v }));
    if (!entries.length) return;
    if (isCons) {
      onAuditCons(target.storeId, target.branchId, entries, note);
    } else {
      onSubmit(entries.map(e => ({ ...e, locId: selLoc })), note);
    }
    setActuals({}); setNote("");
  };

  // For consignment: only show SKUs that have any ledger entry (active at this branch)
  const filteredProds = products.filter(p => p.active !== false &&
    (!search || p.sku.toLowerCase().includes(search.toLowerCase()) || p.name.toLowerCase().includes(search.toLowerCase())) &&
    (!isCons || consLedger.some(e => e.branchId === target.branchId && e.skuId === p.id)));

  return (
    <div >
      <InfoBanner icon="audit" variant="warn">
        นับสต็อคจริงเทียบยอดในระบบ — ทุกการปรับจะถูกบันทึกลง <strong>History</strong> อัตโนมัติ
      </InfoBanner>

      <div style={{ marginBottom: 16 }}>
        <div className="xr-label" style={{ marginBottom: 6 }}>คลังของเรา</div>
        <div style={{ display: "flex", gap: 8, flexWrap: "wrap", marginBottom: 12 }}>
          {storageLocs.map(l => {
            const active = !isCons && selLoc === l.id;
            return (
              <button key={l.id} onClick={() => { setTarget({ kind: "stock", locId: l.id }); setActuals({}); }} className="xr-card xr-clickable" style={{
                padding: "10px 16px", display: "flex", alignItems: "center", gap: 10,
                border: `1.5px solid ${active ? "var(--accent)" : "var(--border)"}`,
                background: active ? "var(--accent-subtle)" : undefined,
              }}>
                <Icon name="warehouse" size={16} style={{ color: active ? "var(--accent-hover)" : "var(--text-3)" }}/>
                <div style={{ textAlign: "left" }}>
                  <div style={{ fontSize: 13, fontWeight: 700, color: active ? "var(--accent-hover)" : "var(--text-1)" }}>{l.name}</div>
                  <LocBadge locType={l.locType}/>
                </div>
              </button>
            );
          })}
        </div>
        {stores.some(s => s.branches.length > 0) && (
          <>
            <div className="xr-label" style={{ marginBottom: 6 }}>ร้าน Consignment / สาขา</div>
            <div style={{ display: "flex", gap: 8, flexWrap: "wrap", marginBottom: selConsStore ? 10 : 0 }}>
              {stores.filter(s => s.branches.length > 0).map(st => {
                const active = selConsStore === st.id;
                return (
                  <button key={st.id} onClick={() => {
                    setSelConsStore(st.id);
                    if (isCons && target.storeId !== st.id) { setTarget({ kind: "stock", locId: storageLocs[0]?.id || "" }); setActuals({}); }
                  }} className="xr-card xr-clickable" style={{
                    padding: "10px 16px", display: "flex", alignItems: "center", gap: 10,
                    border: `1.5px solid ${active ? "var(--purple)" : "var(--border)"}`,
                    background: active ? "var(--purple-bg)" : undefined,
                  }}>
                    <Icon name="store" size={16} style={{ color: active ? "var(--purple)" : "var(--text-3)" }}/>
                    <div style={{ fontSize: 13, fontWeight: 700, color: active ? "var(--purple)" : "var(--text-1)" }}>{st.name}</div>
                  </button>
                );
              })}
            </div>
            {selConsStore && (() => {
              const st = stores.find(s => s.id === selConsStore);
              if (!st) return null;
              return (
                <div style={{ display: "flex", gap: 8, flexWrap: "wrap", paddingLeft: 8, borderLeft: "2px solid var(--purple-bg)" }}>
                  {st.branches.map(b => {
                    const active = isCons && target.branchId === b.id;
                    return (
                      <button key={b.id} onClick={() => { setTarget({ kind: "cons", storeId: st.id, branchId: b.id }); setActuals({}); }} className="xr-card xr-clickable" style={{
                        padding: "8px 14px", display: "flex", alignItems: "center", gap: 8,
                        border: `1.5px solid ${active ? "var(--purple)" : "var(--border)"}`,
                        background: active ? "var(--purple-bg)" : undefined,
                      }}>
                        <Icon name="branch" size={14} style={{ color: active ? "var(--purple)" : "var(--text-3)" }}/>
                        <div style={{ fontSize: 13, fontWeight: 700, color: active ? "var(--purple)" : "var(--text-1)" }}>{b.name}</div>
                      </button>
                    );
                  })}
                </div>
              );
            })()}
          </>
        )}
      </div>

      {(loc || isCons) && (
        <>
          <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 10, gap: 10, flexWrap: "wrap" }}>
            <div style={{ fontWeight: 700, fontSize: 15 }}>
              {isCons
                ? <>สาขา: {consBranch?.name} <span style={{ color: "var(--text-3)", fontWeight: 500, fontSize: 13 }}>({consStore?.name})</span></>
                : <>คลัง: {loc?.name}</>}
            </div>
            <div style={{ display: "flex", gap: 8, alignItems: "center" }}>
              <input className="xr-input xr-input--sm" placeholder="🔍 ค้นหา SKU…" value={search} onChange={e => setSearch(e.target.value)} style={{ width: 180 }}/>
              {changed.length > 0 && <Pill variant="warn">{changed.length} รายการเปลี่ยน</Pill>}
            </div>
          </div>

          {isCons && (
            <InfoBanner icon="info" variant="purple">
              Audit ยอด Consignment — ผลต่างจะถูกบันทึกเป็น <strong>ปรับยอด (adjQty)</strong> ของเดือนปัจจุบัน · มีเฉพาะ SKU ที่เคยมียอดที่สาขานี้
            </InfoBanner>
          )}

          {editBatch && (
            <BatchEditModal
              stock={editBatch}
              product={products.find(p => p.id === editBatch.skuId)}
              location={locations.find(l => l.id === editBatch.locId)}
              onSave={onEditBatch}
              onClose={() => setEditBatch(null)}/>
          )}

          {!isCons && expBatches.length > 0 && (
            <Card style={{ marginBottom: 14, borderColor: "var(--warn-border)" }}>
              <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 8 }}>
                <Icon name="alert" size={14} style={{ color: "var(--warn)" }}/>
                <div style={{ fontWeight: 700, fontSize: 13, color: "var(--warn)" }}>Lot ที่ต้องระวัง ({expBatches.length})</div>
                <span style={{ fontSize: 11, color: "var(--text-3)", marginLeft: "auto" }}>คลิกเพื่อแก้ไข lot / exp / qty</span>
              </div>
              <div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
                {expBatches.map(s => {
                  const p = products.find(x => x.id === s.skuId);
                  const st = expStatus(s.expDate);
                  const d = daysUntil(s.expDate);
                  return (
                    <button key={s.id} onClick={() => setEditBatch(s)} className="xr-clickable" style={{
                      padding: "8px 12px", background: "var(--warn-bg)", borderRadius: "var(--r-sm)",
                      display: "flex", alignItems: "center", gap: 10, width: "100%", textAlign: "left",
                      border: "1px solid transparent",
                    }}>
                      <SkuBadge sku={p?.sku || "—"}/>
                      <span style={{ fontSize: 12, color: "var(--text-2)" }}>{s.qty} {p?.unit} · {s.lot || "no lot"}</span>
                      <span style={{ marginLeft: "auto", fontSize: 12, fontWeight: 700, color: st === "expired" ? "var(--danger)" : "var(--warn)" }}>
                        {fmtD(s.expDate)} {st === "expired" ? `(เลย ${Math.abs(d)} วัน)` : `(อีก ${d} วัน)`}
                      </span>
                      <Icon name="settings" size={12} style={{ color: "var(--text-3)" }}/>
                    </button>
                  );
                })}
              </div>
            </Card>
          )}

          {!isCons && <Card style={{ marginBottom: 14 }}>
            <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: showAllBatches ? 12 : 0 }}>
              <div style={{ fontWeight: 700, fontSize: 13 }}>
                <Icon name="box" size={13} style={{ marginRight: 6, verticalAlign: -1 }}/>
                จัดการ Batch ทั้งหมดในคลังนี้ ({allBatches.length})
              </div>
              <Btn variant="ghost" size="sm" icon={showAllBatches ? "x" : "settings"} onClick={() => setShowAllBatches(v => !v)}>
                {showAllBatches ? "ซ่อน" : "แสดง"}
              </Btn>
            </div>
            {showAllBatches && (
              allBatches.length === 0 ? (
                <div style={{ fontSize: 12, color: "var(--text-3)", padding: "8px 4px" }}>คลังนี้ยังไม่มี batch ที่มี lot/exp</div>
              ) : (
                <div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
                  {allBatches.sort((a, b) => {
                    if (!a.expDate && !b.expDate) return 0;
                    if (!a.expDate) return 1; if (!b.expDate) return -1;
                    return new Date(a.expDate) - new Date(b.expDate);
                  }).map(s => {
                    const p = products.find(x => x.id === s.skuId);
                    const st = expStatus(s.expDate);
                    const colorMap = { warn: "var(--warn)", expired: "var(--danger)", soon: "var(--info)", ok: "var(--text-3)", "no-exp": "var(--text-3)" };
                    return (
                      <button key={s.id} onClick={() => setEditBatch(s)} className="xr-clickable" style={{
                        padding: "8px 12px", background: "var(--surface-2)", borderRadius: "var(--r-sm)",
                        display: "flex", alignItems: "center", gap: 10, width: "100%", textAlign: "left",
                        border: "1px solid var(--border)",
                      }}>
                        <SkuBadge sku={p?.sku || "—"}/>
                        <span style={{ fontSize: 12, color: "var(--text-2)", flex: 1, minWidth: 0, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>
                          {p?.name} · <strong>{s.qty}</strong> {p?.unit} · lot: <strong>{s.lot || "—"}</strong>
                        </span>
                        <span style={{ fontSize: 12, fontWeight: 700, color: colorMap[st] || "var(--text-3)", flexShrink: 0 }}>
                          {s.expDate ? fmtD(s.expDate) : "no exp"}
                        </span>
                        <Icon name="settings" size={12} style={{ color: "var(--text-3)", flexShrink: 0 }}/>
                      </button>
                    );
                  })}
                </div>
              )
            )}
          </Card>}

          <Card padded={false} style={{ marginBottom: 14 }}>
            <div className="xr-table-scroll">
              <table className="xr-table">
                <thead>
                  <tr>
                    <th>SKU</th><th>ชื่อสินค้า</th>
                    <th style={{ textAlign: "right" }}>ยอดในระบบ</th>
                    <th style={{ textAlign: "right" }}>ยอดนับจริง</th>
                    <th style={{ textAlign: "right" }}>ผลต่าง</th>
                  </tr>
                </thead>
                <tbody>
                  {filteredProds.map(p => {
                    const sys = getSysQty(p.id);
                    const actual = actuals[p.id] ?? sys;
                    const diff = getDiff(p.id);
                    return (
                      <tr key={p.id} style={{ background: diff !== 0 ? "var(--warn-bg)" : undefined }}>
                        <td><SkuBadge sku={p.sku}/></td>
                        <td style={{ fontSize: 13 }}>{p.name}</td>
                        <td style={{ textAlign: "right", fontWeight: 700, color: "var(--accent)", fontSize: 15, fontVariantNumeric: "tabular-nums" }}>{sys}</td>
                        <td style={{ textAlign: "right" }}>
                          <input type="number" min="0" value={actual} onChange={e => setActuals(a => ({ ...a, [p.id]: parseInt(e.target.value) || 0 }))}
                            className="xr-input" style={{
                              width: 90, textAlign: "center", fontWeight: 700, fontSize: 14,
                              borderColor: diff !== 0 ? "var(--warn-border)" : undefined,
                              background: diff !== 0 ? "var(--warn-bg)" : "var(--surface-2)",
                            }}/>
                        </td>
                        <td style={{ textAlign: "right", fontWeight: 700, color: diff === 0 ? "var(--text-3)" : diff > 0 ? "var(--success)" : "var(--danger)", fontVariantNumeric: "tabular-nums" }}>
                          {diff === 0 ? "—" : diff > 0 ? `+${diff}` : diff}
                        </td>
                      </tr>
                    );
                  })}
                </tbody>
              </table>
            </div>
          </Card>

          <Card>
            <div style={{ display: "flex", gap: 10, alignItems: "flex-end" }}>
              <FG label="หมายเหตุ" style={{ flex: 1 }}>
                <input className="xr-input" value={note} onChange={e => setNote(e.target.value)}
                  placeholder={isCons ? `นับสต็อคสาขา ${consBranch?.name || ""}` : `นับสต็อคสิ้นเดือน — คลัง${loc?.name || ""}`}/>
              </FG>
              <Btn variant={isCons ? "purple" : "accent"} icon="check" size="lg" onClick={submit} disabled={!changed.length}>
                บันทึก Audit{isCons && " (Consignment)"} {changed.length > 0 && `(${changed.length})`}
              </Btn>
            </div>
          </Card>
        </>
      )}
    </div>
  );
}

// ─── HISTORY ───────────────────────────────────────────────────────────
const ACTION_META_H = {
  "นำเข้า":   { color: "success", icon: "in" },
  "นำออก":    { color: "danger",  icon: "out" },
  "โอนย้าย":  { color: "warn",    icon: "transfer" },
  "Re-pack":  { color: "purple",  icon: "repack" },
  "ปรับ Audit": { color: "info",  icon: "audit" },
  "Reservation Fulfilled": { color: "success", icon: "check" },
};

function HistoryPage({ history, filter, setFilter, onExport }) {
  const types = ["ทั้งหมด", "นำเข้า", "นำออก", "โอนย้าย", "Re-pack", "ปรับ Audit"];
  const filtered = history.filter(h => filter === "ทั้งหมด" || h.action === filter);

  return (
    <div >
      <div style={{ display: "flex", gap: 8, marginBottom: 14, flexWrap: "wrap", alignItems: "center" }}>
        {types.map(t => (
          <button key={t} onClick={() => setFilter(t)} className="xr-btn xr-btn--sm" style={{
            background: filter === t ? "var(--accent)" : undefined,
            color: filter === t ? "#fff" : undefined,
            borderColor: filter === t ? "transparent" : undefined,
          }}>{t}</button>
        ))}
        <Btn variant="ghost" size="sm" icon="download" onClick={onExport} style={{ marginLeft: "auto" }}>Export CSV</Btn>
      </div>

      {filtered.length === 0 ? (
        <EmptyState icon="history" title="ยังไม่มีประวัติ"/>
      ) : (
        <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
          {filtered.map(h => {
            const meta = ACTION_META_H[h.action] || { color: "default", icon: "package" };
            const colorVar = meta.color === "default" ? "var(--text-2)" : `var(--${meta.color})`;
            const bgVar = meta.color === "default" ? "var(--surface-3)" : `var(--${meta.color}-bg)`;
            return (
              <Card key={h.id} padded={false} style={{ padding: "12px 16px" }}>
                <div style={{ display: "flex", gap: 12, alignItems: "flex-start" }}>
                  <div style={{
                    width: 34, height: 34, borderRadius: "var(--r-sm)", flexShrink: 0,
                    background: bgVar, color: colorVar,
                    display: "flex", alignItems: "center", justifyContent: "center",
                  }}>
                    <Icon name={meta.icon} size={16}/>
                  </div>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ display: "flex", alignItems: "center", gap: 6, marginBottom: 4, flexWrap: "wrap" }}>
                      <Pill variant={meta.color === "default" ? "default" : meta.color}>{h.action}</Pill>
                      <span style={{ fontSize: 11, color: "var(--text-3)" }}>{h.user}</span>
                      <span style={{ fontSize: 11, color: "var(--text-3)" }}>· {fmtRel(h.ts)}</span>
                      <span style={{ fontSize: 11, color: "var(--text-3)" }}>· {fmtDT(h.ts)}</span>
                    </div>
                    <div style={{ fontSize: 13, color: "var(--text-1)", lineHeight: 1.5 }}>{h.detail}</div>
                  </div>
                </div>
              </Card>
            );
          })}
        </div>
      )}
    </div>
  );
}

// ─── SETTINGS ──────────────────────────────────────────────────────────
function SettingsPage({ cats, products, locations, repackRules, stocks, stockCount, onSaveCats, onSaveProds, onSaveLocs, onSaveRepack, showToast, askConfirm }) {
  const [activeSection, setActiveSection] = useState("categories");
  const [newCatName, setNewCatName] = useState("");
  const [newCatColor, setNewCatColor] = useState("#3b82f6");
  const [catFilter, setCatFilter] = useState("all");
  const [search, setSearch] = useState("");
  const [editPId, setEditPId] = useState(null);
  const [editPForm, setEditPForm] = useState({});
  const [showAddProd, setShowAddProd] = useState(false);
  const [addPForm, setAddPForm] = useState({ sku: "", barcode: "", name: "", unit: "ซอง", catId: cats[0]?.id || "", active: true });
  const [locForm, setLocForm] = useState({ id: null, name: "", isStorage: true, locType: "storage" });
  const [showLocForm, setShowLocForm] = useState(false);

  const catMap = Object.fromEntries(cats.map(c => [c.id, c]));
  const LOC_TYPES = [
    { id: "storage",     label: "Storage",     desc: "คลังหลัก นับ realtime",    color: "var(--info)" },
    { id: "consignment", label: "Consignment", desc: "ฝากขาย — ตัดตาม report", color: "var(--purple)" },
    { id: "event",       label: "Event/บูธ",  desc: "ชั่วคราว มีคืนสต็อค",     color: "var(--warn)" },
    { id: "outbound",    label: "Outbound",    desc: "ปลายทาง ตัดถาวร",          color: "var(--success)" },
  ];

  const filteredProds = products.filter(p =>
    (catFilter === "all" || p.catId === catFilter) &&
    (p.sku.toLowerCase().includes(search.toLowerCase()) || p.name.toLowerCase().includes(search.toLowerCase()))
  );

  const SECTIONS = [
    { id: "categories", icon: "tag",       label: "หมวดหมู่" },
    { id: "products",   icon: "package",   label: "สินค้า" },
    { id: "locations",  icon: "warehouse", label: "คลัง/สถานที่" },
  ];

  return (
    <div >
      <div style={{ display: "flex", gap: 6, marginBottom: 20, flexWrap: "wrap" }}>
        {SECTIONS.map(s => (
          <button key={s.id} onClick={() => setActiveSection(s.id)} className="xr-btn" style={{
            background: activeSection === s.id ? "var(--accent-subtle)" : undefined,
            color: activeSection === s.id ? "var(--accent-hover)" : undefined,
            borderColor: activeSection === s.id ? "var(--accent-border)" : undefined,
          }}><Icon name={s.icon} size={14}/>{s.label}</button>
        ))}
      </div>

      {activeSection === "categories" && (
        <div style={{ maxWidth: 700 }}>
          <Card style={{ marginBottom: 14 }}>
            <div style={{ fontWeight: 700, marginBottom: 12 }}>เพิ่มหมวดหมู่ใหม่</div>
            <div style={{ display: "grid", gridTemplateColumns: "1fr 70px 100px", gap: 10, alignItems: "flex-end" }}>
              <FG label="ชื่อหมวดหมู่">
                <input className="xr-input" value={newCatName} onChange={e => setNewCatName(e.target.value)} placeholder="เช่น Bundle"/>
              </FG>
              <FG label="สี">
                <input type="color" value={newCatColor} onChange={e => setNewCatColor(e.target.value)}
                  style={{ width: "100%", height: 38, border: "1px solid var(--border)", borderRadius: "var(--r-md)", cursor: "pointer" }}/>
              </FG>
              <Btn variant="accent" icon="plus" onClick={() => {
                if (!newCatName.trim()) return showToast("กรอกชื่อ", "err");
                onSaveCats([...cats, { id: uid(), name: newCatName.trim(), color: newCatColor }]);
                setNewCatName(""); showToast("เพิ่มหมวดหมู่แล้ว");
              }}>เพิ่ม</Btn>
            </div>
          </Card>
          <Card padded={false}>
            <table className="xr-table">
              <thead><tr><th>ชื่อ</th><th>สี</th><th>สินค้า</th><th>จัดการ</th></tr></thead>
              <tbody>
                {cats.map(c => (
                  <tr key={c.id}>
                    <td><CatBadge cat={c}/></td>
                    <td><div style={{ width: 26, height: 26, background: c.color, borderRadius: "var(--r-sm)" }}/></td>
                    <td style={{ color: "var(--text-2)" }}>{products.filter(p => p.catId === c.id).length} รายการ</td>
                    <td>
                      <Btn variant="danger-soft" size="sm" icon="trash" onClick={() => {
                        if (products.some(p => p.catId === c.id)) return showToast("ยังมีสินค้าในหมวดนี้", "err");
                        askConfirm(`ลบหมวด "${c.name}"?`, "สินค้าในหมวดนี้จะไม่มีหมวด", () => {
                          onSaveCats(cats.filter(x => x.id !== c.id)); showToast("ลบหมวดแล้ว");
                        });
                      }}>ลบ</Btn>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </Card>
        </div>
      )}

      {activeSection === "products" && (
        <div>
          <div style={{ display: "flex", gap: 8, marginBottom: 14, flexWrap: "wrap", alignItems: "center" }}>
            <input className="xr-input xr-input--sm" value={search} onChange={e => setSearch(e.target.value)} placeholder="🔍 ค้นหา SKU/ชื่อ" style={{ width: 200 }}/>
            <button onClick={() => setCatFilter("all")} className="xr-btn xr-btn--sm" style={{
              background: catFilter === "all" ? "var(--text-1)" : undefined,
              color: catFilter === "all" ? "var(--surface)" : undefined,
            }}>ทั้งหมด</button>
            {cats.map(c => (
              <button key={c.id} onClick={() => setCatFilter(c.id)} className="xr-btn xr-btn--sm" style={{
                background: catFilter === c.id ? c.color : undefined,
                color: catFilter === c.id ? "#fff" : undefined,
                borderColor: catFilter === c.id ? c.color : undefined,
              }}>{c.name}</button>
            ))}
            <Btn variant="accent" icon="plus" onClick={() => { setShowAddProd(v => !v); setEditPId(null); }} style={{ marginLeft: "auto" }}>เพิ่มสินค้า</Btn>
          </div>

          {(editPId || showAddProd) && (
            <Card className="xr-fade-in" style={{ marginBottom: 14, borderColor: editPId ? "var(--info)" : "var(--success)" }}>
              <div style={{ fontWeight: 700, marginBottom: 12, color: editPId ? "var(--info)" : "var(--success)" }}>
                {editPId ? `แก้ไข: ${editPForm.sku}` : "เพิ่มสินค้าใหม่"}
              </div>
              <ProductForm
                form={editPId ? editPForm : addPForm}
                setForm={editPId ? setEditPForm : setAddPForm}
                cats={cats}
                onSave={() => {
                  const form = editPId ? editPForm : addPForm;
                  if (!form.sku?.trim() || !form.name?.trim()) return showToast("กรอก SKU และชื่อ", "err");
                  if (editPId) {
                    const c = products.find(p => p.sku === form.sku.trim() && p.id !== form.id);
                    if (c) return showToast("SKU นี้มีแล้ว", "err");
                    onSaveProds(products.map(p => p.id === form.id ? { ...form, sku: form.sku.trim() } : p));
                    setEditPId(null); showToast("แก้ไขสำเร็จ");
                  } else {
                    const sku = form.sku.trim();
                    if (products.find(p => p.sku === sku)) return showToast("SKU นี้มีแล้ว", "err");
                    onSaveProds([...products, { ...form, id: uid(), sku, active: true }]);
                    setAddPForm({ sku: "", barcode: "", name: "", unit: "ซอง", catId: cats[0]?.id || "", active: true });
                    setShowAddProd(false); showToast(`เพิ่ม ${sku} แล้ว`);
                  }
                }}
                onCancel={() => { setEditPId(null); setShowAddProd(false); }}
              />
            </Card>
          )}

          <Card padded={false}>
            <div className="xr-table-scroll">
              <table className="xr-table">
                <thead><tr><th>SKU</th><th>ชื่อ</th><th>หมวด</th><th>หน่วย</th><th style={{ textAlign: "right" }}>สต็อค</th><th>สถานะ</th><th>จัดการ</th></tr></thead>
                <tbody>
                  {filteredProds.map(p => {
                    const cnt = stockCount(p.id);
                    const inactive = p.active === false;
                    const isEd = editPId === p.id;
                    return (
                      <tr key={p.id} style={{ opacity: inactive ? .5 : 1, background: isEd ? "var(--info-bg)" : undefined }}>
                        <td><SkuBadge sku={p.sku}/></td>
                        <td style={{ fontSize: 13, whiteSpace: "nowrap" }}>{p.name}</td>
                        <td><CatBadge cat={catMap[p.catId]}/></td>
                        <td style={{ color: "var(--text-3)" }}>{p.unit}</td>
                        <td style={{ textAlign: "right", fontWeight: 700, color: cnt > 0 ? "var(--accent)" : "var(--text-3)", fontVariantNumeric: "tabular-nums" }}>{cnt}</td>
                        <td><Pill variant={inactive ? "default" : "success"}>{inactive ? "หยุด" : "ใช้งาน"}</Pill></td>
                        <td>
                          <div style={{ display: "flex", gap: 4 }}>
                            <button onClick={() => { if (isEd) setEditPId(null); else { setEditPId(p.id); setEditPForm({ ...p }); setShowAddProd(false); } }}
                              className={`xr-btn xr-btn--sm ${isEd ? "" : ""}`}>
                              <Icon name={isEd ? "x" : "edit"} size={12}/>
                            </button>
                            <button onClick={() => { onSaveProds(products.map(x => x.id === p.id ? { ...x, active: x.active === false ? true : false } : x)); showToast(inactive ? `เปิด ${p.sku}` : `ปิด ${p.sku}`); }}
                              className="xr-btn xr-btn--sm">
                              <Icon name={inactive ? "check" : "minus"} size={12}/>
                            </button>
                            <button onClick={() => {
                              if (cnt > 0) return showToast(`ยังมีสต็อค ${cnt} ชิ้น ลบไม่ได้`, "err");
                              askConfirm(`ลบ "${p.name}"?`, `SKU: ${p.sku}`, () => { onSaveProds(products.filter(x => x.id !== p.id)); showToast(`ลบ ${p.sku} แล้ว`); });
                            }} className="xr-btn xr-btn--sm xr-btn--danger-soft" disabled={cnt > 0}>
                              <Icon name="trash" size={12}/>
                            </button>
                          </div>
                        </td>
                      </tr>
                    );
                  })}
                </tbody>
              </table>
            </div>
          </Card>
        </div>
      )}

      {activeSection === "locations" && (
        <div style={{ maxWidth: 720 }}>
          {showLocForm && (
            <Card className="xr-fade-in" style={{ marginBottom: 14, borderColor: "var(--info)" }}>
              <div style={{ fontWeight: 700, marginBottom: 14, color: "var(--info)" }}>{locForm.id ? "แก้ไขสถานที่" : "เพิ่มสถานที่ใหม่"}</div>
              <FG label="ชื่อสถานที่" style={{ marginBottom: 12 }}>
                <input className="xr-input" value={locForm.name} onChange={e => setLocForm(f => ({ ...f, name: e.target.value }))} placeholder="เช่น คลังสาขาใหม่"/>
              </FG>
              <FG label="ประเภทคลัง" style={{ marginBottom: 14 }}>
                <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 8 }}>
                  {LOC_TYPES.map(t => (
                    <button key={t.id} onClick={() => setLocForm(f => ({ ...f, locType: t.id, isStorage: t.id === "storage" }))}
                      className="xr-card xr-clickable" style={{
                        padding: 10, textAlign: "left",
                        border: `1.5px solid ${locForm.locType === t.id ? t.color : "var(--border)"}`,
                        background: locForm.locType === t.id ? `color-mix(in oklab, ${t.color} 6%, transparent)` : undefined,
                      }}>
                      <div style={{ fontSize: 13, fontWeight: 700, color: locForm.locType === t.id ? t.color : "var(--text-1)" }}>{t.label}</div>
                      <div style={{ fontSize: 11, color: "var(--text-3)", marginTop: 2 }}>{t.desc}</div>
                    </button>
                  ))}
                </div>
              </FG>
              <div style={{ display: "flex", gap: 8 }}>
                <Btn variant="accent" icon="check" onClick={() => {
                  const name = locForm.name.trim();
                  if (!name) return showToast("กรอกชื่อ", "err");
                  let updated;
                  if (!locForm.id) {
                    if (locations.find(l => l.name === name)) return showToast("ชื่อนี้มีแล้ว", "err");
                    updated = [...locations, { ...locForm, id: uid(), name }];
                  } else updated = locations.map(l => l.id === locForm.id ? { ...locForm, name } : l);
                  onSaveLocs(updated); setShowLocForm(false); showToast(locForm.id ? "แก้ไขแล้ว" : "เพิ่มคลังแล้ว");
                }}>บันทึก</Btn>
                <Btn variant="ghost" onClick={() => setShowLocForm(false)}>ยกเลิก</Btn>
              </div>
            </Card>
          )}
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 14 }}>
            <span style={{ color: "var(--text-3)", fontSize: 12 }}>{locations.length} สถานที่</span>
            <Btn variant="accent" icon="plus" onClick={() => { setLocForm({ id: null, name: "", isStorage: true, locType: "storage" }); setShowLocForm(true); }}>เพิ่มสถานที่</Btn>
          </div>
          <Card padded={false}>
            <table className="xr-table">
              <thead><tr><th>#</th><th>ชื่อ</th><th>ประเภท</th><th style={{ textAlign: "right" }}>ยอดรวม</th><th>จัดการ</th></tr></thead>
              <tbody>
                {locations.map((l, i) => {
                  const tot = stocks.filter(s => s.locId === l.id).reduce((a, b) => a + b.qty, 0);
                  return (
                    <tr key={l.id}>
                      <td style={{ color: "var(--text-3)" }}>{i + 1}</td>
                      <td style={{ fontWeight: 600 }}>{l.name}</td>
                      <td><LocBadge locType={l.locType}/></td>
                      <td style={{ textAlign: "right", fontWeight: 700, color: "var(--accent)", fontVariantNumeric: "tabular-nums" }}>{tot}</td>
                      <td>
                        <div style={{ display: "flex", gap: 4 }}>
                          <button onClick={() => { setLocForm({ ...l, locType: l.locType || (l.isStorage ? "storage" : "outbound") }); setShowLocForm(true); }} className="xr-btn xr-btn--sm">
                            <Icon name="edit" size={12}/>
                          </button>
                          <button onClick={() => {
                            if (tot > 0) return showToast("ยังมีสต็อค ลบไม่ได้", "err");
                            askConfirm(`ลบคลัง "${l.name}"?`, "ไม่สามารถย้อนกลับได้", () => { onSaveLocs(locations.filter(x => x.id !== l.id)); showToast("ลบแล้ว"); });
                          }} className="xr-btn xr-btn--sm xr-btn--danger-soft" disabled={tot > 0}>
                            <Icon name="trash" size={12}/>
                          </button>
                        </div>
                      </td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </Card>
        </div>
      )}
    </div>
  );
}

function ProductForm({ form, setForm, cats, onSave, onCancel }) {
  return (
    <>
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 2fr", gap: 10, marginBottom: 10 }}>
        {[["รหัส SKU", "sku", "Ori-s"], ["Barcode", "barcode", "8859…"], ["ชื่อสินค้า", "name", "Protein Original Sachet"]].map(([l, f, ph]) => (
          <FG key={f} label={l}>
            <input className="xr-input" value={form[f] || ""} onChange={e => setForm(fm => ({ ...fm, [f]: e.target.value }))} placeholder={ph}/>
          </FG>
        ))}
      </div>
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10, marginBottom: 14 }}>
        <FG label="หน่วย">
          <input className="xr-input" value={form.unit || ""} onChange={e => setForm(f => ({ ...f, unit: e.target.value }))} placeholder="ซอง"/>
        </FG>
        <FG label="หมวดหมู่">
          <select className="xr-select" value={form.catId || ""} onChange={e => setForm(f => ({ ...f, catId: e.target.value }))}>
            {cats.map(c => <option key={c.id} value={c.id}>{c.name}</option>)}
          </select>
        </FG>
      </div>
      <div style={{ display: "flex", gap: 8 }}>
        <Btn variant="accent" icon="check" onClick={onSave}>บันทึก</Btn>
        <Btn variant="ghost" onClick={onCancel}>ยกเลิก</Btn>
      </div>
    </>
  );
}

Object.assign(window, { AuditPage, HistoryPage, SettingsPage });
