/* X-REAL Stock System — Dashboard */
const { useState: useStateD, useMemo: useMemoD } = React;

function Dashboard({ products, locations, stocks, cats, catMap, getQty, getTot, getLocTot, history, reservations, setTab }) {
  const [catFilter, setCatFilter] = useStateD("all");

  const totalQty = stocks.reduce((a, b) => a + b.qty, 0);
  const activeSkus = new Set(stocks.map(s => s.skuId)).size;

  // Expiring soon
  const expBatches = stocks
    .filter(s => ["warn", "expired", "soon"].includes(expStatus(s.expDate)))
    .sort((a, b) => new Date(a.expDate) - new Date(b.expDate));
  const expCritical = expBatches.filter(s => ["warn", "expired"].includes(expStatus(s.expDate))).length;

  // Pending reservations
  const pending = reservations.filter(r => r.status === "pending");

  // Filter products
  const filteredProds = useMemoD(() => {
    const base = catFilter === "all" ? products : products.filter(p => p.catId === catFilter);
    return base.filter(p => p.active !== false);
  }, [catFilter, products]);

  // Stock per location grid
  const lowStockSkus = filteredProds.filter(p => getTot(p.id) > 0 && getTot(p.id) < 30);

  return (
    <div  style={{ display: "flex", flexDirection: "column", gap: 18 }}>
      {/* ── KPI tiles ── */}
      <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(180px, 1fr))", gap: 12 }}>
        <StatCard label="สต็อครวม" value={totalQty.toLocaleString()} sub="ทุกคลังรวมกัน" icon="package" accent="accent"/>
        <StatCard label="SKU ที่มีสต็อค" value={activeSkus} sub={`จาก ${products.filter(p => p.active !== false).length} SKU ทั้งหมด`} icon="box"/>
        <StatCard label="คลังที่ใช้งาน" value={locations.filter(l => getLocTot(l.id) > 0).length} sub={`จาก ${locations.length} สถานที่`} icon="warehouse"/>
        <StatCard label="ใกล้หมดอายุ" value={expCritical} sub="ภายใน 30 วัน" icon="alert" accent={expCritical > 0 ? "danger" : "success"} onClick={expCritical > 0 ? () => setTab("audit") : undefined}/>
        <StatCard label="รอจัดส่ง" value={pending.length} sub="reservations" icon="reserve" accent={pending.length > 0 ? "warn" : "default"} onClick={() => setTab("reserve")}/>
      </div>

      {/* ── Quick action row ── */}
      <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(180px, 1fr))", gap: 12 }}>
        <QuickAction icon="zap"      label="Quick Scan" hint="สแกน → action" accent onClick={() => setTab("quick")}/>
        <QuickAction icon="in"       label="รับเข้า"    hint="หลาย SKU ทีเดียว" onClick={() => setTab("in")}/>
        <QuickAction icon="out"      label="จ่ายออก"    hint="ขายตรง / ฝากขาย" onClick={() => setTab("out")}/>
        <QuickAction icon="transfer" label="โอนคลัง"    hint="ย้าย / คืนสต็อค" onClick={() => setTab("tr")}/>
      </div>

      {/* ── Two-column: Stock by location + Expiring watchlist ── */}
      <div style={{ display: "grid", gridTemplateColumns: "minmax(0, 2fr) minmax(0, 1fr)", gap: 12 }} className="xr-dash-grid">
        <Card padded={false}>
          <div style={{
            display: "flex", alignItems: "center", justifyContent: "space-between",
            padding: "14px 18px", borderBottom: "1px solid var(--border-subtle)", flexWrap: "wrap", gap: 8,
          }}>
            <div>
              <div style={{ fontSize: 14, fontWeight: 700 }}>สต็อคแต่ละคลัง</div>
              <div style={{ fontSize: 11.5, color: "var(--text-3)" }}>realtime balance per location · per SKU</div>
            </div>
            <div style={{ display: "flex", gap: 6, flexWrap: "wrap" }}>
              <button onClick={() => setCatFilter("all")} className="xr-btn xr-btn--sm"
                style={{
                  background: catFilter === "all" ? "var(--text-1)" : undefined,
                  color: catFilter === "all" ? "var(--surface)" : undefined,
                  borderColor: catFilter === "all" ? "var(--text-1)" : undefined,
                }}>
                ทั้งหมด
              </button>
              {cats.map(c => (
                <button key={c.id} onClick={() => setCatFilter(c.id)} className="xr-btn xr-btn--sm"
                  style={{
                    background: catFilter === c.id ? c.color : undefined,
                    color: catFilter === c.id ? "#fff" : c.color,
                    borderColor: catFilter === c.id ? c.color : "var(--border)",
                  }}>{c.name}</button>
              ))}
            </div>
          </div>
          <div className="xr-table-scroll">
            <table className="xr-table" style={{ minWidth: 600 }}>
              <thead>
                <tr>
                  <th>SKU</th>
                  <th>ชื่อสินค้า</th>
                  {locations.map(l => (
                    <th key={l.id} style={{ textAlign: "right" }}>
                      <span style={{ display: "inline-flex", alignItems: "center", gap: 4 }}>
                        <Icon name={LOC_TYPE_META[l.locType]?.icon || "warehouse"} size={11}/>
                        {l.name}
                      </span>
                    </th>
                  ))}
                  <th style={{ textAlign: "right", color: "var(--accent)" }}>รวม</th>
                </tr>
              </thead>
              <tbody>
                {filteredProds.map(p => {
                  const lqs = locations.map(l => getQty(p.id, l.id));
                  const t = lqs.reduce((a, b) => a + b, 0);
                  if (t === 0 && catFilter !== "all") return null;
                  return (
                    <tr key={p.id}>
                      <td><SkuBadge sku={p.sku}/></td>
                      <td style={{ color: "var(--text-1)", fontSize: 13 }}>{p.name}</td>
                      {lqs.map((q, i) => (
                        <td key={i} style={{
                          textAlign: "right",
                          fontVariantNumeric: "tabular-nums",
                          color: q > 0 ? "var(--text-1)" : "var(--text-4)",
                          fontWeight: q > 0 ? 600 : 400,
                        }}>{q > 0 ? q : "—"}</td>
                      ))}
                      <td style={{
                        textAlign: "right", fontWeight: 700, color: "var(--accent)",
                        fontVariantNumeric: "tabular-nums",
                      }}>{t > 0 ? t : "—"}</td>
                    </tr>
                  );
                })}
                <tr style={{ background: "var(--surface-2)" }}>
                  <td colSpan={2} style={{ fontWeight: 700, color: "var(--text-2)", fontSize: 12, textTransform: "uppercase", letterSpacing: .6 }}>
                    Total per location
                  </td>
                  {locations.map(l => (
                    <td key={l.id} style={{
                      textAlign: "right", fontWeight: 700,
                      fontVariantNumeric: "tabular-nums", color: "var(--text-1)",
                    }}>{getLocTot(l.id) || "—"}</td>
                  ))}
                  <td style={{
                    textAlign: "right", fontWeight: 800, color: "var(--accent)",
                    fontVariantNumeric: "tabular-nums",
                  }}>{totalQty.toLocaleString()}</td>
                </tr>
              </tbody>
            </table>
          </div>
        </Card>

        {/* Right column */}
        <div style={{ display: "flex", flexDirection: "column", gap: 12, minWidth: 0 }}>
          {/* Expiring */}
          <Card padded={false}>
            <div style={{
              padding: "14px 18px 12px",
              display: "flex", alignItems: "center", justifyContent: "space-between",
            }}>
              <div>
                <div style={{ fontSize: 13, fontWeight: 700, display: "flex", alignItems: "center", gap: 6 }}>
                  <Icon name="alert" size={14} style={{ color: expBatches.length > 0 ? "var(--warn)" : "var(--text-3)" }}/>
                  ใกล้หมดอายุ
                </div>
                <div style={{ fontSize: 11, color: "var(--text-3)" }}>{expBatches.length} batches</div>
              </div>
              {expBatches.length > 0 && <Pill variant="warn">{expBatches.length}</Pill>}
            </div>
            {expBatches.length === 0 ? (
              <div style={{ padding: "0 18px 18px" }}>
                <div style={{
                  background: "var(--success-bg)", borderRadius: "var(--r-md)",
                  padding: "10px 14px", fontSize: 12, color: "var(--success)",
                  display: "flex", alignItems: "center", gap: 8,
                }}>
                  <Icon name="check" size={14}/>
                  ไม่มี batch ที่ใกล้หมดอายุ
                </div>
              </div>
            ) : (
              <div style={{ maxHeight: 360, overflowY: "auto" }}>
                {expBatches.slice(0, 8).map(s => {
                  const p = products.find(x => x.id === s.skuId);
                  const l = locations.find(x => x.id === s.locId);
                  const st = expStatus(s.expDate);
                  const d = daysUntil(s.expDate);
                  return (
                    <div key={s.id} style={{
                      padding: "10px 18px", borderTop: "1px solid var(--border-subtle)",
                      display: "flex", justifyContent: "space-between", alignItems: "center", gap: 8,
                    }}>
                      <div style={{ minWidth: 0, flex: 1 }}>
                        <div style={{ display: "flex", alignItems: "center", gap: 6, marginBottom: 3 }}>
                          <SkuBadge sku={p?.sku || "—"}/>
                          {s.lot && <span style={{ fontSize: 10, color: "var(--text-3)" }} className="xr-mono">{s.lot}</span>}
                        </div>
                        <div style={{ fontSize: 11.5, color: "var(--text-3)" }}>
                          {l?.name} · {s.qty} {p?.unit}
                        </div>
                      </div>
                      <div style={{ textAlign: "right", flexShrink: 0 }}>
                        <div style={{
                          fontSize: 12, fontWeight: 700,
                          color: st === "expired" ? "var(--danger)" : st === "warn" ? "var(--warn)" : "var(--text-2)",
                        }}>
                          {fmtD(s.expDate)}
                        </div>
                        <div style={{ fontSize: 10.5, color: "var(--text-3)" }}>
                          {st === "expired" ? `เลย ${Math.abs(d)} วัน` : `อีก ${d} วัน`}
                        </div>
                      </div>
                    </div>
                  );
                })}
                {expBatches.length > 8 && (
                  <div style={{ padding: "10px 18px", textAlign: "center" }}>
                    <button onClick={() => setTab("audit")} style={{
                      fontSize: 12, color: "var(--accent-hover)", fontWeight: 600,
                    }}>ดูทั้งหมด {expBatches.length} batches →</button>
                  </div>
                )}
              </div>
            )}
          </Card>

          {/* Recent activity */}
          <Card padded={false}>
            <div style={{
              padding: "14px 18px 12px",
              display: "flex", alignItems: "center", justifyContent: "space-between",
            }}>
              <div>
                <div style={{ fontSize: 13, fontWeight: 700, display: "flex", alignItems: "center", gap: 6 }}>
                  <Icon name="clock" size={14}/>
                  เคลื่อนไหวล่าสุด
                </div>
                <div style={{ fontSize: 11, color: "var(--text-3)" }}>{history.length} รายการ</div>
              </div>
            </div>
            {history.length === 0 ? (
              <div style={{ padding: "0 18px 18px", fontSize: 12, color: "var(--text-3)" }}>ยังไม่มีประวัติ</div>
            ) : (
              <div style={{ maxHeight: 280, overflowY: "auto" }}>
                {history.slice(0, 6).map(h => (
                  <ActivityRow key={h.id} entry={h}/>
                ))}
              </div>
            )}
          </Card>
        </div>
      </div>

      <style>{`
        @media (max-width: 1100px) {
          .xr-dash-grid { grid-template-columns: 1fr !important; }
        }
      `}</style>
    </div>
  );
}

