/* =============================================================
   CoreIQ Office — Supplier profile (detail page with tabs)
   Registers window.OFFICE_SCREENS.supplierDetail
   ============================================================= */
const { useState: sdUseState, useMemo: sdUseMemo, useEffect: sdUseEffect } = React;

const MONTHS = ["Jun","Jul","Aug","Sep","Oct","Nov","Dec","Jan","Feb","Mar","Apr","May"];

function poStatusBadge(st) {
  const m = {
    received:   { c: "badge--paid",    l: "Received" },
    "in-transit":{ c: "badge--hold",   l: "In transit" },
    ordered:    { c: "badge--brand",   l: "Ordered" },
    part:       { c: "badge--hold",    l: "Part-filled" },
  }[st] || { c: "badge--neutral", l: st };
  return <span className={"badge " + m.c}><span className="badge-dot"/> {m.l}</span>;
}
function invStatusBadge(st) {
  const m = {
    paid:    { c: "badge--paid",    l: "Paid" },
    due:     { c: "badge--hold",    l: "Due" },
    overdue: { c: "badge--void",    l: "Overdue" },
    credit:  { c: "badge--brand",   l: "Credit" },
  }[st] || { c: "badge--neutral", l: st };
  return <span className={"badge " + m.c}><span className="badge-dot"/> {m.l}</span>;
}
function ago(d) { return d === 0 ? "Today" : d === 1 ? "Yesterday" : d + " days ago"; }

