// หน้าขายสินค้า (POS) + สแกนบาร์โค้ด + ใบเสร็จ
function PosPage({ ui, user }) {
  const { st, dispatch } = useStore();
  const toast = useToast();
  const wholesale = ui.page === "pos_wholesale";
  const priceOf = (p) => wholesale && p.wprice != null && p.wprice !== "" ? p.wprice : p.price;
  const allMode = ui.branch === "ALL";
  const branch = allMode ? (user.branch || "B1") : ui.branch;
  const brName = allMode ? "ทุกสาขา (รวม)" : branchOf(st, branch).name;

  const [q, setQ] = React.useState("");
  const [cat, setCat] = React.useState("ทั้งหมด");
  const [cart, setCart] = React.useState([]); // {productId, qty, price, locId}
  const [discount, setDiscount] = React.useState(0);
  const [customer, setCustomer] = React.useState("");
  const [pay, setPay] = React.useState("เงินสด");
  const [scanning, setScanning] = React.useState(false);
  const [printSale, setPrintSale] = React.useState(null);
  const [lastAdded, setLastAdded] = React.useState(null);
  const [pendingOpen, setPendingOpen] = React.useState(false);

  const branchLocs = allMode ? st.locations : st.locations.filter((l) => l.branch === branch);
  const qtyAt = (p) => allMode ? stockTotal(p) : stockInBranch(st, p, branch);
  const inCart = (pid) => cart.reduce((a, c) => a + (c.productId === pid ? c.qty : 0), 0);
  const bestLoc = (p) => {
    const locs = branchLocs.filter((l) => (p.stock[l.id] || 0) > 0).sort((a, b) => (p.stock[b.id] || 0) - (p.stock[a.id] || 0));
    return locs[0] ? locs[0].id : (branchLocs[0] ? branchLocs[0].id : null);
  };

  const SERIAL_CATS = ["เครื่อง", "เครื่องมือสอง", "Notebook/MacBook"];
  const partCatNames = st.cats.filter((c) => c.parts).map((c) => c.name);
  const products = st.products.filter((p) =>
    !partCatNames.includes(p.cat) &&
    (cat === "ทั้งหมด" || p.cat === cat) &&
    (q === "" || (p.name + p.sku + p.barcode).toLowerCase().includes(q.toLowerCase())) &&
    // ซ่อนสินค้าประเภทเครื่อง/Notebook ที่ขายแล้ว (สต็อกรวมทุกสาขา = 0)
    !(SERIAL_CATS.includes(p.cat) && stockTotal(p) <= 0)
  );
  const addToCart = (p) => {
    if (qtyAt(p) - inCart(p.id) <= 0) {
      const elsewhere = allMode ? 0 : stockTotal(p) - stockInBranch(st, p, branch);
      toast(elsewhere > 0 ? `หมดในสาขานี้ · มีที่สาขาอื่น ${elsewhere} ชิ้น (ขายข้ามสาขาไม่ได้)` : (allMode ? "สินค้าหมด" : "สินค้าหมดในสาขานี้"), "danger"); return;
    }
    setCart((c) => {
      const ex = c.find((x) => x.productId === p.id);
      if (ex) return c.map((x) => x.productId === p.id ? { ...x, qty: x.qty + 1 } : x);
      return [...c, { productId: p.id, qty: 1, price: priceOf(p), locId: bestLoc(p) }];
    });
    setLastAdded(p.id);
    setTimeout(() => setLastAdded(null), 600);
  };

  const scanBarcode = () => {
    setScanning(true);
    setTimeout(() => {
      const avail = st.products.filter((p) => qtyAt(p) - inCart(p.id) > 0);
      const p = avail[Math.floor(Math.random() * avail.length)];
      setScanning(false);
      if (p) { addToCart(p); toast(`สแกนพบ: ${p.name}`, "info"); }
    }, 1100);
  };

  const onSearchEnter = (e) => {
    if (e.key !== "Enter") return;
    const hit = st.products.find((p) => p.barcode === q.trim() || p.sku.toLowerCase() === q.trim().toLowerCase());
    if (hit) { addToCart(hit); setQ(""); }
  };

  const sub = cart.reduce((a, c) => a + c.qty * c.price, 0);
  const total = Math.max(0, sub - (Number(discount) || 0));

  const checkout = () => {
    const saleBranch = allMode && cart[0] ? ((st.locations.find((l) => l.id === cart[0].locId) || {}).branch || branch) : branch;
    const sale = { branch: saleBranch, items: cart.map((c) => ({ ...c, qty: Number(c.qty) })), discount: Number(discount) || 0, pay: wholesale ? "รอจ่าย" : pay, pending: wholesale, wholesale, customer: customer || (wholesale ? "ร้านค้าส่ง" : "ลูกค้าหน้าร้าน"), by: user.id };
    dispatch({ type: "SALE", sale });
    toast(wholesale ? `บันทึกขายส่ง (รอจ่าย) · ${fmtMoney(total)}` : `บันทึกการขายสำเร็จ · ${fmtMoney(total)}`);
    // grab the sale we just made for printing (id is generated in reducer)
    setTimeout(() => setPrintSale("LATEST"), 50);
    setCart([]); setDiscount(0); setCustomer(""); setPay("เงินสด");
  };
  // ร้านค้าขายส่งที่ยังค้างจ่าย (รอจ่าย)
  const pendingSales = st.sales.filter((s) => s.pending && (allMode || s.branch === branch));
  const latestSale = printSale === "LATEST" ? st.sales[0] : printSale;

  return (
    <div style={{ display: "grid", gridTemplateColumns: "1fr 370px", gap: 16, alignItems: "start" }}>
      {/* ── catalogue ── */}
      <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
        <Card style={{ padding: 14, display: "flex", gap: 10, alignItems: "center", flexWrap: "wrap" }}>
          <div style={{ flex: 1, minWidth: 220 }} onKeyDown={onSearchEnter}>
            <SearchBox value={q} onChange={setQ} placeholder="ค้นหาชื่อ / SKU / ยิงบาร์โค้ดแล้วกด Enter…" />
          </div>
          <Btn kind="soft" onClick={scanBarcode}>▥ สแกนบาร์โค้ด</Btn>
          <div style={{ display: "flex", gap: 6, flexWrap: "wrap" }}>
            {["ทั้งหมด", ...st.cats.filter((c) => !c.parts).map((c) => c.name)].map((c) => (
              <Btn key={c} sm kind={cat === c ? "primary" : "ghost"} onClick={() => setCat(c)}>{c}</Btn>
            ))}
          </div>
        </Card>

        <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(168px, 1fr))", gap: 12 }}>
          {products.map((p, i) => {
            const avail = qtyAt(p) - inCart(p.id);
            const elsewhere = allMode ? 0 : stockTotal(p) - stockInBranch(st, p, branch);
            const atOther = avail <= 0 && elsewhere > 0;
            return (
              <Card key={p.id} hover onClick={() => addToCart(p)} style={{
                padding: 12, cursor: avail > 0 ? "pointer" : "not-allowed", opacity: avail > 0 ? 1 : atOther ? 0.78 : 0.45,
                animation: `ss-rise .4s ${Math.min(i * 30, 300)}ms ease backwards`,
                outline: lastAdded === p.id ? `2.5px solid ${T.primary}` : "none",
              }}>
                <div style={{ display: "flex", justifyContent: "center", marginBottom: 9 }}>
                  <ProductImg p={p} size={74} radius={12} />
                </div>
                <div style={{ fontSize: 12.5, fontWeight: 600, lineHeight: 1.35, height: 34, overflow: "hidden" }}>{p.name}</div>
                <div style={{ display: "flex", alignItems: "baseline", marginTop: 6 }}>
                  <div style={{ fontFamily: T.headFont, fontWeight: 800, fontSize: 15.5, color: wholesale ? "#0E7A4D" : T.primary }}>{fmtMoney(priceOf(p))}{wholesale && p.wprice != null && p.wprice !== "" && <span style={{ fontSize: 9.5, fontWeight: 700, marginLeft: 4, color: "#0E7A4D" }}>ส่ง</span>}</div>
                  <div style={{ marginLeft: "auto", fontSize: 10.5, color: avail > 0 ? (avail <= (p.reorder || 0) ? T.accent : T.sub) : atOther ? T.primary : T.accent, fontWeight: 700 }}>
                    {avail > 0 ? `เหลือ ${avail}` : atOther ? `○ สาขาอื่น ${elsewhere}` : "หมด"}
                  </div>
                </div>
              </Card>
            );
          })}
          {products.length === 0 && <Card style={{ gridColumn: "1/-1" }}><EmptyState text="ไม่พบสินค้า" sub="ลองเปลี่ยนคำค้นหาหรือหมวดหมู่" /></Card>}
        </div>
      </div>

      {/* ── cart ── */}
      <div style={{ display: "flex", flexDirection: "column", gap: 12, position: "sticky", top: 0 }}>
      <Card style={{ padding: 0, overflow: "hidden" }}>
        <div style={{ background: T.heroGrad, color: "#fff", padding: "13px 18px" }}>
          <div style={{ fontFamily: T.headFont, fontWeight: 700, fontSize: 15 }}>{wholesale ? "ตะกร้าขายส่ง" : "ตะกร้าขาย"} · {brName}</div>
          <div style={{ fontSize: 11.5, opacity: 0.85 }}>พนักงาน: {user.name}{wholesale ? " · ราคาส่ง" : ""}</div>
        </div>
        <div style={{ padding: 16, display: "flex", flexDirection: "column", gap: 10 }}>
          {cart.length === 0 && <EmptyState icon="▥" text="ยังไม่มีสินค้าในตะกร้า" sub="คลิกสินค้า หรือสแกนบาร์โค้ด" />}
          {cart.map((c) => {
            const p = prodOf(st, c.productId);
            const locOpts = branchLocs.filter((l) => (p.stock[l.id] || 0) > 0).map((l) => ({ value: l.id, label: `${l.name} (${p.stock[l.id]})` }));
            return (
              <div key={c.productId} className="ss-cart-item" style={{ display: "flex", gap: 10, alignItems: "flex-start", borderBottom: `1px solid ${T.rowBorder}`, paddingBottom: 10 }}>
                <ProductImg p={p} size={40} />
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 12.5, fontWeight: 600, lineHeight: 1.3 }}>{p.name}</div>
                  <div style={{ display: "flex", gap: 6, marginTop: 6, alignItems: "center" }}>
                    <div style={{ display: "flex", alignItems: "center", border: `1px solid ${T.border}`, borderRadius: 8, overflow: "hidden" }}>
                      <button className="ss-qbtn" onClick={() => setCart((cs) => cs.map((x) => x === c ? { ...x, qty: Math.max(1, x.qty - 1) } : x))}>−</button>
                      <span style={{ width: 26, textAlign: "center", fontSize: 13, fontWeight: 700 }}>{c.qty}</span>
                      <button className="ss-qbtn" onClick={() => {
                        if (qtyAt(p) - inCart(p.id) <= 0) { toast("สต็อกไม่พอ", "danger"); return; }
                        setCart((cs) => cs.map((x) => x === c ? { ...x, qty: x.qty + 1 } : x));
                      }}>+</button>
                    </div>
                    <Select value={c.locId} onChange={(v) => setCart((cs) => cs.map((x) => x === c ? { ...x, locId: v } : x))}
                      options={locOpts.length ? locOpts : [{ value: c.locId, label: "—" }]}
                      style={{ padding: "4px 6px", fontSize: 11, borderRadius: 7, flex: 1 }} />
                  </div>
                </div>
                <div style={{ textAlign: "right" }}>
                  <div style={{ fontWeight: 800, fontSize: 13.5 }}>{fmtMoney(c.qty * c.price)}</div>
                  <a className="ss-link" style={{ fontSize: 11, color: T.accent }} onClick={() => setCart((cs) => cs.filter((x) => x !== c))}>ลบ</a>
                </div>
              </div>
            );
          })}

          {cart.length > 0 && (
            <React.Fragment>
              <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 8 }}>
                <Field label="ส่วนลด (บาท)"><NumInput value={discount} min="0" onChange={(e) => setDiscount(e.target.value)} style={{ padding: "7px 10px" }} /></Field>
                <Field label="ชำระโดย"><Select value={pay} onChange={setPay} options={["เงินสด", "โอน/QR", "บัตรเครดิต", "ผ่อน 0%"]} style={{ padding: "7px 10px" }} /></Field>
              </div>
              <Field label={wholesale ? "ร้าน" : "ชื่อลูกค้า / เบอร์โทร (ถ้ามี)"}><TextInput value={customer} onChange={(e) => setCustomer(e.target.value)} placeholder={wholesale ? "ชื่อร้านค้า" : "ลูกค้าหน้าร้าน"} style={{ padding: "7px 10px" }} /></Field>
              <div style={{ background: T.chipBg, borderRadius: 12, padding: "11px 14px", fontSize: 13, display: "flex", flexDirection: "column", gap: 5 }}>
                <div style={{ display: "flex", justifyContent: "space-between", color: T.sub }}><span>รวม {cart.reduce((a, c) => a + c.qty, 0)} ชิ้น</span><span>{fmtMoney(sub)}</span></div>
                <div style={{ display: "flex", justifyContent: "space-between", color: T.sub }}><span>ส่วนลด</span><span>− {fmtMoney(Number(discount) || 0)}</span></div>
                <div style={{ display: "flex", justifyContent: "space-between", fontFamily: T.headFont, fontWeight: 800, fontSize: 19 }}><span>ยอดสุทธิ</span><span style={{ color: T.primary }}>{fmtMoney(total)}</span></div>
              </div>
              <Btn onClick={checkout} style={{ width: "100%", justifyContent: "center", fontSize: 15, padding: "12px 0" }}>{wholesale ? "✓ ชำระเงิน & รอจ่าย" : "✓ ชำระเงิน & ออกใบเสร็จ"}</Btn>
            </React.Fragment>
          )}
        </div>
      </Card>
      {wholesale && (
        <Btn onClick={() => setPendingOpen(true)} style={{ width: "100%", justifyContent: "center", fontSize: 14.5, padding: "13px 0", background: "#E8833A", color: "#fff", borderColor: "#E8833A" }}>
          🏪 ร้านค้าชำระเงิน (รอจ่าย){pendingSales.length > 0 ? ` · ${pendingSales.length}` : ""}
        </Btn>
      )}
      </div>

      {/* scanning overlay */}
      {scanning && (
        <div style={{ position: "fixed", inset: 0, zIndex: 80, background: "rgba(10,18,42,.55)", backdropFilter: "blur(3px)", display: "flex", alignItems: "center", justifyContent: "center" }}>
          <div style={{ background: "#fff", borderRadius: 18, padding: "28px 36px", textAlign: "center", width: 280 }}>
            <div className="ss-scanbox">
              <BarcodeArt value="SCANNING" height={44} />
              <div className="ss-scanline"></div>
            </div>
            <div style={{ fontFamily: T.headFont, fontWeight: 700, marginTop: 14 }}>กำลังสแกน…</div>
            <div style={{ fontSize: 11.5, color: T.sub }}>จำลองการยิงบาร์โค้ดจากเครื่องสแกน</div>
          </div>
        </div>
      )}

      <PrintModal open={!!printSale} onClose={() => setPrintSale(null)} kind="sale" data={latestSale} />

      {/* ── ร้านค้าชำระเงิน (รอจ่าย) — รวมเป็นบิลเดียวต่อร้าน ── */}
      <Modal open={pendingOpen} onClose={() => setPendingOpen(false)} title="ร้านค้าชำระเงิน (รอจ่าย)" width={580}
        footer={<Btn kind="ghost" onClick={() => setPendingOpen(false)}>ปิด</Btn>}>
        {pendingSales.length === 0 ? (
          <EmptyState icon="✓" text="ไม่มีรายการค้างชำระ" sub="บิลขายส่งที่ยังไม่จ่ายจะแสดงที่นี่" />
        ) : (
          <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
            {Object.values(pendingSales.reduce((acc, s) => {
              const k = s.customer || "—";
              (acc[k] = acc[k] || { customer: k, sales: [] }).sales.push(s);
              return acc;
            }, {})).map((g) => {
              const ids = g.sales.map((s) => s.id);
              const gTotal = g.sales.reduce((a, s) => a + saleTotal(s), 0);
              const rows = g.sales.flatMap((s) => s.items.map((it, idx) => ({ saleId: s.id, idx, it })));
              return (
                <div key={g.customer} style={{ border: `1px solid ${T.border}`, borderRadius: 14, overflow: "hidden" }}>
                  <div style={{ display: "flex", alignItems: "center", gap: 12, padding: "11px 14px", background: T.chipBg }}>
                    <div style={{ minWidth: 0, flex: 1 }}>
                      <div style={{ fontFamily: T.headFont, fontWeight: 800, fontSize: 14.5 }}>🏪 {g.customer}</div>
                      <div style={{ fontSize: 11, color: T.sub }}>{rows.length} รายการ · ค้างจ่าย</div>
                    </div>
                    <div style={{ fontFamily: T.headFont, fontWeight: 800, fontSize: 16, color: "#C77700" }}>{fmtMoney(gTotal)}</div>
                    <Btn sm kind="ok" onClick={() => { dispatch({ type: "WHOLESALE_SETTLE", ids, pay: "เงินสด" }); toast(`รับชำระจาก ${g.customer} แล้ว · ${fmtMoney(gTotal)}`); }}>✓ ชำระ</Btn>
                  </div>
                  <div style={{ display: "flex", flexDirection: "column" }}>
                    {rows.map((r) => {
                      const p = prodOf(st, r.it.productId) || { name: "—", img: null };
                      return (
                        <div key={r.saleId + "_" + r.idx} style={{ display: "flex", alignItems: "center", gap: 10, padding: "9px 14px", borderTop: `1px solid ${T.rowBorder}`, fontSize: 12.5 }}>
                          <ProductImg p={p} size={32} />
                          <div style={{ flex: 1, minWidth: 0 }}>
                            <div style={{ fontWeight: 600, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{p.name}</div>
                            <div style={{ fontSize: 11, color: T.sub }}>{r.it.qty} × {fmtMoney(r.it.price)}</div>
                          </div>
                          <div style={{ fontWeight: 700 }}>{fmtMoney(r.it.qty * r.it.price)}</div>
                          <Btn sm kind="dangerSoft" onClick={() => { dispatch({ type: "WHOLESALE_RETURN_ITEM", id: r.saleId, idx: r.idx, by: user.id }); toast(`คืน ${p.name} กลับเข้าสต็อกแล้ว`, "info"); }}>↩ คืน</Btn>
                        </div>
                      );
                    })}
                  </div>
                </div>
              );
            })}
          </div>
        )}
      </Modal>
    </div>
  );
}
window.PosPage = PosPage;
