// items.jsx — Item master list + detail drawer

const { useState: useState_it, useMemo: useMemo_it } = React;

function ItemsScreen({ onNavigate }) {
  const { items, locations, getStockBySku, totalQty, movements } = useStore();
  const [query, setQuery] = useState_it("");
  const [cat, setCat] = useState_it("ทั้งหมด");
  const [stockFilter, setStockFilter] = useState_it("all");
  const [openSku, setOpenSku] = useState_it(null);

  const categories = useMemo_it(() => ["ทั้งหมด", ...new Set(items.map(i => i.category))], [items]);

  const filtered = useMemo_it(() => items.filter(it => {
    if (cat !== "ทั้งหมด" && it.category !== cat) return false;
    if (query && !(it.name.toLowerCase().includes(query.toLowerCase()) || it.sku.toLowerCase().includes(query.toLowerCase()))) return false;
    const q = totalQty(it.sku);
    if (stockFilter === "low" && q >= it.reorder) return false;
    if (stockFilter === "zero" && q > 0) return false;
    return true;
  }), [items, cat, query, stockFilter, totalQty]);

  return (
    <div className="col gap-md">
      {/* Filters bar */}
      <div className="card pad" style={{display:"flex", alignItems:"center", gap:12, flexWrap:"wrap"}}>
        <div className="search" style={{width:300, marginLeft:0}}>
          <Icon name="search" size={15}/>
          <input value={query} onChange={e => setQuery(e.target.value)} placeholder="ค้นหา SKU, ชื่อสินค้า..."/>
        </div>
        <div className="tabs">
          {categories.slice(0, 6).map(c => (
            <div key={c} className={"tab " + (cat === c ? "active" : "")} onClick={() => setCat(c)}>{c}</div>
          ))}
        </div>
        <div className="tabs" style={{marginLeft:"auto"}}>
          <div className={"tab " + (stockFilter === "all" ? "active" : "")} onClick={() => setStockFilter("all")}>ทั้งหมด</div>
          <div className={"tab " + (stockFilter === "low" ? "active" : "")} onClick={() => setStockFilter("low")}>ใกล้หมด</div>
          <div className={"tab " + (stockFilter === "zero" ? "active" : "")} onClick={() => setStockFilter("zero")}>หมด</div>
        </div>
        <button className="btn primary"><Icon name="plus" size={14}/>เพิ่มสินค้า</button>
      </div>

      <div className="card">
        <div className="table-wrap">
          <table className="tbl">
            <thead>
              <tr>
                <th style={{width:100}}>SKU</th>
                <th>ชื่อสินค้า</th>
                <th>หมวด</th>
                <th style={{textAlign:"right"}}>ต้นทุน</th>
                <th style={{textAlign:"right"}}>ราคาขาย</th>
                <th style={{textAlign:"right"}}>คงเหลือรวม</th>
                <th style={{width:180}}>ระดับสต๊อก</th>
                <th style={{width:120, textAlign:"right"}}>กระจายตามที่</th>
                <th style={{width:40}}></th>
              </tr>
            </thead>
            <tbody>
              {filtered.map(it => {
                const q = totalQty(it.sku);
                const locs = getStockBySku(it.sku).length;
                const pct = it.reorder ? Math.min(150, (q / it.reorder) * 100) : 100;
                const status = q === 0 ? "zero" : q < it.reorder ? "low" : "ok";
                return (
                  <tr key={it.sku} className="clickable" onClick={() => setOpenSku(it.sku)}>
                    <td className="cell-sku">{it.sku}</td>
                    <td>
                      <div style={{fontWeight:500}}>{it.name}</div>
                      <div style={{fontSize:11, color:"var(--text-mute)", marginTop:2}}>
                        <span className="mono">{it.barcode}</span>
                      </div>
                    </td>
                    <td><span className="cat-chip">{it.category}</span></td>
                    <td className="cell-num num muted">{fmtMoney(it.cost)}</td>
                    <td className="cell-num num">{fmtMoney(it.price)}</td>
                    <td className="cell-num">
                      <div className="num" style={{fontSize:14, fontWeight:600}}>
                        <AnimNum value={q}/>
                      </div>
                      <div className="muted" style={{fontSize:11, marginTop:1}}>{it.unit}</div>
                    </td>
                    <td>
                      <div style={{display:"flex", alignItems:"center", gap:8}}>
                        <div className={`pbar ${status === "ok" ? "" : status === "low" ? "warn" : "err"}`} style={{flex:1}}>
                          <span style={{width: Math.min(100, pct) + "%"}}/>
                        </div>
                        <span className={`chip ${status === "ok" ? "ok" : status === "low" ? "warn" : "err"}`} style={{fontSize:10.5}}>
                          <span className="dot"/>
                          {status === "ok" ? "ปกติ" : status === "low" ? "ใกล้หมด" : "หมด"}
                        </span>
                      </div>
                      <div className="muted" style={{fontSize:10.5, marginTop:3, fontFamily:"'JetBrains Mono', monospace"}}>min {it.reorder}</div>
                    </td>
                    <td className="cell-num">
                      <span className="chip accent">{locs} ที่</span>
                    </td>
                    <td onClick={e => e.stopPropagation()}>
                      <button className="icon-btn" style={{width:30, height:30}}><Icon name="more" size={14}/></button>
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
      </div>

      <ItemDetailDrawer sku={openSku} open={!!openSku} onClose={() => setOpenSku(null)} onNavigate={onNavigate}/>
    </div>
  );
}

function ItemDetailDrawer({ sku, open, onClose, onNavigate }) {
  const { items, locations, getStockBySku, movements, totalQty } = useStore();
  if (!sku) return <Drawer open={false} onClose={onClose} title=""/>;
  const item = items.find(i => i.sku === sku);
  if (!item) return null;

  const stockRows = getStockBySku(sku);
  const total = totalQty(sku);
  const mvHistory = movements.filter(m => m.sku === sku).slice(0, 12);

  return (
    <Drawer open={open} onClose={onClose} title={item.name} subtitle={`SKU ${item.sku} · ${item.category}`}
      footer={
        <React.Fragment>
          <button className="btn ghost" onClick={onClose}>ปิด</button>
          <button className="btn primary" onClick={() => { onClose(); onNavigate("receive", { sku }); }}>
            <Icon name="in" size={14}/> รับเข้า
          </button>
          <button className="btn danger" onClick={() => { onClose(); onNavigate("issue", { sku }); }}>
            <Icon name="out" size={14}/> จ่ายออก
          </button>
        </React.Fragment>
      }
    >
      {/* Top summary */}
      <div style={{display:"grid", gridTemplateColumns:"1fr 1fr 1fr", gap:10, marginBottom:18}}>
        <SummaryTile label="คงเหลือรวม" value={fmtNum(total)} unit={item.unit} color="#6d7cff"/>
        <SummaryTile label="ราคาขาย" value={fmtMoney(item.price)} color="#38d3a3"/>
        <SummaryTile label="Reorder Point" value={fmtNum(item.reorder)} unit={item.unit} color="#ffb454"/>
      </div>

      {/* Specs */}
      <div className="sect-head">
        <h3>รายละเอียดสินค้า</h3>
        <div className="grow"/>
        <button className="btn sm ghost"><Icon name="edit" size={13}/>แก้ไข</button>
      </div>
      <div className="card pad" style={{display:"grid", gridTemplateColumns:"1fr 1fr", gap:14, marginBottom:18}}>
        <Field label="หมวดหมู่" value={item.category}/>
        <Field label="หน่วยนับ" value={item.unit}/>
        <Field label="ต้นทุน" value={fmtMoney(item.cost)} mono/>
        <Field label="ราคาขาย" value={fmtMoney(item.price)} mono/>
        <Field label="Margin" value={`${Math.round(((item.price-item.cost)/item.price)*100)}%`} mono/>
        <Field label="Barcode" value={item.barcode} mono/>
        <Field label="ผู้จำหน่ายหลัก" value={item.supplier}/>
        <Field label="Reorder" value={`${item.reorder} ${item.unit}`} mono/>
      </div>

      {/* Stock by location */}
      <div className="sect-head">
        <h3>สต๊อกแยกตามที่จัดเก็บ</h3>
      </div>
      <div className="card" style={{marginBottom:18}}>
        <div className="table-wrap">
          <table className="tbl">
            <thead>
              <tr>
                <th>Location</th>
                <th>ประเภท</th>
                <th style={{textAlign:"right"}}>จำนวน</th>
                <th>สัดส่วน</th>
              </tr>
            </thead>
            <tbody>
              {stockRows.map(s => {
                const loc = locations.find(l => l.id === s.loc);
                const pct = total ? (s.qty / total) * 100 : 0;
                return (
                  <tr key={s.loc}>
                    <td>
                      <div style={{fontWeight:500}}>{loc?.name || s.loc}</div>
                      <div className="muted" style={{fontSize:11, marginTop:2}}><span className="mono">{s.loc}</span></div>
                    </td>
                    <td><span className="chip">{loc?.type === "shop" ? "หน้าร้าน" : loc?.type === "qc" ? "QC" : "คลัง"}</span></td>
                    <td className="cell-num num" style={{fontWeight:600}}>{fmtNum(s.qty)}</td>
                    <td>
                      <div style={{display:"flex", alignItems:"center", gap:8}}>
                        <div className="pbar" style={{flex:1}}><span style={{width:pct+"%"}}/></div>
                        <span className="num muted" style={{fontSize:11, width:36, textAlign:"right"}}>{pct.toFixed(0)}%</span>
                      </div>
                    </td>
                  </tr>
                );
              })}
              {stockRows.length === 0 && (
                <tr><td colSpan="4"><EmptyState icon="warehouse" title="ไม่มีสต๊อกในที่ใดเลย"/></td></tr>
              )}
            </tbody>
          </table>
        </div>
      </div>

      {/* Movement history */}
      <div className="sect-head">
        <h3>ประวัติการเคลื่อนไหว</h3>
        <div className="muted" style={{fontSize:12}}>{mvHistory.length} รายการล่าสุด</div>
      </div>
      <div className="card" style={{padding:"6px 16px 10px"}}>
        {mvHistory.map((m, i) => (
          <div key={m.id} style={{display:"flex", alignItems:"center", gap:12, padding:"10px 0", borderBottom: i < mvHistory.length-1 ? "1px solid rgba(255,255,255,0.04)" : "none"}}>
            <div className={"mv-type " + m.type}>
              {m.type === "IN" ? "รับ" : m.type === "OUT" ? "จ่าย" : "โอน"}
            </div>
            <div style={{flex:1, minWidth:0}}>
              <div style={{fontSize:13, fontWeight:500}}>
                {m.type === "IN" && <span>เข้า {m.toLoc}</span>}
                {m.type === "OUT" && <span>ออกจาก {m.fromLoc}</span>}
                {m.type === "XFER" && <span>โอน {m.fromLoc} → {m.toLoc}</span>}
              </div>
              <div className="muted" style={{fontSize:11, marginTop:2}}>{m.ref} · {fmtDateTime(m.ts)}</div>
            </div>
            <div className="num" style={{fontWeight:700, color: m.type === "OUT" ? "var(--danger)" : "var(--ok)"}}>
              {m.type === "OUT" ? "−" : "+"}{fmtNum(m.qty)}
            </div>
          </div>
        ))}
        {mvHistory.length === 0 && <EmptyState icon="history" title="ไม่มีประวัติการเคลื่อนไหว"/>}
      </div>
    </Drawer>
  );
}

function SummaryTile({ label, value, unit, color }) {
  return (
    <div style={{padding:"12px 14px", borderRadius:11, background:`linear-gradient(135deg, ${color}22, ${color}06)`, border:`1px solid ${color}33`}}>
      <div style={{fontSize:11, color:"var(--text-mute)"}}>{label}</div>
      <div style={{fontSize:18, fontWeight:700, marginTop:4}} className="num">{value}{unit && <span style={{fontSize:11, color:"var(--text-mute)", marginLeft:4}}>{unit}</span>}</div>
    </div>
  );
}

function Field({ label, value, mono }) {
  return (
    <div>
      <div style={{fontSize:11, color:"var(--text-mute)", marginBottom:3}}>{label}</div>
      <div style={{fontSize:13, fontWeight:500}} className={mono ? "num" : ""}>{value}</div>
    </div>
  );
}

Object.assign(window, { ItemsScreen });
