/* X-REAL Stock System — Quick Scan + Batch In/Out/Transfer/Repack */

// ─── QUICK SCAN ──────────────────────────────────────────────────────
function QuickScanPage({ products, cats, locations, stocks, getQty, getTot, onScanIn, onScanOut, onAudit, showToast, scanStreamRef, setTab }) {
  const [mode, setMode] = useState("pick"); // pick | scanned
  const [pickedSku, setPickedSku] = useState(null);

  const baan = locations.find(l => l.name === "บ้าน") || locations.find(l => l.isStorage);
  const activeProducts = products.filter(p => p.active !== false);
  const product = pickedSku ? products.find(p => p.id === pickedSku) : null;
  const totalQty = product ? getTot(product.id) : 0;
  const byLoc = product ? locations.map(l => ({ loc: l, qty: getQty(product.id, l.id) })).filter(x => x.qty > 0) : [];

  const onFound = (skuId) => { setPickedSku(skuId); setMode("scanned"); };

  return (
    <div  style={{ maxWidth: 720, margin: "0 auto" }}>
      <InfoBanner icon="zap" variant="accent">
        <strong>โหมดสแกนเร็ว</strong> — สแกน/พิมพ์ barcode แล้วเลือก action ได้ทันที (รับ / จ่าย / นับ)
      </InfoBanner>

      {!product && (
        <Card>
          <div style={{ fontSize: 15, fontWeight: 700, marginBottom: 14 }}>1. สแกนหรือเลือกสินค้า</div>
          <ScanBlock products={activeProducts} onFound={onFound} showToast={showToast} scanStreamRef={scanStreamRef}/>
          <div style={{ marginTop: 8 }}>
            <ProductPicker products={activeProducts} cats={cats} value={pickedSku} onChange={onFound} label="หรือเลือกจากรายการ"/>
          </div>
        </Card>
      )}

      {product && (
        <>
          <Card style={{ marginBottom: 14 }}>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", marginBottom: 14 }}>
              <div>
                <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 4 }}>
                  <SkuBadge sku={product.sku}/>
                  <CatBadge cat={cats.find(c => c.id === product.catId)}/>
                </div>
                <div style={{ fontSize: 17, fontWeight: 700 }}>{product.name}</div>
                <div style={{ fontSize: 12, color: "var(--text-3)", marginTop: 2 }}>หน่วย: {product.unit} · barcode: {product.barcode || "—"}</div>
              </div>
              <Btn variant="ghost" size="sm" onClick={() => { setPickedSku(null); setMode("pick"); }} icon="x">เปลี่ยน</Btn>
            </div>

            {/* Stock breakdown */}
            <div style={{
              background: "var(--surface-2)", borderRadius: "var(--r-md)",
              padding: "14px 16px", marginBottom: 14,
            }}>
              <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", marginBottom: 10 }}>
                <span className="xr-label">สต็อครวมทุกคลัง</span>
                <span style={{ fontSize: 24, fontWeight: 800, color: "var(--accent)", fontVariantNumeric: "tabular-nums" }}>
                  {totalQty} <span style={{ fontSize: 12, color: "var(--text-3)", fontWeight: 500 }}>{product.unit}</span>
                </span>
              </div>
              {byLoc.length > 0 && (
                <div style={{ display: "flex", flexDirection: "column", gap: 5 }}>
                  {byLoc.map(({ loc, qty }) => (
                    <div key={loc.id} style={{
                      display: "flex", justifyContent: "space-between", alignItems: "center",
                      padding: "6px 0", borderTop: "1px solid var(--border-subtle)",
                    }}>
                      <span style={{ display: "flex", alignItems: "center", gap: 6, fontSize: 12.5 }}>
                        <Icon name={LOC_TYPE_META[loc.locType]?.icon || "warehouse"} size={12} style={{ color: "var(--text-3)" }}/>
                        {loc.name}
                      </span>
                      <span style={{ fontSize: 13, fontWeight: 700, color: "var(--text-1)", fontVariantNumeric: "tabular-nums" }}>
                        {qty} <span style={{ color: "var(--text-3)", fontWeight: 400, fontSize: 11 }}>{product.unit}</span>
                      </span>
                    </div>
                  ))}
                </div>
              )}
            </div>

            {/* Action picker */}
            <div style={{ fontSize: 12, fontWeight: 700, color: "var(--text-2)", textTransform: "uppercase", letterSpacing: .6, marginBottom: 10 }}>
              เลือก action
            </div>
            <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(150px, 1fr))", gap: 8 }}>
              <QuickActionTile icon="in" label="รับเข้าคลัง" color="success" onClick={() => setTab("in", { prefill: { skuId: product.id } })}/>
              <QuickActionTile icon="out" label="จ่ายออก" color="danger" onClick={() => setTab("out", { prefill: { skuId: product.id } })}/>
              <QuickActionTile icon="transfer" label="โอน/ย้ายคลัง" color="warn" onClick={() => setTab("tr", { prefill: { skuId: product.id } })}/>
              <QuickActionTile icon="audit" label="นับสต็อค" color="info" onClick={() => setTab("audit", { prefill: { skuId: product.id } })}/>
            </div>
          </Card>

          {/* Inline quick-add/sub for one location */}
          {baan && (
            <Card>
              <div style={{ fontSize: 14, fontWeight: 700, marginBottom: 12 }}>ปรับยอด {baan.name} แบบเร็ว</div>
              <InlineAdjust product={product} loc={baan} curQty={getQty(product.id, baan.id)}
                onScanIn={onScanIn} onScanOut={onScanOut} onAudit={onAudit} showToast={showToast}/>
            </Card>
          )}
        </>
      )}
    </div>
  );
}

