/* Locations.jsx — ระบบโลเคชั่นแบบ grid + แท็กสินค้าคงเหลืออัตโนมัติ */
const { useState: locUseState } = React;

/* สีแสดงระดับการเติมของช่อง */
function fillColor(pct) {
  if (pct === 0) return "var(--line-2)";
  if (pct < 35) return "#9bc7f7";
  if (pct < 70) return "#5a9bf0";
  return "var(--primary-600)";
}

function BinCell({ code, selected, onClick }) {
  const s = useStore();
  const { entries, units, skuCount } = s.binSummary(code);
  const pct = Math.min(100, Math.round(units / s.BIN_CAP * 100));
  const empty = skuCount === 0;
  /* หมวดเด่นในช่อง = สีแถบ */
  const topSku = entries.sort((a, b) => b[1] - a[1])[0];
  const cat = topSku ? s.catOf(topSku[0]) : null;

  return (
    <div className={`bin ${empty ? "empty" : ""} ${selected ? "sel" : ""}`} onClick={onClick}>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
        <span className="bin-code">{code}</span>
        {!empty && <span style={{ width: 8, height: 8, borderRadius: 3, background: cat.color }}></span>}
      </div>
      {empty ? (
        <div className="bin-count" style={{ fontSize: 13, fontWeight: 500 }}>ว่าง</div>
      ) : (
        <div>
          <div className="bin-count">{skuCount}<small> รายการ</small></div>
          <div className="bin-fill-label">{s.fmt(units)} หน่วย · {pct}%</div>
        </div>
      )}
      <div className="bin-bar"><span style={{ width: `${pct}%`, background: fillColor(pct) }}></span></div>
    </div>
  );
}

