/* =============================================================
   CoreIQ Office — Supply & shortages (LIVE · this pharmacy)

   The drug-shortage radar + supplier-exposure scorecard, from the wholesaler
   out-of-stock / backorder events (public.supply_shortage_events; migrated Z
   OrdersPharmXOOSLines + a future PharmX feed). Censored demand that never shows
   up in sales: every line a wholesaler could not fully supply.

   "Exposure" = counts of OOS/backorder events per supplier / per drug — NOT a
   true fill-rate % (we don't carry a clean total-orders denominator), so it counts
   what actually went short rather than overclaim a ratio.
   ============================================================= */
const { useState: ssState, useEffect: ssEffect } = React;

const ssN = (n) => Number(n || 0).toLocaleString("en-AU");
const ssDate = (s) => String(s || "").slice(0, 10);

function StatusBadge({ status }) {
  const cfg = status === "backordered"
    ? { t: "Backordered", bg: "var(--hold-bg)", fg: "var(--hold-text)" }
    : status === "out_of_stock"
    ? { t: "Out of stock", bg: "var(--void-bg)", fg: "var(--void-text)" }
    : { t: status || "—", bg: "var(--bg-subtle)", fg: "var(--text-subtle)" };
  return <span style={{fontSize:9, fontWeight:700, letterSpacing:.3, padding:"2px 7px", borderRadius:10, background:cfg.bg, color:cfg.fg, whiteSpace:"nowrap"}}>{cfg.t}</span>;
}

