/* =============================================================
   CoreIQ Office — Major expansion
   Buying · Staff · Clinical · Customer · Finance · Gov programs · Ops · Admin
   ============================================================= */
const { useState: xUseState, useMemo: xUseMemo } = React;
const STX = { "S-001": "var(--teal-700)", "S-002": "var(--navy-600)", "S-003": "var(--violet-600)" };

// Generic screen shell helper
function Screen({ eyebrow, title, actions, subtabs, activeTab, onTab, children }) {
  return (
    <div className="off-screen">
      <header className="off-screen-header">
        <div className="off-screen-header-meta">
          <span className="off-screen-eyebrow">{eyebrow}</span>
          <h2 className="off-screen-title">{title}</h2>
        </div>
        <div className="off-screen-actions">{actions}</div>
      </header>
      {subtabs && (
        <div className="off-subtabs">
          {subtabs.map(s => (
            <button key={s.k} className={"off-subtab" + (activeTab === s.k ? " off-subtab--active" : "")} onClick={() => onTab(s.k)}>
              {s.l}{s.badge ? <span style={{marginLeft:6, fontSize:10, background:s.badgeColor || 'var(--hold)', color:'var(--hold-fg)', padding:'1px 6px', borderRadius:99, fontWeight:600}}>{s.badge}</span> : null}
            </button>
          ))}
        </div>
      )}
      <div className="off-screen-body">{children}</div>
    </div>
  );
}

function StatusPill({ kind, label }) {
  const map = { paid:"badge--paid", hold:"badge--hold", void:"badge--void", brand:"badge--brand", sched:"badge--sched", neutral:"badge--neutral" };
  return <span className={"badge " + (map[kind] || "badge--neutral")}><span className="badge-dot"/> {label}</span>;
}

// =================================================================
// BUYING — Purchase Orders (formal, separate from Ordering)
// =================================================================
function PurchaseOrders() {
  const { setScreen, setScreenState } = window.useOffice();
  const PO = [
    { id:"PO-4426", supplier:"CSL Seqirus",  ws:"ws-csl",     channel:"Direct (DHL)", store:"S-001", lines:3, units:600, value:9420.00, status:"received",   sent:"12/04/2026", expected:"20/04/2026", received:"20/04/2026", auth:"Suni Kapoor", contractRef:"FLU-2026" },
    { id:"PO-4422", supplier:"Sigma",        ws:"ws-sigma",   channel:"PharmX",       store:"S-001", lines:4, units:158, value:412.40,  status:"received",   sent:"25/05/2026 22:00", expected:"Today 09:00", received:"Today 09:14", auth:"auto", contractRef:"Q2-2026" },
    { id:"PO-4423", supplier:"Symbion",      ws:"ws-symbion", channel:"PharmX",       store:"S-001", lines:2, units:70,  value:624.60,  status:"received",   sent:"25/05/2026 22:00", expected:"Today 11:30", received:"Today 11:30", auth:"auto", contractRef:"Q2-2026" },
    { id:"PO-4424", supplier:"API",          ws:"ws-api",     channel:"EDI",          store:"S-001", lines:6, units:240, value:1142.20, status:"in-transit", sent:"Today 06:30", expected:"Today 16:00", received:null, auth:"Suni Kapoor" },
    { id:"PO-4425", supplier:"GSK Australia",ws:"ws-gsk",     channel:"Direct (DHL)", store:"S-002", lines:1, units:24,  value:380.20,  status:"in-transit", sent:"25/05/2026", expected:"Today 14:00", received:null, auth:"Rachel Pham" },
    { id:"PO-4429", supplier:"Webstercare",  ws:"ws-webster", channel:"Direct (DHL)", store:"S-003", lines:1, units:50,  value:600.00,  status:"submitted",  sent:"Today 11:48", expected:"Tomorrow", received:null, auth:"James Liu" },
    { id:"PO-4430", supplier:"Symbion",      ws:"ws-symbion", channel:"PharmX",       store:"S-003", lines:6, units:188, value:712.30,  status:"submitted",  sent:"Today 12:14", expected:"Tomorrow 09:30", received:null, auth:"James Liu" },
    { id:"PO-4427", supplier:"Diabetes Aust",ws:"ws-ndss",    channel:"EDI",          store:"S-003", lines:5, units:144, value:410.20,  status:"open",       sent:"—", expected:"—", received:null, auth:"—" },
    { id:"PO-4428", supplier:"Sigma",        ws:"ws-sigma",   channel:"PharmX",       store:"S-002", lines:8, units:220, value:884.50,  status:"open",       sent:"—", expected:"—", received:null, auth:"—" },
  ];
  const [filter, setFilter] = xUseState("all");
  const FILTERS = [
    {k:"all", l:"All"}, {k:"open", l:"Draft"}, {k:"submitted", l:"Submitted"},
    {k:"in-transit", l:"In transit"}, {k:"received", l:"Received"},
  ];
  const list = PO.filter(o => filter === "all" || o.status === filter);

  return (
    <Screen eyebrow="Buying · purchase orders" title="Purchase orders"
      actions={<>
        <button className="btn btn--ghost btn--sm">Export</button>
        <button className="btn btn--primary btn--sm"><OIcon name="plus"/> New PO</button>
      </>}>
      <div className="off-kpi-grid">
        <KpiCard label="Open POs" value={PO.filter(o => o.status === "open" || o.status === "submitted").length} delta={{text:"Draft + submitted"}}/>
        <KpiCard label="In transit" value={PO.filter(o => o.status === "in-transit").length} delta={{text:"Awaiting receipt"}}/>
        <KpiCard label="PO value · 30d" value={oMoney(PO.reduce((s, o) => s + o.value, 0))} delta={{dir:"up", text:"▲ 9.1% vs prior 30d"}}/>
        <KpiCard label="Avg lead time" value="1.4 days" delta={{text:"PharmX overnight skews avg"}}/>
      </div>

      <div className="off-table">
        <div className="off-table-toolbar">
          <div className="off-filters">
            {FILTERS.map(f => <button key={f.k} className={"off-filter" + (filter === f.k ? " off-filter--active" : "")} onClick={() => setFilter(f.k)}>{f.l}</button>)}
          </div>
        </div>
        <div className="off-grid" style={{gridTemplateColumns:'110px 1.4fr 110px 100px 60px 60px 110px 130px 130px'}}>
          <div className="off-grid-headcell">PO</div>
          <div className="off-grid-headcell">Supplier · contract</div>
          <div className="off-grid-headcell">Channel</div>
          <div className="off-grid-headcell">Store</div>
          <div className="off-grid-headcell" style={{justifyContent:'flex-end'}}>Lines</div>
          <div className="off-grid-headcell" style={{justifyContent:'flex-end'}}>Units</div>
          <div className="off-grid-headcell" style={{justifyContent:'flex-end'}}>Value</div>
          <div className="off-grid-headcell">Authorised by</div>
          <div className="off-grid-headcell">Status</div>
          {list.map(o => (
            <div key={o.id} className="off-grid-row" style={{ cursor: ["in-transit","received","submitted"].includes(o.status) ? "pointer" : "default" }} onClick={() => { if (["in-transit","received","submitted"].includes(o.status)) setScreen("receiving"); }}>
              <div className="off-grid-cell off-cell-mono off-cell-strong">{o.id}</div>
              <div className="off-grid-cell off-cell-strong">{o.supplier}
                {o.contractRef && <div className="off-cell-mono off-muted" style={{fontSize:11, marginTop:2}}>Contract {o.contractRef}</div>}</div>
              <div className="off-grid-cell"><span className="badge badge--neutral">{o.channel}</span></div>
              <div className="off-grid-cell off-mono">{findS(o.store)?.code}</div>
              <div className="off-grid-cell off-cell-num">{o.lines}</div>
              <div className="off-grid-cell off-cell-num">{o.units}</div>
              <div className="off-grid-cell off-cell-num off-cell-strong">{oMoney(o.value)}</div>
              <div className="off-grid-cell off-muted">{o.auth}</div>
              <div className="off-grid-cell">
                {o.status === "open"       && <StatusPill kind="neutral" label="Draft"/>}
                {o.status === "submitted"  && <StatusPill kind="hold" label="Submitted"/>}
                {o.status === "in-transit" && <StatusPill kind="brand" label="In transit"/>}
                {o.status === "received"   && <StatusPill kind="paid" label="Received"/>}
              </div>
            </div>
          ))}
        </div>
      </div>
    </Screen>
  );
}

