/* =============================================================
   CoreIQ Office — Stores expansion
   Performance comparison · Stock requests · Regions · Procedures
   ============================================================= */
const { useState: stExtUseState, useMemo: stExtUseMemo } = React;

const STORE_COL = { "S-001": "var(--teal-700)", "S-002": "var(--navy-600)", "S-003": "var(--violet-600)" };

const ST_REGIONS = [
  { id: "rg-east",  name: "Eastern Metro",     manager: "Suni Kapoor",  stores: ["S-001","S-002"], color: "var(--teal-700)" },
  { id: "rg-outer", name: "Outer Eastern",     manager: "James Liu",    stores: ["S-003"],          color: "var(--violet-600)" },
  { id: "rg-north", name: "Northern (proposed)", manager: "—",         stores: [],                 color: "var(--text-subtle)" },
];

const ST_REQUESTS = [
  { id: "REQ-118", from: "S-002", to: "S-001", productId: "p008", qty: 24, reason: "Stock-out — patient waiting on script",  requestedBy: "Rachel Pham", ts: "Today 14:18", priority: "urgent",   status: "approved",  responseTs: "Today 14:22", responder: "Suni Kapoor" },
  { id: "REQ-117", from: "S-003", to: "S-001", productId: "p012", qty: 4,  reason: "Cold-chain Insulin Glargine low",        requestedBy: "James Liu",   ts: "Today 11:48", priority: "urgent",   status: "in-transit",responseTs: "Today 11:52", responder: "Suni Kapoor", linkedTransfer: "TR-2208" },
  { id: "REQ-116", from: "S-001", to: "S-003", productId: "p019", qty: 6,  reason: "CGM sensor stock-out — flagged patient", requestedBy: "Suni Kapoor", ts: "Today 10:14", priority: "high",     status: "approved",  responseTs: "Today 10:18", responder: "James Liu" },
  { id: "REQ-115", from: "S-002", to: "S-003", productId: "p014", qty: 12, reason: "Vitamin run-out · promo demand",          requestedBy: "Priya Sharma", ts: "Yesterday",   priority: "normal",   status: "fulfilled", responseTs: "Yesterday",  responder: "James Liu",  linkedTransfer: "TR-2205" },
  { id: "REQ-114", from: "S-001", to: "S-002", productId: "p016", qty: 24, reason: "Paracetamol low",                         requestedBy: "Rachel Pham", ts: "20/05/2026",  priority: "normal",   status: "declined",  responseTs: "20/05/2026", responder: "Rachel Pham", declineReason: "Glen Iris stock also low — ordered fresh PO instead" },
  { id: "REQ-113", from: "S-003", to: "S-001", productId: "p002", qty: 30, reason: "Metformin spike post-clinic referral",    requestedBy: "James Liu",   ts: "19/05/2026",  priority: "high",     status: "fulfilled", responseTs: "19/05/2026", responder: "Suni Kapoor", linkedTransfer: "TR-2199" },
  { id: "REQ-112", from: "S-002", to: "S-001", productId: "p025", qty: 6,  reason: "Probiotic — local promo demand",          requestedBy: "Priya Sharma", ts: "18/05/2026",  priority: "normal",   status: "fulfilled", responseTs: "18/05/2026", responder: "Suni Kapoor" },
];

const ST_CHECKLIST_OPEN = [
  { id: "o1", task: "Unlock storefront and disable alarm", category: "Security", time: "08:25" },
  { id: "o2", task: "Count opening cash float ($200) — two-person sign-off", category: "Cash", time: "08:30" },
  { id: "o3", task: "Open S8 safe and verify register count", category: "S8", time: "08:32" },
  { id: "o4", task: "Power up registers, scanners, label printers", category: "Hardware", time: "08:35" },
  { id: "o5", task: "Test Eftpos terminal (Tyro/Adyen) with $0 ping", category: "Hardware", time: "08:38" },
  { id: "o6", task: "Check cold-chain fridge temperatures (2–8°C)", category: "Compliance", time: "08:40" },
  { id: "o7", task: "Review overnight scripts (eScript queue)", category: "Dispensary", time: "08:42" },
  { id: "o8", task: "Restock front-counter promo items", category: "Merchandising", time: "08:45" },
  { id: "o9", task: "Brief team on today's pickups, counsel due, flags", category: "Team", time: "08:50" },
  { id: "o10", task: "Unlock doors to public · note opening time", category: "Security", time: "08:30" },
];