function QuickActionTile({ icon, label, color, onClick }) {
  return (
    <button onClick={onClick} className="xr-clickable xr-card" style={{
      padding: 14, display: "flex", flexDirection: "column", gap: 6,
      alignItems: "center", textAlign: "center",
    }}>
      <div style={{
        width: 40, height: 40, borderRadius: "var(--r-md)",
        background: `var(--${color}-bg)`, color: `var(--${color})`,
        display: "flex", alignItems: "center", justifyContent: "center",
      }}>
        <Icon name={icon} size={20}/>
      </div>
      <div style={{ fontSize: 12.5, fontWeight: 600 }}>{label}</div>
    </button>
  );
}

function InlineAdjust({ product, loc, curQty, onScanIn, onScanOut, onAudit, showToast }) {
  const [n, setN] = useState(1);
  return (
    <div>
      <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 10 }}>
        <button onClick={() => setN(Math.max(1, n - 1))} className="xr-btn xr-btn--icon">
          <Icon name="minus" size={14}/>
        </button>
        <input type="number" value={n} min="1" onChange={e => setN(Math.max(1, parseInt(e.target.value) || 1))}
          className="xr-input" style={{ textAlign: "center", fontSize: 18, fontWeight: 700 }}/>
        <button onClick={() => setN(n + 1)} className="xr-btn xr-btn--icon">
          <Icon name="plus" size={14}/>
        </button>
        <span style={{ color: "var(--text-3)", fontSize: 12 }}>{product.unit}</span>
      </div>
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 8 }}>
        <Btn variant="success" icon="plus" onClick={() => onScanIn(product.id, loc.id, n)}>+ รับเข้า {n}</Btn>
        <Btn variant="danger" icon="minus" onClick={() => {
          if (curQty < n) return showToast(`สต็อคในคลังเหลือแค่ ${curQty}`, "err");
          onScanOut(product.id, loc.id, n);
        }}>− จ่ายออก {n}</Btn>
      </div>
    </div>
  );
}

// ─── BATCH IN ──────────────────────────────────────────────────────────
function BatchInForm({ products, cats, locations, onSubmit, showToast, scanStreamRef, prefill }) {
  const storageLocs = locations.filter(l => l.isStorage);
  const [locId, setLocId] = useState(storageLocs[0]?.id || "");
  const [rows, setRows] = useState(prefill?.skuId ? [{ id: uid(), skuId: prefill.skuId, qty: "", exp: "", lot: "" }] : []);
  const [globalExp, setGlobalExp] = useState("");
  const [globalLot, setGlobalLot] = useState("");
  const [note, setNote] = useState("");
  const activeProducts = products.filter(p => p.active !== false);

  const addRow = () => setRows(r => [...r, { id: uid(), skuId: "", qty: "", exp: globalExp, lot: globalLot }]);
  const updateRow = (id, field, val) => setRows(r => r.map(row => row.id === id ? { ...row, [field]: val } : row));
  const removeRow = id => setRows(r => r.filter(row => row.id !== id));

  const onScanFound = skuId => {
    const empty = rows.find(r => !r.skuId);
    if (empty) updateRow(empty.id, "skuId", skuId);
    else setRows(r => [...r, { id: uid(), skuId, qty: "", exp: globalExp, lot: globalLot }]);
  };

  const valid = rows.filter(r => r.skuId && parseInt(r.qty) > 0);
  const totalUnits = valid.reduce((a, r) => a + parseInt(r.qty), 0);

  const submit = () => {
    if (!locId) return showToast("กรุณาเลือกคลังรับ", "err");
    if (!valid.length) return showToast("กรุณาเพิ่มสินค้าอย่างน้อย 1 รายการ", "err");
    onSubmit(locId, valid.map(r => ({ skuId: r.skuId, qty: parseInt(r.qty), exp: r.exp, lot: r.lot })), note);
    setRows([]); setNote("");
  };

  return (
    <div  style={{ maxWidth: 860 }}>
      <InfoBanner icon="info">เพิ่มสินค้าหลาย SKU ในครั้งเดียว แล้วกด <strong>บันทึก</strong> ทีเดียว — แต่ละแถวมี lot/exp ต่างกันได้</InfoBanner>

      {/* Step 1: location */}
      <Card style={{ marginBottom: 14 }}>
        <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 12 }}>
          <StepBadge n={1}/>
          <div style={{ fontWeight: 700 }}>เลือกคลังรับสินค้า</div>
        </div>
        <div style={{ display: "flex", gap: 8, flexWrap: "wrap" }}>
          {storageLocs.map(l => (
            <button key={l.id} onClick={() => setLocId(l.id)} className="xr-clickable xr-card" style={{
              padding: "10px 16px", display: "flex", alignItems: "center", gap: 10,
              border: `1.5px solid ${locId === l.id ? "var(--accent)" : "var(--border)"}`,
              background: locId === l.id ? "var(--accent-subtle)" : undefined,
            }}>
              <Icon name="warehouse" size={18} style={{ color: locId === l.id ? "var(--accent-hover)" : "var(--text-3)" }}/>
              <div style={{ textAlign: "left" }}>
                <div style={{ fontSize: 13, fontWeight: 700, color: locId === l.id ? "var(--accent-hover)" : "var(--text-1)" }}>{l.name}</div>
                <LocBadge locType={l.locType}/>
              </div>
              {locId === l.id && <Icon name="check" size={14} style={{ color: "var(--accent)", marginLeft: 4 }}/>}
            </button>
          ))}
        </div>
      </Card>

      {/* Step 2: defaults */}
      <Card style={{ marginBottom: 14 }}>
        <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 12 }}>
          <StepBadge n={2}/>
          <div style={{ fontWeight: 700 }}>ค่า Default <span style={{ color: "var(--text-3)", fontWeight: 400, fontSize: 12 }}>(ใช้ถ้าทุก SKU ใช้ lot/exp เดียวกัน)</span></div>
        </div>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
          <FG label="Lot Number">
            <input className="xr-input" value={globalLot} onChange={e => {
              setGlobalLot(e.target.value);
              setRows(r => r.map(row => ({ ...row, lot: e.target.value })));
            }} placeholder="เช่น LOT-2026-05"/>
          </FG>
          <FG label="วันหมดอายุ (dd/mm/yyyy)">
            <DateInput value={globalExp} onChange={v => {
              setGlobalExp(v);
              setRows(r => r.map(row => ({ ...row, exp: v })));
            }}/>
          </FG>
        </div>
      </Card>

      {/* Step 3: items */}
      <Card style={{ marginBottom: 14 }}>
        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 12 }}>
          <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
            <StepBadge n={3}/>
            <div style={{ fontWeight: 700 }}>รายการสินค้า</div>
          </div>
          {valid.length > 0 && (
            <Pill variant="accent">{valid.length} SKU · {totalUnits} ชิ้น</Pill>
          )}
        </div>
        <ScanBlock products={activeProducts} onFound={onScanFound} showToast={showToast} scanStreamRef={scanStreamRef}/>

        {rows.length > 0 && (
          <div style={{ marginBottom: 12, display: "flex", flexDirection: "column", gap: 8 }}>
            {rows.map(row => {
              const p = products.find(x => x.id === row.skuId);
              return (
                <div key={row.id} className="xr-card xr-batch-row-5" style={{
                  padding: 10, background: "var(--surface-2)",
                }}>
                  <select className="xr-select" value={row.skuId} onChange={e => updateRow(row.id, "skuId", e.target.value)}>
                    <option value="">— เลือกสินค้า —</option>
                    {activeProducts.map(p => <option key={p.id} value={p.id}>{p.sku} — {p.name}</option>)}
                  </select>
                  <input type="number" min="1" value={row.qty} onChange={e => updateRow(row.id, "qty", e.target.value)}
                    placeholder="0" className="xr-input" style={{ textAlign: "center", fontWeight: 700 }}/>
                  <input className="xr-input xr-input--sm" type="text" value={row.lot}
                    onChange={e => updateRow(row.id, "lot", e.target.value)}
                    placeholder="Lot"
                    autoCapitalize="characters" autoCorrect="off" autoComplete="off" spellCheck="false"
                    enterKeyHint="next"/>
                  <DateInput value={row.exp} onChange={v => updateRow(row.id, "exp", v)}/>
                  <button onClick={() => removeRow(row.id)} className="xr-btn xr-btn--icon xr-btn--danger-soft" style={{ width: 36, height: 36 }}>
                    <Icon name="x" size={14}/>
                  </button>
                </div>
              );
            })}
          </div>
        )}

        <button onClick={addRow} className="xr-btn xr-btn--soft" style={{ width: "100%" }}>
          <Icon name="plus" size={15}/> เพิ่มรายการ SKU
        </button>
      </Card>

      <Card>
        <FG label="หมายเหตุ" style={{ marginBottom: 12 }}>
          <input className="xr-input" value={note} onChange={e => setNote(e.target.value)} placeholder="เช่น รับของ PO-2026-05"/>
        </FG>
        <div style={{ display: "flex", gap: 10 }}>
          <Btn variant="accent" size="lg" icon="check" onClick={submit} full>
            บันทึกรับสินค้าเข้า {valid.length > 0 && `(${valid.length} รายการ · ${totalUnits} ชิ้น)`}
          </Btn>
          {rows.length > 0 && <Btn variant="ghost" onClick={() => setRows([])}>ล้าง</Btn>}
        </div>
      </Card>
    </div>
  );
}

