/* ============================================================
   STOCK WAREHOUSE — window.StockWarehouse
   ============================================================ */
(function () {
  const { useState } = React;
  const { useT, useLang, Icon, Panel, Badge, Dot, Stat, DataTable, PageHead, BarChart } = window.UI;
  const baht = (n) => "฿" + Math.round(n).toLocaleString();

  function RoomTabs({ rooms, active, onChange }) {
    const { lang } = useLang();
    return <div className="seg">{rooms.map((r) => <button key={r.key} className={active === r.key ? "on" : ""} onClick={() => onChange(r.key)}>{r.en}{lang === "th" ? <span style={{ color: "var(--tx-ghost)", marginLeft: 6, fontSize: 11 }}>{r.th}</span> : null}</button>)}</div>;
  }
  const stockState = (p) => p.stock <= p.min * 0.25 ? "danger" : p.stock < p.min ? "warn" : "ok";
  const stockLabel = (p, t) => p.stock <= p.min * 0.25 ? t("restock now", "เติมด่วน") : p.stock < p.min ? t("low", "ใกล้หมด") : t("ok", "ปกติ");

  function Products() {
    const t = useT(); const D = window.DATA;
    const [type, setType] = useState("all");
    let rows = D.products;
    if (type === "goods") rows = rows.filter((p) => p.type === "สินค้า" || p.type === "เซ็ต");
    if (type === "pack") rows = rows.filter((p) => p.type === "วัสดุแพ็ค");
    const cols = [
      { key: "sku", label: "SKU", sortable: true, render: (r) => <span className="mono strong">{r.sku}</span> },
      { key: "name", label: t("PRODUCT", "สินค้า"), render: (r) => <div className="th-cell"><span className="strong">{r.name}</span><span className="sub">alias: {r.alias}</span></div> },
      { key: "type", label: t("TYPE", "ประเภท"), render: (r) => <Badge kind={r.type === "วัสดุแพ็ค" ? "info" : r.type === "เซ็ต" ? "accent" : "neutral"}>{r.type}</Badge> },
      { key: "cost", label: t("COST", "ทุน/หน่วย"), sortable: true, render: (r) => <span className="num">{baht(r.cost)}</span> },
      { key: "price", label: t("PRICE", "ราคาขาย"), sortable: true, render: (r) => r.price ? <span className="num strong">{baht(r.price)}</span> : <span style={{ color: "var(--tx-ghost)" }}>—</span> },
      { key: "stock", label: t("ON HAND", "คงเหลือ"), sortable: true, render: (r) => <span className="num strong">{r.stock} <span style={{ color: "var(--tx-faint)", fontWeight: 400 }}>{r.unit}</span></span> },
      { key: "min", label: t("MIN", "ขั้นต่ำ"), render: (r) => <span className="num" style={{ color: "var(--tx-faint)" }}>{r.min}</span> },
      { key: "state", label: t("STATUS", "สถานะ"), sortable: true, sortVal: (r) => r.stock - r.min, render: (r) => <Badge kind={stockState(r)} dot>{stockLabel(r, t)}</Badge> },
    ];
    return (
      <div className="fade-in">
        <Panel title={t("Product master", "รายการสินค้า")} th={t("central SKU registry", "รหัสกลาง")}
          right={<><button className="chip"><Icon name="plug" size={14} />{t("Match names", "จับคู่ชื่อ")}</button><button className="btn primary"><Icon name="plus" size={15} />{t("Add product", "เพิ่มสินค้า")}</button></>}>
          <div style={{ padding: "12px 16px 0", display: "flex", gap: 9 }}>
            <button className={"chip" + (type === "all" ? " on" : "")} onClick={() => setType("all")}>{t("All", "ทั้งหมด")} ({D.products.length})</button>
            <button className={"chip" + (type === "goods" ? " on" : "")} onClick={() => setType("goods")}>{t("Goods", "สินค้า")}</button>
            <button className={"chip" + (type === "pack" ? " on" : "")} onClick={() => setType("pack")}>{t("Packing", "วัสดุแพ็ค")}</button>
          </div>
          <DataTable columns={cols} rows={rows} initialSort={{ key: "state", dir: "asc" }} />
        </Panel>
      </div>
    );
  }

  function Balance() {
    const t = useT(); const D = window.DATA;
    const goods = D.products.filter((p) => p.type !== "วัสดุแพ็ค");
    const totalVal = D.products.reduce((s, p) => s + p.cost * p.stock, 0);
    const packVal = D.products.filter((p) => p.type === "วัสดุแพ็ค").reduce((s, p) => s + p.cost * p.stock, 0);
    const bars = goods.slice(0, 6).map((p) => ({ label: p.alias, v: Math.round(p.cost * p.stock / 1000), label2: "฿" + Math.round(p.cost * p.stock / 1000) + "K", color: "var(--shopee)" }));
    return (
      <div className="fade-in">
        <div className="grid" style={{ gridTemplateColumns: "repeat(4,1fr)", marginBottom: 16 }}>
          <Stat label={t("Total stock value", "มูลค่าสต๊อกรวม")} value={baht(totalVal)} delta="+3.2%" accent="var(--shopee)" />
          <Stat label={t("SKUs in stock", "จำนวน SKU")} value={D.products.length} deltaDir="flat" delta={t("active", "ใช้งาน")} accent="var(--shopee)" />
          <Stat label={t("Packing material value", "มูลค่าวัสดุแพ็ค")} value={baht(packVal)} deltaDir="flat" delta={t("2 items", "2 รายการ")} accent="var(--accent)" />
          <Stat label={t("Below minimum", "ต่ำกว่าขั้นต่ำ")} value="4" deltaDir="down" delta={t("need restock", "ต้องเติม")} accent="var(--danger)" />
        </div>
        <Panel title={t("Stock value by product", "มูลค่าสต๊อกแยกสินค้า")} th={t("cost × on-hand", "ทุน × คงเหลือ")}>
          <div className="panel-pad"><BarChart data={bars} height={200} /></div>
        </Panel>
      </div>
    );
  }

  function Movement() {
    const t = useT();
    const moves = [
      { date: "02 มิ.ย. 08:10", p: "Glow Serum", type: "เบิกออก", qty: -48, ref: "ออเดอร์รายวัน", st: "warn" },
      { date: "02 มิ.ย. 07:30", p: "กล่องพัสดุ #B", type: "เบิกออก", qty: -138, ref: "แพ็คของ", st: "warn" },
      { date: "01 มิ.ย. 16:40", p: "คอลลาเจน", type: "รับเข้า", qty: +120, ref: "PO-2026-051", st: "ok" },
      { date: "01 มิ.ย. 11:20", p: "เซ็ตของขวัญ", type: "ตีกลับเข้า", qty: +1, ref: "MO-88227", st: "info" },
      { date: "01 มิ.ย. 09:05", p: "วิตซี 1000", type: "เบิกออก", qty: -50, ref: "ออเดอร์รายวัน", st: "warn" },
      { date: "31 พ.ค. 14:00", p: "พัดลมพกพา", type: "ปรับยอด", qty: -2, ref: "เช็คสต๊อก", st: "neutral" },
    ];
    const tMap = { "รับเข้า": "ok", "เบิกออก": "warn", "ตีกลับเข้า": "info", "ปรับยอด": "neutral" };
    const cols = [
      { key: "date", label: t("DATE", "วันที่"), render: (r) => <span className="mono" style={{ color: "var(--tx-faint)" }}>{r.date}</span> },
      { key: "p", label: t("PRODUCT", "สินค้า"), render: (r) => <span className="strong">{r.p}</span> },
      { key: "type", label: t("TYPE", "ประเภท"), render: (r) => <Badge kind={tMap[r.type]} dot>{r.type}</Badge> },
      { key: "qty", label: t("QTY", "จำนวน"), sortable: true, render: (r) => <span className="num strong" style={{ color: r.qty > 0 ? "var(--ok)" : "var(--danger)" }}>{r.qty > 0 ? "+" : ""}{r.qty}</span> },
      { key: "ref", label: t("REFERENCE", "อ้างอิง"), render: (r) => <span style={{ color: "var(--tx-faint)" }}>{r.ref}</span> },
    ];
    return (
      <div className="fade-in">
        <Panel title={t("Stock movement", "การเคลื่อนไหวสต๊อก")} th={t("in / out / return / adjust", "รับเข้า · เบิกออก · ตีกลับ · ปรับ")}
          right={<><button className="chip"><Icon name="down" size={14} />{t("Stock out", "เบิกออก")}</button><button className="btn primary"><Icon name="up" size={15} />{t("Stock in", "รับเข้า")}</button></>}>
          <DataTable columns={cols} rows={moves} />
        </Panel>
      </div>
    );
  }

  function LowStock() {
    const t = useT(); const D = window.DATA;
    const low = D.products.filter((p) => p.stock < p.min).sort((a, b) => (a.stock / a.min) - (b.stock / b.min));
    return (
      <div className="fade-in">
        <div className="panel" style={{ borderColor: "oklch(0.66 0.2 27 / 0.4)", background: "oklch(0.66 0.2 27 / 0.08)", marginBottom: 16, padding: "14px 18px", display: "flex", alignItems: "center", gap: 14 }}>
          <span style={{ color: "var(--danger)" }}><Icon name="warn" size={22} /></span>
          <div style={{ flex: 1 }}>
            <div style={{ fontWeight: 700, fontSize: 13.5 }}>{low.length} {t("products below minimum stock", "สินค้าต่ำกว่าขั้นต่ำ")}</div>
            <div style={{ fontSize: 12, color: "var(--tx-dim)" }}>{t("Suggested purchase value", "มูลค่าที่ควรสั่งซื้อ")} ≈ {baht(low.reduce((s, p) => s + p.cost * (p.min * 2 - p.stock), 0))}</div>
          </div>
          <button className="btn primary"><Icon name="plus" size={15} />{t("Create purchase order", "สร้างใบสั่งซื้อ")}</button>
        </div>
        <div className="grid" style={{ gridTemplateColumns: "repeat(2,1fr)" }}>
          {low.map((p) => {
            const pct = Math.round(p.stock / p.min * 100);
            return (
              <Panel key={p.id}>
                <div className="panel-pad">
                  <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", marginBottom: 12 }}>
                    <div><div style={{ fontWeight: 700, fontSize: 14 }}>{p.name}</div><div className="mono" style={{ fontSize: 11, color: "var(--tx-faint)" }}>{p.sku} · {p.alias}</div></div>
                    <Badge kind={stockState(p)} dot>{stockLabel(p, t)}</Badge>
                  </div>
                  <div style={{ display: "flex", justifyContent: "space-between", fontSize: 11, color: "var(--tx-faint)", marginBottom: 5 }}>
                    <span>{t("On hand", "คงเหลือ")} <b style={{ color: "var(--tx)" }}>{p.stock}</b> / {t("min", "ขั้นต่ำ")} {p.min}</span>
                    <span className="mono">{pct}%</span>
                  </div>
                  <div style={{ height: 7, background: "var(--panel-3)", borderRadius: 99 }}>
                    <div style={{ width: Math.min(100, pct) + "%", height: "100%", borderRadius: 99, background: stockState(p) === "danger" ? "var(--danger)" : "var(--warn)", boxShadow: `0 0 8px ${stockState(p) === "danger" ? "var(--danger)" : "var(--warn)"}` }} />
                  </div>
                  <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginTop: 14 }}>
                    <span style={{ fontSize: 12, color: "var(--tx-dim)" }}>{t("Suggest order", "ควรสั่ง")} <b className="mono" style={{ color: "var(--tx)" }}>{p.min * 2 - p.stock}</b> {p.unit}</span>
                    <button className="chip">{t("Restock", "เติมสต๊อก")}</button>
                  </div>
                </div>
              </Panel>
            );
          })}
        </div>
      </div>
    );
  }

  function StockWarehouse({ onNav }) {
    const t = useT();
    const Hero = window.OfficeHero;
    const [room, setRoom] = useState("products");
    const rooms = [
      { key: "products", en: "Products", th: "สินค้า" },
      { key: "balance", en: "Stock Balance", th: "คงเหลือ" },
      { key: "movement", en: "Movement", th: "เคลื่อนไหว" },
      { key: "low", en: "Low Stock", th: "ใกล้หมด" },
    ];
    return (
      <div className="main">
        <Hero office="stock" />
        <PageHead
          crumbs={<><a onClick={() => onNav("city")}>{t("System Map", "แผนที่ระบบ")}</a><Icon name="chev" size={12} /><span style={{ color: "var(--shopee)" }}>Stock Warehouse</span></>}
          title="Stock Warehouse" th="คลังสินค้า"
          right={<RoomTabs rooms={rooms} active={room} onChange={setRoom} />} />
        {room === "products" && <Products />}
        {room === "balance" && <Balance />}
        {room === "movement" && <Movement />}
        {room === "low" && <LowStock />}
      </div>
    );
  }
  window.StockWarehouse = StockWarehouse;
})();
