// ============================================================
// warehouse.jsx — Warehouse / Location map view
// ============================================================

function WarehouseScreen({ state, setState }) {
  const toast = useToast();
  const [selectedWh, setSelectedWh] = useState(state.warehouses[0]?.id);
  const [selectedLoc, setSelectedLoc] = useState(null);

  const [whForm, setWhForm] = useState(null);
  const [locForm, setLocForm] = useState(null);
  const [zoneForm, setZoneForm] = useState(false);
  const [confirmDelWh, setConfirmDelWh] = useState(null);
  const [confirmDelLoc, setConfirmDelLoc] = useState(null);
  const [confirmDelZone, setConfirmDelZone] = useState(null);

  // Re-select if current warehouse deleted
  useEffect(() => {
    if (!state.warehouses.find(w => w.id === selectedWh)) {
      setSelectedWh(state.warehouses[0]?.id || null);
      setSelectedLoc(null);
    }
  }, [state.warehouses, selectedWh]);

  const warehouse = state.warehouses.find(w => w.id === selectedWh);
  const locations = state.locations.filter(l => l.warehouseId === selectedWh);

  const locStats = locations.map(loc => ({
    ...loc,
    qty: getStockByLocation(state, loc.id),
    items: Object.entries(state.stock).filter(([k, q]) => k.endsWith("|" + loc.id) && q > 0).length,
  }));

  const totalQty = locStats.reduce((s, l) => s + l.qty, 0);
  const totalCap = locStats.reduce((s, l) => s + l.capacity, 0);
  const occupied = locStats.filter(l => l.qty > 0).length;

  // group locations by zone
  const byZone = {};
  locStats.forEach(l => {
    if (!byZone[l.zone]) byZone[l.zone] = [];
    byZone[l.zone].push(l);
  });

  const detail = selectedLoc ? locStats.find(l => l.id === selectedLoc) : null;
  const detailItems = detail ? Object.entries(state.stock)
    .filter(([k, q]) => k.endsWith("|" + detail.id) && q > 0)
    .map(([k, q]) => {
      const sku = k.split("|")[0];
      const p = state.products.find(x => x.sku === sku);
      return { sku, qty: q, product: p };
    }) : [];

  // ============ Handlers ============
  const saveWarehouse = (w) => {
    const clean = { ...w, _existing: undefined };
    setState(s => {
      let warehouses = [...s.warehouses];
      let newLocations = s.locations;
      if (w._existing) {
        warehouses = warehouses.map(x => x.id === w.id ? { ...x, ...clean } : x);
        DB.upsertWarehouse(clean);
        toast(`บันทึก ${w.name}`, "success");
      } else {
        if (warehouses.some(x => x.id === w.id)) { toast("รหัสคลังซ้ำกับที่มีอยู่", "danger"); return s; }
        warehouses = [...warehouses, clean];
        const seedLocs = [1, 2, 3, 4].map(rack => ({
          id: `${w.id}-A${rack}`, warehouseId: w.id, zone: "A", rack, code: `A${rack}`, capacity: 500,
        }));
        newLocations = [...s.locations, ...seedLocs];
        DB.upsertWarehouse(clean);
        DB.upsertLocations(seedLocs);
        toast(`เพิ่ม ${w.name} เรียบร้อย`, "success");
        setTimeout(() => setSelectedWh(w.id), 50);
      }
      return { ...s, warehouses, locations: newLocations };
    });
    setWhForm(null);
  };

  const doDeleteWarehouse = (id) => {
    const whLocs = state.locations.filter(l => l.warehouseId === id);
    const hasStock = whLocs.some(l => getStockByLocation(state, l.id) > 0);
    if (hasStock) { toast("ลบไม่ได้: คลังนี้ยังมีสินค้าคงเหลืออยู่", "danger"); return; }
    setState(s => ({
      ...s,
      warehouses: s.warehouses.filter(w => w.id !== id),
      locations: s.locations.filter(l => l.warehouseId !== id),
    }));
    DB.deleteWarehouse(id); // CASCADE deletes locations in DB
    toast("ลบคลังเรียบร้อย", "success");
  };

  const saveLocation = (loc) => {
    const clean = { ...loc, _existing: undefined };
    setState(s => {
      let locations = [...s.locations];
      if (loc._existing) {
        locations = locations.map(x => x.id === loc.id ? { ...x, ...clean } : x);
        toast(`บันทึก ${loc.id}`, "success");
      } else {
        if (locations.some(x => x.id === loc.id)) { toast("ช่องนี้มีอยู่แล้ว", "danger"); return s; }
        locations = [...locations, clean];
        toast(`เพิ่มช่อง ${loc.id}`, "success");
      }
      return { ...s, locations };
    });
    DB.upsertLocation(clean);
    setLocForm(null);
  };

  const doDeleteLocation = (id) => {
    const qty = getStockByLocation(state, id);
    if (qty > 0) { toast(`ลบไม่ได้: ช่อง ${id} ยังมีสินค้า ${formatNumber(qty)} หน่วย`, "danger"); return; }
    setState(s => ({ ...s, locations: s.locations.filter(l => l.id !== id) }));
    DB.deleteLocation(id);
    if (selectedLoc === id) setSelectedLoc(null);
    toast(`ลบช่อง ${id} เรียบร้อย`, "success");
  };

  const addZone = (newLocs) => {
    setState(s => ({ ...s, locations: [...s.locations, ...newLocs] }));
    DB.upsertLocations(newLocs);
    toast(`เพิ่มโซน ${newLocs[0].zone} (${newLocs.length} ช่อง)`, "success");
    setZoneForm(false);
  };

  const doDeleteZone = (zone) => {
    const zoneLocs = locations.filter(l => l.zone === zone);
    const hasStock = zoneLocs.some(l => getStockByLocation(state, l.id) > 0);
    if (hasStock) { toast(`ลบไม่ได้: โซน ${zone} ยังมีสินค้า`, "danger"); return; }
    setState(s => ({ ...s, locations: s.locations.filter(l => !(l.warehouseId === selectedWh && l.zone === zone)) }));
    DB.deleteLocations(zoneLocs.map(l => l.id));
    toast(`ลบโซน ${zone} เรียบร้อย`, "success");
  };

  if (!warehouse) {
    return (
      <>
        <div className="page-header">
          <div><div className="page-title">แผนผังคลังสินค้า</div></div>
          <button className="btn btn-accent" onClick={() => setWhForm({})}><Icon name="plus" size={13}/> เพิ่มคลังใหม่</button>
        </div>
        <div className="card"><EmptyState icon="warehouse" title="ยังไม่มีคลังสินค้า" sub="กดปุ่ม + เพิ่มคลังใหม่ เพื่อเริ่มต้น"/></div>
        <WarehouseForm open={!!whForm} onClose={() => setWhForm(null)} onSave={saveWarehouse} initial={whForm}/>
      </>
    );
  }

  return (
    <>
      <div className="page-header">
        <div>
          <div className="page-title">แผนผังคลังสินค้า</div>
          <div className="page-sub">ดูสินค้าคงเหลือในแต่ละ location · {warehouse?.name}</div>
        </div>
        <div className="row">
          <select className="select" style={{ width: "auto", padding: "8px 12px" }} value={selectedWh} onChange={e => { setSelectedWh(e.target.value); setSelectedLoc(null); }}>
            {state.warehouses.map(w => <option key={w.id} value={w.id}>{w.code} · {w.name}</option>)}
          </select>
          <button className="btn btn-secondary" title="แก้ไขคลังนี้" onClick={() => setWhForm({ ...warehouse, _existing: true })}>
            <Icon name="edit" size={13}/>
          </button>
          <button className="btn btn-secondary" title="ลบคลังนี้" onClick={() => setConfirmDelWh(warehouse)}>
            <Icon name="trash" size={13}/>
          </button>
          <button className="btn btn-accent" onClick={() => setWhForm({})}>
            <Icon name="plus" size={13}/> เพิ่มคลังใหม่
          </button>
        </div>
      </div>

      <div className="stats-grid">
        <StatCard label="พื้นที่ใช้งาน" value={Math.round((totalQty / totalCap) * 100)} suffix="%" icon="warehouse" delta={`${formatNumber(totalQty)}/${formatNumber(totalCap)} หน่วย`} deltaDir=""/>
        <StatCard label="ใช้งาน / ทั้งหมด" value={occupied} icon="package" delta={`/ ${locations.length} ช่อง`} deltaDir=""/>
        <StatCard label="ประเภทคลัง" valueText={warehouse?.type} icon="info" delta={`อุณหภูมิ ${warehouse?.temp}`} deltaDir=""/>
        <StatCard label="จำนวน SKU" value={new Set(Object.keys(state.stock).filter(k => locations.some(l => k.endsWith("|"+l.id)) && state.stock[k] > 0).map(k => k.split("|")[0])).size} icon="chart" delta="active" deltaDir=""/>
      </div>

      <div style={{ display: "grid", gridTemplateColumns: selectedLoc ? "1fr 360px" : "1fr", gap: 14 }}>
        <div className="card card-pad-0">
          <div className="card-header">
            <h3>ผังการจัดเก็บ</h3>
            <div className="row" style={{ gap: 12 }}>
              <div className="row" style={{ gap: 12, fontSize: 11.5 }}>
                <LegendDot color="var(--surface-2)" label="ว่าง"/>
                <LegendDot color="var(--accent)" label="มีสินค้า"/>
                <LegendDot color="var(--warn)" label="ใกล้เต็ม"/>
                <LegendDot color="var(--success)" label="เต็ม"/>
              </div>
              <button className="btn btn-accent btn-sm" onClick={() => setZoneForm(true)}>
                <Icon name="plus" size={12}/> เพิ่มโซน
              </button>
            </div>
          </div>
          <div style={{ padding: 22 }}>
            <div className="col" style={{ gap: 18 }}>
              {Object.entries(byZone).map(([zone, cells]) => (
                <div key={zone}>
                  <div className="row" style={{ marginBottom: 8, gap: 8 }}>
                    <div style={{
                      fontFamily: "var(--font-mono)",
                      fontSize: 13, fontWeight: 600,
                      background: "var(--fg)",
                      color: "var(--surface)",
                      width: 26, height: 26,
                      borderRadius: 6,
                      display: "grid", placeItems: "center",
                    }}>{zone}</div>
                    <div style={{ flex: 1 }}>
                      <div style={{ fontSize: 12.5, fontWeight: 500 }}>โซน {zone}</div>
                      <div className="text-xs muted">
                        {cells.filter(c => c.qty > 0).length}/{cells.length} ช่องใช้งาน
                      </div>
                    </div>
                    <button className="btn btn-ghost btn-sm" title="เพิ่มช่องในโซนนี้" onClick={() => {
                      const nextRack = Math.max(0, ...cells.map(c => c.rack)) + 1;
                      setLocForm({ zone, rack: nextRack, capacity: 500 });
                    }}>
                      <Icon name="plus" size={12}/> ช่อง
                    </button>
                    <button className="btn btn-ghost btn-icon btn-sm" title="ลบโซนทั้งหมด" onClick={() => setConfirmDelZone(zone)}>
                      <Icon name="trash" size={13}/>
                    </button>
                  </div>
                  <div className="warehouse-map" style={{ gridTemplateColumns: "repeat(4, 1fr)" }}>
                    {cells.map(c => {
                      const pct = c.qty / c.capacity;
                      const cls = c.qty <= 0 ? "empty" : pct > 0.85 ? "full" : pct > 0.6 ? "high" : "";
                      return (
                        <div key={c.id} className={`location-cell ${cls}`}
                          style={selectedLoc === c.id ? { borderColor: "var(--accent)", boxShadow: "0 0 0 4px var(--accent-ring)" } : {}}
                          onClick={() => setSelectedLoc(c.id)}>
                          <div className="row" style={{ justifyContent: "space-between", alignItems: "flex-start" }}>
                            <div className="location-code">{c.id}</div>
                            <div className="row" style={{ gap: 0 }}>
                              <button className="btn btn-ghost btn-icon" style={{ padding: 2 }} onClick={(e) => { e.stopPropagation(); setLocForm({ ...c, _existing: true }); }}>
                                <Icon name="edit" size={11}/>
                              </button>
                              <button className="btn btn-ghost btn-icon" style={{ padding: 2 }} onClick={(e) => { e.stopPropagation(); setConfirmDelLoc(c); }}>
                                <Icon name="trash" size={11}/>
                              </button>
                            </div>
                          </div>
                          <div className="location-qty">
                            <AnimatedNumber value={c.qty}/>
                          </div>
                          <div className="text-xs muted">{c.items} SKU · cap {formatNumber(c.capacity)}</div>
                          {c.qty > 0 && (
                            <div className="location-fill" style={{ width: `${Math.min(100, pct * 100)}%`, background: pct > 0.85 ? "var(--success)" : pct > 0.6 ? "var(--warn)" : "var(--accent)" }}/>
                          )}
                        </div>
                      );
                    })}
                  </div>
                </div>
              ))}
              {Object.keys(byZone).length === 0 && <EmptyState icon="warehouse" title="ยังไม่มีโซนในคลังนี้" sub="กดปุ่ม + เพิ่มโซน เพื่อเริ่มต้น"/>}
            </div>
          </div>
        </div>

        {selectedLoc && detail && (
          <div className="card card-pad-0">
            <div className="card-header">
              <div>
                <h3 className="mono">{detail.id}</h3>
                <div className="card-header-sub">โซน {detail.zone} · ชั้น {detail.rack}</div>
              </div>
              <button className="btn btn-ghost btn-icon" onClick={() => setSelectedLoc(null)}>
                <Icon name="x" size={14}/>
              </button>
            </div>
            <div style={{ padding: 18 }}>
              <div className="stat" style={{ marginBottom: 14 }}>
                <div className="stat-label"><Icon name="package" size={12}/> สินค้าคงเหลือ</div>
                <div className="stat-value"><AnimatedNumber value={detail.qty}/></div>
                <div className="text-xs muted">จาก capacity {formatNumber(detail.capacity)}</div>
              </div>
              <div className="text-xs uppercase muted" style={{ marginBottom: 8 }}>รายการสินค้าใน location</div>
              <div className="col" style={{ gap: 6 }}>
                {detailItems.map(it => (
                  <div key={it.sku} style={{ padding: "10px 12px", background: "var(--surface-2)", borderRadius: 6 }}>
                    <div className="row" style={{ justifyContent: "space-between" }}>
                      <div>
                        <div style={{ fontSize: 13, fontWeight: 500 }}>{it.product?.name}</div>
                        <div className="mono text-xs muted">{it.sku}</div>
                      </div>
                      <div style={{ textAlign: "right" }}>
                        <div className="tnum" style={{ fontWeight: 600 }}>{formatNumber(it.qty)}</div>
                        <div className="text-xs muted">{it.product?.unit}</div>
                      </div>
                    </div>
                  </div>
                ))}
                {detailItems.length === 0 && <EmptyState icon="package" title="ช่องนี้ว่าง" sub="ยังไม่มีสินค้าจัดเก็บ"/>}
              </div>
            </div>
          </div>
        )}
      </div>

      <WarehouseForm open={!!whForm} initial={whForm} onSave={saveWarehouse} onClose={() => setWhForm(null)}/>
      <LocationForm open={!!locForm} initial={locForm}
        warehouseId={selectedWh} existingLocations={locations}
        onSave={saveLocation} onClose={() => setLocForm(null)}/>
      <ZoneForm open={zoneForm} onClose={() => setZoneForm(false)}
        warehouseId={selectedWh} existingZones={Object.keys(byZone)}
        onSave={addZone}/>
      <ConfirmDialog
        open={!!confirmDelWh}
        title="ยืนยันลบคลังสินค้า"
        message={`ต้องการลบคลัง "${confirmDelWh?.name}" ใช่หรือไม่? ช่องเก็บสินค้าทั้งหมดในคลังนี้จะถูกลบด้วย (ลบได้เฉพาะคลังที่ไม่มีสต๊อกคงเหลือ)`}
        danger onConfirm={() => doDeleteWarehouse(confirmDelWh.id)}
        onClose={() => setConfirmDelWh(null)}/>
      <ConfirmDialog
        open={!!confirmDelLoc}
        title="ยืนยันลบช่องเก็บสินค้า"
        message={`ลบช่อง ${confirmDelLoc?.id}?`}
        danger onConfirm={() => doDeleteLocation(confirmDelLoc.id)}
        onClose={() => setConfirmDelLoc(null)}/>
      <ConfirmDialog
        open={!!confirmDelZone}
        title="ยืนยันลบโซน"
        message={`ลบโซน "${confirmDelZone}" และทุกช่องในโซนนี้?`}
        danger onConfirm={() => doDeleteZone(confirmDelZone)}
        onClose={() => setConfirmDelZone(null)}/>
    </>
  );
}

function LegendDot({ color, label }) {
  return (
    <span className="row" style={{ gap: 5, color: "var(--fg-3)" }}>
      <span style={{ width: 10, height: 10, background: color, borderRadius: 2, border: "1px solid var(--border)" }}/>
      {label}
    </span>
  );
}

Object.assign(window, { WarehouseScreen });