function QuickAction({ icon, label, hint, accent, onClick }) {
  return (
    <button onClick={onClick} className="xr-card xr-clickable" style={{
      padding: "16px 18px",
      display: "flex", alignItems: "center", gap: 12, textAlign: "left",
      background: accent ? "linear-gradient(135deg, var(--accent), var(--accent-hover))" : undefined,
      color: accent ? "#fff" : undefined,
      border: accent ? "none" : undefined,
    }}>
      <div style={{
        width: 40, height: 40, borderRadius: "var(--r-md)",
        background: accent ? "rgba(255,255,255,.2)" : "var(--accent-subtle)",
        color: accent ? "#fff" : "var(--accent-hover)",
        display: "flex", alignItems: "center", justifyContent: "center",
        flexShrink: 0,
      }}>
        <Icon name={icon} size={20}/>
      </div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: 14, fontWeight: 700 }}>{label}</div>
        <div style={{ fontSize: 11.5, opacity: accent ? .85 : .6, marginTop: 1 }}>{hint}</div>
      </div>
      <Icon name="chevron-right" size={16} style={{ opacity: .5 }}/>
    </button>
  );
}

const ACTION_META = {
  "นำเข้า":   { color: "success", icon: "in" },
  "นำออก":    { color: "danger",  icon: "out" },
  "โอนย้าย":  { color: "warn",    icon: "transfer" },
  "Re-pack":  { color: "purple",  icon: "repack" },
  "ปรับ Audit": { color: "info",    icon: "audit" },
  "Reservation Fulfilled": { color: "success", icon: "check" },
};