// =================================================================
// BUYING — Supplier price lists & contract pricing
// =================================================================
function PriceLists() {
  const [supplier, setSupplier] = xUseState("ws-sigma");
  const supList = [
    {id:"ws-sigma", name:"Sigma Healthcare", contract:"Q2-2026", validUntil:"30/06/2026", lines:1402, version:"v18", uploaded:"01/04/2026"},
    {id:"ws-symbion", name:"Symbion", contract:"Q2-2026", validUntil:"30/06/2026", lines:1118, version:"v12", uploaded:"01/04/2026"},
    {id:"ws-api", name:"API", contract:"Annual 2026", validUntil:"31/12/2026", lines:884, version:"v8", uploaded:"15/01/2026"},
    {id:"ws-gsk", name:"GSK Australia", contract:"Direct", validUntil:"open", lines:42, version:"v3", uploaded:"22/05/2026"},
    {id:"ws-csl", name:"CSL Seqirus", contract:"FLU-2026", validUntil:"31/08/2026", lines:8, version:"v1", uploaded:"12/04/2026"},
  ];
  const current = supList.find(s => s.id === supplier);

  const SAMPLE_LINES = [
    {sku:"9319912445221", name:"Metformin XR 500mg", listCost:5.20, contractCost:4.20, savings:19, qty:30, moq:60, eff:"01/04/2026"},
    {sku:"9333091001284", name:"Atorvastatin 40mg", listCost:9.10, contractCost:8.10, savings:11, qty:30, moq:60, eff:"01/04/2026"},
    {sku:"9333091002145", name:"Sertraline 50mg", listCost:10.40, contractCost:9.20, savings:12, qty:30, moq:30, eff:"01/04/2026"},
    {sku:"9333091015223", name:"Esomeprazole 20mg", listCost:5.80, contractCost:5.00, savings:14, qty:30, moq:60, eff:"01/04/2026"},
    {sku:"9333091003121", name:"Amoxicillin 500mg", listCost:5.10, contractCost:4.30, savings:16, qty:20, moq:40, eff:"01/04/2026"},
    {sku:"9333091022774", name:"Insulin Glargine 100u/ml", listCost:21.40, contractCost:18.60, savings:13, qty:5, moq:10, eff:"01/04/2026"},
    {sku:"9325113022113", name:"Endone 5mg", listCost:7.90, contractCost:6.80, savings:14, qty:20, moq:20, eff:"01/04/2026"},
  ];

  return (
    <Screen eyebrow="Buying · contract pricing" title="Supplier price lists"
      actions={<>
        <button className="btn btn--secondary btn--sm"><OIcon name="transfer"/> Sync from supplier</button>
        <button className="btn btn--primary btn--sm"><OIcon name="plus"/> Upload price list</button>
      </>}>
      <div style={{display:'grid', gridTemplateColumns:'260px 1fr', gap:14}}>
        <div className="off-card" style={{padding:8}}>
          {supList.map(s => (
            <button key={s.id} onClick={() => setSupplier(s.id)} style={{
              textAlign:'left', padding:'10px 12px', border:'none', background: supplier === s.id ? 'var(--brand-bg)' : 'transparent',
              borderRadius:7, cursor:'pointer', fontFamily:'inherit', marginBottom:2, color: supplier === s.id ? 'var(--brand)' : 'var(--text)',
            }}>
              <div style={{fontWeight:500, fontSize:13}}>{s.name}</div>
              <div className="off-cell-mono off-muted" style={{fontSize:11, marginTop:2}}>{s.contract} · {s.lines.toLocaleString()} lines</div>
            </button>
          ))}
        </div>

        <div>
          <div className="off-card" style={{marginBottom:14, flexDirection:'row', alignItems:'center', gap:14, padding:'14px 18px'}}>
            <div style={{width:44, height:44, borderRadius:11, background:'var(--brand)', color:'var(--brand-fg)', display:'grid', placeItems:'center'}}><OIcon name="doc" width={20} height={20}/></div>
            <div style={{flex:1}}>
              <div style={{fontWeight:600, fontSize:16, letterSpacing:'-0.01em'}}>{current.name}</div>
              <div className="off-mono off-muted" style={{fontSize:12, marginTop:2}}>Contract {current.contract} · Valid to {current.validUntil} · {current.version} · Uploaded {current.uploaded}</div>
            </div>
            <StatusPill kind="paid" label="Active"/>
            <button className="btn btn--ghost btn--sm">History</button>
          </div>

          <div className="off-kpi-grid">
            <KpiCard label="Lines" value={current.lines.toLocaleString()}/>
            <KpiCard label="Avg savings vs list" value="13.4%" delta={{dir:"up", text:"Negotiated discount"}}/>
            <KpiCard label="Days until expiry" value="34" delta={{dir:"down", text:"Renegotiate before " + current.validUntil}}/>
            <KpiCard label="Out-of-contract SKUs" value="22" delta={{dir:"down", text:"Buying at list price"}}/>
          </div>

          <div className="off-table">
            <div className="off-grid" style={{gridTemplateColumns:'140px 1.4fr 90px 100px 80px 70px 70px 100px'}}>
              <div className="off-grid-headcell">SKU</div>
              <div className="off-grid-headcell">Product</div>
              <div className="off-grid-headcell" style={{justifyContent:'flex-end'}}>List cost</div>
              <div className="off-grid-headcell" style={{justifyContent:'flex-end'}}>Contract cost</div>
              <div className="off-grid-headcell" style={{justifyContent:'flex-end'}}>Savings</div>
              <div className="off-grid-headcell" style={{justifyContent:'flex-end'}}>Pack</div>
              <div className="off-grid-headcell" style={{justifyContent:'flex-end'}}>MOQ</div>
              <div className="off-grid-headcell">Effective</div>
              {SAMPLE_LINES.map(l => (
                <div key={l.sku} className="off-grid-row">
                  <div className="off-grid-cell off-cell-mono">{l.sku}</div>
                  <div className="off-grid-cell off-cell-strong">{l.name}</div>
                  <div className="off-grid-cell off-cell-num" style={{textDecoration:'line-through', color:'var(--text-subtle)'}}>{oMoney(l.listCost)}</div>
                  <div className="off-grid-cell off-cell-num off-cell-strong">{oMoney(l.contractCost)}</div>
                  <div className="off-grid-cell off-cell-num" style={{color:'var(--paid-text)', fontWeight:500}}>−{l.savings}%</div>
                  <div className="off-grid-cell off-cell-num">{l.qty}</div>
                  <div className="off-grid-cell off-cell-num">{l.moq}</div>
                  <div className="off-grid-cell off-cell-mono off-muted">{l.eff}</div>
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>
    </Screen>
  );
}

// =================================================================
// BUYING — Backorders
// =================================================================
function Backorders() {
  const BO = [
    {id:"BO-118", productId:"p008", supplier:"Sigma", store:"S-002", qty:24, original:"PO-4395", ordered:"10/05/2026", eta:"Tomorrow", reason:"Manufacturer shortage", status:"in-transit", waiting:18},
    {id:"BO-117", productId:"p012", supplier:"Sigma", store:"S-001", qty:10, original:"PO-4423", ordered:"Yesterday", eta:"05/06/2026", reason:"Cold-chain shipping delay", status:"delayed", waiting:1},
    {id:"BO-116", productId:"p005", supplier:"Sigma", store:"S-001", qty:40, original:"PO-4422", ordered:"Yesterday", eta:"Resolved", reason:"Short-shipped 2 units", status:"resolved", waiting:0},
    {id:"BO-115", productId:"p019", supplier:"NDSS", store:"S-001", qty:6, original:"PO-4408", ordered:"08/05/2026", eta:"31/05/2026", reason:"National sensor shortage", status:"delayed", waiting:14},
    {id:"BO-114", productId:"p001", supplier:"GSK", store:"S-003", qty:24, original:"PO-4412", ordered:"20/05/2026", eta:"Today 14:00", reason:"Direct shipment in flight", status:"in-transit", waiting:8},
    {id:"BO-113", productId:"p010", supplier:"Symbion", store:"S-002", qty:60, original:"PO-4395", ordered:"10/05/2026", eta:"Substituted", reason:"Generic substituted with Amoxil", status:"substituted", waiting:0},
  ];

  return (
    <Screen eyebrow="Buying · backorder management" title="Backorders"
      actions={<>
        <button className="btn btn--ghost btn--sm">Notify patients waiting</button>
        <button className="btn btn--primary btn--sm">Chase suppliers</button>
      </>}>
      <div className="off-kpi-grid">
        <KpiCard label="Active backorders" value={BO.filter(b => b.status === "in-transit" || b.status === "delayed").length} delta={{dir:"down", text:"Open with suppliers"}}/>
        <KpiCard label="Patients affected" value={BO.reduce((s, b) => s + b.waiting, 0)} delta={{dir:"down", text:"Waiting on scripts"}}/>
        <KpiCard label="Avg delay" value="8.2 days" delta={{text:"Past expected date"}}/>
        <KpiCard label="Resolved · 30d" value="42" delta={{dir:"up", text:"Cleared or substituted"}}/>
      </div>

      <div className="off-table">
        <div className="off-grid" style={{gridTemplateColumns:'90px 1.4fr 100px 90px 80px 1.2fr 110px 110px 110px'}}>
          <div className="off-grid-headcell">ID</div>
          <div className="off-grid-headcell">Product</div>
          <div className="off-grid-headcell">Supplier</div>
          <div className="off-grid-headcell">Store</div>
          <div className="off-grid-headcell" style={{justifyContent:'flex-end'}}>Qty</div>
          <div className="off-grid-headcell">Reason</div>
          <div className="off-grid-headcell">Expected</div>
          <div className="off-grid-headcell">Patients</div>
          <div className="off-grid-headcell">Status</div>
          {BO.map(b => {
            const p = findP(b.productId);
            return (
              <div key={b.id} className="off-grid-row">
                <div className="off-grid-cell off-cell-mono off-cell-strong">{b.id}</div>
                <div className="off-grid-cell off-cell-strong">{p?.name} <span className="off-muted" style={{fontWeight:400}}>· {p?.strength}</span></div>
                <div className="off-grid-cell">{b.supplier}</div>
                <div className="off-grid-cell off-mono">{findS(b.store)?.code}</div>
                <div className="off-grid-cell off-cell-num">{b.qty}</div>
                <div className="off-grid-cell off-muted">{b.reason}</div>
                <div className="off-grid-cell off-cell-mono">{b.eta}</div>
                <div className="off-grid-cell off-cell-num" style={{color: b.waiting > 5 ? 'var(--void-text)' : 'var(--text)'}}>
                  {b.waiting > 0 ? b.waiting + " waiting" : "—"}
                </div>
                <div className="off-grid-cell">
                  {b.status === "in-transit"  && <StatusPill kind="brand" label="In transit"/>}
                  {b.status === "delayed"     && <StatusPill kind="void" label="Delayed"/>}
                  {b.status === "resolved"    && <StatusPill kind="paid" label="Resolved"/>}
                  {b.status === "substituted" && <StatusPill kind="neutral" label="Substituted"/>}
                </div>
              </div>
            );
          })}
        </div>
      </div>
    </Screen>
  );
}

// =================================================================
// BUYING — Buying groups & formulary
// =================================================================
function BuyingGroups() {
  const [tab, setTab] = xUseState("groups");

  const GROUPS = [
    {id:"BG-PSA", name:"Pharmacy Guild · Buying Group", scope:"National", members:1240, spendQ:2940000, rebate:"2.4% quarterly", joinedOn:"2014", primary:true, contact:"buying@guild.org.au"},
    {id:"BG-CSO", name:"CSO · Community Service Obligation", scope:"Federal", members:"All approved pharmacies", spendQ:0, rebate:"Subsidised wholesale margin", joinedOn:"Mandatory", primary:false, contact:"—"},
    {id:"BG-IND", name:"Independent Pharmacy Co-op", scope:"Victoria", members:118, spendQ:184200, rebate:"1.8% biannual + volume", joinedOn:"2019", primary:false, contact:"co-op@indyphvic.au"},
  ];

  const FORMULARY = [
    {name:"Statins", drug:"Atorvastatin",  preferred:"Generic · Sigma",  approved:["Generic · Sigma","Lipitor · Pfizer","Generic · Apotex"], on:["S-001","S-002","S-003"]},
    {name:"PPIs",    drug:"Esomeprazole",  preferred:"Generic · Sandoz", approved:["Generic · Sandoz","Nexium · AstraZeneca","Generic · Apotex"], on:["S-001","S-002","S-003"]},
    {name:"SSRIs",   drug:"Sertraline",    preferred:"Generic · Mylan",  approved:["Generic · Mylan","Zoloft · Pfizer"], on:["S-001","S-002"]},
    {name:"Inhaled corticosteroids", drug:"Salbutamol", preferred:"Ventolin · GSK", approved:["Ventolin · GSK","Asmol · Alphapharm"], on:["S-001","S-002","S-003"]},
    {name:"Metformin", drug:"Metformin XR", preferred:"Generic · Sigma", approved:["Generic · Sigma","Diabex · Alphapharm","Glucophage · Merck"], on:["S-001","S-002","S-003"]},
  ];

  return (
    <Screen eyebrow="Buying · groups &amp; formulary" title="Buying groups &amp; formulary"
      activeTab={tab} onTab={setTab}
      subtabs={[{k:"groups", l:"Buying groups"}, {k:"formulary", l:"Formulary"}, {k:"approvedSuppliers", l:"Approved suppliers"}]}>
      {tab === "groups" && (
        <div style={{display:'flex', flexDirection:'column', gap:12}}>
          {GROUPS.map(g => (
            <div key={g.id} className="off-card" style={{padding:0, overflow:'hidden'}}>
              <div style={{padding:'14px 18px', borderBottom:'1px solid var(--border)', display:'flex', alignItems:'center', gap:12}}>
                <div style={{width:44, height:44, borderRadius:11, background: g.primary ? 'var(--brand)' : 'var(--navy-700)', color:'#fff', display:'grid', placeItems:'center'}}>
                  <OIcon name="users" width={20} height={20}/>
                </div>
                <div style={{flex:1}}>
                  <div style={{display:'flex', alignItems:'center', gap:8}}>
                    <span style={{fontWeight:600, fontSize:15}}>{g.name}</span>
                    {g.primary && <StatusPill kind="brand" label="Primary"/>}
                  </div>
                  <div className="off-cell-mono off-muted" style={{fontSize:12, marginTop:2}}>{g.scope} · Joined {g.joinedOn} · {typeof g.members === "number" ? g.members.toLocaleString() + " members" : g.members}</div>
                </div>
                <StatusPill kind="paid" label="Active"/>
              </div>
              <div style={{display:'grid', gridTemplateColumns:'repeat(3,1fr)'}}>
                <div style={{padding:'14px 18px', borderRight:'1px solid var(--border)'}}>
                  <div style={{fontSize:11, textTransform:'uppercase', letterSpacing:'0.06em', color:'var(--text-subtle)', fontWeight:500}}>Spend through group · Q</div>
                  <div style={{fontSize:22, fontWeight:600, marginTop:2, fontVariantNumeric:'tabular-nums'}}>{g.spendQ > 0 ? oMoney(g.spendQ) : "—"}</div>
                </div>
                <div style={{padding:'14px 18px', borderRight:'1px solid var(--border)'}}>
                  <div style={{fontSize:11, textTransform:'uppercase', letterSpacing:'0.06em', color:'var(--text-subtle)', fontWeight:500}}>Rebate / benefit</div>
                  <div style={{fontSize:14, fontWeight:500, marginTop:6}}>{g.rebate}</div>
                </div>
                <div style={{padding:'14px 18px'}}>
                  <div style={{fontSize:11, textTransform:'uppercase', letterSpacing:'0.06em', color:'var(--text-subtle)', fontWeight:500}}>Contact</div>
                  <div className="off-cell-mono" style={{fontSize:12, marginTop:6}}>{g.contact}</div>
                </div>
              </div>
            </div>
          ))}
        </div>
      )}
      {tab === "formulary" && (
        <div className="off-table">
          <div className="off-grid" style={{gridTemplateColumns:'1fr 1.2fr 1.4fr 1fr 130px'}}>
            <div className="off-grid-headcell">Class</div>
            <div className="off-grid-headcell">Drug</div>
            <div className="off-grid-headcell">Approved alternatives</div>
            <div className="off-grid-headcell">Preferred</div>
            <div className="off-grid-headcell">In stores</div>
            {FORMULARY.map(f => (
              <div key={f.name} className="off-grid-row">
                <div className="off-grid-cell off-cell-strong">{f.name}</div>
                <div className="off-grid-cell">{f.drug}</div>
                <div className="off-grid-cell off-muted">{f.approved.length} · {f.approved.slice(0,2).join("; ")}{f.approved.length > 2 ? "…" : ""}</div>
                <div className="off-grid-cell"><span className="badge badge--brand">{f.preferred}</span></div>
                <div className="off-grid-cell">{f.on.length === 3 ? "All" : f.on.map(id => findS(id)?.code).join(", ")}</div>
              </div>
            ))}
          </div>
        </div>
      )}
      {tab === "approvedSuppliers" && (
        <div className="off-table">
          <div className="off-grid" style={{gridTemplateColumns:'1.4fr 130px 130px 130px 110px 110px'}}>
            <div className="off-grid-headcell">Supplier</div>
            <div className="off-grid-headcell">Approved on</div>
            <div className="off-grid-headcell">Last audit</div>
            <div className="off-grid-headcell">TGA licence</div>
            <div className="off-grid-headcell">SKUs</div>
            <div className="off-grid-headcell">Status</div>
            {OD.SUPPLIERS.map(s => (
              <div key={s.id} className="off-grid-row">
                <div className="off-grid-cell off-cell-strong">{s.name}</div>
                <div className="off-grid-cell off-mono off-muted">2014</div>
                <div className="off-grid-cell off-mono off-muted">22/04/2026</div>
                <div className="off-grid-cell off-mono">VIC-{s.id.slice(-4)}</div>
                <div className="off-grid-cell off-cell-num">{OD.PRODUCTS.filter(p => p.supplier === s.id).length || "—"}</div>
                <div className="off-grid-cell"><StatusPill kind="paid" label="Approved"/></div>
              </div>
            ))}
          </div>
        </div>
      )}
    </Screen>
  );
}

// =================================================================
// BUYING — EDI status & message log
// =================================================================
function EDIStatus() {
  const FEEDS = [
    {id:"PharmX-Sigma",  partner:"Sigma",   channel:"PharmX",   status:"healthy", lastOk:"12s ago", msgs24:142, errors24:0,  cutoff:"16:00 daily"},
    {id:"PharmX-Symbion",partner:"Symbion", channel:"PharmX",   status:"healthy", lastOk:"24s ago", msgs24:118, errors24:1,  cutoff:"15:30 daily"},
    {id:"EDI-API",       partner:"API",     channel:"EDI X12",  status:"healthy", lastOk:"2m ago",  msgs24:42,  errors24:0,  cutoff:"Twice weekly"},
    {id:"EDI-NDSS",      partner:"NDSS",    channel:"EDI X12",  status:"warning", lastOk:"4h ago",  msgs24:8,   errors24:2,  cutoff:"Daily", warning:"Slow ack"},
    {id:"DHL-GSK",       partner:"GSK",     channel:"Direct API",status:"healthy",lastOk:"18m ago", msgs24:12,  errors24:0,  cutoff:"Order ahead"},
    {id:"DHL-CSL",       partner:"CSL",     channel:"Direct API",status:"healthy",lastOk:"3h ago",  msgs24:3,   errors24:0,  cutoff:"Seasonal"},
    {id:"PBS-Online",    partner:"Services AU",channel:"PBS Online",status:"healthy",lastOk:"4m ago",msgs24:248,errors24:1,  cutoff:"Realtime"},
  ];

  const RECENT = [
    {ts:"14:32:18", feed:"PharmX-Sigma", type:"855 PO Ack",      ref:"PO-4422", status:"ok"},
    {ts:"14:18:04", feed:"EDI-API",      type:"856 ASN",         ref:"PO-4424", status:"ok"},
    {ts:"13:48:22", feed:"PBS-Online",   type:"Claim submit",   ref:"Rx 894-221", status:"ok"},
    {ts:"13:42:10", feed:"PharmX-Symbion",type:"810 Invoice",   ref:"INV-SYM-2204", status:"ok"},
    {ts:"12:14:48", feed:"PharmX-Symbion",type:"850 PO submit",  ref:"PO-4430", status:"ok"},
    {ts:"11:48:18", feed:"PharmX-Sigma", type:"850 PO submit",  ref:"PO-4428", status:"ok"},
    {ts:"10:18:42", feed:"EDI-NDSS",     type:"855 PO Ack",      ref:"PO-4408", status:"warning", note:"Late ack · 4h after submit"},
    {ts:"09:14:08", feed:"PharmX-Sigma", type:"856 ASN",         ref:"PO-4422", status:"ok"},
    {ts:"08:42:22", feed:"EDI-NDSS",     type:"850 PO submit",   ref:"PO-4427", status:"error", note:"Schema validation · field 'lot' missing"},
    {ts:"08:30:14", feed:"PBS-Online",   type:"Handshake",       ref:"—", status:"ok"},
  ];

  return (
    <Screen eyebrow="Buying · integrations" title="EDI &amp; message log"
      actions={<>
        <button className="btn btn--secondary btn--sm"><OIcon name="transfer"/> Re-handshake</button>
        <button className="btn btn--ghost btn--sm">Download log</button>
      </>}>
      <div className="off-kpi-grid">
        <KpiCard label="Active feeds" value={FEEDS.length} delta={{dir:"up", text: FEEDS.filter(f => f.status === "healthy").length + " healthy"}}/>
        <KpiCard label="Messages · 24h" value={FEEDS.reduce((s, f) => s + f.msgs24, 0)} delta={{text:"PO + ASN + invoice + claims"}}/>
        <KpiCard label="Errors · 24h" value={FEEDS.reduce((s, f) => s + f.errors24, 0)} delta={{dir:"down", text:"Schema or ack issues"}}/>
        <KpiCard label="Warnings" value={FEEDS.filter(f => f.status === "warning").length} delta={{dir:"down", text:"Slow ack feeds"}}/>
      </div>

      <div className="off-card">
        <h3 className="off-card-title">Feeds</h3>
        <div className="off-grid" style={{gridTemplateColumns:'1.4fr 110px 130px 110px 80px 90px 110px'}}>
          <div className="off-grid-headcell">Feed</div>
          <div className="off-grid-headcell">Channel</div>
          <div className="off-grid-headcell">Last OK</div>
          <div className="off-grid-headcell">Cutoff</div>
          <div className="off-grid-headcell" style={{justifyContent:'flex-end'}}>Msgs 24h</div>
          <div className="off-grid-headcell" style={{justifyContent:'flex-end'}}>Errors</div>
          <div className="off-grid-headcell">Status</div>
          {FEEDS.map(f => (
            <div key={f.id} className="off-grid-row">
              <div className="off-grid-cell off-cell-strong">{f.partner}
                <div className="off-cell-mono off-muted" style={{marginTop:2, fontSize:11}}>{f.id}</div></div>
              <div className="off-grid-cell"><span className="badge badge--neutral">{f.channel}</span></div>
              <div className="off-grid-cell off-cell-mono off-muted">{f.lastOk}</div>
              <div className="off-grid-cell off-cell-mono off-muted">{f.cutoff}</div>
              <div className="off-grid-cell off-cell-num">{f.msgs24}</div>
              <div className="off-grid-cell off-cell-num" style={{color: f.errors24 > 0 ? 'var(--void-text)' : 'var(--text-muted)'}}>{f.errors24}</div>
              <div className="off-grid-cell">
                {f.status === "healthy" && <StatusPill kind="paid" label="Healthy"/>}
                {f.status === "warning" && <StatusPill kind="hold" label={f.warning || "Warning"}/>}
              </div>
            </div>
          ))}
        </div>
      </div>

      <div className="off-card" style={{marginTop:14}}>
        <h3 className="off-card-title">Recent messages</h3>
        <div className="off-grid" style={{gridTemplateColumns:'110px 1.4fr 1fr 1.2fr 110px'}}>
          <div className="off-grid-headcell">Timestamp</div>
          <div className="off-grid-headcell">Feed</div>
          <div className="off-grid-headcell">Type</div>
          <div className="off-grid-headcell">Reference / note</div>
          <div className="off-grid-headcell">Result</div>
          {RECENT.map((m, i) => (
            <div key={i} className="off-grid-row">
              <div className="off-grid-cell off-cell-mono off-muted">{m.ts}</div>
              <div className="off-grid-cell">{m.feed}</div>
              <div className="off-grid-cell off-muted">{m.type}</div>
              <div className="off-grid-cell off-cell-mono">
                {m.ref}
                {m.note && <div style={{fontSize:11, color: m.status === "error" ? 'var(--void-text)' : 'var(--hold-text)', marginTop:2}}>{m.note}</div>}
              </div>
              <div className="off-grid-cell">
                {m.status === "ok"      && <StatusPill kind="paid" label="ACK"/>}
                {m.status === "warning" && <StatusPill kind="hold" label="Slow"/>}
                {m.status === "error"   && <StatusPill kind="void" label="Error"/>}
              </div>
            </div>
          ))}
        </div>
      </div>
    </Screen>
  );
}

// =================================================================
// STAFF — profiles, schedules, performance, training
// =================================================================
function Staff() {
  const [tab, setTab] = xUseState("profiles");

  return (
    <Screen eyebrow="People &amp; roster" title="Staff"
      activeTab={tab} onTab={setTab}
      subtabs={[
        {k:"profiles", l:"Profiles"},
        {k:"roster", l:"Shift roster"},
        {k:"performance", l:"Performance"},
        {k:"training", l:"Training &amp; compliance"},
      ]}
      actions={<>
        <button className="btn btn--ghost btn--sm">Export</button>
        <button className="btn btn--primary btn--sm"><OIcon name="plus"/> Invite staff</button>
      </>}>
      {tab === "profiles" && <StaffProfiles/>}
      {tab === "roster" && <StaffRoster/>}
      {tab === "performance" && <StaffPerformance/>}
      {tab === "training" && <StaffTraining/>}
    </Screen>
  );
}

function StaffProfiles() {
  return (
    <div className="off-table">
      <div className="off-grid" style={{gridTemplateColumns:'40px 1.4fr 1.2fr 1fr 130px 100px 100px 110px'}}>
        <div className="off-grid-headcell"></div>
        <div className="off-grid-headcell">Name</div>
        <div className="off-grid-headcell">Email</div>
        <div className="off-grid-headcell">Role</div>
        <div className="off-grid-headcell">Stores</div>
        <div className="off-grid-headcell">AHPRA</div>
        <div className="off-grid-headcell">2FA</div>
        <div className="off-grid-headcell">Status</div>
        {OD.USERS.map(u => (
          <div key={u.id} className="off-grid-row">
            <div className="off-grid-cell"><div className="off-side-user-av" style={{width:28, height:28, background:'var(--brand)', color:'#fff'}}>{(u.first[0]+u.last[0]).toUpperCase()}</div></div>
            <div className="off-grid-cell off-cell-strong">{u.first} {u.last}</div>
            <div className="off-grid-cell off-cell-mono">{u.email}</div>
            <div className="off-grid-cell">{u.role}</div>
            <div className="off-grid-cell off-cell-mono">{u.stores[0] === "—" ? "Org-wide" : u.stores.map(id => findS(id)?.code).join(", ")}</div>
            <div className="off-grid-cell off-cell-mono">{u.role.toLowerCase().includes("pharmacist") ? "PHA0001" + u.id.slice(-3) : "—"}</div>
            <div className="off-grid-cell">{u.twoFA ? <StatusPill kind="paid" label="On"/> : <StatusPill kind="hold" label="Off"/>}</div>
            <div className="off-grid-cell">
              {u.status === "active"  && <StatusPill kind="paid" label="Active"/>}
              {u.status === "leave"   && <StatusPill kind="neutral" label="Leave"/>}
              {u.status === "pending" && <StatusPill kind="hold" label="Pending"/>}
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

function StaffRoster() {
  const DAYS = ["Mon 26", "Tue 27", "Wed 28", "Thu 29", "Fri 30", "Sat 31", "Sun 01"];
  const SHIFTS = [
    {staff:"SK", store:"S-001", day:0, start:"08:30", end:"17:00"},
    {staff:"RP", store:"S-001", day:0, start:"12:00", end:"19:00"},
    {staff:"JL", store:"S-003", day:0, start:"09:00", end:"18:00"},
    {staff:"PS", store:"S-002", day:0, start:"09:00", end:"15:00"},
    {staff:"SK", store:"S-001", day:1, start:"08:30", end:"17:00"},
    {staff:"DP", store:"S-001", day:1, start:"12:00", end:"19:00"},
    {staff:"RP", store:"S-002", day:1, start:"08:30", end:"17:00"},
    {staff:"JL", store:"S-003", day:1, start:"09:00", end:"18:00"},
    {staff:"SK", store:"S-001", day:2, start:"08:30", end:"17:00"},
    {staff:"RP", store:"S-002", day:2, start:"08:30", end:"15:00"},
    {staff:"JL", store:"S-003", day:2, start:"09:00", end:"18:00"},
    {staff:"DP", store:"S-001", day:2, start:"12:00", end:"19:00"},
    {staff:"SK", store:"S-001", day:3, start:"08:30", end:"17:00"},
    {staff:"RP", store:"S-001", day:3, start:"12:00", end:"19:00"},
    {staff:"JL", store:"S-003", day:3, start:"09:00", end:"18:00"},
    {staff:"PS", store:"S-002", day:3, start:"09:00", end:"15:00"},
    {staff:"SK", store:"S-001", day:4, start:"08:30", end:"17:00"},
    {staff:"DP", store:"S-001", day:4, start:"12:00", end:"19:00"},
    {staff:"RP", store:"S-002", day:4, start:"08:30", end:"19:00"},
    {staff:"JL", store:"S-003", day:4, start:"09:00", end:"18:00"},
    {staff:"DP", store:"S-001", day:5, start:"09:00", end:"17:00"},
    {staff:"JL", store:"S-003", day:5, start:"09:00", end:"15:00"},
    {staff:"PS", store:"S-002", day:6, start:"10:00", end:"14:00"},
    {staff:"JL", store:"S-003", day:6, start:"10:00", end:"15:00"},
  ];
  const STAFF = ["SK", "RP", "JL", "DP", "PS"];

  return (
    <div className="off-card" style={{padding:0, overflow:'hidden'}}>
      <div style={{padding:'14px 18px', borderBottom:'1px solid var(--border)', display:'flex', alignItems:'center', justifyContent:'space-between'}}>
        <div>
          <h3 className="off-card-title" style={{margin:0}}>Week of 26 May 2026</h3>
          <div className="off-cell-mono off-muted" style={{fontSize:12, marginTop:2}}>{SHIFTS.length} shifts · {SHIFTS.reduce((s, sh) => s + (parseInt(sh.end) - parseInt(sh.start)), 0)}h scheduled</div>
        </div>
        <div style={{display:'flex', gap:8}}>
          <button className="btn btn--ghost btn--sm">← Last week</button>
          <button className="btn btn--ghost btn--sm">Next week →</button>
          <button className="btn btn--primary btn--sm"><OIcon name="plus"/> Add shift</button>
        </div>
      </div>
      <div style={{display:'grid', gridTemplateColumns:`80px repeat(7, 1fr)`, borderBottom:'1px solid var(--border)'}}>
        <div style={{padding:'10px 12px', fontSize:11, textTransform:'uppercase', letterSpacing:'0.06em', color:'var(--text-subtle)', fontWeight:500, background:'var(--bg-subtle)', borderRight:'1px solid var(--border)'}}>Staff</div>
        {DAYS.map(d => <div key={d} style={{padding:'10px 12px', fontSize:12, fontWeight:500, background:'var(--bg-subtle)', borderRight:'1px solid var(--border)', textAlign:'center'}}>{d}</div>)}
      </div>
      {STAFF.map(initials => (
        <div key={initials} style={{display:'grid', gridTemplateColumns:`80px repeat(7, 1fr)`, borderBottom:'1px solid var(--border-subtle)'}}>
          <div style={{padding:'12px', display:'flex', alignItems:'center', gap:8, borderRight:'1px solid var(--border)', background:'var(--bg-subtle)'}}>
            <div className="off-side-user-av" style={{width:24, height:24, background:'var(--brand)', color:'#fff', fontSize:10}}>{initials}</div>
          </div>
          {DAYS.map((_, dayIdx) => {
            const shifts = SHIFTS.filter(s => s.staff === initials && s.day === dayIdx);
            return (
              <div key={dayIdx} style={{padding:'8px', borderRight:'1px solid var(--border-subtle)', minHeight:60, display:'flex', flexDirection:'column', gap:4}}>
                {shifts.map((sh, i) => (
                  <div key={i} style={{background:STX[sh.store] + "22", borderLeft:'3px solid '+STX[sh.store], padding:'4px 8px', borderRadius:4, fontSize:11}}>
                    <div style={{fontWeight:500, color:STX[sh.store]}}>{findS(sh.store)?.code}</div>
                    <div className="off-cell-mono off-muted" style={{fontSize:10}}>{sh.start}–{sh.end}</div>
                  </div>
                ))}
              </div>
            );
          })}
        </div>
      ))}
    </div>
  );
}

function StaffPerformance() {
  const PERF = [
    {init:"SK", role:"PIC",   sales30d:48420, scripts30d:184, basket:42.10, txTime:"1m 48s", refundRate:0.4, rxAccuracy:99.8},
    {init:"RP", role:"PIC",   sales30d:38240, scripts30d:148, basket:38.90, txTime:"2m 02s", refundRate:0.6, rxAccuracy:99.6},
    {init:"JL", role:"Pharm", sales30d:42180, scripts30d:162, basket:39.40, txTime:"1m 54s", refundRate:0.5, rxAccuracy:99.7},
    {init:"DP", role:"Pharm", sales30d:28140, scripts30d:118, basket:35.20, txTime:"2m 18s", refundRate:0.8, rxAccuracy:99.4},
    {init:"PS", role:"Asst.", sales30d:18420, scripts30d:0,   basket:24.80, txTime:"1m 32s", refundRate:0.4, rxAccuracy:null},
  ];

  return (
    <div className="off-table">
      <div className="off-grid" style={{gridTemplateColumns:'40px 1fr 110px 130px 130px 100px 110px 110px 100px'}}>
        <div className="off-grid-headcell"></div>
        <div className="off-grid-headcell">Staff</div>
        <div className="off-grid-headcell">Role</div>
        <div className="off-grid-headcell" style={{justifyContent:'flex-end'}}>Sales 30d</div>
        <div className="off-grid-headcell" style={{justifyContent:'flex-end'}}>Scripts 30d</div>
        <div className="off-grid-headcell" style={{justifyContent:'flex-end'}}>Avg basket</div>
        <div className="off-grid-headcell" style={{justifyContent:'flex-end'}}>Avg tx time</div>
        <div className="off-grid-headcell" style={{justifyContent:'flex-end'}}>Refund rate</div>
        <div className="off-grid-headcell" style={{justifyContent:'flex-end'}}>Rx accuracy</div>
        {PERF.map(p => (
          <div key={p.init} className="off-grid-row">
            <div className="off-grid-cell"><div className="off-side-user-av" style={{width:28, height:28, background:'var(--brand)', color:'#fff'}}>{p.init}</div></div>
            <div className="off-grid-cell off-cell-strong">{p.init}</div>
            <div className="off-grid-cell">{p.role}</div>
            <div className="off-grid-cell off-cell-num off-cell-strong">{oMoney(p.sales30d)}</div>
            <div className="off-grid-cell off-cell-num">{p.scripts30d || "—"}</div>
            <div className="off-grid-cell off-cell-num">{oMoney(p.basket)}</div>
            <div className="off-grid-cell off-cell-num off-mono">{p.txTime}</div>
            <div className="off-grid-cell off-cell-num" style={{color: p.refundRate < 0.5 ? 'var(--paid-text)' : p.refundRate > 0.7 ? 'var(--hold-text)' : 'var(--text)'}}>{p.refundRate.toFixed(1)}%</div>
            <div className="off-grid-cell off-cell-num off-cell-strong">{p.rxAccuracy !== null ? p.rxAccuracy.toFixed(1) + "%" : "—"}</div>
          </div>
        ))}
      </div>
    </div>
  );
}

function StaffTraining() {
  const REC = [
    {init:"SK", name:"Suni Kapoor", course:"AHPRA registration · renewal", status:"current", due:"30/09/2026", required:true},
    {init:"SK", name:"Suni Kapoor", course:"Vaccination training (level 4)", status:"current", due:"31/12/2026", required:true},
    {init:"SK", name:"Suni Kapoor", course:"S8 controlled drug handling", status:"current", due:"30/06/2027", required:true},
    {init:"RP", name:"Rachel Pham", course:"AHPRA registration · renewal", status:"current", due:"30/09/2026", required:true},
    {init:"RP", name:"Rachel Pham", course:"Vaccination training (level 4)", status:"due-soon", due:"22/06/2026", required:true},
    {init:"RP", name:"Rachel Pham", course:"MedsCheck accreditation", status:"current", due:"15/03/2027", required:true},
    {init:"JL", name:"James Liu",   course:"AHPRA registration · renewal", status:"current", due:"30/09/2026", required:true},
    {init:"JL", name:"James Liu",   course:"Naloxone training", status:"current", due:"01/08/2027", required:false},
    {init:"DP", name:"Daniel Park", course:"AHPRA registration · renewal", status:"overdue", due:"01/05/2026", required:true},
    {init:"DP", name:"Daniel Park", course:"Vaccination training (level 4)", status:"current", due:"31/12/2026", required:true},
    {init:"PS", name:"Priya Sharma",course:"Pharmacy assistant cert IV", status:"in-progress", due:"31/12/2026", required:true},
    {init:"PS", name:"Priya Sharma",course:"First aid", status:"current", due:"22/04/2027", required:true},
  ];

  return (
    <>
      <div className="off-kpi-grid">
        <KpiCard label="Compliance rate" value={Math.round(REC.filter(r => r.status === "current").length / REC.length * 100) + "%"} delta={{dir:"up", text:"Across required courses"}}/>
        <KpiCard label="Overdue" value={REC.filter(r => r.status === "overdue").length} delta={{dir:"down", text:"Action required"}}/>
        <KpiCard label="Due in 30 days" value={REC.filter(r => r.status === "due-soon").length} delta={{text:"Schedule renewal"}}/>
        <KpiCard label="In progress" value={REC.filter(r => r.status === "in-progress").length} delta={{text:"Currently studying"}}/>
      </div>
      <div className="off-table">
        <div className="off-grid" style={{gridTemplateColumns:'40px 1fr 1.6fr 110px 110px 100px'}}>
          <div className="off-grid-headcell"></div>
          <div className="off-grid-headcell">Staff</div>
          <div className="off-grid-headcell">Course / certification</div>
          <div className="off-grid-headcell">Required</div>
          <div className="off-grid-headcell">Due</div>
          <div className="off-grid-headcell">Status</div>
          {REC.map((r, i) => (
            <div key={i} className="off-grid-row">
              <div className="off-grid-cell"><div className="off-side-user-av" style={{width:24, height:24, background:'var(--brand)', color:'#fff', fontSize:10}}>{r.init}</div></div>
              <div className="off-grid-cell">{r.name}</div>
              <div className="off-grid-cell off-cell-strong">{r.course}</div>
              <div className="off-grid-cell">{r.required ? <StatusPill kind="brand" label="Required"/> : <span className="off-muted">Optional</span>}</div>
              <div className="off-grid-cell off-cell-mono off-muted">{r.due}</div>
              <div className="off-grid-cell">
                {r.status === "current"     && <StatusPill kind="paid" label="Current"/>}
                {r.status === "due-soon"    && <StatusPill kind="hold" label="Due soon"/>}
                {r.status === "overdue"     && <StatusPill kind="void" label="Overdue"/>}
                {r.status === "in-progress" && <StatusPill kind="brand" label="In progress"/>}
              </div>
            </div>
          ))}
        </div>
      </div>
    </>
  );
}

window.OFFICE_SCREENS = Object.assign(window.OFFICE_SCREENS || {}, {
  purchaseOrders: PurchaseOrders,
  priceLists: PriceLists,
  backorders: Backorders,
  buyingGroups: BuyingGroups,
  ediStatus: EDIStatus,
  staff: Staff,
});

// Export shared helpers for sibling Babel scripts
Object.assign(window, { Screen, StatusPill });
