// หน้าคลัง & Location — คงเหลือรายตำแหน่ง + โอนย้าย
function LocationsPage({ ui, user }) {
  const { st, dispatch } = useStore();
  const toast = useToast();
  const [sel, setSel] = React.useState(null); // selected location id
  const [tf, setTf] = React.useState(null); // {productId, from}
  const [tfTo, setTfTo] = React.useState("");
  const [tfQty, setTfQty] = React.useState(1);
  const [showAdd, setShowAdd] = React.useState(false);
  const [delLoc, setDelLoc] = React.useState(null);
  const canManage = ["owner", "manager", "stock"].includes(user.role);
  const addBranch = ui.branch === "ALL" ? (user.branch || st.branches[0].id) : ui.branch;
  const [nl, setNl] = React.useState({ branch: addBranch, name: "" });

  const locs = st.locations.filter((l) => ui.branch === "ALL" || l.branch === ui.branch);
  const itemsAt = (locId) => st.products.filter((p) => (p.stock[locId] || 0) > 0).map((p) => ({ p, qty: p.stock[locId] }));
  const selLoc = st.locations.find((l) => l.id === sel);
  const valueAt = (locId) => itemsAt(locId).reduce((a, { p, qty }) => a + p.cost * qty, 0);
  const qtyAt = (locId) => itemsAt(locId).reduce((a, x) => a + x.qty, 0);

  const doTransfer = () => {
    if (!tfTo || !tfQty) { toast("เลือกปลายทางและจำนวน", "danger"); return; }
    const p = prodOf(st, tf.productId);
    if ((p.stock[tf.from] || 0) < tfQty) { toast("จำนวนเกินสต็อกที่มี", "danger"); return; }
    dispatch({ type: "TRANSFER", productId: tf.productId, from: tf.from, to: tfTo, qty: Number(tfQty), by: user.id });
    toast(`โอน ${p.name} × ${tfQty} → ${locName(st, tfTo)} แล้ว`);
    setTf(null); setTfTo(""); setTfQty(1);
  };

  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
      <div style={{ display: "flex", alignItems: "center", gap: 10, flexWrap: "wrap" }}>
        <div style={{ fontSize: 13, color: T.sub, flex: 1, minWidth: 200 }}>
          คลิก Location เพื่อดูสินค้าคงเหลือภายใน · การโอนย้ายบันทึกความเคลื่อนไหวให้อัตโนมัติ
        </div>
        {canManage && <Btn onClick={() => { setNl({ branch: addBranch, name: "" }); setShowAdd(true); }}>⊕ เพิ่ม Location</Btn>}
      </div>
      <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(250px, 1fr))", gap: 13 }}>
        {locs.map((l, i) => {
          const items = itemsAt(l.id);
          const count = items.reduce((a, x) => a + x.qty, 0);
          const br = branchOf(st, l.branch);
          const active = sel === l.id;
          return (
            <Card key={l.id} hover onClick={() => setSel(active ? null : l.id)} style={{
              padding: 16, cursor: "pointer", animation: `ss-rise .4s ${i * 40}ms ease backwards`,
              outline: active ? `2.5px solid ${T.primary}` : "none",
              background: active ? `linear-gradient(180deg, ${T.chipBg}, ${T.surface})` : T.surface,
            }}>
              <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
                <div style={{ width: 40, height: 40, borderRadius: 11, background: T.heroGrad, color: "#fff", fontFamily: T.headFont, fontWeight: 800, display: "flex", alignItems: "center", justifyContent: "center", fontSize: 14 }}>{l.code}</div>
                <div style={{ minWidth: 0 }}>
                  <div style={{ fontFamily: T.headFont, fontWeight: 700, fontSize: 14.5, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{l.name}</div>
                  <div style={{ fontSize: 11.5, color: T.sub, whiteSpace: "nowrap" }}>{br.name}</div>
                </div>
                {canManage && (
                  <button className="ss-btn" onClick={(e) => { e.stopPropagation(); if (qtyAt(l.id) > 0) { toast("ยังมีสินค้าคงเหลือใน Location นี้ — โอนออกก่อนลบ", "danger"); return; } setDelLoc(l); }}
                    title="ลบ Location" style={{ marginLeft: "auto", border: "none", cursor: "pointer", background: T.chipBg, color: T.sub, borderRadius: 8, width: 28, height: 28, fontSize: 13, flex: "none" }}>✕</button>
                )}
              </div>
              <div style={{ display: "flex", gap: 12, marginTop: 12, fontSize: 11.5, whiteSpace: "nowrap", alignItems: "baseline" }}>
                <div><b style={{ fontFamily: T.headFont, fontSize: 15 }}>{items.length}</b> <span style={{ color: T.sub }}>รายการ</span></div>
                <div><b style={{ fontFamily: T.headFont, fontSize: 15 }}>{count}</b> <span style={{ color: T.sub }}>ชิ้น</span></div>
                <div style={{ marginLeft: "auto", color: T.sub, overflow: "hidden", textOverflow: "ellipsis" }}>ทุน <b style={{ color: T.text }}>{fmtMoney(valueAt(l.id))}</b></div>
              </div>
            </Card>
          );
        })}
      </div>

      {selLoc && (
        <Card style={{ padding: "8px 18px 10px", animation: "ss-rise .35s ease" }}>
          <SectionTitle right={<span style={{ fontSize: 12, color: T.sub }}>{locName(st, selLoc.id)}</span>}>สินค้าใน {selLoc.code} · {selLoc.name}</SectionTitle>
          {itemsAt(selLoc.id).length === 0 && <EmptyState text="ไม่มีสินค้าใน Location นี้" />}
          {itemsAt(selLoc.id).map(({ p, qty }, i, arr) => (
            <div key={p.id} style={{ display: "flex", alignItems: "center", gap: 11, fontSize: 13, padding: "9px 2px", borderBottom: i < arr.length - 1 ? `1px solid ${T.rowBorder}` : "none" }}>
              <ProductImg p={p} size={36} />
              <div style={{ minWidth: 0, flex: 1 }}>
                <div style={{ fontWeight: 600 }}>{p.name}</div>
                <div style={{ fontSize: 11, color: T.sub, fontFamily: "monospace" }}>{p.sku}</div>
              </div>
              <div style={{ fontFamily: T.headFont, fontWeight: 800, fontSize: 16 }}>{qty} <span style={{ fontSize: 11, fontWeight: 500, color: T.sub }}>ชิ้น</span></div>
              <Btn sm kind="soft" onClick={() => { setTf({ productId: p.id, from: selLoc.id }); setTfQty(1); setTfTo(""); }}>⇄ โอนย้าย</Btn>
            </div>
          ))}
        </Card>
      )}

      {/* ── โอนย้าย ── */}
      <Modal open={!!tf} onClose={() => setTf(null)} title="โอนย้ายสินค้า" width={460}
        footer={<React.Fragment>
          <Btn kind="ghost" onClick={() => setTf(null)}>ยกเลิก</Btn>
          <Btn onClick={doTransfer}>⇄ ยืนยันโอนย้าย</Btn>
        </React.Fragment>}>
        {tf && (
          <div style={{ display: "flex", flexDirection: "column", gap: 13 }}>
            <div style={{ display: "flex", alignItems: "center", gap: 10, background: T.chipBg, borderRadius: 12, padding: "10px 14px" }}>
              <ProductImg p={prodOf(st, tf.productId)} size={40} />
              <div>
                <div style={{ fontWeight: 700, fontSize: 13.5 }}>{prodOf(st, tf.productId).name}</div>
                <div style={{ fontSize: 11.5, color: T.sub }}>จาก {locName(st, tf.from)} · มี {prodOf(st, tf.productId).stock[tf.from]} ชิ้น</div>
              </div>
            </div>
            <Field label="ไปยัง Location" req>
              <Select value={tfTo} onChange={setTfTo} placeholder="— เลือกปลายทาง (ข้ามสาขาได้) —"
                options={st.locations.filter((l) => l.id !== tf.from).map((l) => ({ value: l.id, label: locName(st, l.id) }))} />
            </Field>
            <Field label="จำนวน" req>
              <NumInput value={tfQty} min="1" max={prodOf(st, tf.productId).stock[tf.from]} onChange={(e) => setTfQty(e.target.value)} />
            </Field>
          </div>
        )}
      </Modal>

      {/* ── เพิ่ม Location ── */}
      <Modal open={showAdd} onClose={() => setShowAdd(false)} title="เพิ่ม Location ใหม่" width={440}
        footer={<React.Fragment>
          <Btn kind="ghost" onClick={() => setShowAdd(false)}>ยกเลิก</Btn>
          <Btn onClick={() => {
            if (!nl.name) { toast("ระบุชื่อ Location", "danger"); return; }
            dispatch({ type: "LOC_ADD", branch: nl.branch, name: nl.name });
            toast(`เพิ่ม ${nl.name} ใน ${branchOf(st, nl.branch).short} แล้ว`);
            setShowAdd(false);
          }}>⊕ เพิ่ม Location</Btn>
        </React.Fragment>}>
        <div style={{ display: "flex", flexDirection: "column", gap: 13 }}>
          <Field label="สาขา" req>
            <Select value={nl.branch} onChange={(v) => setNl((x) => ({ ...x, branch: v }))} options={st.branches.map((b) => ({ value: b.id, label: b.name }))} />
          </Field>
          <Field label="ชื่อ Location" req><TextInput value={nl.name} onChange={(e) => setNl((x) => ({ ...x, name: e.target.value }))} placeholder="เช่น ตู้โชว์หน้าร้าน 2, ชั้นวางเครื่องใหม่" /></Field>
          <div style={{ fontSize: 11.5, color: T.sub, background: T.chipBg, borderRadius: 10, padding: "8px 12px" }}>ระบบจะออกรหัส Location ให้อัตโนมัติตามสาขา</div>
        </div>
      </Modal>

      {/* ── ลบ Location ── */}
      <Modal open={!!delLoc} onClose={() => setDelLoc(null)} title="ยืนยันการลบ Location" width={420}
        footer={<React.Fragment>
          <Btn kind="ghost" onClick={() => setDelLoc(null)}>ยกเลิก</Btn>
          <Btn kind="danger" onClick={() => { dispatch({ type: "LOC_DEL", id: delLoc.id }); toast(`ลบ ${delLoc.name} แล้ว`, "info"); if (sel === delLoc.id) setSel(null); setDelLoc(null); }}>✕ ลบ Location</Btn>
        </React.Fragment>}>
        {delLoc && <div style={{ fontSize: 13, lineHeight: 1.7 }}>ลบ <b>{delLoc.code} · {delLoc.name}</b> ({branchOf(st, delLoc.branch).short})?<br /><span style={{ color: T.sub, fontSize: 12 }}>Location ที่ไม่มีสินค้าคงเหลือเท่านั้นจึงจะลบได้</span></div>}
      </Modal>
    </div>
  );
}
window.LocationsPage = LocationsPage;
