/* Banyan Pharmacy — Suppliers (orders, status, reliability) */

function relLabel(r) { return r === "reliable" ? "Reliable" : r === "watch" ? "Watch" : "Slipping"; }
function ordersSummary(ids) {
  const list = D.orders.filter((o) => o.supplierId === ids);
  const open = list.filter((o) => o.status !== "delivered").length;
  const bad = list.filter((o) => o.status === "short" || o.status === "delayed").length;
  return { open, bad, total: list.length };
}

function SuppliersPage() {
  const app = useApp();
  const focusId = app.loopFocus && app.loopFocus.kind === "supplier" ? app.loopFocus.id : null;
  const rows = [...D.suppliers].sort((a, b) => a.fill - b.fill); // weakest first
  return (
    <main className="page">
      <div className="ph">
        <div>
          <h1>Suppliers</h1>
          <div className="sub">Live orders and a reliability read — store-chat signals fused with order data</div>
        </div>
      </div>

      <div className="col g16">
        {rows.map((s) => {
          const sum = ordersSummary(s.id);
          const focus = focusId === s.id;
          const tone = s.fill >= 95 ? "" : s.fill >= 90 ? "warn" : "bad";
          return (
            <div key={s.id} className={cx("card pad", focus && "focus-glow")} style={{ cursor: "pointer", transition: "box-shadow 200ms" }}
              onClick={() => app.nav({ name: "supplier", id: s.id })}>
              <div className="flex ic jb g12 wrap">
                <div className="flex ic g12">
                  <window.Avatar initials={s.initials} size="lg" org />
                  <div>
                    <div className="flex ic g8"><span style={{ fontSize: 17, fontWeight: 600, letterSpacing: "-0.01em" }}>{s.name}</span><span className={cx("rel-chip", s.reliability)}><span className="dot" />{relLabel(s.reliability)}</span></div>
                    <div className="store-sub">{s.kind} · <span className="mono">{s.id}</span></div>
                  </div>
                </div>
                <div className="flex ic g8">
                  {sum.bad > 0 && <span className="pill blocked"><span className="dot" />{sum.bad} need attention</span>}
                  <span className="muted nowrap">{sum.open} open order{sum.open !== 1 ? "s" : ""}</span>
                  <Icons.chevRight size={16} className="muted" />
                </div>
              </div>

              <div className="grid2 mt16" style={{ gap: 24 }}>
                <div className={cx("metric-bar", tone)}>
                  <div className="mb-top"><span className="mb-k">Fill rate</span><span className="mb-v">{s.fill}%</span></div>
                  <div className="track"><i style={{ width: s.fill + "%" }} /></div>
                </div>
                <div className={cx("metric-bar", s.onTime >= 92 ? "" : s.onTime >= 85 ? "warn" : "bad")}>
                  <div className="mb-top"><span className="mb-k">On-time</span><span className="mb-v">{s.onTime}%</span></div>
                  <div className="track"><i style={{ width: s.onTime + "%" }} /></div>
                </div>
              </div>

              <div className="flex ic jb g12 wrap mt16" style={{ paddingTop: 14, borderTop: "1px solid var(--rule-soft)" }}>
                <div className="flex ic g8">
                  <span className="lbl" style={{ textTransform: "none", fontWeight: 500, fontSize: 13, color: "var(--mute)" }}>Short-supply incidents · 30d</span>
                  <span style={{ fontWeight: 600, color: s.incidents30 ? "var(--clay-deep)" : "var(--body)" }}>{s.incidents30}</span>
                  <span className={cx("flex ic g6", "muted")} style={{ fontSize: 12 }}>{s.trend === "down" ? <Icons.trendDown size={14} style={{ color: "var(--clay)" }} /> : <Icons.trendUp size={14} style={{ color: "var(--green)" }} />}{s.trend === "down" ? "worsening" : "steady"}</span>
                </div>
                {s.signal && <window.Prov muted>{s.signal}</window.Prov>}
              </div>
            </div>
          );
        })}
      </div>
    </main>
  );
}