function StepBadge({ n }) {
  return (
    <div style={{
      width: 22, height: 22, borderRadius: 999,
      background: "var(--accent)", color: "#fff",
      display: "flex", alignItems: "center", justifyContent: "center",
      fontSize: 11, fontWeight: 700, flexShrink: 0,
    }}>{n}</div>
  );
}

// ─── BATCH OUT ─────────────────────────────────────────────────────────
function BatchOutForm({ products, cats, locations, stocks, stores, consLedger, getQty, getTot, onSubmit, onConsSend, onConsReport, showToast, scanStreamRef, prefill }) {
  const [purpose, setPurpose] = useState("sale");
  const [storeId, setStoreId] = useState("");
  const [branchId, setBranchId] = useState("");
  const [rows, setRows] = useState(prefill?.skuId ? [{ id: uid(), skuId: prefill.skuId, qty: "" }] : []);
  const [reason, setReason] = useState("จำหน่าย");
  const [note, setNote] = useState("");

  const baan = locations.find(l => l.name === "บ้าน") || locations.find(l => l.isStorage);
  const activeProducts = products.filter(p => p.active !== false);
  const store = stores.find(s => s.id === storeId);
  const branch = store?.branches.find(b => b.id === branchId);

  // Compute branch balance for sku (for "report sold" purpose)
  const branchBal = (skuId) => consLedger
    .filter(e => e.branchId === branchId && e.skuId === skuId)
    .reduce((a, e) => a + (e.sentQty || 0) - (e.soldQty || 0) - (e.returnQty || 0) + (e.adjQty || 0), 0);

  // For sale: avail from บ้าน. For cons-send: avail from บ้าน. For cons-sold: avail = branch balance.
  const availForRow = (skuId) => {
    if (!skuId) return 0;
    if (purpose === "cons-sold") return branchId ? branchBal(skuId) : 0;
    return baan ? getQty(skuId, baan.id) : 0;
  };

  const addRow = skuId => {
    if (skuId && rows.find(r => r.skuId === skuId)) return showToast("SKU นี้เพิ่มแล้ว", "err");
    setRows(r => [...r, { id: uid(), skuId: skuId || "", qty: "" }]);
  };
  const updateRow = (id, field, val) => setRows(r => r.map(row => row.id === id ? { ...row, [field]: val } : row));
  const removeRow = id => setRows(r => r.filter(row => row.id !== id));

  const valid = rows.filter(r => r.skuId && parseInt(r.qty) > 0);
  const totalUnits = valid.reduce((a, r) => a + parseInt(r.qty), 0);

  const submit = () => {
    if (!valid.length) return showToast("กรุณาเพิ่มรายการสินค้า", "err");
    const items = valid.map(r => ({ skuId: r.skuId, qty: parseInt(r.qty) }));
    let ok = false;
    if (purpose === "sale") {
      if (!baan) return showToast("ไม่พบคลังบ้าน", "err");
      ok = onSubmit(baan.id, items, reason, note);
    } else if (purpose === "cons-send") {
      if (!storeId || !branchId) return showToast("กรุณาเลือกร้านและสาขา", "err");
      ok = onConsSend(storeId, branchId, items, note);
    } else if (purpose === "cons-sold") {
      if (!storeId || !branchId) return showToast("กรุณาเลือกร้านและสาขา", "err");
      ok = onConsReport(storeId, branchId, items, note);
    }
    if (ok) { setRows([]); setNote(""); }
  };

  const purposes = [
    { id: "sale",      icon: "tag",   label: "ขายตรงจากบ้าน",    desc: "Wholesale / ส่งร้าน / ตัดสต็อคบ้าน", color: "var(--danger)" },
    { id: "cons-send", icon: "store", label: "ส่งของไปฝากขาย",   desc: "บ้าน → สาขา (ตัดบ้าน + เพิ่มยอดสาขา)", color: "var(--info)" },
    { id: "cons-sold", icon: "tag",   label: "ตัดยอดขายฝากขาย", desc: "รายงานยอดขายจากสาขา", color: "var(--purple)" },
  ];
  const needsBranch = purpose === "cons-send" || purpose === "cons-sold";

  return (
    <div  style={{ maxWidth: 860 }}>
      <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(180px,1fr))", gap: 10, marginBottom: 14 }}>
        {purposes.map(pu => (
          <button key={pu.id} onClick={() => { setPurpose(pu.id); setRows([]); setStoreId(""); setBranchId(""); }}
            className="xr-clickable xr-card" style={{
              padding: 14,
              border: `1.5px solid ${purpose === pu.id ? pu.color : "var(--border)"}`,
              background: purpose === pu.id ? `color-mix(in oklab, ${pu.color} 6%, transparent)` : undefined,
              textAlign: "left",
            }}>
            <div style={{
              width: 32, height: 32, borderRadius: "var(--r-md)",
              background: `color-mix(in oklab, ${pu.color} 12%, transparent)`,
              color: pu.color,
              display: "flex", alignItems: "center", justifyContent: "center", marginBottom: 6,
            }}>
              <Icon name={pu.icon} size={16}/>
            </div>
            <div style={{ fontSize: 13.5, fontWeight: 700, color: purpose === pu.id ? pu.color : "var(--text-1)" }}>{pu.label}</div>
            <div style={{ fontSize: 11.5, color: "var(--text-3)", marginTop: 3 }}>{pu.desc}</div>
          </button>
        ))}
      </div>

      {needsBranch && (
        <Card style={{ marginBottom: 14 }}>
          <div style={{ fontWeight: 700, marginBottom: 10, fontSize: 13 }}>ร้านค้า / สาขา</div>
          {stores.length === 0 ? (
            <EmptyState icon="store" title="ยังไม่มีร้าน Consignment" hint="ไปที่หน้า Consignment → จัดการร้าน/สาขา"/>
          ) : (
            <>
              <div style={{ display: "flex", gap: 6, flexWrap: "wrap", marginBottom: 10 }}>
                {stores.map(s => (
                  <button key={s.id} onClick={() => { setStoreId(s.id); setBranchId(s.branches[0]?.id || ""); }}
                    className="xr-card xr-clickable" style={{
                      padding: "7px 12px",
                      border: `1.5px solid ${storeId === s.id ? "var(--purple)" : "var(--border)"}`,
                      background: storeId === s.id ? "var(--purple-bg)" : undefined,
                      fontSize: 13, fontWeight: 600,
                      color: storeId === s.id ? "var(--purple)" : "var(--text-1)",
                    }}><Icon name="store" size={13} style={{ marginRight: 5, verticalAlign: -2 }}/>{s.name}</button>
                ))}
              </div>
              {store && (
                store.branches.length === 0 ? (
                  <div style={{ fontSize: 12, color: "var(--text-3)", padding: "6px 4px" }}>ร้านนี้ยังไม่มีสาขา</div>
                ) : (
                  <div style={{ display: "flex", gap: 6, flexWrap: "wrap" }}>
                    {store.branches.map(b => (
                      <button key={b.id} onClick={() => setBranchId(b.id)} className="xr-btn xr-btn--sm" style={{
                        background: branchId === b.id ? "var(--purple-bg)" : undefined,
                        color: branchId === b.id ? "var(--purple)" : undefined,
                        borderColor: branchId === b.id ? "var(--purple-border)" : undefined,
                      }}>{b.name}</button>
                    ))}
                  </div>
                )
              )}
            </>
          )}
        </Card>
      )}

      <Card style={{ marginBottom: 14 }}>
        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 12 }}>
          <div style={{ fontWeight: 700 }}>รายการสินค้า</div>
          {valid.length > 0 && <Pill variant="danger">{valid.length} SKU · {totalUnits} ชิ้น</Pill>}
        </div>
        <ScanBlock products={activeProducts} onFound={addRow} showToast={showToast} scanStreamRef={scanStreamRef}/>

        {rows.length > 0 && (
          <div style={{ marginBottom: 12, display: "flex", flexDirection: "column", gap: 8 }}>
            {rows.map(row => {
              const p = products.find(x => x.id === row.skuId);
              const avail = availForRow(row.skuId);
              const overLimit = parseInt(row.qty) > avail;
              const availLabel = purpose === "cons-sold" ? "คงเหลือสาขา" : "ในคลังบ้าน";
              return (
                <div key={row.id} className="xr-card xr-batch-row-3" style={{
                  padding: 10, background: "var(--surface-2)",
                }}>
                  <div>
                    <select className="xr-select" value={row.skuId} onChange={e => updateRow(row.id, "skuId", e.target.value)}>
                      <option value="">— เลือกสินค้า —</option>
                      {activeProducts.map(pp => {
                        const q = availForRow(pp.id);
                        return <option key={pp.id} value={pp.id}>{pp.sku} — {pp.name} ({q} {pp.unit})</option>;
                      })}
                    </select>
                    {p && (
                      <div style={{ fontSize: 11, marginTop: 4, color: avail > 0 ? "var(--text-3)" : "var(--danger)" }}>
                        {availLabel}: <strong style={{ color: avail > 0 ? "var(--text-1)" : "var(--danger)" }}>{avail} {p.unit}</strong>
                      </div>
                    )}
                  </div>
                  <input type="number" min="1" max={avail} value={row.qty} onChange={e => updateRow(row.id, "qty", e.target.value)}
                    placeholder="0" className="xr-input" style={{
                      textAlign: "center", fontWeight: 700,
                      borderColor: overLimit ? "var(--danger-border)" : undefined,
                      color: overLimit ? "var(--danger)" : undefined,
                    }}/>
                  <button onClick={() => removeRow(row.id)} className="xr-btn xr-btn--icon xr-btn--danger-soft" style={{ width: 36, height: 36 }}>
                    <Icon name="x" size={14}/>
                  </button>
                </div>
              );
            })}
          </div>
        )}

        <button onClick={() => addRow("")} className="xr-btn xr-btn--soft" style={{ width: "100%" }}>
          <Icon name="plus" size={15}/> เพิ่มรายการ SKU
        </button>
      </Card>

      <Card>
        {purpose === "sale" && (
          <div style={{ display: "grid", gridTemplateColumns: "1fr 2fr", gap: 12, marginBottom: 12 }}>
            <FG label="เหตุผล">
              <select className="xr-select" value={reason} onChange={e => setReason(e.target.value)}>
                {["จำหน่าย", "หมดอายุ", "เสียหาย", "คืนผู้ผลิต", "ตัวอย่าง/Sample", "อื่นๆ"].map(r => <option key={r}>{r}</option>)}
              </select>
            </FG>
            <FG label="หมายเหตุ">
              <input className="xr-input" value={note} onChange={e => setNote(e.target.value)} placeholder="เลขออเดอร์, ชื่อร้าน…"/>
            </FG>
          </div>
        )}
        {purpose !== "sale" && (
          <FG label="หมายเหตุ" style={{ marginBottom: 12 }}>
            <input className="xr-input" value={note} onChange={e => setNote(e.target.value)} placeholder={purpose === "cons-send" ? "เช่น รอบส่งกลางเดือน" : "เช่น รายงานยอดประจำสัปดาห์"}/>
          </FG>
        )}
        <Btn variant={purpose === "sale" ? "danger" : purpose === "cons-send" ? "info" : "purple"} size="lg" icon="check" onClick={submit} full>
          {purpose === "sale" && "บันทึกจ่ายออก"}
          {purpose === "cons-send" && (branch ? `ส่งของไป ${branch.name}` : "ส่งของไปฝากขาย")}
          {purpose === "cons-sold" && (branch ? `บันทึกยอดขาย ${branch.name}` : "บันทึกยอดขายฝาก")}
          {valid.length > 0 && ` (${valid.length} รายการ · ${totalUnits} ชิ้น)`}
        </Btn>
      </Card>
    </div>
  );
}