const ST_CHECKLIST_CLOSE = [
  { id: "c1", task: "Lock doors to public · finalise queue", category: "Security", time: "19:00" },
  { id: "c2", task: "Close active sales, void held sales", category: "POS", time: "19:02" },
  { id: "c3", task: "Run End-of-day · reconcile registers", category: "Cash", time: "19:05" },
  { id: "c4", task: "Count cash, lodge tomorrow's float, drop excess to safe", category: "Cash", time: "19:15" },
  { id: "c5", task: "S8 register countersign — two pharmacists", category: "S8", time: "19:20" },
  { id: "c6", task: "Lock S8 safe", category: "S8", time: "19:22" },
  { id: "c7", task: "Confirm cold-chain temperatures logged", category: "Compliance", time: "19:25" },
  { id: "c8", task: "Submit PBS Online Claiming batch", category: "Compliance", time: "19:30" },
  { id: "c9", task: "Power down non-essential equipment", category: "Hardware", time: "19:35" },
  { id: "c10", task: "Set alarm, lock storefront", category: "Security", time: "19:40" },
];

// =================================================================
// STORES — expanded landing
// =================================================================
function StoresExpanded() {
  const { setScreen, setScreenState, pushToast } = window.useOffice();
  const [tab, setTab] = stExtUseState("compare");

  return (
    <div className="off-screen">
      <header className="off-screen-header">
        <div className="off-screen-header-meta">
          <span className="off-screen-eyebrow">Head-office function</span>
          <h2 className="off-screen-title">Stores</h2>
        </div>
        <div className="off-screen-actions">
          <button className="btn btn--ghost btn--sm">Export</button>
          <button className="btn btn--primary btn--sm"><OIcon name="plus"/> Add store</button>
        </div>
      </header>

      <div className="off-subtabs">
        <button className={"off-subtab" + (tab === "list" ? " off-subtab--active" : "")} onClick={() => setTab("list")}>All stores</button>
        <button className={"off-subtab" + (tab === "compare" ? " off-subtab--active" : "")} onClick={() => setTab("compare")}>Performance comparison</button>
        <button className={"off-subtab" + (tab === "regions" ? " off-subtab--active" : "")} onClick={() => setTab("regions")}>Regions &amp; groups</button>
        <button className={"off-subtab" + (tab === "requests" ? " off-subtab--active" : "")} onClick={() => setTab("requests")}>
          Stock requests
          <span style={{marginLeft:6, fontSize:10, background:'var(--hold)', color:'var(--hold-fg)', padding:'1px 6px', borderRadius:99, fontWeight:600}}>
            {ST_REQUESTS.filter(r => r.status === "approved" || r.status === "in-transit").length}
          </span>
        </button>
        <button className={"off-subtab" + (tab === "procedures" ? " off-subtab--active" : "")} onClick={() => setTab("procedures")}>Procedures</button>
      </div>

      <div className="off-screen-body">
        {tab === "list" && <StoresListInline/>}
        {tab === "compare" && <PerformanceComparison/>}
        {tab === "regions" && <Regions/>}
        {tab === "requests" && <StockRequests/>}
        {tab === "procedures" && <Procedures/>}
      </div>
    </div>
  );
}