// ---- Overview tab ------------------------------------------------
function TabOverview({ id, period, setTab }) {
  const ext = window.supExt(id);
  const sp = window.supSpend(id, period);
  const share = window.supSpendShare(id, period);
  const delta = window.supSpendDelta(id);
  const trend = window.supSpend12(id);
  const tmax = Math.max(...trend, 1);
  const bo = window.supBackorders(id);
  const openBal = window.supOpenBalance(id);
  const t = window.supType(id);
  const KpiCard = window.KpiCard;

  return (
    <div>
      {bo.length > 0 && (
        <div className={"sup-alert" + (bo.length >= 6 ? " sup-alert--bad" : "")}>
          <window.OIcon name="alert"/>
          <span><strong>{bo.length} line{bo.length > 1 ? "s" : ""} on backorder</strong> with this supplier — {bo.reduce((s, b) => s + b.qty, 0)} units across affected stores.</span>
          <button className="btn btn--ghost btn--sm" style={{ marginLeft: "auto" }} onClick={() => setTab("backorders")}>View</button>
        </div>
      )}

      <div className="sup-ov-kpis">
        <KpiCard label={"Spend · " + window.SUP_DATA.PERIODS.find(p => p.key === period).label} value={window.supMoneyK(sp)} delta={isFinite(delta) && sp > 0 ? { dir: delta >= 0 ? "up" : "down", text: (delta >= 0 ? "+" : "") + (delta * 100).toFixed(1) + "% MoM" } : { text: "New account" }}/>
        <KpiCard label="Share of purchasing" value={(share * 100).toFixed(1) + "%"} delta={{ text: t.label }}/>
        <KpiCard label="On-time delivery" value={ext.onTime == null ? "—" : ext.onTime + "%"} delta={ext.onTime == null ? { text: ext.leadTime + "-day lead" } : { dir: ext.onTime >= 95 ? "up" : "down", text: ext.leadTime + "-day lead" }}/>
        <KpiCard label="Open balance" value={openBal > 0 ? window.supMoneyK(openBal) : "$0"} delta={{ text: ext.terms.payment }}/>
      </div>

      <div className="sup-cols">
        <div className="sup-sec">
          <div className="sup-sec-head"><span className="sup-sec-title">Spend · trailing 12 months</span><span style={{ marginLeft: "auto", fontSize:'var(--fs-12)', color: "var(--text-muted)" }}>Total {window.supMoneyK(trend.reduce((a, b) => a + b, 0))}</span></div>
          <div className="sup-sec-body">
            <div className="sup-trend">
              {trend.map((v, i) => (
                <div key={i} className="sup-trend-col">
                  <div className={"sup-trend-bar" + (i < 6 ? " sup-trend-bar--dim" : "")} style={{ height: (v / tmax * 100) + "%", background: i >= 6 ? t.color : undefined }} title={window.supMoneyK(v)}/>
                  <div className="sup-trend-x">{MONTHS[i]}</div>
                </div>
              ))}
            </div>
          </div>
        </div>

        <div className="sup-sec">
          <div className="sup-sec-head"><span className="sup-sec-title">Account rep</span></div>
          <div className="sup-sec-body">
            <div className="sup-rep">
              <div className="sup-rep-av">{ext.rep.name.split(" ").map(w => w[0]).slice(0, 2).join("")}</div>
              <div>
                <div className="sup-rep-name">{ext.rep.name}</div>
                <div className="sup-rep-title">{ext.rep.title}</div>
              </div>
            </div>
            <div className="sup-rep-contacts">
              <div className="sup-rep-contact"><window.OIcon name="phone"/> {ext.rep.mobile}</div>
              <div className="sup-rep-contact"><window.OIcon name="doc"/> <a href={"mailto:" + ext.rep.email}>{ext.rep.email}</a></div>
              <div className="sup-rep-contact"><window.OIcon name="truck"/> {ext.channel}</div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

// ---- Catalogue tab ----------------------------------------------
function TabCatalogue({ id }) {
  const cat = window.supCatalogue(id);
  return (
    <div className="sup-sec">
      <div className="sup-sec-head">
        <span className="sup-sec-title">SKUs supplied</span>
        <span className="sup-tab-count" style={{ marginLeft: 8 }}>{cat.length}</span>
        <button className="btn btn--ghost btn--sm sup-sec-action"><window.OIcon name="plus"/> Link SKU</button>
      </div>
      <div className="sup-grid">
        <div className="sup-grid-row sup-grid-row--head" style={{ gridTemplateColumns: "2fr 110px 90px 90px 80px 90px" }}>
          <span>Product</span><span>PDE</span><span className="sup-grid-num">Buy ex</span><span className="sup-grid-num">Sell</span><span className="sup-grid-num">MOQ</span><span className="sup-grid-num">On hand</span>
        </div>
        {cat.map(p => (
          <div key={p.id} className="sup-grid-row sup-grid-row--body" style={{ gridTemplateColumns: "2fr 110px 90px 90px 80px 90px" }}>
            <div style={{ minWidth: 0 }}>
              <div className="sup-grid-strong">{p.name} {p.strength !== "—" ? p.strength : ""}</div>
              <div className="sup-grid-muted" style={{ fontSize: 11.5, marginTop: 1 }}>
                {p.pack}{p.schedule !== "—" ? " · " + p.schedule : ""}{p.pbs ? " · PBS" : ""}
              </div>
            </div>
            <span className="sup-grid-mono sup-grid-muted">{p.pde}</span>
            <span className="sup-grid-num sup-grid-strong">{window.officeMoney(p.cost)}</span>
            <span className="sup-grid-num">{window.officeMoney(p.price)}</span>
            <span className="sup-grid-num">{p.moq}</span>
            <span className="sup-grid-num">{p.onHand}</span>
          </div>
        ))}
        {cat.length === 0 && <div className="sup-grid-row"><span className="sup-grid-muted">No SKUs linked to this supplier.</span></div>}
      </div>
    </div>
  );
}

// ---- Purchase orders tab ----------------------------------------
function TabPOs({ id }) {
  const pos = window.supPurchaseOrders(id);
  const { pushToast } = window.useOffice();
  return (
    <div className="sup-sec">
      <div className="sup-sec-head">
        <span className="sup-sec-title">Purchase orders</span>
        <span className="sup-tab-count" style={{ marginLeft: 8 }}>{pos.length}</span>
        <button className="btn btn--primary btn--sm sup-sec-action" onClick={() => pushToast({ kind: "paid", icon: "plus", title: "New purchase order", meta: "Draft started for this supplier" })}><window.OIcon name="plus"/> New PO</button>
      </div>
      <div className="sup-grid">
        <div className="sup-grid-row sup-grid-row--head" style={{ gridTemplateColumns: "120px 90px 80px 1fr 130px 110px" }}>
          <span>PO number</span><span>Store</span><span className="sup-grid-num">Lines</span><span>Date</span><span>Status</span><span className="sup-grid-num">Value</span>
        </div>
        {pos.map(po => (
          <div key={po.id} className="sup-grid-row sup-grid-row--body" style={{ gridTemplateColumns: "120px 90px 80px 1fr 130px 110px" }}>
            <span className="sup-grid-mono sup-grid-strong">{po.id}</span>
            <span className="sup-grid-mono sup-grid-muted">{po.store}</span>
            <span className="sup-grid-num">{po.lines}</span>
            <span className="sup-grid-muted">{ago(po.daysAgo)}{po.eta ? " · ETA " + po.eta : ""}</span>
            <span>{poStatusBadge(po.status)}</span>
            <span className="sup-grid-num sup-grid-strong">{window.officeMoney(po.value)}</span>
          </div>
        ))}
      </div>
    </div>
  );
}

// ---- Invoices tab -----------------------------------------------
function TabInvoices({ id }) {
  const inv = window.supInvoices(id);
  const open = window.supOpenBalance(id);
  return (
    <>
      <div className="sup-cols" style={{ gridTemplateColumns: "1fr 1fr 1fr", marginBottom: 14 }}>
        <div className="sup-kpi"><div className="sup-kpi-l">Open balance</div><div className="sup-kpi-v">{window.supMoneyK(open)}</div><div className="sup-kpi-sub">{window.supExt(id).terms.payment}</div></div>
        <div className="sup-kpi"><div className="sup-kpi-l">Settlement</div><div className="sup-kpi-v" style={{ fontSize:'var(--fs-18)' }}>{window.supExt(id).terms.settlement || "—"}</div><div className="sup-kpi-sub">early-payment discount</div></div>
        <div className="sup-kpi"><div className="sup-kpi-l">Credits · 12mo</div><div className="sup-kpi-v">{window.supExt(id).credits}%</div><div className="sup-kpi-sub">of purchases returned</div></div>
      </div>
      <div className="sup-sec">
        <div className="sup-sec-head"><span className="sup-sec-title">Invoices &amp; credits</span><span className="sup-tab-count" style={{ marginLeft: 8 }}>{inv.length}</span><button className="btn btn--ghost btn--sm sup-sec-action"><window.OIcon name="doc"/> Log credit</button></div>
        <div className="sup-grid">
          <div className="sup-grid-row sup-grid-row--head" style={{ gridTemplateColumns: "140px 1fr 120px 110px 120px" }}>
            <span>Document</span><span>Date</span><span>Terms</span><span>Status</span><span className="sup-grid-num">Amount</span>
          </div>
          {inv.map(v => (
            <div key={v.id} className="sup-grid-row sup-grid-row--body" style={{ gridTemplateColumns: "140px 1fr 120px 110px 120px" }}>
              <span className="sup-grid-mono sup-grid-strong">{v.id}</span>
              <span className="sup-grid-muted">{ago(v.daysAgo)}</span>
              <span className="sup-grid-muted">{v.terms}</span>
              <span>{invStatusBadge(v.status)}</span>
              <span className="sup-grid-num sup-grid-strong" style={{ color: v.amount < 0 ? "var(--brand)" : undefined }}>{window.officeMoney(v.amount)}</span>
            </div>
          ))}
        </div>
      </div>
    </>
  );
}

// ---- Performance tab --------------------------------------------
function TabPerformance({ id }) {
  const ext = window.supExt(id);
  const bars = [
    { l: "On-time delivery", v: ext.onTime, sub: "Orders delivered by the promised date" },
    { l: "Fill rate", v: ext.fillRate, sub: "Lines supplied in full, first attempt" },
    { l: "DIFOT", v: ext.difot, sub: "Delivered in full, on time" },
  ];
  function barColor(v) { return v == null ? "var(--border-strong)" : v >= 95 ? "var(--paid)" : v >= 90 ? "var(--hold)" : "var(--void)"; }
  return (
    <div className="sup-cols">
      <div className="sup-sec">
        <div className="sup-sec-head"><span className="sup-sec-title">Service performance · 12 months</span></div>
        <div className="sup-sec-body">
          {ext.isNew && <div className="sup-modal-hint" style={{ marginBottom: 12 }}>No delivery history yet — performance builds once orders start flowing.</div>}
          {bars.map(b => (
            <div key={b.l} className="sup-perfbar">
              <div className="sup-perfbar-top"><span className="sup-perfbar-l">{b.l}</span><span className="sup-perfbar-v">{b.v == null ? "—" : b.v + "%"}</span></div>
              <div className="sup-perfbar-track"><i style={{ width: (b.v || 0) + "%", background: barColor(b.v) }}/></div>
              <div className="sup-perfbar-sub">{b.sub}</div>
            </div>
          ))}
        </div>
      </div>
      <div className="sup-sec">
        <div className="sup-sec-head"><span className="sup-sec-title">At a glance</span></div>
        <div className="sup-sec-body">
          <div className="sup-kv">
            <div className="sup-kv-row"><span className="sup-kv-k">Avg lead time</span><span className="sup-kv-v">{ext.leadTime} day{ext.leadTime > 1 ? "s" : ""}</span></div>
            <div className="sup-kv-row"><span className="sup-kv-k">Order cut-off</span><span className="sup-kv-v" style={{ fontSize:'var(--fs-12)' }}>{ext.cutoff}</span></div>
            <div className="sup-kv-row"><span className="sup-kv-k">Credits / returns</span><span className="sup-kv-v">{ext.credits}%</span></div>
            <div className="sup-kv-row"><span className="sup-kv-k">Open backorders</span><span className="sup-kv-v">{window.SUP_DATA.BACKORDERS[id] || 0}</span></div>
            <div className="sup-kv-row"><span className="sup-kv-k">Channel</span><span className="sup-kv-v">{ext.channel}</span></div>
          </div>
        </div>
      </div>
    </div>
  );
}

// ---- Terms & accounts tab ---------------------------------------
function TabTerms({ id }) {
  const ext = window.supExt(id);
  const accts = window.supAccounts(id);
  const s = window.OFFICE_DATA.SUPPLIERS.find(x => x.id === id);
  return (
    <div className="sup-cols">
      <div>
        <div className="sup-sec">
          <div className="sup-sec-head"><span className="sup-sec-title">Trading terms</span><button className="btn btn--ghost btn--sm sup-sec-action"><window.OIcon name="settings"/> Edit</button></div>
          <div className="sup-sec-body">
            <div className="sup-kv">
              <div className="sup-kv-row">
                <span className="sup-kv-k">Order priority</span>
                <span className="sup-kv-v" style={{ display: "flex", alignItems: "center", gap: 8 }}>
                  <span className={"sup-line-badge " + (typeof window.supLine(id) === "number" ? "sup-line-badge--n" + (window.supLine(id) <= 3 ? window.supLine(id) : "x") : "sup-line-badge--" + window.supLine(id))}>{window.supLineLabel(id)}</span>
                  {window.supIsRanked(id) && (
                    <span style={{ display: "inline-flex", gap: 4 }}>
                      <button className="sup-line-move" title="Promote" onClick={() => window.supMoveLine(id, -1)}><window.OIcon name="arrow-up"/></button>
                      <button className="sup-line-move" title="Demote" onClick={() => window.supMoveLine(id, 1)}><window.OIcon name="arrow-down"/></button>
                    </span>
                  )}
                </span>
              </div>
              <div className="sup-kv-row"><span className="sup-kv-k">Payment terms</span><span className="sup-kv-v">{ext.terms.payment}</span></div>
              <div className="sup-kv-row"><span className="sup-kv-k">Settlement discount</span><span className="sup-kv-v">{ext.terms.settlement || "—"}</span></div>
              <div className="sup-kv-row"><span className="sup-kv-k">Volume rebate</span><span className="sup-kv-v">{ext.terms.rebate || "—"}</span></div>
              <div className="sup-kv-row"><span className="sup-kv-k">Min order / freight</span><span className="sup-kv-v">{ext.terms.moq}</span></div>
              <div className="sup-kv-row"><span className="sup-kv-k">Returns policy</span><span className="sup-kv-v">{ext.terms.returns}</span></div>
            </div>
          </div>
        </div>
        <div className="sup-sec">
          <div className="sup-sec-head"><span className="sup-sec-title">Company</span></div>
          <div className="sup-sec-body">
            <div className="sup-kv">
              <div className="sup-kv-row"><span className="sup-kv-k">ABN</span><span className="sup-kv-v is-mono">{ext.abn}</span></div>
              <div className="sup-kv-row"><span className="sup-kv-k">Address</span><span className="sup-kv-v" style={{ fontSize:'var(--fs-12)' }}>{ext.address}</span></div>
              <div className="sup-kv-row"><span className="sup-kv-k">Website</span><span className="sup-kv-v is-mono">{ext.web}</span></div>
              <div className="sup-kv-row"><span className="sup-kv-k">Phone</span><span className="sup-kv-v is-mono">{s.phone}</span></div>
            </div>
          </div>
        </div>
      </div>
      <div className="sup-sec">
        <div className="sup-sec-head"><span className="sup-sec-title">Per-store accounts</span><span className="sup-tab-count" style={{ marginLeft: 8 }}>{accts.length}</span></div>
        <div className="sup-sec-body" style={{ paddingTop: 4, paddingBottom: 4 }}>
          {accts.map(a => (
            <div key={a.storeId} className="sup-acct">
              <div className="sup-acct-av">{a.code}</div>
              <div className="sup-acct-meta">
                <div className="sup-acct-store">{a.store}</div>
                <div className="sup-acct-num">{a.account} · since {a.since}</div>
              </div>
              <span className={"badge " + (a.status === "active" ? "badge--paid" : "badge--hold")}><span className="badge-dot"/> {a.status === "active" ? "Active" : "On hold"}</span>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

// ---- Documents tab ----------------------------------------------
function TabDocs({ id }) {
  const ext = window.supExt(id);
  const docs = ext.docs || [];
  function docBadge(st) {
    const m = { current: { c: "badge--paid", l: "Current" }, review: { c: "badge--hold", l: "Review due" }, stale: { c: "badge--void", l: "Out of date" } }[st] || { c: "badge--neutral", l: st };
    return <span className={"badge " + m.c}><span className="badge-dot"/> {m.l}</span>;
  }
  return (
    <div className="sup-sec">
      <div className="sup-sec-head"><span className="sup-sec-title">Documents &amp; compliance</span><span className="sup-tab-count" style={{ marginLeft: 8 }}>{docs.length}</span><button className="btn btn--ghost btn--sm sup-sec-action"><window.OIcon name="plus"/> Upload</button></div>
      <div className="sup-sec-body" style={{ paddingTop: 4, paddingBottom: 4 }}>
        {docs.map((d, i) => (
          <div key={i} className="sup-doc">
            <div className="sup-doc-ic"><window.OIcon name="doc"/></div>
            <div className="sup-doc-meta">
              <div className="sup-doc-name">{d.name}</div>
              <div className="sup-doc-sub">{d.type} · updated {d.updated}{d.expires ? " · expires " + d.expires : ""}</div>
            </div>
            {docBadge(d.status)}
            <button className="btn btn--ghost btn--sm" style={{ marginLeft: 10 }}><window.OIcon name="chevron-right"/></button>
          </div>
        ))}
      </div>
    </div>
  );
}

// =================================================================
// PROFILE SHELL
// =================================================================
// -----------------------------------------------------------------
// SUPPLIER DETAIL — LIVE · this pharmacy
// Real supplier profile (passed from the list) + the products that name it as
// primary supplier, fetched from /products?supplierId. Trading history is shown
// as an honest empty state — no spend/PO/invoice data was migrated.
// -----------------------------------------------------------------
function SupplierDetail() {
  const { screenState, setScreen, setScreenState } = window.useOffice();
  const s = screenState.supplier;
  const openProduct = (pid) => { setScreenState((st) => ({ ...st, activeProductId: pid, productFrom: "supplierDetail" })); setScreen("productDetail"); };
  const [products, setProducts] = React.useState([]);
  const [loadingP, setLoadingP] = React.useState(true);

  React.useEffect(() => {
    if (!s) return undefined;
    let alive = true;
    setLoadingP(true);
    window.OfficeAPI.listProducts({ supplierId: s.id, limit: 200 })
      .then((ps) => { if (alive) { setProducts(ps || []); setLoadingP(false); } })
      .catch(() => { if (alive) setLoadingP(false); });
    return () => { alive = false; };
  }, [s && s.id]);

  if (!s) {
    return (
      <div className="off-screen"><div className="off-screen-body"><div className="off-empty" style={{padding:40}}>
        <div className="empty-title">No supplier selected.</div>
        <button className="btn btn--secondary btn--sm" style={{marginTop:10}} onClick={() => setScreen("suppliers")}>Back to suppliers</button>
      </div></div></div>
    );
  }

  const money2 = (c) => "$" + (Number(c || 0) / 100).toFixed(2);
  const loc = [s.locality, s.region].filter(Boolean).join(", ") || null;

  return (
    <div className="off-screen">
      <header className="off-screen-header">
        <div className="off-screen-header-meta">
          <span className="off-screen-eyebrow">
            <button className="btn btn--ghost btn--sm" style={{padding:0, height:'auto', fontSize:'var(--fs-12)', verticalAlign:'baseline'}} onClick={() => setScreen("suppliers")}>‹ Suppliers</button> · live from Aurora
          </span>
          <h2 className="off-screen-title">{s.name}</h2>
        </div>
      </header>

      <div className="off-screen-body">
        <div className="off-kpi-grid">
          <KpiCard label="Products supplied" value={s.productCount.toLocaleString("en-AU")} delta={{ text: "named as primary supplier" }}/>
          <KpiCard label="Payment terms" value={s.paymentTermsDays != null ? "Net " + s.paymentTermsDays : "—"} delta={{ text: s.orderMethod || "order method n/a" }}/>
          <KpiCard label="Account #" value={s.accountNumber || "—"} delta={{ text: s.code ? "code " + s.code : "" }}/>
          <KpiCard label="Status" value={s.isActive ? "Active" : "Inactive"} delta={{ text: s.supplierType || "" }}/>
        </div>

        <div className="dash-grid" style={{marginTop:16}}>
          <div className="off-card">
            <div className="off-card-header"><h3 className="off-card-title">Contact & ordering</h3></div>
            <div style={{display:'flex', flexDirection:'column', gap:0}}>
              <SupKV k="Contact" v={s.contactName}/>
              <SupKV k="Email" v={s.email} mail/>
              <SupKV k="Phone" v={s.phone}/>
              <SupKV k="ABN" v={s.abn}/>
              <SupKV k="Location" v={loc}/>
              <SupKV k="Order method" v={s.orderMethod}/>
            </div>
          </div>
          <div className="off-card">
            <div className="off-card-header"><h3 className="off-card-title">Trading history</h3></div>
            <div className="off-empty" style={{padding:'28px 16px'}}>
              <div className="empty-icon"><window.OIcon name="info" width={20} height={20}/></div>
              <div className="empty-title">No purchase history yet</div>
              <div style={{fontSize:'var(--fs-12)', color:'var(--text-subtle)', textAlign:'center', maxWidth:340}}>
                Spend, orders, invoices and on-time metrics populate as you raise purchase orders — none were migrated from Z.
              </div>
            </div>
          </div>
        </div>

        <div className="off-table" style={{marginTop:16}}>
          <div className="off-table-toolbar">
            <span style={{fontSize:'var(--fs-13)', fontWeight:600}}>Products from this supplier</span>
            <div style={{marginLeft:'auto', fontSize:'var(--fs-12)', color:'var(--text-muted)'}}>
              {loadingP ? "loading…" : (products.length >= 200 ? "first 200 of " + s.productCount.toLocaleString("en-AU") : products.length.toLocaleString("en-AU") + " of " + s.productCount.toLocaleString("en-AU"))}
            </div>
          </div>
          <div className="off-grid" style={{gridTemplateColumns:'minmax(220px,1.6fr) 150px 80px 100px 100px'}}>
            <div className="off-grid-headcell">Product</div>
            <div className="off-grid-headcell">SKU</div>
            <div className="off-grid-headcell">Sched</div>
            <div className="off-grid-headcell" style={{justifyContent:'flex-end'}}>Cost</div>
            <div className="off-grid-headcell" style={{justifyContent:'flex-end'}}>Sell</div>
            {products.map((p) => (
              <div key={p.id} className="off-grid-row" style={{cursor:'pointer'}} onClick={() => openProduct(p.id)}>
                <div className="off-grid-cell off-cell-strong">{p.name && p.name !== "-" ? p.name : p.sku}</div>
                <div className="off-grid-cell off-cell-mono">{p.sku}</div>
                <div className="off-grid-cell">{p.schedule ? <window.SchedBadge schedule={p.schedule} compact/> : ""}</div>
                <div className="off-grid-cell off-cell-num off-muted">{p.costPriceCents == null ? "—" : money2(p.costPriceCents)}</div>
                <div className="off-grid-cell off-cell-num">{money2(p.sellPriceCents)}</div>
              </div>
            ))}
          </div>
          {!loadingP && products.length === 0 && <div className="off-empty" style={{padding:24}}><div className="empty-title">No products link to this supplier.</div></div>}
        </div>
      </div>
    </div>
  );
}

function SupKV({ k, v, mail }) {
  return (
    <div className="alert-row" style={{cursor:'default'}}>
      <div style={{flex:'0 0 110px', fontSize:'var(--fs-12)', color:'var(--text-subtle)'}}>{k}</div>
      <div style={{flex:1, fontSize:'var(--fs-13)', color: v ? 'var(--text)' : 'var(--text-subtle)', overflow:'hidden', textOverflow:'ellipsis'}}>
        {v ? (mail ? <a href={"mailto:" + v}>{v}</a> : v) : "—"}
      </div>
    </div>
  );
}

function TabBackorders({ id }) {
  const bo = window.supBackorders(id);
  if (bo.length === 0) {
    return (
      <div className="sup-sec"><div className="empty" style={{ padding: 48 }}>
        <div className="empty-icon"><window.OIcon name="check-circle" width={22} height={22}/></div>
        <h4 className="empty-title">No backorders</h4>
        <p className="empty-meta">Every line from this supplier is currently available.</p>
      </div></div>
    );
  }
  return (
    <div className="sup-sec">
      <div className="sup-sec-head"><span className="sup-sec-title">Lines on backorder</span><span className="sup-tab-count" style={{ marginLeft: 8 }}>{bo.length}</span><button className="btn btn--secondary btn--sm sup-sec-action"><window.OIcon name="phone"/> Chase supplier</button></div>
      <div className="sup-grid">
        <div className="sup-grid-row sup-grid-row--head" style={{ gridTemplateColumns: "2fr 90px 110px 130px" }}>
          <span>Product</span><span className="sup-grid-num">Qty</span><span className="sup-grid-num">Waiting</span><span>ETA</span>
        </div>
        {bo.map((b, i) => (
          <div key={i} className="sup-grid-row sup-grid-row--body" style={{ gridTemplateColumns: "2fr 90px 110px 130px" }}>
            <span className="sup-grid-strong">{b.product} {b.strength !== "—" ? b.strength : ""}</span>
            <span className="sup-grid-num">{b.qty}</span>
            <span className="sup-grid-num">{b.waiting}d</span>
            <span>{b.eta === "No ETA" ? <span className="badge badge--void"><span className="badge-dot"/> No ETA</span> : <span className="sup-grid-muted">{b.eta}</span>}</span>
          </div>
        ))}
      </div>
    </div>
  );
}

window.OFFICE_SCREENS = Object.assign(window.OFFICE_SCREENS || {}, { supplierDetail: SupplierDetail });
