// locations.jsx — Locations screen with auto stock tracking

const { useState: useState_lo, useMemo: useMemo_lo } = React;

function LocationsScreen({ onNavigate }) {
  const { locations, items, stock, getStockByLoc, totalQty, transfer, movements } = useStore();
  const [selectedLoc, setSelectedLoc] = useState_lo(locations[0]?.id);
  const [transferOpen, setTransferOpen] = useState_lo(false);
  const [query, setQuery] = useState_lo("");

  const locUtilization = useMemo_lo(() => {
    return locations.map(l => {
      const rows = getStockByLoc(l.id);
      const units = rows.reduce((a, b) => a + b.qty, 0);
      const skus = rows.length;
      const value = rows.reduce((a, r) => {
        const it = items.find(i => i.sku === r.sku);
        return a + (it?.cost || 0) * r.qty;
      }, 0);
      const util = l.capacity ? (units / l.capacity) * 100 : 0;
      return { ...l, units, skus, value, util };
    });
  }, [locations, items, getStockByLoc]);

  const selected = locUtilization.find(l => l.id === selectedLoc);
  const selectedRows = selected ? getStockByLoc(selected.id) : [];
  const filteredRows = selectedRows.filter(r => {
    if (!query) return true;
    const it = items.find(i => i.sku === r.sku);
    return it && (it.name.toLowerCase().includes(query.toLowerCase()) || it.sku.toLowerCase().includes(query.toLowerCase()));
  });

  const recentMv = movements.filter(m => m.fromLoc === selected?.id || m.toLoc === selected?.id).slice(0, 6);

  return (
    <div className="col gap-md">
      {/* Location cards grid */}
      <div style={{display:"grid", gridTemplateColumns:"repeat(auto-fill, minmax(220px, 1fr))", gap:12}}>
        {locUtilization.map(l => {
          const ico = l.type === "shop" ? "store" : l.type === "qc" ? "qc" : "warehouse";
          const isActive = l.id === selectedLoc;
          const utilClass = l.util > 90 ? "err" : l.util > 75 ? "warn" : "";
          return (
            <div key={l.id} className={"loc-card " + (isActive ? "active" : "")} onClick={() => setSelectedLoc(l.id)} style={{cursor:"pointer"}}>
              <div style={{display:"flex", alignItems:"flex-start", gap:12, marginBottom:14}}>
                <div className={"loc-icon " + (l.type === "shop" ? "shop" : l.type === "qc" ? "qc" : "")}>
                  <Icon name={ico} size={20}/>
                </div>
                <div style={{flex:1, minWidth:0}}>
                  <div style={{fontWeight:600, fontSize:13.5}}>{l.name}</div>
                  <div style={{fontSize:11, color:"var(--text-mute)", marginTop:2, display:"flex", gap:7}}>
                    <span className="mono">{l.id}</span>
                    <span>·</span>
                    <span>{l.zone}</span>
                  </div>
                </div>
              </div>
              <div style={{display:"flex", justifyContent:"space-between", alignItems:"baseline", marginBottom:6}}>
                <span style={{fontSize:11, color:"var(--text-mute)"}}>การใช้พื้นที่</span>
                <span className="num" style={{fontSize:12, fontWeight:600}}>{Math.round(l.util)}%</span>
              </div>
              <div className={`pbar ${utilClass}`}><span style={{width: Math.min(100, l.util) + "%"}}/></div>
              <div style={{display:"grid", gridTemplateColumns:"1fr 1fr 1fr", gap:8, marginTop:14, paddingTop:14, borderTop:"1px solid var(--border)"}}>
                <div>
                  <div style={{fontSize:10.5, color:"var(--text-dim)"}}>SKU</div>
                  <div className="num" style={{fontWeight:600, fontSize:14}}>{l.skus}</div>
                </div>
                <div>
                  <div style={{fontSize:10.5, color:"var(--text-dim)"}}>หน่วย</div>
                  <div className="num" style={{fontWeight:600, fontSize:14}}>{fmtNum(l.units)}</div>
                </div>
                <div>
                  <div style={{fontSize:10.5, color:"var(--text-dim)"}}>มูลค่า</div>
                  <div className="num" style={{fontWeight:600, fontSize:13}}>฿{Math.round(l.value/1000)}k</div>
                </div>
              </div>
            </div>
          );
        })}
      </div>

      {/* Selected location detail */}
      {selected && (
        <div style={{display:"grid", gridTemplateColumns:"1.6fr 1fr", gap:14}}>
          <div className="card">
            <div className="card-head">
              <div>
                <div className="card-title">สต๊อกใน {selected.name}</div>
                <div className="card-sub">{filteredRows.length} SKU · อัปเดตอัตโนมัติเมื่อมีการเคลื่อนไหว</div>
              </div>
              <div className="search" style={{width:200, marginLeft:"auto"}}>
                <Icon name="search" size={14}/>
                <input placeholder="ค้นหา..." value={query} onChange={e => setQuery(e.target.value)}/>
              </div>
              <button className="btn sm primary" onClick={() => setTransferOpen(true)}>
                <Icon name="transfer" size={13}/>โอนสต๊อก
              </button>
            </div>
            <div className="table-wrap" style={{maxHeight:480}}>
              <table className="tbl">
                <thead>
                  <tr>
                    <th style={{width:90}}>SKU</th>
                    <th>ชื่อสินค้า</th>
                    <th style={{textAlign:"right"}}>จำนวน</th>
                    <th>สถานะ</th>
                  </tr>
                </thead>
                <tbody>
                  {filteredRows.map(r => {
                    const it = items.find(i => i.sku === r.sku);
                    if (!it) return null;
                    const total = totalQty(r.sku);
                    const sharePct = total ? (r.qty/total)*100 : 0;
                    const status = r.qty === 0 ? "zero" : r.qty < (it.reorder * 0.5) ? "low" : "ok";
                    return (
                      <tr key={r.sku}>
                        <td className="cell-sku">{it.sku}</td>
                        <td>
                          <div style={{fontWeight:500}}>{it.name}</div>
                          <div className="muted" style={{fontSize:11, marginTop:2}}>{sharePct.toFixed(0)}% ของสต๊อกรวม</div>
                        </td>
                        <td className="cell-num">
                          <div className="num" style={{fontSize:14, fontWeight:600}}><AnimNum value={r.qty}/></div>
                          <div className="muted" style={{fontSize:10.5}}>{it.unit}</div>
                        </td>
                        <td>
                          <span className={`chip ${status === "ok" ? "ok" : status === "low" ? "warn" : "err"}`}>
                            <span className="dot"/>
                            {status === "ok" ? "ปกติ" : status === "low" ? "ใกล้หมด" : "หมด"}
                          </span>
                        </td>
                      </tr>
                    );
                  })}
                  {filteredRows.length === 0 && (
                    <tr><td colSpan="4"><EmptyState icon="package" title="ไม่พบสินค้าในที่นี้"/></td></tr>
                  )}
                </tbody>
              </table>
            </div>
          </div>

          {/* Recent movements + map */}
          <div className="col gap-md">
            <div className="card">
              <div className="card-head">
                <div>
                  <div className="card-title">การเคลื่อนไหวล่าสุด</div>
                  <div className="card-sub">In/Out ของ {selected.name}</div>
                </div>
              </div>
              <div style={{padding:"6px 16px 10px"}}>
                {recentMv.map((m, i) => {
                  const direction = m.toLoc === selected.id ? "IN" : "OUT";
                  return (
                    <div key={m.id} style={{display:"flex", gap:12, padding:"9px 0", borderBottom: i < recentMv.length-1 ? "1px solid rgba(255,255,255,0.04)" : "none"}}>
                      <div className={"mv-type " + direction}>{direction === "IN" ? "เข้า" : "ออก"}</div>
                      <div style={{flex:1, minWidth:0}}>
                        <div style={{fontSize:12.5, fontWeight:500, overflow:"hidden", textOverflow:"ellipsis", whiteSpace:"nowrap"}}>{m.itemName}</div>
                        <div className="muted" style={{fontSize:11, marginTop:2}}>{m.ref} · {timeAgo(m.ts)}</div>
                      </div>
                      <div className="num" style={{fontWeight:700, color: direction === "IN" ? "var(--ok)" : "var(--danger)"}}>
                        {direction === "IN" ? "+" : "−"}{fmtNum(m.qty)}
                      </div>
                    </div>
                  );
                })}
                {recentMv.length === 0 && <EmptyState icon="history" title="ยังไม่มีการเคลื่อนไหว"/>}
              </div>
            </div>

            <div className="card pad">
              <div style={{display:"flex", alignItems:"center", gap:8, marginBottom:14}}>
                <Icon name="alert" size={14} stroke={2}/>
                <div className="card-title" style={{fontSize:13}}>การแจ้งเตือนอัตโนมัติ</div>
              </div>
              {(() => {
                const lowAt = filteredRows.filter(r => {
                  const it = items.find(i => i.sku === r.sku);
                  return it && r.qty < it.reorder * 0.5;
                });
                const overUtil = selected.util > 85;
                if (lowAt.length === 0 && !overUtil) {
                  return <div className="chip ok" style={{padding:"7px 12px", width:"100%", justifyContent:"center"}}><Icon name="check" size={12}/>ทุกอย่างปกติ</div>;
                }
                return (
                  <div style={{display:"flex", flexDirection:"column", gap:8}}>
                    {overUtil && (
                      <div style={{display:"flex", gap:10, padding:"10px 12px", background:"rgba(255,176,84,0.08)", borderRadius:9, border:"1px solid rgba(255,176,84,0.25)"}}>
                        <Icon name="alert" size={15} stroke={2} style={{color:"var(--warn)", flexShrink:0, marginTop:2}}/>
                        <div>
                          <div style={{fontSize:12.5, fontWeight:600}}>การใช้พื้นที่สูง</div>
                          <div className="muted" style={{fontSize:11.5, marginTop:2}}>ใช้พื้นที่ {Math.round(selected.util)}% — ควรพิจารณาโอนสต๊อก</div>
                        </div>
                      </div>
                    )}
                    {lowAt.slice(0, 3).map(r => {
                      const it = items.find(i => i.sku === r.sku);
                      return (
                        <div key={r.sku} style={{display:"flex", gap:10, padding:"10px 12px", background:"rgba(255,107,120,0.07)", borderRadius:9, border:"1px solid rgba(255,107,120,0.22)"}}>
                          <Icon name="alert" size={15} stroke={2} style={{color:"var(--danger)", flexShrink:0, marginTop:2}}/>
                          <div style={{flex:1, minWidth:0}}>
                            <div style={{fontSize:12.5, fontWeight:600, overflow:"hidden", textOverflow:"ellipsis", whiteSpace:"nowrap"}}>{it.name}</div>
                            <div className="muted" style={{fontSize:11.5, marginTop:2}}>เหลือ {r.qty} {it.unit} ใน {selected.id}</div>
                          </div>
                        </div>
                      );
                    })}
                  </div>
                );
              })()}
            </div>
          </div>
        </div>
      )}

      <TransferModal open={transferOpen} onClose={() => setTransferOpen(false)} fromLoc={selectedLoc}/>
    </div>
  );
}