function ShortageRadar() {
  const { setScreen, setScreenState } = window.useOffice();
  const [data, setData] = ssState(null);
  const [events, setEvents] = ssState([]);
  const [supplier, setSupplier] = ssState("");
  const [status, setStatus] = ssState("");
  const [search, setSearch] = ssState("");
  const [err, setErr] = ssState(null);
  const [loading, setLoading] = ssState(true);

  ssEffect(() => {
    let alive = true;
    window.OfficeAPI.shortageSummary()
      .then((d) => { if (alive) { setData(d); setErr(null); } })
      .catch((e) => { if (alive) setErr(String(e.message || e)); });
    return () => { alive = false; };
  }, []);
  ssEffect(() => {
    let alive = true;
    setLoading(true);
    const q = { limit: 200 };
    if (supplier) q.supplier = supplier;
    if (status) q.status = status;
    if (search.trim()) q.search = search.trim();
    window.OfficeAPI.supplyShortages(q)
      .then((ev) => { if (alive) { setEvents(ev || []); setLoading(false); } })
      .catch((e) => { if (alive) { setErr(String(e.message || e)); setLoading(false); } });
    return () => { alive = false; };
  }, [supplier, status, search]);

  const openProduct = (pid) => { if (!pid) return; setScreenState((st) => ({ ...st, activeProductId: pid, productFrom: "shortageRadar" })); setScreen("productDetail"); };
  const s = data && data.summary;
  const bySupplier = (data && data.bySupplier) || [];
  const topProducts = (data && data.topProducts) || [];
  const Kpi = window.KpiCard;
  const maxSup = Math.max(1, ...bySupplier.map((r) => r.events));

  return (
    <div className="off-screen">
      <header className="off-screen-header">
        <div className="off-screen-header-meta">
          <span className="off-screen-eyebrow">live · this pharmacy · wholesaler supply events</span>
          <h2 className="off-screen-title">Supply &amp; shortages</h2>
        </div>
      </header>

      <div className="off-screen-body">
        {err && <div className="off-card" style={{borderColor:"var(--void-border)", background:"var(--void-bg)", color:"var(--void-text)", padding:"12px 16px"}}><window.OIcon name="alert"/> {err}</div>}

        {s && Kpi && (
          <div style={{display:"grid", gridTemplateColumns:"repeat(4, 1fr)", gap:14, marginBottom:18}}>
            <Kpi label="Shortage events" value={ssN(s.totalEvents)} delta={{ text: ssDate(s.firstAt) + " → " + ssDate(s.lastAt) }}/>
            <Kpi label="Drugs affected" value={ssN(s.productsAffected)} delta={{ text: "distinct lines short" }}/>
            <Kpi label="Out of stock" value={ssN(s.outOfStock)} delta={{ text: "no supply", dir: "down" }}/>
            <Kpi label="Backordered" value={ssN(s.backordered)} delta={{ text: "delayed, has ETA" }}/>
          </div>
        )}

        <div style={{display:"grid", gridTemplateColumns:"1fr 1fr", gap:16, marginBottom:16}}>
          {/* Supplier exposure scorecard */}
          <div className="off-card">
            <div className="off-card-header">
              <h3 className="off-card-title">Supplier exposure</h3>
              <span className="off-card-meta">events · drugs short · click to filter</span>
            </div>
            <div style={{display:"flex", flexDirection:"column", gap:8}}>
              {bySupplier.slice(0, 8).map((r, i) => (
                <div key={i} style={{display:"flex", alignItems:"center", gap:10, cursor:"pointer", opacity: supplier && supplier !== r.supplier ? 0.5 : 1}}
                  onClick={() => setSupplier(supplier === r.supplier ? "" : r.supplier)}>
                  <div style={{flex:"0 0 150px", fontSize:"var(--fs-12)", overflow:"hidden", textOverflow:"ellipsis", whiteSpace:"nowrap"}}>{r.supplier || "—"}</div>
                  <div style={{flex:1, background:"var(--bg-subtle)", borderRadius:5, height:18, position:"relative"}}>
                    <div style={{position:"absolute", left:0, top:0, bottom:0, width: Math.max(2, (r.events / maxSup) * 100) + "%", background:"var(--brand)", borderRadius:5, opacity:0.85}}/>
                  </div>
                  <div style={{flex:"0 0 120px", textAlign:"right", fontSize:"var(--fs-12)", fontVariantNumeric:"tabular-nums"}}>{ssN(r.events)} · {ssN(r.productsAffected)} drugs</div>
                </div>
              ))}
              {bySupplier.length === 0 && <div style={{padding:"12px 4px", fontSize:"var(--fs-13)", color:"var(--text-subtle)"}}>No supplier data.</div>}
            </div>
          </div>

          {/* Most-shorted-drug watch list */}
          <div className="off-card">
            <div className="off-card-header">
              <h3 className="off-card-title">Most-shorted drugs</h3>
              <span className="off-card-meta">the watch list</span>
            </div>
            <div className="off-grid" style={{gridTemplateColumns:"1fr 70px 90px"}}>
              <div className="off-grid-headcell">Drug</div>
              <div className="off-grid-headcell" style={{justifyContent:"flex-end"}}>Times</div>
              <div className="off-grid-headcell" style={{justifyContent:"flex-end"}}>Last</div>
              {topProducts.slice(0, 8).map((r, i) => (
                <div key={i} className="off-grid-row" style={{cursor: r.productId ? "pointer" : "default"}} onClick={() => openProduct(r.productId)}>
                  <div className="off-grid-cell off-cell-strong" style={{overflow:"hidden", textOverflow:"ellipsis", whiteSpace:"nowrap"}}>{r.productDescription || "—"}</div>
                  <div className="off-grid-cell off-cell-num">{ssN(r.events)}</div>
                  <div className="off-grid-cell off-cell-num off-muted" style={{fontSize:"var(--fs-11)"}}>{ssDate(r.lastAt)}</div>
                </div>
              ))}
            </div>
          </div>
        </div>

        {/* Recent events + filters */}
        <div className="off-card">
          <div className="off-card-header">
            <h3 className="off-card-title">Shortage events</h3>
            <div style={{display:"flex", gap:8, alignItems:"center"}}>
              {supplier && <button className="btn btn--ghost btn--sm" onClick={() => setSupplier("")}>✕ {supplier}</button>}
              <div style={{display:"flex", gap:6}}>
                {[["", "All"], ["out_of_stock", "Out of stock"], ["backordered", "Backordered"]].map(([k, label]) => (
                  <button key={k} className={"btn btn--sm " + (status === k ? "btn--primary" : "btn--ghost")} onClick={() => setStatus(k)}>{label}</button>
                ))}
              </div>
              <input className="off-input" style={{minWidth:200}} placeholder="Filter drug / reorder…" value={search} onChange={(e) => setSearch(e.target.value)}/>
            </div>
          </div>
          {!loading && events.length === 0 && <div style={{padding:"12px 4px", fontSize:"var(--fs-13)", color:"var(--text-subtle)"}}>No shortage events match.</div>}
          {events.length > 0 && (
            <div className="off-grid" style={{gridTemplateColumns:"96px 1fr 150px 90px 96px"}}>
              <div className="off-grid-headcell">Date</div>
              <div className="off-grid-headcell">Drug</div>
              <div className="off-grid-headcell">Supplier</div>
              <div className="off-grid-headcell" style={{justifyContent:"flex-end"}}>Short</div>
              <div className="off-grid-headcell" style={{justifyContent:"flex-end"}}>Status</div>
              {events.map((e, i) => (
                <div key={i} className="off-grid-row" style={{cursor: e.productId ? "pointer" : "default"}} onClick={() => openProduct(e.productId)}>
                  <div className="off-grid-cell off-cell-mono" style={{fontSize:"var(--fs-11)"}}>{ssDate(e.orderedAt)}</div>
                  <div className="off-grid-cell off-cell-strong" style={{overflow:"hidden", textOverflow:"ellipsis", whiteSpace:"nowrap"}}>{e.productDescription || "—"}</div>
                  <div className="off-grid-cell" style={{overflow:"hidden", textOverflow:"ellipsis", whiteSpace:"nowrap", fontSize:"var(--fs-12)"}}>{e.supplierName || "—"}</div>
                  <div className="off-grid-cell off-cell-num">{(e.qtyBackordered ?? 0) > 0 ? ssN(e.qtyBackordered) : ssN(e.qtyOutOfStock)}</div>
                  <div className="off-grid-cell" style={{justifyContent:"flex-end"}}><StatusBadge status={e.status}/></div>
                </div>
              ))}
            </div>
          )}
          {events.length >= 200 && <div style={{padding:"10px 2px", fontSize:"var(--fs-12)", color:"var(--text-subtle)"}}>Showing the 200 most recent matching events.</div>}
        </div>
      </div>
    </div>
  );
}

window.OFFICE_SCREENS = Object.assign(window.OFFICE_SCREENS || {}, { shortageRadar: ShortageRadar });