function StoresListInline() {
  const { setScreen, setScreenState } = window.useOffice();
  return (
    <div className="off-table">
      <div className="off-grid" style={{gridTemplateColumns:'80px 1.4fr 1fr 130px 110px 130px 130px 130px 80px'}}>
        <div className="off-grid-headcell">Code</div>
        <div className="off-grid-headcell">Store</div>
        <div className="off-grid-headcell">Manager</div>
        <div className="off-grid-headcell" style={{justifyContent:'flex-end'}}>Registers</div>
        <div className="off-grid-headcell" style={{justifyContent:'flex-end'}}>Patients</div>
        <div className="off-grid-headcell" style={{justifyContent:'flex-end'}}>Today</div>
        <div className="off-grid-headcell" style={{justifyContent:'flex-end'}}>MTD</div>
        <div className="off-grid-headcell" style={{justifyContent:'flex-end'}}>Stock value</div>
        <div className="off-grid-headcell">Open</div>
        {OD.STORES.map(s => (
          <div key={s.id} className="off-grid-row">
            <div className="off-grid-cell"><div className="off-topbar-store-av" style={{width:28, height:28, borderRadius:6, background:STORE_COL[s.id], color:'#fff'}}>{s.code}</div></div>
            <div className="off-grid-cell off-cell-strong">
              {s.name}
              <div className="off-cell-mono off-muted" style={{marginTop:2, fontSize:11}}>{s.address}</div>
            </div>
            <div className="off-grid-cell">{s.manager}</div>
            <div className="off-grid-cell off-cell-num">{s.registers}</div>
            <div className="off-grid-cell off-cell-num">{s.patients.toLocaleString()}</div>
            <div className="off-grid-cell off-cell-num">{oMoney(s.takings.today)}</div>
            <div className="off-grid-cell off-cell-num">{oMoney(s.takings.mtd)}</div>
            <div className="off-grid-cell off-cell-num">{oMoney(s.stockValue)}</div>
            <div className="off-grid-cell">
              <button className="btn btn--ghost btn--sm" onClick={() => { setScreenState({ activeStoreId: s.id }); setScreen("storeDetail"); }}>Open</button>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

// =================================================================
// PERFORMANCE COMPARISON
// =================================================================
function PerformanceComparison() {
  const [period, setPeriod] = stExtUseState("mtd");
  const [metric, setMetric] = stExtUseState("revenue");

  const METRICS = [
    { id: "revenue",      label: "Revenue",         val: s => s.takings[period === "today" ? "today" : period === "ytd" ? "ytd" : "mtd"],   fmt: v => oMoney(v) },
    { id: "scripts",      label: "Scripts dispensed", val: s => s.scripts[period === "today" ? "today" : period === "ytd" ? "ytd" : "mtd"], fmt: v => v.toLocaleString() },
    { id: "patients",     label: "Patient base",    val: s => s.patients,    fmt: v => v.toLocaleString() },
    { id: "stockValue",   label: "Stock value",     val: s => s.stockValue,  fmt: v => oMoney(v) },
    { id: "perRegister",  label: "Revenue per register", val: s => s.takings.mtd / s.registers, fmt: v => oMoney(v) },
    { id: "perPatient",   label: "Revenue per patient",  val: s => s.takings.mtd / s.patients,  fmt: v => oMoney(v) },
  ];

  // Per-metric rows with bar visualisation
  const rows = METRICS.map(m => ({
    metric: m,
    values: OD.STORES.map(s => ({ store: s, value: m.val(s) })),
  }));

  return (
    <>
      <div style={{display:'flex', gap:8, marginBottom:14, flexWrap:'wrap'}}>
        <div style={{fontSize:11, textTransform:'uppercase', letterSpacing:'0.06em', color:'var(--text-subtle)', fontWeight:500, alignSelf:'center', marginRight:4}}>Period</div>
        {[["today","Today"],["mtd","Month to date"],["ytd","Year to date"]].map(([k, label]) => (
          <button key={k} className={"off-filter" + (period === k ? " off-filter--active" : "")} onClick={() => setPeriod(k)}>{label}</button>
        ))}
      </div>

      {/* Hero metric: revenue */}
      <div className="off-card">
        <div className="off-card-header">
          <h3 className="off-card-title">Revenue · {period === "today" ? "today" : period === "ytd" ? "YTD" : "MTD"}</h3>
          <button className="btn btn--ghost btn--sm">Export</button>
        </div>
        <div className="dash-chart" style={{height:160}}>
          {OD.REVENUE_30D["S-001"].map((_, i) => (
            <div key={i} style={{flex:1, display:'flex', gap:1, alignItems:'flex-end'}}>
              {OD.STORES.map(s => {
                const v = OD.REVENUE_30D[s.id][i];
                const max = 6500;
                return <div key={s.id} style={{flex:1, background:STORE_COL[s.id], height:(v/max*100)+'%', borderRadius:'2px 2px 0 0', opacity: i === 29 ? 1 : 0.92}}/>;
              })}
            </div>
          ))}
        </div>
        <div className="dash-chart-legend">
          {OD.STORES.map(s => (
            <span key={s.id}>
              <span className="dash-chart-legend-dot" style={{background:STORE_COL[s.id]}}/>
              {s.name} · {oMoney(s.takings[period === "today" ? "today" : period === "ytd" ? "ytd" : "mtd"])}
            </span>
          ))}
        </div>
      </div>

      {/* Multi-metric comparison */}
      <div className="off-card" style={{marginTop:14}}>
        <div className="off-card-header">
          <h3 className="off-card-title">Side-by-side · {period === "today" ? "today" : period === "ytd" ? "YTD" : "MTD"}</h3>
        </div>
        <div style={{display:'flex', flexDirection:'column', gap:0}}>
          {rows.map((row, i) => {
            const max = Math.max(...row.values.map(v => v.value));
            const leader = row.values.find(v => v.value === max);
            return (
              <div key={row.metric.id} style={{display:'grid', gridTemplateColumns:'200px 1fr 90px', gap:14, padding:'14px 0', borderBottom: i < rows.length - 1 ? '1px solid var(--border-subtle)' : 'none', alignItems:'center'}}>
                <div>
                  <div style={{fontWeight:500, fontSize:13}}>{row.metric.label}</div>
                  <div className="off-cell-mono off-muted" style={{fontSize:11, marginTop:2}}>Leader · {leader.store.name}</div>
                </div>
                <div style={{display:'grid', gridTemplateColumns:'repeat(3, 1fr)', gap:14}}>
                  {row.values.map(v => {
                    const pct = max > 0 ? (v.value / max) * 100 : 0;
                    return (
                      <div key={v.store.id}>
                        <div style={{display:'flex', alignItems:'center', gap:6, marginBottom:4}}>
                          <div style={{width:14, height:14, borderRadius:3, background:STORE_COL[v.store.id]}}/>
                          <span style={{fontSize:11, color:'var(--text-muted)', flex:1}}>{v.store.code}</span>
                          <span className="off-cell-num" style={{fontWeight:500, fontSize:13}}>{row.metric.fmt(v.value)}</span>
                        </div>
                        <div style={{height:6, background:'var(--bg-muted)', borderRadius:3, overflow:'hidden'}}>
                          <div style={{height:'100%', width: pct + '%', background: STORE_COL[v.store.id]}}/>
                        </div>
                      </div>
                    );
                  })}
                </div>
                <div className="off-cell-num off-cell-strong" style={{textAlign:'right'}}>
                  {row.metric.fmt(row.values.reduce((s, v) => s + v.value, 0))}
                  <div className="off-cell-mono off-muted" style={{fontSize:10, marginTop:2}}>Group</div>
                </div>
              </div>
            );
          })}
        </div>
      </div>

      {/* Index vs group average */}
      <div className="off-card" style={{marginTop:14}}>
        <div className="off-card-header">
          <h3 className="off-card-title">Index vs group average</h3>
          <span className="off-mono off-muted" style={{fontSize:12}}>100 = group avg</span>
        </div>
        <div className="off-grid" style={{gridTemplateColumns:'1.4fr 130px 130px 130px 130px'}}>
          <div className="off-grid-headcell">Store</div>
          <div className="off-grid-headcell" style={{justifyContent:'flex-end'}}>Revenue idx</div>
          <div className="off-grid-headcell" style={{justifyContent:'flex-end'}}>Scripts idx</div>
          <div className="off-grid-headcell" style={{justifyContent:'flex-end'}}>$/patient idx</div>
          <div className="off-grid-headcell" style={{justifyContent:'flex-end'}}>$/register idx</div>
          {OD.STORES.map(s => {
            const avgRev = OD.STORES.reduce((sum, x) => sum + x.takings.mtd, 0) / OD.STORES.length;
            const avgScr = OD.STORES.reduce((sum, x) => sum + x.scripts.mtd, 0) / OD.STORES.length;
            const avgPp  = OD.STORES.reduce((sum, x) => sum + x.takings.mtd / x.patients, 0) / OD.STORES.length;
            const avgPr  = OD.STORES.reduce((sum, x) => sum + x.takings.mtd / x.registers, 0) / OD.STORES.length;
            const idx = (val, avg) => Math.round((val / avg) * 100);
            const cell = (v) => ({color: v >= 110 ? 'var(--paid-text)' : v <= 90 ? 'var(--void-text)' : 'var(--text)'});
            return (
              <div key={s.id} className="off-grid-row">
                <div className="off-grid-cell">
                  <div style={{display:'flex', alignItems:'center', gap:10}}>
                    <div className="off-topbar-store-av" style={{width:24, height:24, borderRadius:5, background:STORE_COL[s.id], color:'#fff', fontSize:9}}>{s.code}</div>
                    <span className="off-cell-strong">{s.name}</span>
                  </div>
                </div>
                <div className="off-grid-cell off-cell-num off-cell-strong" style={cell(idx(s.takings.mtd, avgRev))}>{idx(s.takings.mtd, avgRev)}</div>
                <div className="off-grid-cell off-cell-num off-cell-strong" style={cell(idx(s.scripts.mtd, avgScr))}>{idx(s.scripts.mtd, avgScr)}</div>
                <div className="off-grid-cell off-cell-num off-cell-strong" style={cell(idx(s.takings.mtd / s.patients, avgPp))}>{idx(s.takings.mtd / s.patients, avgPp)}</div>
                <div className="off-grid-cell off-cell-num off-cell-strong" style={cell(idx(s.takings.mtd / s.registers, avgPr))}>{idx(s.takings.mtd / s.registers, avgPr)}</div>
              </div>
            );
          })}
        </div>
      </div>
    </>
  );
}

// =================================================================
// REGIONS
// =================================================================
function Regions() {
  const { pushToast } = window.useOffice();

  return (
    <>
      <div className="off-card" style={{marginBottom:14, flexDirection:'row', alignItems:'center', gap:14, padding:'14px 18px'}}>
        <OIcon name="info" style={{color:'var(--brand)'}}/>
        <div style={{flex:1, fontSize:13, color:'var(--text-muted)'}}>
          Group stores into regions to scope reports, manager access, and bulk operations. Useful as the network grows past a handful of stores.
        </div>
        <button className="btn btn--primary btn--sm" onClick={() => pushToast({kind:'paid', icon:'plus', title:'New region', meta:'Wizard would open here'})}>
          <OIcon name="plus"/> New region
        </button>
      </div>

      <div style={{display:'flex', flexDirection:'column', gap:12}}>
        {ST_REGIONS.map(r => {
          const stores = r.stores.map(id => OD.STORES.find(s => s.id === id)).filter(Boolean);
          const rev = stores.reduce((s, x) => s + x.takings.mtd, 0);
          const scripts = stores.reduce((s, x) => s + x.scripts.mtd, 0);
          const patients = stores.reduce((s, x) => s + x.patients, 0);
          return (
            <div key={r.id} className="off-card" style={{padding:0, overflow:'hidden'}}>
              <div style={{padding:'16px 20px', borderBottom:'1px solid var(--border)', display:'flex', alignItems:'center', gap:14}}>
                <div style={{width:44, height:44, borderRadius:11, background:r.color, color:'#fff', display:'grid', placeItems:'center'}}>
                  <OIcon name="store" width={20} height={20}/>
                </div>
                <div style={{flex:1}}>
                  <div style={{display:'flex', alignItems:'center', gap:10}}>
                    <div style={{fontSize:16, fontWeight:600, letterSpacing:'-0.01em'}}>{r.name}</div>
                    {stores.length === 0
                      ? <span className="badge badge--neutral">Empty</span>
                      : <span className="badge badge--paid"><span className="badge-dot"/> {stores.length} {stores.length === 1 ? "store" : "stores"}</span>}
                  </div>
                  <div className="off-cell-mono off-muted" style={{fontSize:12, marginTop:2}}>Manager · {r.manager}</div>
                </div>
                <button className="btn btn--ghost btn--sm">Edit</button>
              </div>

              {stores.length > 0 ? (
                <>
                  <div style={{display:'grid', gridTemplateColumns:'repeat(3, 1fr)'}}>
                    <div style={{padding:'14px 20px', borderRight:'1px solid var(--border)', borderBottom:'1px solid var(--border)'}}>
                      <div style={{fontSize:11, textTransform:'uppercase', letterSpacing:'0.06em', color:'var(--text-subtle)', fontWeight:500}}>Revenue MTD</div>
                      <div style={{fontSize:22, fontWeight:600, fontVariantNumeric:'tabular-nums', letterSpacing:'-0.015em', marginTop:2}}>{oMoney(rev)}</div>
                    </div>
                    <div style={{padding:'14px 20px', borderRight:'1px solid var(--border)', borderBottom:'1px solid var(--border)'}}>
                      <div style={{fontSize:11, textTransform:'uppercase', letterSpacing:'0.06em', color:'var(--text-subtle)', fontWeight:500}}>Scripts MTD</div>
                      <div style={{fontSize:22, fontWeight:600, fontVariantNumeric:'tabular-nums', letterSpacing:'-0.015em', marginTop:2}}>{scripts.toLocaleString()}</div>
                    </div>
                    <div style={{padding:'14px 20px', borderBottom:'1px solid var(--border)'}}>
                      <div style={{fontSize:11, textTransform:'uppercase', letterSpacing:'0.06em', color:'var(--text-subtle)', fontWeight:500}}>Patient base</div>
                      <div style={{fontSize:22, fontWeight:600, fontVariantNumeric:'tabular-nums', letterSpacing:'-0.015em', marginTop:2}}>{patients.toLocaleString()}</div>
                    </div>
                  </div>
                  <div style={{padding:'12px 20px', background:'var(--bg-subtle)', display:'flex', gap:8, flexWrap:'wrap', alignItems:'center'}}>
                    <span style={{fontSize:11, textTransform:'uppercase', letterSpacing:'0.06em', color:'var(--text-subtle)', fontWeight:500, marginRight:4}}>Stores</span>
                    {stores.map(s => (
                      <span key={s.id} className="badge" style={{background:STORE_COL[s.id] + "22", color:STORE_COL[s.id], borderColor:STORE_COL[s.id] + "44"}}>
                        {s.code} · {s.name}
                      </span>
                    ))}
                  </div>
                </>
              ) : (
                <div style={{padding:'18px 20px', display:'flex', alignItems:'center', gap:10, fontSize:13, color:'var(--text-muted)'}}>
                  <OIcon name="plus" style={{color:'var(--text-subtle)'}}/>
                  <span>No stores assigned yet — drag a store here, or assign from the store detail.</span>
                </div>
              )}
            </div>
          );
        })}
      </div>
    </>
  );
}

// =================================================================
// STOCK REQUESTS
// =================================================================
function StockRequests() {
  const { pushToast } = window.useOffice();
  const [filter, setFilter] = stExtUseState("active");
  const [creating, setCreating] = stExtUseState(false);

  const FILTERS = [
    { key: "active",   label: "Active",    pred: r => ["approved","in-transit","pending"].includes(r.status) },
    { key: "pending",  label: "Awaiting response", pred: r => r.status === "pending" },
    { key: "fulfilled", label: "Fulfilled", pred: r => r.status === "fulfilled" },
    { key: "declined", label: "Declined",  pred: r => r.status === "declined" },
    { key: "all",      label: "All",       pred: () => true },
  ];

  const list = ST_REQUESTS.filter(FILTERS.find(f => f.key === filter).pred);

  return (
    <>
      <div className="off-card" style={{marginBottom:14, flexDirection:'row', alignItems:'center', gap:14, padding:'14px 18px'}}>
        <OIcon name="info" style={{color:'var(--brand)'}}/>
        <div style={{flex:1, fontSize:13, color:'var(--text-muted)'}}>
          Stock requests are how a store asks another for stock — they need approval from the source store before becoming a transfer.
          Use these for unplanned needs (stock-out, patient waiting). For routine movements, create a transfer directly.
        </div>
        <button className="btn btn--primary btn--sm" onClick={() => setCreating(true)}>
          <OIcon name="plus"/> New request
        </button>
      </div>

      <div className="off-kpi-grid">
        <KpiCard label="Active requests"   value={ST_REQUESTS.filter(r => ["approved","in-transit","pending"].includes(r.status)).length} delta={{dir:"up", text:"Awaiting fulfillment"}}/>
        <KpiCard label="Avg response time" value="4m 18s" delta={{text:"Across last 30 requests"}}/>
        <KpiCard label="Fulfillment rate"  value="86%" delta={{text:"Approved & delivered"}}/>
        <KpiCard label="Urgent · today"    value={ST_REQUESTS.filter(r => r.priority === "urgent" && r.ts.includes("Today")).length} delta={{dir:"down", text:"Inter-store stock-outs"}}/>
      </div>

      <div className="off-table">
        <div className="off-table-toolbar">
          <div className="off-filters">
            {FILTERS.map(f => {
              const c = ST_REQUESTS.filter(f.pred).length;
              return (
                <button key={f.key} className={"off-filter" + (filter === f.key ? " off-filter--active" : "")} onClick={() => setFilter(f.key)}>
                  {f.label} <span className="off-filter-count">{c}</span>
                </button>
              );
            })}
          </div>
        </div>
        <div className="off-grid" style={{gridTemplateColumns:'100px 110px 110px 1.4fr 70px 110px 130px 130px 110px'}}>
          <div className="off-grid-headcell">ID</div>
          <div className="off-grid-headcell">From</div>
          <div className="off-grid-headcell">To</div>
          <div className="off-grid-headcell">Product · reason</div>
          <div className="off-grid-headcell" style={{justifyContent:'flex-end'}}>Qty</div>
          <div className="off-grid-headcell">Priority</div>
          <div className="off-grid-headcell">Requested</div>
          <div className="off-grid-headcell">Response</div>
          <div className="off-grid-headcell">Status</div>
          {list.map(r => {
            const product = findP(r.productId);
            const from = findS(r.from);
            const to = findS(r.to);
            return (
              <div key={r.id} className="off-grid-row">
                <div className="off-grid-cell off-cell-mono off-cell-strong">{r.id}</div>
                <div className="off-grid-cell">
                  <span className="badge" style={{background:STORE_COL[r.from] + "22", color:STORE_COL[r.from], borderColor:STORE_COL[r.from] + "44"}}>{from?.code}</span>
                </div>
                <div className="off-grid-cell">
                  <span className="badge" style={{background:STORE_COL[r.to] + "22", color:STORE_COL[r.to], borderColor:STORE_COL[r.to] + "44"}}>{to?.code}</span>
                </div>
                <div className="off-grid-cell">
                  <div className="off-cell-strong">{product?.name} <span className="off-muted" style={{fontWeight:400}}>· {product?.strength}</span></div>
                  <div className="off-cell-mono off-muted" style={{fontSize:11, marginTop:2}}>{r.reason}</div>
                  {r.declineReason && <div className="off-muted" style={{fontSize:11, marginTop:2, color:'var(--void-text)'}}>Declined · {r.declineReason}</div>}
                  {r.linkedTransfer && <div className="off-muted" style={{fontSize:11, marginTop:2}}>Linked to transfer <strong>{r.linkedTransfer}</strong></div>}
                </div>
                <div className="off-grid-cell off-cell-num off-cell-strong">{r.qty}</div>
                <div className="off-grid-cell">
                  {r.priority === "urgent" && <span className="badge badge--void"><span className="badge-dot"/> Urgent</span>}
                  {r.priority === "high"   && <span className="badge badge--hold"><span className="badge-dot"/> High</span>}
                  {r.priority === "normal" && <span className="badge badge--neutral"><span className="badge-dot"/> Normal</span>}
                </div>
                <div className="off-grid-cell off-cell-mono off-muted" style={{fontSize:11}}>
                  {r.ts}<br/>
                  <span style={{color:'var(--text)'}}>{r.requestedBy}</span>
                </div>
                <div className="off-grid-cell off-cell-mono off-muted" style={{fontSize:11}}>
                  {r.responseTs}<br/>
                  <span style={{color:'var(--text)'}}>{r.responder}</span>
                </div>
                <div className="off-grid-cell">
                  {r.status === "pending"    && <span className="badge badge--hold"><span className="badge-dot"/> Awaiting</span>}
                  {r.status === "approved"   && <span className="badge badge--brand"><span className="badge-dot"/> Approved</span>}
                  {r.status === "in-transit" && <span className="badge badge--brand"><span className="badge-dot"/> In transit</span>}
                  {r.status === "fulfilled"  && <span className="badge badge--paid"><span className="badge-dot"/> Fulfilled</span>}
                  {r.status === "declined"   && <span className="badge badge--void"><span className="badge-dot"/> Declined</span>}
                </div>
              </div>
            );
          })}
        </div>
      </div>

      {creating && <StockRequestModal onClose={() => setCreating(false)} onSubmit={() => { setCreating(false); pushToast({kind:'paid', icon:'check-circle', title:'Stock request sent', meta:'Source store will respond'}); }}/>}
    </>
  );
}

function StockRequestModal({ onClose, onSubmit }) {
  const [from, setFrom] = stExtUseState("S-001");
  const [to, setTo] = stExtUseState("S-002");
  const [productId, setProductId] = stExtUseState("p008");
  const [qty, setQty] = stExtUseState(12);
  const [priority, setPriority] = stExtUseState("normal");
  const [reason, setReason] = stExtUseState("");

  return (
    <div className="app-overlay" onClick={onClose}>
      <div className="app-overlay-card" style={{width:600}} onClick={e => e.stopPropagation()}>
        <div className="app-overlay-head">
          <h3>Request stock from another store</h3>
          <button className="off-topbar-btn" onClick={onClose} style={{marginLeft:'auto', border:'none'}}><OIcon name="x"/></button>
        </div>
        <div style={{padding:'18px 22px', display:'flex', flexDirection:'column', gap:14}}>
          <div style={{display:'grid', gridTemplateColumns:'1fr auto 1fr', gap:10, alignItems:'flex-end'}}>
            <div className="field">
              <label className="field-label">Request from</label>
              <select className="input select" value={from} onChange={e => setFrom(e.target.value)}>
                {OD.STORES.map(s => <option key={s.id} value={s.id}>{s.name}</option>)}
              </select>
            </div>
            <div style={{marginBottom:8, padding:'8px 10px', color:'var(--text-subtle)'}}>→</div>
            <div className="field">
              <label className="field-label">Deliver to</label>
              <select className="input select" value={to} onChange={e => setTo(e.target.value)}>
                {OD.STORES.filter(s => s.id !== from).map(s => <option key={s.id} value={s.id}>{s.name}</option>)}
              </select>
            </div>
          </div>

          <div style={{display:'grid', gridTemplateColumns:'1.4fr 100px 130px', gap:10}}>
            <div className="field">
              <label className="field-label">Product</label>
              <select className="input select" value={productId} onChange={e => setProductId(e.target.value)}>
                {OD.PRODUCTS.map(p => <option key={p.id} value={p.id}>{p.name} · {p.strength}</option>)}
              </select>
            </div>
            <div className="field">
              <label className="field-label">Quantity</label>
              <input className="input tabular" type="number" value={qty} onChange={e => setQty(parseInt(e.target.value) || 0)}/>
            </div>
            <div className="field">
              <label className="field-label">Priority</label>
              <select className="input select" value={priority} onChange={e => setPriority(e.target.value)}>
                <option value="normal">Normal</option>
                <option value="high">High</option>
                <option value="urgent">Urgent · patient waiting</option>
              </select>
            </div>
          </div>

          <div className="field">
            <label className="field-label">Reason</label>
            <textarea className="input" rows={2} placeholder="e.g. Stock-out — patient waiting on script" value={reason} onChange={e => setReason(e.target.value)} style={{height:'auto', padding:12}}/>
          </div>
        </div>
        <div style={{padding:'12px 22px', borderTop:'1px solid var(--border)', display:'flex', gap:10, justifyContent:'flex-end', background:'var(--bg-subtle)'}}>
          <button className="btn btn--ghost" onClick={onClose}>Cancel</button>
          <button className="btn btn--primary" onClick={onSubmit}><OIcon name="check"/> Send request</button>
        </div>
      </div>
    </div>
  );
}

// =================================================================
// PROCEDURES — opening / closing checklists
// =================================================================
function Procedures() {
  const [side, setSide] = stExtUseState("open");
  const list = side === "open" ? ST_CHECKLIST_OPEN : ST_CHECKLIST_CLOSE;

  // Local checkmarks
  const [checked, setChecked] = stExtUseState(new Set([side === "open" ? "o1" : "c1"]));
  const toggle = (id) => setChecked(s => { const n = new Set(s); n.has(id) ? n.delete(id) : n.add(id); return n; });
  React.useEffect(() => setChecked(new Set([side === "open" ? "o1" : "c1"])), [side]);

  const grouped = list.reduce((acc, t) => { (acc[t.category] = acc[t.category] || []).push(t); return acc; }, {});
  const progress = Math.round((checked.size / list.length) * 100);

  return (
    <>
      <div className="off-card" style={{marginBottom:14, flexDirection:'row', alignItems:'center', gap:14, padding:'14px 18px'}}>
        <OIcon name="info" style={{color:'var(--brand)'}}/>
        <div style={{flex:1, fontSize:13, color:'var(--text-muted)'}}>
          Standard operating procedures for opening &amp; closing. Edit the master here — each store sees this on the POS sign-in &amp; close-register screen. Completion is logged to the audit trail.
        </div>
        <button className="btn btn--ghost btn--sm">Audit log</button>
        <button className="btn btn--primary btn--sm">
          <OIcon name="edit"/> Edit master
        </button>
      </div>

      <div style={{display:'flex', gap:8, marginBottom:14}}>
        <button className={"off-filter" + (side === "open" ? " off-filter--active" : "")} onClick={() => setSide("open")}>
          Opening procedure <span className="off-filter-count">{ST_CHECKLIST_OPEN.length}</span>
        </button>
        <button className={"off-filter" + (side === "close" ? " off-filter--active" : "")} onClick={() => setSide("close")}>
          Closing procedure <span className="off-filter-count">{ST_CHECKLIST_CLOSE.length}</span>
        </button>
      </div>

      <div style={{display:'grid', gridTemplateColumns:'1fr 280px', gap:14}}>
        <div style={{display:'flex', flexDirection:'column', gap:12}}>
          {Object.entries(grouped).map(([category, tasks]) => (
            <div key={category} className="off-card" style={{padding:0, overflow:'hidden'}}>
              <div style={{padding:'12px 18px', background:'var(--bg-subtle)', borderBottom:'1px solid var(--border)', display:'flex', alignItems:'center', justifyContent:'space-between'}}>
                <div style={{fontWeight:600, fontSize:13, letterSpacing:'-0.01em'}}>{category}</div>
                <div className="off-cell-mono off-muted" style={{fontSize:11}}>{tasks.filter(t => checked.has(t.id)).length}/{tasks.length} done</div>
              </div>
              <div style={{display:'flex', flexDirection:'column'}}>
                {tasks.map(t => {
                  const done = checked.has(t.id);
                  return (
                    <label key={t.id} style={{padding:'12px 18px', borderBottom:'1px solid var(--border-subtle)', display:'flex', alignItems:'center', gap:12, cursor:'pointer'}}>
                      <input type="checkbox" checked={done} onChange={() => toggle(t.id)}/>
                      <div style={{flex:1, textDecoration: done ? 'line-through' : 'none', color: done ? 'var(--text-muted)' : 'var(--text)', fontSize:14}}>{t.task}</div>
                      <div className="off-cell-mono off-muted" style={{fontSize:11}}>{t.time}</div>
                    </label>
                  );
                })}
              </div>
            </div>
          ))}
        </div>

        <div style={{display:'flex', flexDirection:'column', gap:14, position:'sticky', top:0}}>
          <div className="off-card">
            <div className="off-card-title">Progress</div>
            <div style={{fontSize:36, fontWeight:600, letterSpacing:'-0.02em', fontVariantNumeric:'tabular-nums', lineHeight:1}}>{checked.size}/{list.length}</div>
            <div style={{height:8, background:'var(--bg-muted)', borderRadius:4, overflow:'hidden'}}>
              <div style={{height:'100%', width:progress+'%', background:'var(--brand)'}}/>
            </div>
            <div className="off-muted" style={{fontSize:12}}>{progress}% complete · est. {side === "open" ? "25 minutes" : "40 minutes"}</div>
          </div>

          <div className="off-card">
            <div className="off-card-title">Applies to</div>
            <div style={{display:'flex', flexDirection:'column', gap:6, fontSize:13}}>
              {OD.STORES.map(s => (
                <div key={s.id} style={{display:'flex', alignItems:'center', gap:8}}>
                  <div className="off-topbar-store-av" style={{width:20, height:20, borderRadius:4, background:STORE_COL[s.id], color:'#fff', fontSize:8}}>{s.code}</div>
                  <span>{s.name}</span>
                </div>
              ))}
            </div>
            <button className="btn btn--ghost btn--sm" style={{alignSelf:'flex-start'}}>Customise per store</button>
          </div>

          <div className="off-card">
            <div className="off-card-title">Recent runs</div>
            <div style={{display:'flex', flexDirection:'column', gap:8, fontSize:13}}>
              {[
                { store: "S-001", who: "Suni K.",   ts: "Today 08:30",       dur: "22 min" },
                { store: "S-002", who: "Rachel P.", ts: "Today 08:30",       dur: "18 min" },
                { store: "S-003", who: "James L.",  ts: "Today 09:00",       dur: "24 min" },
                { store: "S-001", who: "Suni K.",   ts: "Yesterday 19:40",   dur: "38 min" },
              ].map((r, i) => (
                <div key={i} style={{display:'flex', justifyContent:'space-between', alignItems:'center'}}>
                  <div>
                    <div style={{fontWeight:500}}>{findS(r.store)?.code} · {r.who}</div>
                    <div className="off-cell-mono off-muted" style={{fontSize:11}}>{r.ts}</div>
                  </div>
                  <div className="off-mono off-muted">{r.dur}</div>
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>
    </>
  );
}

// Overwrite the Stores screen registration
window.OFFICE_SCREENS = Object.assign(window.OFFICE_SCREENS || {}, {
  stores: StoresExpanded,
});
