/* =============================================================
   CoreIQ Office — Label designer + queue, Stocktake
   ============================================================= */
const { useState: lblUseState, useMemo: lblUseMemo, useRef: lblUseRef } = React;

// -----------------------------------------------------------------
// LABEL DESIGNER + QUEUE
// -----------------------------------------------------------------
function Labels() {
  const { pushToast } = window.useOffice();
  const [tab, setTab] = lblUseState("designer");

  return (
    <div className="off-screen">
      <header className="off-screen-header">
        <div className="off-screen-header-meta">
          <span className="off-screen-eyebrow">Labels</span>
          <h2 className="off-screen-title">Label designer &amp; queue</h2>
        </div>
        <div className="off-screen-actions">
          <button className="btn btn--ghost btn--sm"><OIcon name="printer"/> Printer status</button>
          <button className="btn btn--primary btn--sm" onClick={() => pushToast({kind:'paid', icon:'check', title:'Template saved', meta:'Available across all stores'})}>
            <OIcon name="check"/> Save template
          </button>
        </div>
      </header>

      <div className="off-subtabs">
        <button className={"off-subtab" + (tab === "designer" ? " off-subtab--active" : "")} onClick={() => setTab("designer")}>Designer</button>
        <button className={"off-subtab" + (tab === "queue" ? " off-subtab--active" : "")} onClick={() => setTab("queue")}>
          Queue
          <span style={{marginLeft:6, fontSize:10, background:'var(--hold)', color:'var(--hold-fg)', padding:'1px 6px', borderRadius:99, fontWeight:600}}>
            {OD.LABEL_QUEUE.filter(l => l.status === "queued").length}
          </span>
        </button>
        <button className={"off-subtab" + (tab === "templates" ? " off-subtab--active" : "")} onClick={() => setTab("templates")}>Templates</button>
      </div>

      <div className="off-screen-body">
        {tab === "designer" && <LabelDesigner/>}
        {tab === "queue" && <LabelQueue/>}
        {tab === "templates" && <LabelTemplates/>}
      </div>
    </div>
  );
}