function SupplierDetail({ route }) {
  const app = useApp();
  const s = D.supplierById[route.id];
  if (!s) return <main className="page"><div className="empty">Supplier not found.</div></main>;
  const orders = D.orders.filter((o) => o.supplierId === s.id);
  const storeIds = [...new Set(D.stores.filter((st) => st.suppliers.includes(s.id)).map((st) => st.id))];

  return (
    <main className="page">
      <a className="back" onClick={() => app.nav({ name: "suppliers" })}><Icons.arrowLeft size={15} />All suppliers</a>
      <div className="ph">
        <div>
          <div className="flex ic g10" style={{ marginBottom: 8 }}>
            <span className={cx("rel-chip", s.reliability)}><span className="dot" />{relLabel(s.reliability)}</span>
            <span className="store-sub">{s.kind}</span>
          </div>
          <h1>{s.name}</h1>
          <div className="sub">{s.note} <span className="ref">{s.id}</span></div>
        </div>
      </div>

      <div className="stat-row">
        <div className="stat"><div className="k">Fill rate</div><div className="v tn">{s.fill}%</div></div>
        <div className="stat"><div className="k">On-time</div><div className="v tn">{s.onTime}%</div></div>
        <div className={cx("stat", s.incidents30 && "accent")}><div className="k">Incidents · 30d</div><div className={cx("v tn", s.incidents30 && "clay")}>{s.incidents30}</div></div>
        <div className="stat"><div className="k">Stores supplied</div><div className="v tn">{storeIds.length}</div></div>
      </div>

      <section className="section">
        <SectionHead title="Live orders" count={orders.length} />
        <div className="card" style={{ overflow: "hidden" }}>
          <table className="t">
            <thead><tr><th>Order</th><th>Store</th><th>SKU</th><th className="right">Qty</th><th>Due</th><th>Status</th><th>Note</th></tr></thead>
            <tbody>
              {orders.map((o) => (
                <tr key={o.id}>
                  <td className="mono" style={{ fontSize: 12 }}>{o.id}</td>
                  <td>{D.storeById[o.storeId].locality}</td>
                  <td>{window.skuName(o.sku)}</td>
                  <td className="right tnum">{o.qty}</td>
                  <td className="muted">{window.shortDate(o.due)}</td>
                  <td><span className={cx("ord-status", o.status)}>{o.status}</span></td>
                  <td className="muted" style={{ fontSize: 12.5, maxWidth: 220 }}>{o.note || "—"}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </section>

      <div className="grid2" style={{ alignItems: "start" }}>
        <section className="section">
          <SectionHead title="Stores supplied" count={storeIds.length} />
          <div className="card"><div className="list">
            {storeIds.map((id) => {
              const st = D.storeById[id];
              return (
                <div key={id} className="row bare click" onClick={() => app.nav({ name: "store", id })}>
                  <div className="main"><div className="title" style={{ fontSize: 14 }}>{st.locality}</div><div className="meta">{st.region}</div></div>
                  <div className="right"><window.FormatBadge format={st.format} /></div>
                </div>
              );
            })}
          </div></div>
        </section>

        <section className="section">
          <SectionHead title="Recent signals" />
          <div className="card pad">
            {s.signal ? (
              <div className="col g12">
                <div className="chat-snip">
                  <div className="cs-from"><span className="wa"><Icons.message size={9} style={{ color: "#fff" }} /></span>Flagged from store chats</div>
                  <div className="cs-text">{s.id === "sup_sunrise1" ? "“Sunrise still hasn't delivered — 3rd time this month.”" : "“Expedite request open for the ward.”"}</div>
                </div>
                <window.Prov>{s.signal}</window.Prov>
              </div>
            ) : (
              <div className="empty" style={{ padding: "8px 2px" }}>No incidents flagged this month. Deliveries on track.</div>
            )}
          </div>
        </section>
      </div>
    </main>
  );
}

window.Pages = window.Pages || {};
window.Pages.Suppliers = SuppliersPage;
window.Pages.SupplierDetail = SupplierDetail;