function Locations({ go }) {
  const s = useStore();
  const [sel, setSel] = locUseState(null);
  const [zone, setZone] = locUseState("all");

  const zones = zone === "all" ? s.ZONES : s.ZONES.filter(z => z.id === zone);

  /* สถิติรวม */
  const totalBins = s.locations.length;
  const usedBins = s.locations.filter(l => s.binSummary(l.code).skuCount > 0).length;
  const avgFill = Math.round(s.locations.reduce((a, l) => a + Math.min(100, s.binSummary(l.code).units / s.BIN_CAP * 100), 0) / totalBins);

  const selData = sel ? s.binSummary(sel) : null;

  return (
    <div className="page fade-up">
      <div className="page-head" style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-end", flexWrap: "wrap", gap: 14 }}>
        <div>
          <h2>ผังโลเคชั่นคลัง</h2>
          <p>แต่ละช่องแท็กสินค้าคงเหลืออัตโนมัติ · คลิกช่องเพื่อดูรายละเอียด</p>
        </div>
        <div style={{ display: "flex", gap: 22 }}>
          {[
            { l: "ช่องที่ใช้งาน", v: `${usedBins}/${totalBins}` },
            { l: "อัตราเต็มเฉลี่ย", v: `${avgFill}%` },
          ].map((x, i) => (
            <div key={i} style={{ textAlign: "right" }}>
              <div style={{ fontSize: 12, color: "var(--muted)" }}>{x.l}</div>
              <div className="num" style={{ fontSize: 20, fontWeight: 600 }}>{x.v}</div>
            </div>
          ))}
        </div>
      </div>

      {/* ตัวกรองโซน + legend */}
      <div style={{ display: "flex", gap: 10, marginBottom: 18, flexWrap: "wrap", alignItems: "center" }}>
        <div className={`chip ${zone === "all" ? "active" : ""}`} onClick={() => setZone("all")}>ทุกโซน</div>
        {s.ZONES.map(z => (
          <div key={z.id} className={`chip ${zone === z.id ? "active" : ""}`} onClick={() => setZone(z.id)}>โซน {z.id}</div>
        ))}
        <div style={{ flex: 1 }}></div>
        <div style={{ display: "flex", alignItems: "center", gap: 12, fontSize: 12, color: "var(--muted)" }}>
          <span>อัตราเต็ม:</span>
          {[["ว่าง", "var(--line-2)"], ["น้อย", "#9bc7f7"], ["ปานกลาง", "#5a9bf0"], ["เต็ม", "var(--primary-600)"]].map(([l, c]) => (
            <span key={l} style={{ display: "flex", alignItems: "center", gap: 5 }}><span style={{ width: 12, height: 8, borderRadius: 3, background: c }}></span>{l}</span>
          ))}
        </div>
      </div>

      <div style={{ display: "flex", flexDirection: "column", gap: 22 }}>
        {zones.map(z => (
          <div key={z.id}>
            <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 12 }}>
              <span style={{ width: 28, height: 28, borderRadius: 9, background: "var(--primary-soft)", color: "var(--primary-700)", display: "grid", placeItems: "center", fontWeight: 600, fontSize: 14, fontFamily: "var(--mono)" }}>{z.id}</span>
              <span style={{ fontWeight: 600, fontSize: 15 }}>{z.name}</span>
              <span className="badge badge-gray">{s.locations.filter(l => l.zone === z.id).length} ช่อง</span>
            </div>
            <div className="zone-grid stagger" style={{ gridTemplateColumns: `repeat(${z.cols}, 1fr)` }}>
              {s.locations.filter(l => l.zone === z.id).map(l => (
                <BinCell key={l.code} code={l.code} selected={sel === l.code} onClick={() => setSel(l.code)} />
              ))}
            </div>
          </div>
        ))}
      </div>

      {/* drawer รายละเอียดช่อง */}
      {sel && (
        <Drawer onClose={() => setSel(null)}
          headIcon={<span style={{ width: 46, height: 46, borderRadius: 13, background: "var(--primary-soft)", color: "var(--primary-700)", display: "grid", placeItems: "center" }}><Icons.pin size={24}/></span>}
          title={<span className="num">โลเคชั่น {sel}</span>}
          sub={(s.ZONES.find(z => z.id === sel[0]) || {}).name}
          footer={
            <React.Fragment>
              <button className="btn btn-ghost" onClick={() => { setSel(null); go("receive"); }}><Icons.receive size={16}/>รับเข้าช่องนี้</button>
              <button className="btn btn-primary" onClick={() => { setSel(null); go("issue"); }}><Icons.issue size={16}/>จ่ายออก</button>
            </React.Fragment>
          }>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12, marginBottom: 18 }}>
            {[
              { l: "จำนวนรายการ", v: `${selData.skuCount} SKU` },
              { l: "หน่วยรวม", v: s.fmt(selData.units) },
              { l: "อัตราเต็ม", v: `${Math.min(100, Math.round(selData.units / s.BIN_CAP * 100))}%` },
              { l: "มูลค่าในช่อง", v: `฿${s.fmtMoney(selData.entries.reduce((a, [sku, q]) => a + q * s.itemOf(sku).price, 0))}` },
            ].map((x, i) => (
              <div key={i} style={{ background: "var(--surface)", border: "1px solid var(--line)", borderRadius: 12, padding: "12px 14px" }}>
                <div style={{ fontSize: 12, color: "var(--muted)" }}>{x.l}</div>
                <div className="num" style={{ fontSize: 18, fontWeight: 600, marginTop: 3 }}>{x.v}</div>
              </div>
            ))}
          </div>

          <SectionHead title="สินค้าในช่องนี้" sub="แท็กอัตโนมัติตามการเคลื่อนไหว" />
          {selData.skuCount === 0 ? (
            <Empty icon={<Icons.box size={22}/>} title="ช่องว่าง" sub="ยังไม่มีสินค้าจัดเก็บที่นี่" />
          ) : (
            <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
              {selData.entries.sort((a, b) => b[1] - a[1]).map(([sku, q]) => {
                const it = s.itemOf(sku);
                return (
                  <div key={sku} style={{ display: "flex", alignItems: "center", gap: 12, padding: "10px 12px", border: "1px solid var(--line)", borderRadius: 12, background: "var(--surface)" }}>
                    <ItemThumb sku={sku} size={38}/>
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <div style={{ fontWeight: 600, fontSize: 13.5, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{it.name}</div>
                      <div className="num" style={{ fontSize: 11.5, color: "var(--muted-2)" }}>{sku}</div>
                    </div>
                    <div className="num" style={{ fontWeight: 600 }}>{s.fmt(q)} <span style={{ fontSize: 12, color: "var(--muted)", fontWeight: 500 }}>{it.unit}</span></div>
                  </div>
                );
              })}
            </div>
          )}
        </Drawer>
      )}
    </div>
  );
}
window.Locations = Locations;