// ─── TRANSFER (multi-SKU) ──────────────────────────────────────────────
function TransferForm({ products, cats, locations, stocks, getTot, getQty, onSubmit, onBatchSubmit, showToast, scanStreamRef, prefill }) {
  const [moveType, setMoveType] = useState("out");
  const [fromId, setFromId] = useState("");
  const [toId, setToId] = useState("");
  const [rows, setRows] = useState(prefill?.skuId ? [{ id: uid(), skuId: prefill.skuId, qty: "" }] : []);
  const [note, setNote] = useState("");

  const storageLocs = locations.filter(l => l.isStorage);
  const fromLocs = moveType === "out" ? storageLocs : locations.filter(l => !l.isStorage);
  const toLocs   = moveType === "out" ? locations : storageLocs;
  const activeProducts = products.filter(p => p.active !== false);

  const reset = () => { setFromId(""); setToId(""); setRows([]); };
  const addRow = skuId => {
    if (skuId && rows.find(r => r.skuId === skuId)) return showToast("SKU นี้เพิ่มแล้ว", "err");
    setRows(r => [...r, { id: uid(), skuId: skuId || "", qty: "" }]);
  };
  const updateRow = (id, field, val) => setRows(r => r.map(row => row.id === id ? { ...row, [field]: val } : row));
  const removeRow = id => setRows(r => r.filter(row => row.id !== id));

  const valid = rows.filter(r => r.skuId && parseInt(r.qty) > 0);
  const totalUnits = valid.reduce((a, r) => a + parseInt(r.qty), 0);

  const submit = () => {
    if (!fromId || !toId) return showToast("กรุณาเลือกต้นทาง/ปลายทาง", "err");
    if (fromId === toId) return showToast("ต้นทางและปลายทางต้องต่างกัน", "err");
    if (!valid.length) return showToast("กรุณาเพิ่มสินค้าอย่างน้อย 1 รายการ", "err");
    for (const r of valid) {
      const avail = getQty(r.skuId, fromId);
      const p = products.find(x => x.id === r.skuId);
      if (parseInt(r.qty) > avail) return showToast(`${p?.sku} มีแค่ ${avail}`, "err");
    }
    const items = valid.map(r => ({ skuId: r.skuId, qty: parseInt(r.qty) }));
    const prefix = moveType === "return" ? "[คืนสต็อค] " : "";
    const ok = onBatchSubmit
      ? onBatchSubmit(fromId, toId, items, prefix + note)
      : items.every(it => onSubmit(it.skuId, fromId, toId, it.qty, prefix + note));
    if (ok !== false) { setRows([]); setNote(""); }
  };

  return (
    <div  style={{ maxWidth: 860 }}>
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10, marginBottom: 14 }}>
        {[
          { id: "out", icon: "transfer", label: "ส่งออกจาก Storage", desc: "บ้าน → Fulfillment / บูธ / ร้าน", color: "var(--warn)" },
          { id: "return", icon: "in", label: "คืนสต็อคกลับ Storage", desc: "บูธ / Consignment → บ้าน", color: "var(--success)" },
        ].map(mt => (
          <button key={mt.id} onClick={() => { setMoveType(mt.id); reset(); }} className="xr-card xr-clickable" style={{
            padding: 16, textAlign: "left",
            border: `1.5px solid ${moveType === mt.id ? mt.color : "var(--border)"}`,
            background: moveType === mt.id ? `color-mix(in oklab, ${mt.color} 6%, transparent)` : undefined,
          }}>
            <div style={{
              width: 36, height: 36, borderRadius: "var(--r-md)",
              background: `color-mix(in oklab, ${mt.color} 12%, transparent)`,
              color: mt.color,
              display: "flex", alignItems: "center", justifyContent: "center", marginBottom: 8,
            }}>
              <Icon name={mt.icon} size={18}/>
            </div>
            <div style={{ fontSize: 14, fontWeight: 700, color: moveType === mt.id ? mt.color : "var(--text-1)" }}>{mt.label}</div>
            <div style={{ fontSize: 12, color: "var(--text-3)", marginTop: 3 }}>{mt.desc}</div>
          </button>
        ))}
      </div>

      <Card style={{ marginBottom: 14 }}>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
          <FG label="จากคลัง">
            <select className="xr-select" value={fromId} onChange={e => setFromId(e.target.value)}>
              <option value="">— เลือกต้นทาง —</option>
              {fromLocs.map(l => (
                <option key={l.id} value={l.id}>{l.name}</option>
              ))}
            </select>
          </FG>
          <FG label="ไปที่">
            <select className="xr-select" value={toId} onChange={e => setToId(e.target.value)} disabled={!fromId}>
              <option value="">— เลือกปลายทาง —</option>
              {toLocs.filter(l => l.id !== fromId).map(l => (
                <option key={l.id} value={l.id}>{l.name}</option>
              ))}
            </select>
          </FG>
        </div>

        {fromId && toId && (
          <div className="xr-fade-in" style={{
            marginTop: 12, padding: "10px 14px", background: "var(--surface-2)",
            border: "1px solid var(--border)", borderRadius: "var(--r-md)",
            display: "flex", alignItems: "center", gap: 14,
          }}>
            <div style={{ textAlign: "center", minWidth: 80 }}>
              <div style={{ fontWeight: 700, fontSize: 13 }}>{locations.find(l => l.id === fromId)?.name}</div>
              <LocBadge locType={locations.find(l => l.id === fromId)?.locType}/>
            </div>
            <Icon name="arrow-right" size={20} style={{ color: moveType === "return" ? "var(--success)" : "var(--warn)" }}/>
            <div style={{ textAlign: "center", minWidth: 80 }}>
              <div style={{ fontWeight: 700, fontSize: 13 }}>{locations.find(l => l.id === toId)?.name}</div>
              <LocBadge locType={locations.find(l => l.id === toId)?.locType}/>
            </div>
          </div>
        )}
      </Card>

      <Card style={{ marginBottom: 14 }}>
        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 12 }}>
          <div style={{ fontWeight: 700 }}>รายการสินค้าที่โอน</div>
          {valid.length > 0 && <Pill variant="accent">{valid.length} SKU · {totalUnits} ชิ้น</Pill>}
        </div>
        <ScanBlock products={activeProducts} onFound={addRow} showToast={showToast} scanStreamRef={scanStreamRef}/>

        {rows.length > 0 && (
          <div style={{ marginBottom: 12, display: "flex", flexDirection: "column", gap: 8 }}>
            {rows.map(row => {
              const p = products.find(x => x.id === row.skuId);
              const avail = fromId && row.skuId ? getQty(row.skuId, fromId) : 0;
              const overLimit = parseInt(row.qty) > avail;
              return (
                <div key={row.id} className="xr-card xr-batch-row-3" style={{
                  padding: 10, background: "var(--surface-2)",
                }}>
                  <div>
                    <select className="xr-select" value={row.skuId} onChange={e => updateRow(row.id, "skuId", e.target.value)}>
                      <option value="">— เลือกสินค้า —</option>
                      {activeProducts.map(pp => {
                        const q = fromId ? getQty(pp.id, fromId) : 0;
                        return <option key={pp.id} value={pp.id}>{pp.sku} — {pp.name} ({q} {pp.unit})</option>;
                      })}
                    </select>
                    {p && (
                      <div style={{ fontSize: 11, marginTop: 4, color: avail > 0 ? "var(--text-3)" : "var(--danger)" }}>
                        ในคลังต้นทาง: <strong style={{ color: avail > 0 ? "var(--text-1)" : "var(--danger)" }}>{avail} {p.unit}</strong>
                      </div>
                    )}
                  </div>
                  <input type="number" min="1" max={avail} value={row.qty} onChange={e => updateRow(row.id, "qty", e.target.value)}
                    placeholder="0" className="xr-input" style={{
                      textAlign: "center", fontWeight: 700,
                      borderColor: overLimit ? "var(--danger-border)" : undefined,
                      color: overLimit ? "var(--danger)" : undefined,
                    }}/>
                  <button onClick={() => removeRow(row.id)} className="xr-btn xr-btn--icon xr-btn--danger-soft" style={{ width: 36, height: 36 }}>
                    <Icon name="x" size={14}/>
                  </button>
                </div>
              );
            })}
          </div>
        )}

        <button onClick={() => addRow("")} className="xr-btn xr-btn--soft" style={{ width: "100%" }}>
          <Icon name="plus" size={15}/> เพิ่มรายการ SKU
        </button>
      </Card>

      <Card>
        <FG label="หมายเหตุ" style={{ marginBottom: 12 }}>
          <input className="xr-input" value={note} onChange={e => setNote(e.target.value)} placeholder={moveType === "return" ? "เช่น คืนของหลังออกบูธ" : "เช่น ส่ง Fulfillment รอบ A"}/>
        </FG>
        <Btn variant={moveType === "return" ? "success" : "accent"} icon="check" size="lg" onClick={submit} full>
          {moveType === "return" ? "บันทึกคืนสต็อค" : "บันทึกโอนย้ายคลัง"} {valid.length > 0 && `(${valid.length} รายการ · ${totalUnits} ชิ้น)`}
        </Btn>
      </Card>
    </div>
  );
}