function TransferModal({ open, onClose, fromLoc }) {
  const { items, locations, getStock, transfer } = useStore();
  const otherLocs = locations.filter(l => l.id !== fromLoc);
  const [sku, setSku] = useState_lo("");
  const [toLoc, setToLoc] = useState_lo(otherLocs[0]?.id);
  const [qty, setQty] = useState_lo(1);
  const [note, setNote] = useState_lo("");

  React.useEffect(() => {
    if (open) { setSku(""); setToLoc(otherLocs[0]?.id); setQty(1); setNote(""); }
  }, [open]);

  const available = sku ? getStock(sku, fromLoc) : 0;
  const itemsWithStock = items.filter(it => getStock(it.sku, fromLoc) > 0);
  const canSubmit = sku && qty > 0 && qty <= available && toLoc && toLoc !== fromLoc;

  return (
    <Modal open={open} onClose={onClose} title="โอนสต๊อกระหว่างคลัง" subtitle={`ต้นทาง: ${fromLoc}`}
      footer={
        <React.Fragment>
          <button className="btn ghost" onClick={onClose}>ยกเลิก</button>
          <button className="btn primary" disabled={!canSubmit} onClick={() => {
            transfer({ sku, fromLoc, toLoc, qty, note });
            onClose();
          }}><Icon name="transfer" size={14}/>โอนสต๊อก</button>
        </React.Fragment>
      }
    >
      <div className="fld" style={{marginBottom:12}}>
        <label>สินค้า</label>
        <select className="select" value={sku} onChange={e => setSku(e.target.value)}>
          <option value="">-- เลือกสินค้า --</option>
          {itemsWithStock.map(it => (
            <option key={it.sku} value={it.sku}>{it.sku} — {it.name} (มี {getStock(it.sku, fromLoc)})</option>
          ))}
        </select>
      </div>
      <div style={{display:"grid", gridTemplateColumns:"1fr 1fr", gap:12, marginBottom:12}}>
        <div className="fld">
          <label>คลังปลายทาง</label>
          <select className="select" value={toLoc} onChange={e => setToLoc(e.target.value)}>
            {otherLocs.map(l => <option key={l.id} value={l.id}>{l.name}</option>)}
          </select>
        </div>
        <div className="fld">
          <label>จำนวน {sku && <span className="muted" style={{marginLeft:6}}>(มี {available})</span>}</label>
          <QtyStepper value={qty} onChange={setQty} max={available || 99999}/>
        </div>
      </div>
      <div className="fld">
        <label>หมายเหตุ</label>
        <textarea className="input" rows={2} value={note} onChange={e => setNote(e.target.value)} placeholder="เหตุผลการโอน..."/>
      </div>
      {sku && qty > available && (
        <div className="chip err" style={{marginTop:10, padding:"6px 10px"}}><Icon name="alert" size={12}/>สต๊อกต้นทางไม่พอ</div>
      )}
    </Modal>
  );
}

Object.assign(window, { LocationsScreen });