function LabelDesigner() {
  const [templateId, setTemplateId] = lblUseState("lt-shelf");
  const template = OD.LABEL_TEMPLATES.find(t => t.id === templateId);

  // Canvas elements — relative positions on the label
  const [elements, setElements] = lblUseState([
    { id: "e1", type: "text",     content: "Paracetamol 500mg",      x: 4, y: 3,  w: 50, h: 6, fontSize: 11, weight: 600 },
    { id: "e2", type: "text",     content: "100 tablets",            x: 4, y: 11, w: 30, h: 4, fontSize: 8,  weight: 400 },
    { id: "e3", type: "text",     content: "$6.95",                  x: 38, y: 13, w: 18, h: 9, fontSize: 14, weight: 600 },
    { id: "e4", type: "barcode",  content: "9300673112225",          x: 4, y: 17, w: 52, h: 6, fontSize: 6,  weight: 400 },
  ]);
  const [selectedId, setSelectedId] = lblUseState("e1");
  const selected = elements.find(e => e.id === selectedId);

  // mm → px conversion for the on-screen preview (scale 4× so small labels are visible)
  const SCALE = 4;

  function updateSel(field, value) {
    setElements(els => els.map(e => e.id === selectedId ? { ...e, [field]: value } : e));
  }

  function addElement(type) {
    const id = "e" + Date.now();
    const defaults = type === "barcode"
      ? { content: "9300673000000", x: 4, y: 4, w: template.width / 2, h: 5, fontSize: 6, weight: 400 }
      : type === "logo"
        ? { content: "CoreIQ", x: 4, y: 4, w: 22, h: 4, fontSize: 8, weight: 600 }
        : { content: "Edit me", x: 4, y: 4, w: template.width / 2, h: 4, fontSize: 9, weight: 400 };
    setElements(els => [...els, { id, type: type === "logo" ? "text" : type, ...defaults }]);
    setSelectedId(id);
  }

  return (
    <div className="label-designer">
      {/* LEFT PANE — elements & assets */}
      <div className="label-pane">
        <div className="label-pane-head">Add element</div>
        <div className="label-pane-body">
          {[
            { type: "text",       label: "Text field",   icon: "type"     },
            { type: "barcode",    label: "Barcode",      icon: "barcode"  },
            { type: "field",      label: "Bind: product name", icon: "tag"  },
            { type: "field",      label: "Bind: price",       icon: "tag"  },
            { type: "field",      label: "Bind: SKU",         icon: "tag"  },
            { type: "field",      label: "Bind: expiry",      icon: "tag"  },
            { type: "field",      label: "Bind: pack size",   icon: "tag"  },
            { type: "logo",       label: "Logo · CoreIQ", icon: "logo"  },
            { type: "shape",      label: "Rectangle",    icon: "square"   },
            { type: "shape",      label: "Divider line", icon: "minus"    },
          ].map((it, i) => (
            <div key={i} className="label-element" onClick={() => addElement(it.type)}>
              <div className="label-element-icon">
                <OIcon name={
                  it.type === "barcode" ? "barcode" :
                  it.type === "logo"    ? "loyalty" :
                  it.type === "shape"   ? "stock" :
                  it.type === "field"   ? "tag" : "doc"
                } width={14} height={14}/>
              </div>
              <div style={{flex:1}}>{it.label}</div>
              <OIcon name="plus" width={12} height={12} style={{color:'var(--text-subtle)'}}/>
            </div>
          ))}

          <div style={{fontSize:11, color:'var(--text-subtle)', textTransform:'uppercase', letterSpacing:'0.06em', fontWeight:500, marginTop:18, marginBottom:8}}>Starting template</div>
          <select className="input select" value={templateId} onChange={e => setTemplateId(e.target.value)} style={{height:36, fontSize:13}}>
            {OD.LABEL_TEMPLATES.map(t => <option key={t.id} value={t.id}>{t.name} · {t.width}×{t.height}mm</option>)}
          </select>
        </div>
      </div>

      {/* CENTRE — canvas */}
      <div className="label-pane">
        <div className="label-pane-head" style={{display:'flex', alignItems:'center', justifyContent:'space-between'}}>
          <span>Canvas · {template.width} × {template.height} mm</span>
          <div style={{display:'flex', alignItems:'center', gap:8, fontSize:11, color:'var(--text-muted)', textTransform:'none', letterSpacing:0, fontWeight:400}}>
            <span>Preview {SCALE}×</span>
            <button className="btn btn--ghost btn--sm">Reset</button>
          </div>
        </div>
        <div className="label-stage">
          <div
            className="label-canvas"
            style={{width: template.width * SCALE, height: template.height * SCALE}}
            onClick={(e) => { if (e.target.classList.contains('label-canvas')) setSelectedId(null); }}
          >
            {elements.map(el => (
              <div
                key={el.id}
                className={"label-canvas-el label-canvas-el--" + el.type + (selectedId === el.id ? " label-canvas-el--selected" : "")}
                style={{
                  left: el.x * SCALE,
                  top:  el.y * SCALE,
                  width: el.w * SCALE,
                  height: el.h * SCALE,
                  fontSize: el.fontSize,
                  fontWeight: el.weight,
                }}
                onClick={() => setSelectedId(el.id)}
              >
                {el.type === "barcode" ? <span>{el.content}</span> : el.content}
              </div>
            ))}
          </div>
        </div>
      </div>

      {/* RIGHT — properties */}
      <div className="label-pane">
        <div className="label-pane-head">Properties</div>
        <div className="label-pane-body">
          {!selected ? (
            <div style={{padding:'24px 0', textAlign:'center', color:'var(--text-muted)', fontSize:13}}>
              Select an element to edit its properties.
            </div>
          ) : (
            <>
              <div className="label-prop-row">
                <span className="label-prop-label">Type</span>
                <span style={{fontFamily:'var(--font-mono)', fontSize:13, color:'var(--text)'}}>{selected.type}</span>
              </div>
              <div className="label-prop-row">
                <span className="label-prop-label">Content</span>
                <input className="input" value={selected.content} onChange={e => updateSel("content", e.target.value)}/>
              </div>
              <div className="label-prop-row" style={{display:'grid', gridTemplateColumns:'1fr 1fr', gap:8}}>
                <div>
                  <span className="label-prop-label">X (mm)</span>
                  <input className="input tabular" type="number" value={selected.x} onChange={e => updateSel("x", parseFloat(e.target.value) || 0)}/>
                </div>
                <div>
                  <span className="label-prop-label">Y (mm)</span>
                  <input className="input tabular" type="number" value={selected.y} onChange={e => updateSel("y", parseFloat(e.target.value) || 0)}/>
                </div>
                <div>
                  <span className="label-prop-label">Width</span>
                  <input className="input tabular" type="number" value={selected.w} onChange={e => updateSel("w", parseFloat(e.target.value) || 0)}/>
                </div>
                <div>
                  <span className="label-prop-label">Height</span>
                  <input className="input tabular" type="number" value={selected.h} onChange={e => updateSel("h", parseFloat(e.target.value) || 0)}/>
                </div>
              </div>
              {selected.type === "text" && (
                <>
                  <div className="label-prop-row">
                    <span className="label-prop-label">Font size (pt)</span>
                    <input className="input tabular" type="number" value={selected.fontSize} onChange={e => updateSel("fontSize", parseInt(e.target.value) || 8)}/>
                  </div>
                  <div className="label-prop-row">
                    <span className="label-prop-label">Weight</span>
                    <select className="input select" value={selected.weight} onChange={e => updateSel("weight", parseInt(e.target.value))}>
                      <option value={400}>Regular · 400</option>
                      <option value={500}>Medium · 500</option>
                      <option value={600}>Bold · 600</option>
                    </select>
                  </div>
                </>
              )}
              <div className="label-prop-row">
                <button className="btn btn--ghost btn--sm" style={{color:'var(--void)'}} onClick={() => { setElements(els => els.filter(e => e.id !== selectedId)); setSelectedId(null); }}>
                  <OIcon name="trash"/> Delete element
                </button>
              </div>
            </>
          )}

          <div style={{borderTop:'1px solid var(--border)', paddingTop:12, marginTop:12}}>
            <div className="label-prop-label" style={{marginBottom:8}}>Output</div>
            <div style={{fontSize:12, color:'var(--text-muted)', marginBottom:8}}>{template.printer}</div>
            <button className="btn btn--primary btn--block btn--sm"><OIcon name="printer"/> Print 1 sample</button>
            <button className="btn btn--secondary btn--block btn--sm" style={{marginTop:6}}>Send to queue…</button>
          </div>
        </div>
      </div>
    </div>
  );
}