function ActivityRow({ entry }) {
  const meta = ACTION_META[entry.action] || { color: "default", icon: "package" };
  const colorVar = meta.color === "default" ? "var(--text-2)" : `var(--${meta.color === "purple" ? "purple" : meta.color})`;
  const bgVar = meta.color === "default" ? "var(--surface-3)" : `var(--${meta.color === "purple" ? "purple" : meta.color}-bg)`;
  return (
    <div style={{
      padding: "10px 18px", display: "flex", gap: 10, alignItems: "flex-start",
      borderTop: "1px solid var(--border-subtle)",
    }}>
      <div style={{
        width: 28, height: 28, borderRadius: "var(--r-sm)", flexShrink: 0,
        background: bgVar, color: colorVar,
        display: "flex", alignItems: "center", justifyContent: "center",
      }}>
        <Icon name={meta.icon} size={14}/>
      </div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: 12, color: "var(--text-1)", lineHeight: 1.4 }}>{entry.detail}</div>
        <div style={{ display: "flex", gap: 10, marginTop: 3 }}>
          <span style={{ fontSize: 10.5, color: "var(--text-3)" }}>{entry.user}</span>
          <span style={{ fontSize: 10.5, color: "var(--text-3)" }}>· {fmtRel(entry.ts)}</span>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { Dashboard });