// ─── REPACK ────────────────────────────────────────────────────────────
function RepackForm({ products, cats, locations, stocks, repackRules, getQty, onSubmit, showToast, onSaveRules, askConfirm }) {
  const [parentId, setParentId] = useState("");
  const [childId, setChildId] = useState("");
  const [locId, setLocId] = useState("");
  const [qtyP, setQtyP] = useState("");
  const [note, setNote] = useState("");
  const [showManage, setShowManage] = useState(false);
  const [newRule, setNewRule] = useState({ parentSku: "", childSku: "", ratio: "" });

  const storageLocs = locations.filter(l => l.isStorage);
  const pp = products.find(p => p.id === parentId);
  const cp = products.find(p => p.id === childId);
  const rule = repackRules.find(r => r.parentSku === pp?.sku && r.childSku === cp?.sku);
  const ratio = rule?.ratio || 0;
  const parentAvail = parentId && locId ? getQty(parentId, locId) : 0;
  const childQty = (parseInt(qtyP) || 0) * ratio;
  const parentProds = products.filter(p => repackRules.some(r => r.parentSku === p.sku) && p.active !== false);
  const possibleChildren = repackRules.filter(r => r.parentSku === pp?.sku)
    .map(r => { const c = products.find(p => p.sku === r.childSku); return c ? { ...c, ratio: r.ratio } : null; })
    .filter(Boolean);

  const submit = () => {
    if (!parentId || !childId || !locId) return showToast("กรุณากรอกข้อมูลให้ครบ", "err");
    const n = parseInt(qtyP) || 0;
    if (n <= 0) return showToast("กรุณากรอกจำนวน", "err");
    if (n > parentAvail) return showToast(`สต็อค ${pp?.sku} มีแค่ ${parentAvail}`, "err");
    const ok = onSubmit(parentId, childId, n, locId, note);
    if (ok) { setQtyP(""); setNote(""); }
  };

  const addRule = () => {
    const { parentSku, childSku, ratio } = newRule;
    if (!parentSku || !childSku || !parseInt(ratio)) return showToast("กรอกข้อมูลให้ครบ", "err");
    if (repackRules.find(r => r.parentSku === parentSku && r.childSku === childSku)) return showToast("สูตรนี้มีแล้ว", "err");
    onSaveRules([...repackRules, { id: uid(), parentSku, childSku, ratio: parseInt(ratio) }]);
    setNewRule({ parentSku: "", childSku: "", ratio: "" });
    showToast("เพิ่มสูตรแล้ว");
  };
  const delRule = (id, label) => { askConfirm(`ลบสูตร "${label}"?`, null, () => { onSaveRules(repackRules.filter(r => r.id !== id)); showToast("ลบสูตรแล้ว"); }); };

  return (
    <div  style={{ maxWidth: 720 }}>
      <InfoBanner icon="repack" variant="accent">
        Re-pack แปลง SKU หนึ่งเป็นอีก SKU ตามสัดส่วน — เช่น <strong>กระปุก 2lbs × 1 → ซอง × 26</strong> — สามารถเพิ่ม/ลบสูตรได้เอง
      </InfoBanner>

      {/* Rule chips */}
      <Card style={{ marginBottom: 14 }}>
        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 10 }}>
          <div style={{ fontWeight: 700, fontSize: 13 }}>สูตร Re-pack ในระบบ</div>
          <Btn variant="ghost" size="sm" icon={showManage ? "x" : "settings"} onClick={() => setShowManage(v => !v)}>
            {showManage ? "ซ่อน" : "จัดการ"}
          </Btn>
        </div>
        <div style={{ display: "flex", gap: 6, flexWrap: "wrap" }}>
          {repackRules.map(r => {
            const pp2 = products.find(p => p.sku === r.parentSku);
            const cp2 = products.find(p => p.sku === r.childSku);
            if (!pp2 || !cp2) return null;
            const active = parentId === pp2.id && childId === cp2.id;
            return (
              <button key={r.id} onClick={() => { setParentId(pp2.id); setChildId(cp2.id); setQtyP(""); }}
                className="xr-card xr-clickable" style={{
                  padding: "6px 10px",
                  border: `1.5px solid ${active ? "var(--accent)" : "var(--border)"}`,
                  background: active ? "var(--accent-subtle)" : "var(--surface-2)",
                  fontSize: 11.5, display: "flex", alignItems: "center", gap: 5,
                }}>
                <span style={{ fontWeight: 700, color: "var(--text-1)" }} className="xr-mono">{r.parentSku}</span>
                <span style={{ color: "var(--text-3)" }}>×1 →</span>
                <span style={{ fontWeight: 700, color: "var(--accent-hover)" }} className="xr-mono">{r.childSku}</span>
                <span style={{ color: "var(--text-3)" }}>×{r.ratio}</span>
              </button>
            );
          })}
        </div>
        {showManage && (
          <div className="xr-fade-in" style={{
            marginTop: 12, padding: 12, background: "var(--surface-2)", borderRadius: "var(--r-md)",
          }}>
            <div style={{ marginBottom: 10, display: "flex", flexDirection: "column", gap: 5 }}>
              {repackRules.map(r => (
                <div key={r.id} style={{
                  display: "flex", alignItems: "center", justifyContent: "space-between",
                  padding: "6px 12px", background: "var(--surface)",
                  borderRadius: "var(--r-sm)", border: "1px solid var(--border)",
                }}>
                  <span style={{ fontSize: 12 }} className="xr-mono">
                    <strong>{r.parentSku}</strong> ×1 → <strong style={{ color: "var(--accent-hover)" }}>{r.childSku}</strong> ×{r.ratio}
                  </span>
                  <Btn size="sm" variant="danger-soft" onClick={() => delRule(r.id, `${r.parentSku}→${r.childSku}×${r.ratio}`)}>ลบ</Btn>
                </div>
              ))}
            </div>
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 70px 80px", gap: 6, alignItems: "flex-end" }}>
              <FG label="Parent SKU">
                <select className="xr-select xr-input--sm" value={newRule.parentSku} onChange={e => setNewRule(n => ({ ...n, parentSku: e.target.value }))}>
                  <option value="">— SKU —</option>
                  {products.map(p => <option key={p.id} value={p.sku}>{p.sku}</option>)}
                </select>
              </FG>
              <FG label="Child SKU">
                <select className="xr-select xr-input--sm" value={newRule.childSku} onChange={e => setNewRule(n => ({ ...n, childSku: e.target.value }))}>
                  <option value="">— SKU —</option>
                  {products.map(p => <option key={p.id} value={p.sku}>{p.sku}</option>)}
                </select>
              </FG>
              <FG label="× Ratio">
                <input className="xr-input xr-input--sm" type="number" min="1" value={newRule.ratio} onChange={e => setNewRule(n => ({ ...n, ratio: e.target.value }))} placeholder="12" style={{ textAlign: "center" }}/>
              </FG>
              <Btn variant="accent" size="sm" onClick={addRule} icon="plus">เพิ่ม</Btn>
            </div>
          </div>
        )}
      </Card>

      <Card>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12, marginBottom: 12 }}>
          <FG label="SKU ต้นทาง (Parent)">
            <select className="xr-select" value={parentId} onChange={e => { setParentId(e.target.value); setChildId(""); setQtyP(""); }}>
              <option value="">— เลือก Parent —</option>
              {parentProds.map(p => <option key={p.id} value={p.id}>{p.sku} — {p.name}</option>)}
            </select>
          </FG>
          <FG label="SKU ปลายทาง (Child)">
            <select className="xr-select" value={childId} onChange={e => { setChildId(e.target.value); setQtyP(""); }} disabled={!parentId}>
              <option value="">— เลือก Child —</option>
              {possibleChildren.map(c => <option key={c.id} value={c.id}>{c.sku} — {c.name} (×{c.ratio})</option>)}
            </select>
          </FG>
        </div>
        <FG label="คลังที่ทำ Re-pack" style={{ marginBottom: 12 }}>
          <div style={{ display: "flex", gap: 8, flexWrap: "wrap" }}>
            {storageLocs.map(l => {
              const q = parentId ? getQty(parentId, l.id) : 0;
              return (
                <button key={l.id} onClick={() => setLocId(l.id)} className="xr-card xr-clickable" style={{
                  padding: "9px 14px", textAlign: "left", minWidth: 130,
                  border: `1.5px solid ${locId === l.id ? "var(--accent)" : "var(--border)"}`,
                  background: locId === l.id ? "var(--accent-subtle)" : undefined,
                }}>
                  <div style={{ fontSize: 13, fontWeight: 700, color: locId === l.id ? "var(--accent-hover)" : "var(--text-1)" }}>{l.name}</div>
                  {parentId && <div style={{ fontSize: 11.5, color: q > 0 ? "var(--accent-hover)" : "var(--text-3)", marginTop: 2 }}>มี {q} {pp?.unit}</div>}
                </button>
              );
            })}
          </div>
        </FG>

        {parentId && childId && locId && (
          <div className="xr-fade-in" style={{
            padding: 14, background: "var(--accent-subtle-2)",
            border: "1px solid var(--accent-border)", borderRadius: "var(--r-md)",
            marginBottom: 12, display: "flex", alignItems: "center", gap: 12,
          }}>
            <div style={{ textAlign: "center", minWidth: 90 }}>
              <div style={{ fontSize: 13, fontWeight: 700 }} className="xr-mono">{pp?.sku}</div>
              <div style={{ fontSize: 11, color: "var(--text-3)" }}>คงเหลือ {parentAvail} {pp?.unit}</div>
            </div>
            <div style={{ flex: 1, textAlign: "center" }}>
              <Icon name="repack" size={22} style={{ color: "var(--accent-hover)" }}/>
              {ratio > 0 && <div style={{ fontSize: 11.5, color: "var(--accent-hover)", fontWeight: 700, marginTop: 2 }}>×1 → ×{ratio}</div>}
            </div>
            <div style={{ textAlign: "center", minWidth: 90 }}>
              <div style={{ fontSize: 13, fontWeight: 700 }} className="xr-mono">{cp?.sku}</div>
              {childQty > 0 && <div style={{ fontSize: 12, fontWeight: 700, color: "var(--success)" }}>+{childQty} {cp?.unit}</div>}
            </div>
          </div>
        )}

        {parentId && childId && locId && (
          <FG label={`จำนวน ${pp?.unit} ที่จะ Re-pack (สูงสุด ${parentAvail})`}>
            <input className="xr-input" type="number" min="1" max={parentAvail} value={qtyP} onChange={e => setQtyP(e.target.value)} placeholder={`1–${parentAvail}`}/>
          </FG>
        )}
        <FG label="หมายเหตุ" style={{ marginTop: 8, marginBottom: 12 }}>
          <input className="xr-input" value={note} onChange={e => setNote(e.target.value)} placeholder="หมายเหตุ"/>
        </FG>
        <Btn variant="accent" icon="check" size="lg" onClick={submit} full>
          บันทึก Re-pack
        </Btn>
      </Card>
    </div>
  );
}

Object.assign(window, { QuickScanPage, BatchInForm, BatchOutForm, TransferForm, RepackForm });