function LabelQueue() {
  const { pushToast } = window.useOffice();
  const queue = OD.LABEL_QUEUE;

  return (
    <div className="off-table">
      <div className="off-table-toolbar">
        <div style={{fontSize:13, color:'var(--text-muted)'}}>
          {queue.filter(l => l.status === "queued").length} queued · {queue.filter(l => l.status === "printed").length} printed today
        </div>
        <div style={{marginLeft:'auto', display:'flex', gap:8}}>
          <button className="btn btn--ghost btn--sm">Clear printed</button>
          <button className="btn btn--primary btn--sm" onClick={() => pushToast({kind:'paid', icon:'printer', title:'Sending to printer', meta:`${queue.filter(l => l.status === "queued").length} labels`})}>
            <OIcon name="printer"/> Print all queued
          </button>
        </div>
      </div>

      <div className="off-grid" style={{gridTemplateColumns:'120px 1fr 140px 70px 110px 120px 100px'}}>
        <div className="off-grid-headcell">Template</div>
        <div className="off-grid-headcell">Product</div>
        <div className="off-grid-headcell">Store</div>
        <div className="off-grid-headcell" style={{justifyContent:'flex-end'}}>Qty</div>
        <div className="off-grid-headcell">Queued by</div>
        <div className="off-grid-headcell">Status</div>
        <div className="off-grid-headcell">Action</div>

        {queue.map(l => {
          const t = OD.LABEL_TEMPLATES.find(x => x.id === l.template);
          const p = findP(l.productId);
          const s = findS(l.store);
          return (
            <div key={l.id} className="off-grid-row">
              <div className="off-grid-cell">{t.name}</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">{s.name}</div>
              <div className="off-grid-cell off-cell-num off-cell-strong">{l.qty}</div>
              <div className="off-grid-cell off-cell-mono">{l.queuedBy}<div style={{fontSize:11, color:'var(--text-subtle)'}}>{l.queuedAt}</div></div>
              <div className="off-grid-cell">
                {l.status === "queued"  && <span className="badge badge--hold"><span className="badge-dot"/> Queued</span>}
                {l.status === "printed" && <span className="badge badge--paid"><span className="badge-dot"/> Printed {l.printedAt}</span>}
                {l.status === "error"   && <span className="badge badge--void"><span className="badge-dot"/> {l.errorReason}</span>}
              </div>
              <div className="off-grid-cell">
                {l.status === "queued"  && <button className="btn btn--primary btn--sm" onClick={() => pushToast({kind:'paid', icon:'printer', title:`Printing ${l.qty} × ${p.name}`})}>Print</button>}
                {l.status === "error"   && <button className="btn btn--secondary btn--sm">Retry</button>}
                {l.status === "printed" && <button className="btn btn--ghost btn--sm">Reprint</button>}
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

function LabelTemplates() {
  return (
    <div style={{display:'grid', gridTemplateColumns:'repeat(3, 1fr)', gap:14}}>
      {OD.LABEL_TEMPLATES.map(t => (
        <div key={t.id} className="off-card" style={{cursor:'pointer'}}>
          <div style={{
            background:'#fff',
            border:'1px dashed var(--border-strong)',
            borderRadius:8,
            padding:12,
            color:'#000',
            aspectRatio: `${t.width} / ${t.height}`,
            position:'relative',
            display:'flex',
            flexDirection:'column',
            justifyContent:'space-between',
          }}>
            <div style={{fontSize:11, fontWeight:600, lineHeight:1.2}}>{t.thumb === "ndss" ? "BD Pen Needles" : t.thumb === "promo" ? "SUMMER SAVERS" : "Sample Product 500mg"}</div>
            {t.thumb === "promo"
              ? <div style={{fontSize:24, fontWeight:600, textAlign:'center', marginTop:'auto'}}>30% OFF</div>
              : <div style={{display:'flex', justifyContent:'space-between', alignItems:'flex-end'}}>
                  <div style={{fontFamily:'var(--font-mono)', fontSize:7}}>9300673112225</div>
                  <div style={{fontSize:14, fontWeight:600}}>$6.95</div>
                </div>
            }
            <div style={{height:8, marginTop:6, background:'repeating-linear-gradient(to right, #000 0, #000 1.5px, #fff 1.5px, #fff 2.5px, #000 2.5px, #000 4px, #fff 4px, #fff 5px)'}}></div>
          </div>
          <div>
            <div className="off-card-title">{t.name}</div>
            <div className="off-card-meta">{t.width} × {t.height} {t.units} · {t.printer}</div>
          </div>
          <div style={{fontSize:12, color:'var(--text-muted)'}}>{t.description}</div>
          <div style={{display:'flex', gap:6}}>
            <button className="btn btn--secondary btn--sm" style={{flex:1}}>Edit</button>
            <button className="btn btn--ghost btn--sm" style={{flex:1}}>Duplicate</button>
          </div>
        </div>
      ))}
    </div>
  );
}

// =================================================================
// STOCKTAKE
// =================================================================
function Stocktake() {
  const { setScreen, setScreenState, pushToast, scope } = window.useOffice();
  const [tab, setTab] = lblUseState("active");

  const active = OD.STOCKTAKES.find(s => s.status === "in-progress");

  return (
    <div className="off-screen">
      <header className="off-screen-header">
        <div className="off-screen-header-meta">
          <span className="off-screen-eyebrow">Stock · stocktake</span>
          <h2 className="off-screen-title">Cycle counts</h2>
        </div>
        <div className="off-screen-actions">
          <button className="btn btn--ghost btn--sm">Export history</button>
          <button className="btn btn--primary btn--sm" onClick={() => { setScreenState({ activeStocktakeId: "new" }); setTab("session"); }}>
            <OIcon name="plus"/> Start new count
          </button>
        </div>
      </header>

      <div className="off-subtabs">
        <button className={"off-subtab" + (tab === "active" ? " off-subtab--active" : "")} onClick={() => setTab("active")}>
          Active{active && <span style={{marginLeft:6, background:'var(--hold)', color:'var(--hold-fg)', padding:'1px 6px', borderRadius:99, fontSize:10, fontWeight:600}}>1</span>}
        </button>
        <button className={"off-subtab" + (tab === "session" ? " off-subtab--active" : "")} onClick={() => setTab("session")}>Count session</button>
        <button className={"off-subtab" + (tab === "history" ? " off-subtab--active" : "")} onClick={() => setTab("history")}>History</button>
      </div>

      <div className="off-screen-body">
        {tab === "active" && <StocktakeActive/>}
        {tab === "session" && <StocktakeSession/>}
        {tab === "history" && <StocktakeHistory/>}
      </div>
    </div>
  );
}

function StocktakeActive() {
  const { pushToast } = window.useOffice();
  const inProgress = OD.STOCKTAKES.filter(s => s.status === "in-progress");

  if (inProgress.length === 0) {
    return (
      <div className="off-empty" style={{padding:60, background:'var(--surface)', border:'1px dashed var(--border-strong)', borderRadius:12}}>
        <div className="empty-icon"><OIcon name="clipboard" width={22} height={22}/></div>
        <div style={{fontSize:16, fontWeight:600, marginTop:4}}>No active counts</div>
        <div style={{fontSize:13, color:'var(--text-muted)', maxWidth:'42ch', textAlign:'center'}}>Start a new cycle count to spot-check stock by category, supplier, or location. Variances flow into the audit log automatically.</div>
        <button className="btn btn--primary btn--sm" style={{marginTop:8}}>Start a count</button>
      </div>
    );
  }

  return (
    <div style={{display:'flex', flexDirection:'column', gap:12}}>
      {inProgress.map(s => (
        <div key={s.id} className="off-card" style={{flexDirection:'row', alignItems:'center', gap:18}}>
          <div style={{width:48, height:48, borderRadius:12, background:'var(--hold-bg)', color:'var(--hold)', display:'grid', placeItems:'center'}}>
            <OIcon name="clipboard" width={20} height={20}/>
          </div>
          <div style={{flex:1}}>
            <div style={{fontSize:16, fontWeight:600, letterSpacing:'-0.01em'}}>{s.scope}</div>
            <div style={{fontSize:12, color:'var(--text-muted)', fontFamily:'var(--font-mono)'}}>
              {s.id} · {findS(s.storeId)?.name} · Started {s.started} by {s.startedBy}
            </div>
            <div style={{display:'flex', gap:14, marginTop:8, fontSize:13}}>
              <div><strong className="off-num">{s.counted}</strong> <span className="off-muted">of {s.expected} counted</span></div>
              <div className="off-muted">·</div>
              <div><strong style={{color:'var(--hold-text)'}}>{s.variance.count}</strong> <span className="off-muted">variance{s.variance.count === 1 ? "" : "s"} ({oMoney(s.variance.value)})</span></div>
            </div>
            <div style={{height:6, background:'var(--bg-muted)', borderRadius:3, overflow:'hidden', marginTop:8}}>
              <div style={{height:'100%', width: ((s.counted / s.expected) * 100) + "%", background:'var(--hold)'}}></div>
            </div>
          </div>
          <button className="btn btn--ghost btn--sm">Pause</button>
          <button className="btn btn--primary btn--sm" onClick={() => pushToast({kind:'hold', icon:'check', title:'Resuming count', meta:s.scope})}>
            Resume count
          </button>
        </div>
      ))}
    </div>
  );
}

function StocktakeSession() {
  const { pushToast, scope } = window.useOffice();
  const [filterType, setFilterType] = lblUseState("category");
  const [filterValue, setFilterValue] = lblUseState("Diabetes");
  const [storeId, setStoreId] = lblUseState(scope === "all" ? "S-001" : scope);

  // Apply filter to product list for the chosen store
  const items = lblUseMemo(() => {
    const stock = OD.STOCK[storeId] || {};
    return OD.PRODUCTS
      .filter(p => {
        if (!stock[p.id]) return false;
        if (filterType === "category" && p.category !== filterValue) return false;
        if (filterType === "schedule" && p.schedule !== filterValue) return false;
        if (filterType === "supplier" && p.supplier !== filterValue) return false;
        return true;
      })
      .map(p => ({ product: p, stock: stock[p.id] }));
  }, [storeId, filterType, filterValue]);

  // Local counts
  const [counts, setCounts] = lblUseState({});
  const setCount = (id, v) => setCounts(c => ({ ...c, [id]: v }));

  const countedItems = items.filter(i => counts[i.product.id] !== undefined && counts[i.product.id] !== "");
  const varianceItems = countedItems.filter(i => parseInt(counts[i.product.id]) !== i.stock.onHand);
  const varianceValue = varianceItems.reduce((s, i) => s + ((parseInt(counts[i.product.id]) - i.stock.onHand) * i.product.cost), 0);

  return (
    <div className="count-screen">
      {/* LEFT — count table */}
      <div className="off-table" style={{display:'flex', flexDirection:'column', overflow:'hidden'}}>
        <div className="off-table-toolbar" style={{flexShrink:0}}>
          <select className="input select" value={storeId} onChange={e => setStoreId(e.target.value)} style={{height:34, fontSize:13, width:160}}>
            {OD.STORES.map(s => <option key={s.id} value={s.id}>{s.name}</option>)}
          </select>
          <div className="off-table-toolbar-sep"/>
          <select className="input select" value={filterType} onChange={e => setFilterType(e.target.value)} style={{height:34, fontSize:13, width:130}}>
            <option value="category">By category</option>
            <option value="schedule">By schedule</option>
            <option value="supplier">By supplier</option>
            <option value="location">By location</option>
          </select>
          <select className="input select" value={filterValue} onChange={e => setFilterValue(e.target.value)} style={{height:34, fontSize:13, flex:1, maxWidth:200}}>
            {filterType === "category" && [...new Set(OD.PRODUCTS.map(p => p.category))].map(c => <option key={c}>{c}</option>)}
            {filterType === "schedule" && ["S2","S3","S4","S8"].map(s => <option key={s}>{s}</option>)}
            {filterType === "supplier" && OD.SUPPLIERS.map(s => <option key={s.id} value={s.id}>{s.name}</option>)}
          </select>
          <div className="off-row off-muted" style={{marginLeft:'auto', fontSize:13}}>
            <OIcon name="barcode"/> <span>Scan barcode to count</span>
          </div>
        </div>

        <div style={{flex:1, overflowY:'auto', minHeight:0}}>
          <div className="count-item-row count-item-row--header">
            <div></div>
            <div>Product</div>
            <div style={{textAlign:'right'}}>Expected</div>
            <div style={{textAlign:'right'}}>Counted</div>
            <div>Lot</div>
            <div>Expiry</div>
            <div style={{textAlign:'right'}}>Variance</div>
          </div>
          {items.map((it, i) => {
            const cv = counts[it.product.id];
            const counted = cv !== undefined && cv !== "";
            const variance = counted ? parseInt(cv) - it.stock.onHand : 0;
            return (
              <div key={it.product.id} className={"count-item-row" + (counted ? variance === 0 ? " count-item-row--counted" : " count-item-row--variance" : "")}>
                <div style={{width:32, height:32, borderRadius:7, background: counted ? variance === 0 ? 'var(--paid)' : 'var(--hold)' : 'var(--bg-muted)', color:'#fff', display:'grid', placeItems:'center', fontSize:11, fontWeight:600}}>
                  {counted ? <OIcon name="check" width={12} height={12}/> : i + 1}
                </div>
                <div>
                  <div style={{fontWeight:500, fontSize:13}}>{it.product.name} <span className="off-muted" style={{fontWeight:400}}>· {it.product.strength}</span></div>
                  <div className="off-mono off-muted">{it.product.sku} · {it.stock.location}</div>
                </div>
                <div className="off-num off-cell-strong" style={{textAlign:'right'}}>{it.stock.onHand}</div>
                <div style={{textAlign:'right'}}>
                  <input
                    className="count-input"
                    type="number"
                    placeholder="—"
                    value={cv ?? ""}
                    onChange={e => setCount(it.product.id, e.target.value)}
                  />
                </div>
                <div className="off-mono off-muted">{it.stock.lot}</div>
                <div className="off-mono off-muted">{it.stock.expiry}</div>
                <div className="off-num" style={{textAlign:'right', fontWeight:500, color: variance > 0 ? 'var(--paid)' : variance < 0 ? 'var(--void)' : 'var(--text-muted)'}}>
                  {counted ? (variance > 0 ? "+" : "") + variance : "—"}
                </div>
              </div>
            );
          })}
        </div>
      </div>

      {/* RIGHT — session summary */}
      <div style={{display:'flex', flexDirection:'column', gap:12}}>
        <div className="off-card">
          <div className="off-card-title">Cycle count session</div>
          <div style={{fontSize:13, color:'var(--text-muted)', lineHeight:1.5}}>
            <strong style={{color:'var(--text)'}}>{filterType === "category" ? filterValue : filterType === "schedule" ? filterValue : findSup(filterValue)?.name}</strong> at <strong style={{color:'var(--text)'}}>{findS(storeId)?.name}</strong>
            <br/>{items.length} SKUs in scope
          </div>
          <div style={{display:'grid', gridTemplateColumns:'1fr 1fr', gap:10, marginTop:6}}>
            <div>
              <div style={{fontSize:11, textTransform:'uppercase', letterSpacing:'0.06em', color:'var(--text-subtle)', fontWeight:500}}>Progress</div>
              <div style={{fontSize:22, fontWeight:600, letterSpacing:'-0.01em', fontVariantNumeric:'tabular-nums'}}>{countedItems.length}/{items.length}</div>
            </div>
            <div>
              <div style={{fontSize:11, textTransform:'uppercase', letterSpacing:'0.06em', color:'var(--text-subtle)', fontWeight:500}}>Variances</div>
              <div style={{fontSize:22, fontWeight:600, letterSpacing:'-0.01em', fontVariantNumeric:'tabular-nums', color: varianceItems.length === 0 ? 'var(--paid)' : 'var(--hold-text)'}}>{varianceItems.length}</div>
            </div>
          </div>
          <div style={{height:8, background:'var(--bg-muted)', borderRadius:4, overflow:'hidden'}}>
            <div style={{height:'100%', width: items.length > 0 ? ((countedItems.length / items.length) * 100) + "%" : "0%", background:'var(--brand)'}}></div>
          </div>
        </div>

        {varianceItems.length > 0 && (
          <div className="off-card" style={{borderColor:'var(--hold-border)', background:'var(--hold-bg)'}}>
            <div className="off-card-title" style={{color:'var(--hold-text)'}}>Variances detected</div>
            <div style={{fontSize:13, color:'var(--hold-text)', lineHeight:1.5}}>
              {varianceItems.length} item{varianceItems.length > 1 ? "s" : ""} off · net value {oMoney(varianceValue)}.
              <br/>You'll be asked to attach a reason at finalisation.
            </div>
          </div>
        )}

        <div className="off-card">
          <div className="off-card-title">Actions</div>
          <button className="btn btn--secondary btn--block btn--sm">Save and pause</button>
          <button className="btn btn--ghost btn--block btn--sm" style={{color:'var(--void)'}}>Abandon count</button>
          <button
            className="btn btn--primary btn--block"
            disabled={countedItems.length === 0}
            onClick={() => pushToast({kind:'paid', icon:'check-circle', title:`Cycle count finalised`, meta:`${countedItems.length} items · ${varianceItems.length} variances logged`})}
          >
            <OIcon name="check"/> Finalise count
          </button>
        </div>
      </div>
    </div>
  );
}

function StocktakeHistory() {
  return (
    <div className="off-table">
      <div className="off-grid" style={{gridTemplateColumns:'110px 1fr 120px 130px 100px 110px 100px 100px'}}>
        <div className="off-grid-headcell">ID</div>
        <div className="off-grid-headcell">Scope</div>
        <div className="off-grid-headcell">Store</div>
        <div className="off-grid-headcell">Started by</div>
        <div className="off-grid-headcell" style={{justifyContent:'flex-end'}}>Items</div>
        <div className="off-grid-headcell" style={{justifyContent:'flex-end'}}>Variance</div>
        <div className="off-grid-headcell" style={{justifyContent:'flex-end'}}>Value</div>
        <div className="off-grid-headcell">Status</div>
        {OD.STOCKTAKES.map(s => (
          <div key={s.id} className="off-grid-row">
            <div className="off-grid-cell off-cell-mono">{s.id}</div>
            <div className="off-grid-cell off-cell-strong">
              {s.scope}
              <div className="off-mono off-muted" style={{marginTop:2}}>{s.started}{s.finished ? ` → ${s.finished}` : ""}</div>
            </div>
            <div className="off-grid-cell">{findS(s.storeId)?.name}</div>
            <div className="off-grid-cell">{s.startedBy}</div>
            <div className="off-grid-cell off-cell-num">{s.counted}/{s.expected}</div>
            <div className="off-grid-cell off-cell-num" style={{color: s.variance.count === 0 ? 'var(--paid-text)' : 'var(--hold-text)', fontWeight:500}}>
              {s.variance.count === 0 ? "Balanced" : s.variance.count}
            </div>
            <div className="off-grid-cell off-cell-num">{s.variance.value === 0 ? "—" : oMoney(s.variance.value)}</div>
            <div className="off-grid-cell">
              {s.status === "complete"    && <span className="badge badge--paid"><span className="badge-dot"/> Complete</span>}
              {s.status === "in-progress" && <span className="badge badge--hold"><span className="badge-dot"/> In progress</span>}
              {s.status === "abandoned"   && <span className="badge badge--void"><span className="badge-dot"/> Abandoned</span>}
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

window.OFFICE_SCREENS = Object.assign(window.OFFICE_SCREENS || {}, {
  labels: Labels,
  stocktake: Stocktake,
});
