/* =====================================================================
   AI-COS — Calibration Jobs: board + gated worksheet + review/approve
   ===================================================================== */
function JobsModule({ onNav, openJob, jobId, setJobId }) {
  const [view, setView] = useState('board');
  const [recv, setRecv] = useState(false);
  const DB = window.DB;
  if (jobId) return <JobDetail jobId={jobId} onBack={() => setJobId(null)} onNav={onNav} />;

  const stageColor = { Received: '#94a3b8', Assigned: '#2f6fed', 'In progress': '#c9820a', Review: '#7a5bff', Approved: '#15a06b', Dispatched: '#0f7a4f' };

  return (
    <div className="page page-wide rise">
      <div className="row" style={{ justifyContent: 'space-between', alignItems: 'flex-end', marginBottom: 18 }}>
        <div>
          <div className="h-page">Calibration Jobs</div>
          <div className="h-sub">Receipt → execution → review → certificate · ISO 17025 gated workflow</div>
        </div>
        <div className="row" style={{ gap: 8 }}>
          <div className="seg">
            <button className={view === 'board' ? 'on' : ''} onClick={() => setView('board')}>Board</button>
            <button className={view === 'list' ? 'on' : ''} onClick={() => setView('list')}>List</button>
          </div>
          <Btn variant="ghost" icon="filter" size="sm" onClick={() => window.toast('Filters applied', 'info')}>Filter</Btn>
          <Btn variant="primary" icon="plus" onClick={() => setRecv(true)}>Receive equipment</Btn>
        </div>
      </div>

      {view === 'board' ? (
        <div style={{ display: 'grid', gridTemplateColumns: `repeat(${DB.stages.length}, minmax(190px,1fr))`, gap: 12, overflowX: 'auto', paddingBottom: 8 }}>
          {DB.stages.map((stage) => {
            const items = DB.jobs.filter((j) => j.stage === stage);
            return (
              <div key={stage} style={{ minWidth: 190 }}>
                <div className="row" style={{ gap: 7, padding: '0 4px 10px' }}>
                  <span style={{ width: 8, height: 8, borderRadius: '50%', background: stageColor[stage] }} />
                  <span style={{ fontSize: 12.5, fontWeight: 700 }}>{stage}</span>
                  <span className="badge b-neutral" style={{ marginLeft: 'auto' }}>{items.length}</span>
                </div>
                <div style={{ display: 'flex', flexDirection: 'column', gap: 9 }}>
                  {items.map((j) => <JobCard key={j.id} job={j} onClick={() => setJobId(j.id)} accent={stageColor[stage]} />)}
                  {!items.length && <div style={{ border: '1.5px dashed var(--border-2)', borderRadius: 11, padding: 18, textAlign: 'center', color: 'var(--text-3)', fontSize: 11.5 }}>No jobs</div>}
                </div>
              </div>
            );
          })}
        </div>
      ) : (
        <div className="card">
          <table className="tbl">
            <thead><tr><th>Job</th><th>Customer</th><th>Type</th><th>Items</th><th>Stage</th><th>Technician</th><th>SLA</th><th>Due</th><th></th></tr></thead>
            <tbody>
              {DB.jobs.map((j) => {
                const c = DB.custById(j.customer);
                return (
                  <tr key={j.id} className="clickable" onClick={() => setJobId(j.id)}>
                    <td className="mono cell-strong" style={{ fontSize: 12.5 }}>{j.id}</td>
                    <td><div className="row" style={{ gap: 7 }}><span className="avatar avatar-sm" style={{ background: c.color, borderRadius: 6 }}>{c.short}</span>{c.short}</div></td>
                    <td>{j.type}</td><td className="num">{j.items}</td>
                    <td><StatusBadge status={j.stage} /></td>
                    <td>{j.tech ? <div className="row" style={{ gap: 6 }}><Avatar id={j.tech} size="sm" /><span style={{ fontSize: 12 }}>{DB.staffById(j.tech).name.split(' ')[0]}</span></div> : <span className="faint">Unassigned</span>}</td>
                    <td style={{ width: 90 }}><Bar pct={j.sla} color={j.sla > 85 ? 'var(--ok)' : j.sla > 50 ? 'var(--primary-600)' : 'var(--warn)'} /></td>
                    <td><span style={{ fontWeight: 600, color: j.due <= DB.TODAY ? 'var(--bad)' : 'var(--text)' }}>{DB.rel(j.due)}</span></td>
                    <td><Icon name="chevR" size={16} style={{ color: 'var(--text-3)' }} /></td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
      )}
      {recv && <FormModal title="Receive equipment & create job" sub="ADAM-QMS-L4-F-002 · receipt → assignment queue" icon="box" fields={[
        { label: 'Customer', type: 'select', options: DB.customers.map((c) => c.name) },
        { label: 'PO / contract ref.', type: 'text', placeholder: 'e.g. AMC-2026-PDO' },
        { label: 'Service type', type: 'select', options: ['Calibration', 'Bump test', 'Calibration + repair'] },
        { label: 'No. of items', type: 'number', placeholder: '1' },
        { label: 'Condition / accessories on receipt', type: 'textarea', full: true, placeholder: 'Physical condition, accessories returned…' },
      ]} submitLabel="Create job" onClose={() => setRecv(false)} onSubmit={() => { setRecv(false); window.toast('Job created · receipt acknowledgment issued'); }} wide />}
    </div>
  );
}

function JobCard({ job, onClick, accent }) {
  const c = window.DB.custById(job.customer);
  const pr = { High: 'bad', Normal: 'neutral', Low: 'neutral' }[job.priority];
  return (
    <div className="card hover-lift" style={{ padding: 12, cursor: 'pointer', borderRadius: 12, borderLeft: `3px solid ${accent}` }} onClick={onClick}>
      <div className="row" style={{ justifyContent: 'space-between' }}>
        <span className="mono cell-strong" style={{ fontSize: 12 }}>{job.id}</span>
        {job.priority === 'High' && <Badge kind="bad">High</Badge>}
      </div>
      <div className="row" style={{ gap: 7, marginTop: 9 }}>
        <span className="avatar avatar-sm" style={{ background: c.color, borderRadius: 6 }}>{c.short}</span>
        <span style={{ fontSize: 12.5, fontWeight: 600 }}>{c.name.split(' ').slice(0, 2).join(' ')}</span>
      </div>
      <div className="row" style={{ justifyContent: 'space-between', marginTop: 9 }}>
        <span className="tag">{job.type}</span>
        <span className="faint" style={{ fontSize: 11.5 }}>{job.items} items</span>
      </div>
      <div className="divider" style={{ margin: '10px 0' }} />
      <div className="row" style={{ justifyContent: 'space-between' }}>
        {job.tech ? <Avatar id={job.tech} size="sm" /> : <span className="tag" style={{ color: 'var(--text-3)' }}>Unassigned</span>}
        <span className="row" style={{ gap: 4, fontSize: 11.5, fontWeight: 600, color: job.due <= window.DB.TODAY ? 'var(--bad)' : 'var(--text-2)' }}>
          <Icon name="clock" size={12} />{window.DB.rel(job.due)}
        </span>
      </div>
    </div>
  );
}

/* =================== Job detail = gated worksheet ===================== */
function JobDetail({ jobId, onBack, onNav }) {
  const DB = window.DB;
  const job = DB.jobs.find((j) => j.id === jobId) || DB.jobs[1];
  const ws = DB.worksheet;
  const c = DB.custById(job.customer);
  const [signOpen, setSignOpen] = useState(false);
  const [phase, setPhase] = useState('review'); // review | issuing | issued
  const [tab, setTab] = useState('worksheet');

  const allPass = ws.testPoints.every((p) => p.pass);

  const doSign = () => { setSignOpen(false); setPhase('issuing'); };
  useEffect(() => {
    if (phase === 'issuing') { const t = setTimeout(() => setPhase('issued'), 3400); return () => clearTimeout(t); }
  }, [phase]);

  return (
    <div className="page page-wide rise">
      {/* breadcrumb / header */}
      <div className="row" style={{ gap: 10, marginBottom: 14, flexWrap: 'wrap' }}>
        <button className="icon-btn" onClick={onBack}><Icon name="chevL" size={17} /></button>
        <div style={{ minWidth: 0 }}>
          <div className="row" style={{ gap: 9, flexWrap: 'wrap' }}>
            <span className="h-page" style={{ fontSize: 20, whiteSpace: 'nowrap' }}>{job.id}</span>
            <StatusBadge status={phase === 'issued' ? 'Approved' : job.stage} />
            {job.priority === 'High' && <Badge kind="bad">High priority</Badge>}
          </div>
          <div className="h-sub">{c.name} · {job.items} items · {job.type} · received {DB.rel(job.recvd)}</div>
        </div>
        <span className="spacer" />
        <Btn icon="history" size="sm" onClick={() => window.toast('Full audit trail opened', 'info')}>Audit trail</Btn>
        <Btn icon="ext" size="sm" onClick={() => setTab('traceability')}>Traceability</Btn>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1fr 360px', gap: 16, alignItems: 'start' }}>
        {/* LEFT — worksheet */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
          {/* worksheet header card */}
          <div className="card">
            <div className="card-head">
              <Icon name="flask" size={17} style={{ color: 'var(--primary-600)' }} />
              <div>
                <div className="h-sec" style={{ fontSize: 14 }}>Worksheet {ws.id}</div>
                <div className="faint" style={{ fontSize: 11.5 }}>{ws.model} · S/N {ws.serial}</div>
              </div>
              <span className="spacer" />
              <Badge kind="info" icon="lock">Bound to {ws.method} {ws.methodRev}</Badge>
            </div>
            <div className="card-body" style={{ display: 'grid', gridTemplateColumns: 'repeat(4,1fr)', gap: 14 }}>
              {[['Monitor', ws.monitor], ['Method', `${ws.methodTitle}`], ['Technician', DB.staffById(ws.tech).name], ['Started', `Today · ${ws.started}`]].map(([k, v], i) => (
                <div key={i}><div className="eyebrow" style={{ fontSize: 10 }}>{k}</div><div style={{ fontSize: 13, fontWeight: 650, marginTop: 3 }}>{v}</div></div>
              ))}
            </div>
          </div>

          {/* tabs */}
          <div className="card">
            <div style={{ padding: '0 16px' }}>
              <div className="tabs">
                {['worksheet', 'assignment', 'readings', 'traceability'].map((t) => (
                  <div key={t} className={`tab${tab === t ? ' on' : ''}`} onClick={() => setTab(t)} style={{ textTransform: 'capitalize' }}>{t}</div>
                ))}
              </div>
            </div>

            {tab === 'worksheet' && (
              <div className="card-body" style={{ display: 'flex', flexDirection: 'column', gap: 11 }}>
                <div className="row" style={{ justifyContent: 'space-between' }}>
                  <div className="h-sec" style={{ fontSize: 13.5 }}>Standards-enforcement gates</div>
                  <Badge kind="ai" icon="sparkles">Enforced in flow</Badge>
                </div>
                {ws.gates.map((g) => <Gate key={g.key} gate={g} />)}
                <AINote title="Drift check — span reading trending down" clause="AIX-06">
                  H₂S span as-found 24.3 ppm vs historical mean 24.9 ±0.4. Within ±10% tolerance, but a slow downward drift is flagged for confirmation before submit.
                </AINote>
              </div>
            )}

            {tab === 'assignment' && <JobAssignment job={job} ws={ws} />}

            {tab === 'readings' && <WorksheetReadings ws={ws} />}

            {tab === 'traceability' && (
              <div className="card-body">
                <TraceChain ws={ws} />
              </div>
            )}
          </div>
        </div>

        {/* RIGHT — review / approve rail */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 16, position: 'sticky', top: 0 }}>
          {phase !== 'issued' ? (
            <div className="card">
              <div className="card-head"><Icon name="signature" size={16} style={{ color: 'var(--primary-600)' }} /><div className="h-sec" style={{ fontSize: 14 }}>Review &amp; approval</div></div>
              <div className="card-body" style={{ display: 'flex', flexDirection: 'column', gap: 13 }}>
                <div className="row" style={{ gap: 10 }}>
                  <Avatar id={ws.tech} />
                  <div style={{ flex: 1 }}><div style={{ fontSize: 12.5, fontWeight: 650 }}>{DB.staffById(ws.tech).name}</div><div className="faint" style={{ fontSize: 11 }}>Executed worksheet</div></div>
                  <Badge kind="ok" icon="check">Submitted</Badge>
                </div>
                <div style={{ height: 1, background: 'var(--border)' }} />
                <div className="row" style={{ gap: 10 }}>
                  <Avatar id="U-001" />
                  <div style={{ flex: 1 }}><div style={{ fontSize: 12.5, fontWeight: 650 }}>Ahmed Al Habsi</div><div className="faint" style={{ fontSize: 11 }}>Authorized signatory · independent</div></div>
                  <Badge kind="warn" dot>Pending</Badge>
                </div>
                <div className="ai-note" style={{ background: 'var(--info-bg)', border: '1px solid var(--primary-100)' }}>
                  <span className="ai-badge-ico" style={{ color: 'var(--primary-600)', borderColor: 'var(--primary-100)' }}><Icon name="check-shield" size={15} /></span>
                  <div style={{ fontSize: 11.5 }}><b>Segregation enforced.</b> Reviewer ≠ executing technician (ISO 17025 §7.7). One approval composes, numbers, renders, hashes &amp; publishes the certificate.</div>
                </div>
                <div className="col" style={{ gap: 8 }}>
                  <Btn variant="primary" size="lg" icon="signature" onClick={() => setSignOpen(true)} disabled={!allPass}>Approve &amp; e-sign</Btn>
                  <Btn variant="ghost" icon="x" onClick={() => window.toast('Returned to technician for rework', 'warn')}>Return for rework</Btn>
                </div>
              </div>
            </div>
          ) : (
            <IssuedCard onNav={onNav} />
          )}

          {/* per-stage turnaround / SLA (WFX-04) */}
          <StageTurnaround job={job} />

          {/* mini summary */}
          <div className="card card-pad">
            <div className="eyebrow" style={{ marginBottom: 10 }}>Job items · {job.items}</div>
            {[['Calibrated & passed', job.items - 1, 'ok'], ['Awaiting review', 1, 'warn']].map(([l, n, t], i) => (
              <div key={i} className="row" style={{ justifyContent: 'space-between', padding: '6px 0' }}>
                <span className="row" style={{ gap: 7, fontSize: 12.5 }}><span className="dot" style={{ width: 7, height: 7, borderRadius: '50%', background: t === 'ok' ? 'var(--ok)' : 'var(--warn)' }} />{l}</span>
                <b>{n}</b>
              </div>
            ))}
          </div>
        </div>
      </div>

      {signOpen && <SignModal onClose={() => setSignOpen(false)} onSign={doSign} ws={ws} />}
      {phase === 'issuing' && <IssuingOverlay />}
    </div>
  );
}

/* ---- Traceability chain ---- */
function TraceChain({ ws }) {
  const steps = [
    { ico: 'certificate', t: 'Result', s: `Worksheet ${ws.id}`, color: 'var(--primary-600)' },
    { ico: 'flask', t: 'Method', s: `${ws.method} ${ws.methodRev} · validated`, color: 'var(--ai)' },
    { ico: 'cylinder', t: 'Reference cylinder', s: 'CYL-2451 · H₂S 25 ppm · cert L-88241', color: 'var(--ok)' },
    { ico: 'gauge', t: 'Reference instrument', s: 'FLOW-001 rotameter · in-cal', color: 'var(--ok)' },
    { ico: 'shield', t: 'Issuing body', s: 'Air Products / BOC — national traceability', color: 'var(--warn)' },
  ];
  return (
    <div>
      <div className="row" style={{ justifyContent: 'space-between', marginBottom: 12 }}>
        <div className="h-sec" style={{ fontSize: 13.5 }}>Metrological traceability chain</div>
        <Badge kind="info">ISO 17025 §6.5</Badge>
      </div>
      <div style={{ position: 'relative', paddingLeft: 6 }}>
        {steps.map((st, i) => (
          <div key={i} className="row" style={{ gap: 13, alignItems: 'flex-start', paddingBottom: i < steps.length - 1 ? 16 : 0, position: 'relative' }}>
            {i < steps.length - 1 && <span style={{ position: 'absolute', left: 17, top: 34, bottom: 0, width: 2, background: 'var(--border-2)' }} />}
            <span style={{ width: 36, height: 36, borderRadius: 10, background: '#fff', border: `1.5px solid ${st.color}`, color: st.color, display: 'grid', placeItems: 'center', flex: 'none', zIndex: 1 }}><Icon name={st.ico} size={17} /></span>
            <div style={{ paddingTop: 3 }}><div style={{ fontWeight: 700, fontSize: 13 }}>{st.t}</div><div className="faint mono" style={{ fontSize: 11.5, marginTop: 1 }}>{st.s}</div></div>
            <Icon name="link" size={14} style={{ color: 'var(--text-3)', marginLeft: 'auto', marginTop: 11 }} />
          </div>
        ))}
      </div>
    </div>
  );
}

/* ---- e-sign modal ---- */
function SignModal({ onClose, onSign, ws }) {
  const [pin, setPin] = useState('');
  return (
    <React.Fragment>
      <div className="scrim" onClick={onClose} />
      <div className="modal">
        <div style={{ padding: '20px 24px', borderBottom: '1px solid var(--border)' }} className="row">
          <span className="kpi-ico" style={{ background: 'var(--primary-50)', color: 'var(--primary-600)', width: 36, height: 36 }}><Icon name="signature" size={18} /></span>
          <div><div style={{ fontWeight: 750, fontSize: 16 }}>Authorize &amp; e-sign certificate</div><div className="faint" style={{ fontSize: 12 }}>ISO 17025 §7.8 · authorized signatory only</div></div>
          <span className="spacer" /><button className="icon-btn" onClick={onClose}><Icon name="x" size={17} /></button>
        </div>
        <div style={{ padding: 24 }}>
          <div className="card" style={{ background: 'var(--surface-2)', padding: 14, marginBottom: 16 }}>
            <div className="row" style={{ justifyContent: 'space-between', marginBottom: 8 }}><span className="faint" style={{ fontSize: 12 }}>Monitor</span><b style={{ fontSize: 12.5 }}>{ws.model} · {ws.serial}</b></div>
            <div className="row" style={{ justifyContent: 'space-between', marginBottom: 8 }}><span className="faint" style={{ fontSize: 12 }}>Method</span><b style={{ fontSize: 12.5 }}>{ws.method} {ws.methodRev}</b></div>
            <div className="row" style={{ justifyContent: 'space-between', marginBottom: 8 }}><span className="faint" style={{ fontSize: 12 }}>Result</span><Badge kind="ok" icon="check">Pass · all test points</Badge></div>
            <div className="row" style={{ justifyContent: 'space-between' }}><span className="faint" style={{ fontSize: 12 }}>Uncertainty</span><b className="mono" style={{ fontSize: 12.5 }}>±0.62 ppm (k=2)</b></div>
          </div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 9 }}>
            {['I confirm independent review of the results and worksheet.', 'I am the authorized signatory for this method & scope.'].map((t, i) => (
              <label key={i} className="row" style={{ gap: 9, fontSize: 12.5, cursor: 'pointer' }}>
                <span style={{ width: 18, height: 18, borderRadius: 5, background: 'var(--ok)', display: 'grid', placeItems: 'center', flex: 'none' }}><Icon name="check" size={12} style={{ color: '#fff' }} /></span>{t}
              </label>
            ))}
          </div>
          <label className="eyebrow" style={{ fontSize: 10.5, display: 'block', margin: '16px 0 5px' }}>Re-authenticate · signing PIN</label>
          <div className="searchbox" style={{ width: '100%', cursor: 'text' }}>
            <Icon name="lock" size={15} />
            <input type="password" value={pin} onChange={(e) => setPin(e.target.value)} placeholder="••••••" autoFocus />
          </div>
          <div className="row" style={{ gap: 10, marginTop: 20 }}>
            <Btn variant="ghost" onClick={onClose} style={{ flex: 1 }}>Cancel</Btn>
            <Btn variant="primary" icon="signature" onClick={onSign} style={{ flex: 2 }}>Sign &amp; issue certificate</Btn>
          </div>
        </div>
      </div>
    </React.Fragment>
  );
}

/* ---- issuance overlay (the one-action chain) ---- */
function IssuingOverlay() {
  const steps = ['Compose from approved worksheet', 'Assign certificate number', 'Render on controlled template', 'Hash & tamper-protect', 'Archive (retention)', 'Publish to portal & email'];
  const [done, setDone] = useState(0);
  useEffect(() => { const t = setInterval(() => setDone((d) => Math.min(d + 1, steps.length)), 480); return () => clearInterval(t); }, []);
  return (
    <React.Fragment>
      <div className="scrim" style={{ background: 'rgba(11,26,46,.6)' }} />
      <div className="modal" style={{ width: 460, padding: 28, textAlign: 'center' }}>
        <div style={{ width: 56, height: 56, borderRadius: 16, background: 'var(--primary-50)', color: 'var(--primary-600)', display: 'grid', placeItems: 'center', margin: '0 auto 14px' }}>
          <Icon name="certificate" size={28} />
        </div>
        <div style={{ fontWeight: 800, fontSize: 18, letterSpacing: '-.3px' }}>Issuing certificate</div>
        <div className="faint" style={{ fontSize: 12.5, marginBottom: 20 }}>One approval — the whole chain, no manual steps</div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 9, textAlign: 'left' }}>
          {steps.map((s, i) => (
            <div key={i} className="row" style={{ gap: 11, opacity: i <= done ? 1 : .4, transition: 'opacity .3s' }}>
              <span style={{ width: 24, height: 24, borderRadius: '50%', flex: 'none', display: 'grid', placeItems: 'center', background: i < done ? 'var(--ok)' : i === done ? 'var(--primary-600)' : '#eef1f6', color: i <= done ? '#fff' : 'var(--text-3)' }}>
                {i < done ? <Icon name="check" size={13} /> : i === done ? <span className="spin" style={{ width: 12, height: 12, border: '2px solid rgba(255,255,255,.4)', borderTopColor: '#fff', borderRadius: '50%' }} /> : <span style={{ fontSize: 10 }}>{i + 1}</span>}
              </span>
              <span style={{ fontSize: 13, fontWeight: i === done ? 700 : 500 }}>{s}</span>
            </div>
          ))}
        </div>
      </div>
      <style>{`@keyframes spin{to{transform:rotate(360deg)}}.spin{animation:spin .7s linear infinite}`}</style>
    </React.Fragment>
  );
}

/* ---- issued success card ---- */
function IssuedCard({ onNav }) {
  return (
    <div className="card" style={{ borderColor: 'var(--ok-line)', overflow: 'hidden' }}>
      <div style={{ background: 'linear-gradient(120deg, var(--ok-bg), #fff)', padding: '18px 18px 14px', textAlign: 'center' }}>
        <div style={{ width: 48, height: 48, borderRadius: 14, background: 'var(--ok)', color: '#fff', display: 'grid', placeItems: 'center', margin: '0 auto 10px', boxShadow: '0 4px 14px rgba(21,160,107,.4)' }}><Icon name="check" size={26} /></div>
        <div style={{ fontWeight: 800, fontSize: 16 }}>Certificate issued</div>
        <div className="faint" style={{ fontSize: 12 }}>Published to portal · emailed · attached to dispatch</div>
      </div>
      <div className="card-body" style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
        <div className="row" style={{ justifyContent: 'space-between' }}><span className="faint" style={{ fontSize: 12 }}>Certificate №</span><b className="mono">ADAM-CAL-26-04189</b></div>
        <div className="row" style={{ justifyContent: 'space-between' }}><span className="faint" style={{ fontSize: 12 }}>Status</span><Badge kind="ok" dot>Valid · verifiable</Badge></div>
        <div className="row" style={{ gap: 10, padding: '8px 0' }}>
          <QRBox />
          <div style={{ fontSize: 11.5, color: 'var(--text-2)' }}>Tamper-evident QR resolves to a public verification page returning <b>Valid / Superseded / Withdrawn</b> — without exposing other customer data.</div>
        </div>
        <Btn variant="primary" icon="certificate" onClick={() => onNav('certs')}>View certificate</Btn>
        <Btn variant="ghost" icon="truck" onClick={() => window.toast('Equipment dispatched · job closed · due-date surveillance on')}>Dispatch &amp; close job</Btn>
      </div>
    </div>
  );
}

function QRBox({ size = 66 }) {
  // deterministic pseudo-QR
  const n = 11; const cells = [];
  let s = 7;
  for (let y = 0; y < n; y++) for (let x = 0; x < n; x++) { s = (s * 48271) % 2147483647; const on = (s % 100) > 52; const corner = (x < 3 && y < 3) || (x > n - 4 && y < 3) || (x < 3 && y > n - 4); cells.push(corner || on); }
  return (
    <div style={{ width: size, height: size, flex: 'none', background: '#fff', border: '1px solid var(--border)', borderRadius: 8, padding: 5, display: 'grid', gridTemplateColumns: `repeat(${n},1fr)`, gap: 0 }}>
      {cells.map((on, i) => <span key={i} style={{ background: on ? 'var(--ink)' : 'transparent' }} />)}
    </div>
  );
}

/* =================== Job assignment — team + tasks ==================== */
const GRANT_META = { S: ['Sign', 'ai'], R: ['Review', 'info'], E: ['Execute', 'ok'], '-': ['Not authorized', 'bad'] };
function grantFor(uid, method) {
  const row = (window.DB.competency || []).find((c) => c.staff === uid);
  return (row && row.grants[method]) || '-';
}
function pickAssignees(job, ws) {
  const DB = window.DB;
  const method = ws.method;
  const techId = job.tech || ws.tech;
  const can = (lvls, exclude) => (DB.competency || [])
    .filter((c) => lvls.includes(c.grants[method]) && !exclude.includes(c.staff))
    .map((c) => c.staff);
  const reviewer = can(['R', 'S'], [techId])[0] || 'U-002';
  const signatory = can(['S'], [techId, reviewer])[0] || can(['S'], [techId])[0] || 'U-001';
  // a second execute-capable technician (never the reviewer/signatory) for shared items
  const coTech = can(['E', 'R', 'S'], [techId, reviewer, signatory])[0] || techId;
  return { techId, reviewer, signatory, planner: 'U-007', coTech };
}
function JobAssignment({ job, ws }) {
  const DB = window.DB;
  const { techId, reviewer, signatory, planner, coTech } = pickAssignees(job, ws);
  const [reassign, setReassign] = useState(false);
  const curIdx = DB.stages.indexOf(job.stage);

  const team = [
    { uid: techId, hat: 'Calibration technician', need: 'E', sub: 'Executes the worksheet · records readings' },
    { uid: reviewer, hat: 'Independent reviewer', need: 'R', sub: 'Checks results · must differ from executor (§7.7)' },
    { uid: signatory, hat: 'Authorized signatory', need: 'S', sub: 'Approves & e-signs the certificate (§7.8)' },
    { uid: planner, hat: 'Lab manager', need: 'plan', sub: 'Receipt, assignment & dispatch' },
  ];

  // per-stage task list assigned to people
  const tasks = [
    { name: 'Equipment receipt & condition record', uid: planner, atStage: 0, ref: 'ADAM-QMS-L4-F-002' },
    { name: 'Assign job & verify competency', uid: planner, atStage: 1, ref: 'ISO 17025 §6.2' },
    { name: 'Method & standards validity gate', uid: techId, atStage: 2, ref: '§6.4 / 6.5' },
    { name: `Calibrate & functional checks · ${job.items} item${job.items > 1 ? 's' : ''}`, uid: techId, atStage: 2, ref: ws.methodTitle },
    { name: 'Independent review', uid: reviewer, atStage: 3, ref: '§7.7' },
    { name: 'Approve & e-sign certificate', uid: signatory, atStage: 4, ref: '§7.8' },
    { name: 'Dispatch & close job', uid: planner, atStage: 5, ref: 'one-action issuance' },
  ];
  const statusOf = (s) => curIdx > s ? 'done' : curIdx === s ? 'active' : 'pending';

  // per-item allocation (synthesised for the demo)
  const items = Array.from({ length: job.items }, (_, i) => {
    const n = i + 1;
    const itemTech = i % 3 === 2 ? coTech : techId; // a couple shared to a second technician
    const st = curIdx >= 4 ? 'Done' : curIdx >= 3 ? (i === job.items - 1 ? 'In review' : 'Done')
      : curIdx >= 2 ? (i < Math.ceil(job.items / 2) ? 'Done' : i === Math.ceil(job.items / 2) ? 'In progress' : 'Queued')
      : 'Queued';
    return { sn: `${job.id.split('-').slice(-1)[0]}-${String(n).padStart(2, '0')}`, tech: itemTech, st };
  });
  const itemTone = { Done: 'ok', 'In progress': 'warn', 'In review': 'info', Queued: 'neutral' };

  return (
    <div className="card-body" style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
      {/* ---- assigned team ---- */}
      <div>
        <div className="row" style={{ justifyContent: 'space-between', marginBottom: 10 }}>
          <div className="row" style={{ gap: 7 }}><Icon name="users" size={15} style={{ color: 'var(--primary-600)' }} /><span className="h-sec" style={{ fontSize: 13.5 }}>Assigned team</span></div>
          <Btn size="sm" variant="ghost" icon="users" onClick={() => setReassign(true)}>Reassign</Btn>
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2,1fr)', gap: 10 }}>
          {team.map((m, i) => {
            const s = DB.staffById(m.uid);
            const g = m.need === 'plan' ? null : grantFor(m.uid, ws.method);
            const gm = g ? GRANT_META[g] : null;
            const ok = m.need === 'plan' || g === m.need || (m.need === 'R' && g === 'S') || (m.need === 'E' && (g === 'R' || g === 'S'));
            return (
              <div key={i} style={{ border: '1px solid var(--border)', borderRadius: 11, padding: '12px 13px' }}>
                <div className="eyebrow" style={{ fontSize: 9 }}>{m.hat}</div>
                <div className="row" style={{ gap: 9, marginTop: 8 }}>
                  <Avatar id={m.uid} />
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontSize: 13, fontWeight: 700 }}>{s.name}</div>
                    <div className="faint" style={{ fontSize: 11 }}>{s.role}</div>
                  </div>
                  {m.need === 'plan'
                    ? <Badge kind="neutral">Coordinator</Badge>
                    : <Badge kind={ok ? gm[1] : 'bad'} icon={ok ? 'check-shield' : 'alert'}>{ok ? `Authorized · ${gm[0]}` : 'Gate fail'}</Badge>}
                </div>
                <div className="faint" style={{ fontSize: 11, marginTop: 8 }}>{m.sub}</div>
                {m.need !== 'plan' && <div className="mono faint" style={{ fontSize: 10.5, marginTop: 4 }}>{ws.method} grant: {g} · valid</div>}
              </div>
            );
          })}
        </div>
        <div className="ai-note" style={{ marginTop: 10, background: 'var(--info-bg)', border: '1px solid var(--primary-100)' }}>
          <span className="ai-badge-ico" style={{ color: 'var(--primary-600)', borderColor: 'var(--primary-100)' }}><Icon name="check-shield" size={15} /></span>
          <div style={{ fontSize: 11.5 }}><b>Competency gate (ISO 17025 §6.2).</b> Only staff authorized for <b>{ws.method}</b> can be assigned. Execute, review and sign are separate grants — the same person can never review or sign their own work.</div>
        </div>
      </div>

      {/* ---- task assignment / checklist ---- */}
      <div>
        <div className="row" style={{ gap: 7, marginBottom: 4 }}><Icon name="check-circle" size={15} style={{ color: 'var(--primary-600)' }} /><span className="h-sec" style={{ fontSize: 13.5 }}>Tasks &amp; responsibilities</span><span className="faint" style={{ fontSize: 11, marginLeft: 6 }}>— each step is owned by a named person</span></div>
        <div>
          {tasks.map((t, i) => {
            const st = statusOf(t.atStage);
            const s = DB.staffById(t.uid);
            const tone = st === 'done' ? 'ok' : st === 'active' ? 'warn' : 'neutral';
            return (
              <div key={i} className="row" style={{ gap: 11, padding: '11px 2px', borderBottom: i < tasks.length - 1 ? '1px solid var(--border)' : 'none', alignItems: 'center' }}>
                <span style={{ width: 26, height: 26, borderRadius: '50%', flex: 'none', display: 'grid', placeItems: 'center',
                  background: st === 'done' ? 'var(--ok)' : st === 'active' ? 'var(--warn-bg)' : '#eef1f6',
                  color: st === 'done' ? '#fff' : st === 'active' ? 'var(--warn)' : 'var(--text-3)' }}>
                  {st === 'done' ? <Icon name="check" size={14} /> : st === 'active' ? <span className="spin" style={{ width: 11, height: 11, border: '2px solid var(--warn)', borderTopColor: 'transparent', borderRadius: '50%' }} /> : <span style={{ fontSize: 10, fontWeight: 700 }}>{i + 1}</span>}
                </span>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 12.5, fontWeight: 650 }}>{t.name}</div>
                  <div className="faint mono" style={{ fontSize: 10.5, marginTop: 1 }}>{t.ref}</div>
                </div>
                <div className="row" style={{ gap: 7, width: 150, flex: 'none' }}>
                  <Avatar id={t.uid} size="sm" />
                  <span style={{ fontSize: 11.5, fontWeight: 600 }}>{s.name.split(' ')[0]} {s.name.split(' ')[1] ? s.name.split(' ')[1][0] + '.' : ''}</span>
                </div>
                <Badge kind={tone} dot={st !== 'done'}>{st === 'done' ? 'Done' : st === 'active' ? 'In progress' : 'Pending'}</Badge>
              </div>
            );
          })}
        </div>
      </div>

      {/* ---- per-item allocation ---- */}
      <div>
        <div className="row" style={{ gap: 7, marginBottom: 8 }}><Icon name="box" size={15} style={{ color: 'var(--primary-600)' }} /><span className="h-sec" style={{ fontSize: 13.5 }}>Per-item allocation</span></div>
        <table className="tbl">
          <thead><tr><th>Item / asset</th><th>Assigned technician</th><th>Status</th></tr></thead>
          <tbody>
            {items.map((it, i) => {
              const s = DB.staffById(it.tech);
              return (
                <tr key={i}>
                  <td className="mono cell-strong" style={{ fontSize: 12 }}>{ws.model.split(' ')[0]}-{it.sn}</td>
                  <td><div className="row" style={{ gap: 7 }}><Avatar id={it.tech} size="sm" /><span style={{ fontSize: 12 }}>{s.name}</span></div></td>
                  <td><Badge kind={itemTone[it.st]} dot={it.st !== 'Done'}>{it.st}</Badge></td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>

      {reassign && <FormModal title="Reassign job" sub={`${job.id} · competency-gated to ${ws.method}`} icon="users" fields={[
        { label: 'Calibration technician', type: 'select', options: DB.staff.filter((s) => ['E', 'R', 'S'].includes(grantFor(s.id, ws.method))).map((s) => `${s.name} · ${GRANT_META[grantFor(s.id, ws.method)][0]}`) },
        { label: 'Independent reviewer', type: 'select', options: DB.staff.filter((s) => ['R', 'S'].includes(grantFor(s.id, ws.method))).map((s) => s.name) },
        { label: 'Authorized signatory', type: 'select', options: DB.staff.filter((s) => grantFor(s.id, ws.method) === 'S').map((s) => s.name) },
        { label: 'Target completion', type: 'date' },
        { label: 'Note to team', type: 'textarea', full: true, placeholder: 'Optional handover note…' },
      ]} submitLabel="Reassign & notify" onClose={() => setReassign(false)} onSubmit={() => { setReassign(false); window.toast('Job reassigned · team notified · audit-logged'); }} wide />}
    </div>
  );
}

/* =================== Per-stage turnaround / SLA (WFX-04) ============= */
function StageTurnaround({ job }) {
  const DB = window.DB;
  const curIdx = DB.stages.indexOf(job.stage);
  // representative durations (hours) per stage transition + SLA target
  const rows = [
    { from: 'Received', to: 'Assigned', actual: 3, target: 4 },
    { from: 'Assigned', to: 'In progress', actual: 6, target: 8 },
    { from: 'In progress', to: 'Review', actual: 30, target: 36 },
    { from: 'Review', to: 'Approved', actual: 11, target: 8 }, // SLA breach example
    { from: 'Approved', to: 'Dispatched', actual: 2, target: 4 },
  ];
  const fmtH = (h) => h >= 24 ? +(h / 24).toFixed(1) + 'd' : h + 'h';
  let total = 0;
  let breached = false;
  return (
    <div className="card">
      <div className="card-head">
        <Icon name="clock" size={15} style={{ color: 'var(--primary-600)' }} />
        <div className="h-sec" style={{ fontSize: 13.5 }}>Turnaround by stage</div>
        <span className="spacer" />
        <Badge kind="info">WFX-04</Badge>
      </div>
      <div className="card-body" style={{ paddingTop: 4 }}>
        {rows.map((r, i) => {
          const done = curIdx > i;
          const active = curIdx === i;
          const breach = done && r.actual > r.target;
          if (done) total += r.actual;
          if (breach) breached = true;
          return (
            <div key={i} className="row" style={{ justifyContent: 'space-between', padding: '7px 0', borderBottom: i < rows.length - 1 ? '1px solid var(--border)' : 'none' }}>
              <span className="row" style={{ gap: 8, fontSize: 12 }}>
                <span style={{ width: 7, height: 7, borderRadius: '50%', flex: 'none', background: done ? (breach ? 'var(--bad)' : 'var(--ok)') : active ? 'var(--warn)' : 'var(--border-2)' }} />
                <span style={{ color: done ? 'var(--text)' : 'var(--text-3)' }}>{r.from} → {r.to}</span>
              </span>
              <span className="row" style={{ gap: 7 }}>
                <span className="mono" style={{ fontSize: 11.5, color: breach ? 'var(--bad)' : done ? 'var(--text-2)' : 'var(--text-3)' }}>{done ? fmtH(r.actual) : active ? 'running…' : '—'}</span>
                <span className="faint mono" style={{ fontSize: 10.5 }}>/ {fmtH(r.target)}</span>
                {breach && <Badge kind="bad">SLA</Badge>}
              </span>
            </div>
          );
        })}
        <div className="row" style={{ justifyContent: 'space-between', marginTop: 10, paddingTop: 10, borderTop: '2px solid var(--ink)' }}>
          <b style={{ fontSize: 12.5 }}>Total turnaround</b>
          <b className="mono" style={{ fontSize: 13 }}>{fmtH(total || 0)}{curIdx < DB.stages.length - 1 ? ' · so far' : ''}</b>
        </div>
        {breached && <div className="faint" style={{ fontSize: 11, marginTop: 8, color: 'var(--bad)' }}><Icon name="alert" size={11} /> One stage exceeded its SLA — surfaced on the operations dashboard.</div>}
      </div>
    </div>
  );
}

Object.assign(window, { JobsModule, QRBox, TraceChain, JobAssignment, StageTurnaround });

/* =================== Editable worksheet readings ===================== */
const GAS_SETS = {
  h2s: { label: 'Single-gas H₂S', method: 'CAL-MD-011 Rev 2', mu: '±0.62 ppm', rows: [
    { point: 'Fresh Air Zero', applied: '0 ppm', expected: 0, unit: 'ppm', tol: 2, init: 0.0 },
    { point: 'Span Check', applied: '25 ppm H₂S', expected: 25, unit: 'ppm', tolPct: 10, init: 24.3 },
  ], alarms: [['Low Alarm Test', '10 ppm'], ['High Alarm Test', '15 ppm']] },
  multi: { label: 'Multi-gas (LEL/O₂/CO/H₂S)', method: 'CAL-MD-014 Rev 4', mu: '±0.6 ppm', rows: [
    { point: 'LEL', applied: '50 %LEL', expected: 50, unit: '%LEL', tolPct: 5, init: 49 },
    { point: 'Oxygen (O₂)', applied: '20.9 %vol', expected: 20.9, unit: '%vol', tol: 0.5, init: 20.9 },
    { point: 'Carbon Monoxide (CO)', applied: '50 ppm', expected: 50, unit: 'ppm', tolPct: 10, init: 48 },
    { point: 'Hydrogen Sulphide (H₂S)', applied: '25 ppm', expected: 25, unit: 'ppm', tolPct: 10, init: 24.6 },
  ], alarms: [['Alarm Test', 'Set-points']] },
};
function evalRow(r, val) {
  const tol = r.tol != null ? r.tol : (r.tolPct / 100) * r.expected;
  return Math.abs(val - r.expected) <= tol + 1e-9;
}
function WorksheetReadings({ ws }) {
  const DB = window.DB;
  const [set, setSet] = useState('h2s');
  const cfg = GAS_SETS[set];
  const [vals, setVals] = useState({});
  const [alarms, setAlarms] = useState({});
  const [funcs, setFuncs] = useState({});
  const [witness, setWitness] = useState(false);
  const [wname, setWname] = useState('');
  // reset when set changes
  useEffect(() => {
    const v = {}; cfg.rows.forEach((r) => { v[r.point] = r.init; }); setVals(v);
    const a = {}; cfg.alarms.forEach(([n]) => { a[n] = true; }); setAlarms(a);
    const f = {}; ws.functional.forEach((x) => { f[x.item] = true; }); setFuncs(f);
  }, [set]);
  const rowPass = (r) => { const v = vals[r.point]; return v !== '' && v != null && !isNaN(v) && evalRow(r, +v); };
  const allMeasPass = cfg.rows.every(rowPass);
  const allAlarms = cfg.alarms.every(([n]) => alarms[n]);
  const allFuncs = ws.functional.every((x) => funcs[x.item]);
  const overall = allMeasPass && allAlarms && allFuncs;

  return (
    <div>
      <div className="card-body" style={{ display: 'flex', alignItems: 'center', gap: 12, borderBottom: '1px solid var(--border)' }}>
        <span className="eyebrow" style={{ fontSize: 9.5 }}>Sensor set</span>
        <div className="seg">{Object.entries(GAS_SETS).map(([k, c]) => <button key={k} className={set === k ? 'on' : ''} onClick={() => setSet(k)}>{c.label}</button>)}</div>
        <span className="spacer" />
        <span className="tag"><Icon name="lock" size={11} />{cfg.method}</span>
        <Badge kind="ai" icon="sparkles">Live evaluation</Badge>
      </div>
      <div className="card-body" style={{ display: 'grid', gridTemplateColumns: 'repeat(4,1fr)', gap: '13px 16px', borderBottom: '1px solid var(--border)' }}>
        {[['Sensor type', set === 'h2s' ? 'H₂S' : 'LEL/O₂/CO/H₂S'], ['Calibration gas', set === 'h2s' ? '25 ppm H₂S' : '4-gas mix'], ['Cylinder', set === 'h2s' ? 'CYL-2451' : 'CYL-2453'], ['Ambient', `${ws.env.temp} °C / ${ws.env.rh} %RH`]].map(([k, v], i) => (
          <div key={i}><div className="eyebrow" style={{ fontSize: 9.5 }}>{k}</div><div style={{ fontSize: 12.5, fontWeight: 650, marginTop: 3 }}>{v}</div></div>
        ))}
      </div>

      <div className="row" style={{ padding: '13px 18px 4px' }}><Icon name="flask" size={14} style={{ color: 'var(--primary-600)' }} /><span className="h-sec" style={{ fontSize: 13 }}>Calibration results</span><span className="faint" style={{ fontSize: 11, marginLeft: 8 }}>— enter the as-found reading; pass/fail computes live</span></div>
      <table className="tbl">
        <thead><tr><th>Test point</th><th>Applied</th><th>Expected</th><th>Actual reading</th><th>Tolerance</th><th>Result</th></tr></thead>
        <tbody>
          {cfg.rows.map((r) => {
            const pass = rowPass(r);
            const tolTxt = r.tol != null ? `±${r.tol} ${r.unit}` : `±${r.tolPct}%`;
            return (
              <tr key={r.point}>
                <td className="cell-strong" style={{ fontSize: 12.5 }}>{r.point}</td>
                <td className="mono" style={{ fontSize: 12 }}>{r.applied}</td>
                <td className="mono faint" style={{ fontSize: 12 }}>{r.expected} {r.unit}</td>
                <td><input type="number" step="0.1" value={vals[r.point] ?? ''} onChange={(e) => setVals((s) => ({ ...s, [r.point]: e.target.value }))}
                  style={{ width: 92, fontFamily: 'var(--mono)', fontSize: 12.5, padding: '5px 8px', borderRadius: 7, border: `1.5px solid ${pass ? 'var(--ok-line)' : 'var(--bad-line)'}`, background: pass ? 'var(--ok-bg)' : 'var(--bad-bg)', outline: 'none' }} /> <span className="faint" style={{ fontSize: 11 }}>{r.unit}</span></td>
                <td className="mono faint" style={{ fontSize: 12 }}>{tolTxt}</td>
                <td>{pass ? <Badge kind="ok" icon="check">Pass</Badge> : <Badge kind="bad" icon="x">Out of tol.</Badge>}</td>
              </tr>
            );
          })}
          {cfg.alarms.map(([n, sp]) => (
            <tr key={n}>
              <td className="cell-strong" style={{ fontSize: 12.5 }}>{n}</td>
              <td className="mono" style={{ fontSize: 12 }}>{sp}</td><td className="faint" colSpan="2" style={{ fontSize: 11.5 }}>Audible · visual · vibration alarm activation</td>
              <td className="faint mono" style={{ fontSize: 12 }}>N/A</td>
              <td><button className={`badge ${alarms[n] ? 'b-ok' : 'b-neutral'}`} style={{ cursor: 'pointer', border: 'none' }} onClick={() => setAlarms((s) => ({ ...s, [n]: !s[n] }))}>{alarms[n] ? <React.Fragment><Icon name="check" size={12} />Activated</React.Fragment> : 'Mark activated'}</button></td>
            </tr>
          ))}
        </tbody>
      </table>

      <div className="row" style={{ padding: '14px 18px 8px' }}><Icon name="check-shield" size={14} style={{ color: 'var(--primary-600)' }} /><span className="h-sec" style={{ fontSize: 13 }}>Functional checks</span></div>
      <div className="card-body" style={{ paddingTop: 0, display: 'grid', gridTemplateColumns: 'repeat(5,1fr)', gap: 9 }}>
        {ws.functional.map((f) => {
          const ok = funcs[f.item];
          return (
            <div key={f.item} onClick={() => setFuncs((s) => ({ ...s, [f.item]: !s[f.item] }))} style={{ cursor: 'pointer', border: `1px solid ${ok ? 'var(--ok-line)' : 'var(--border-2)'}`, borderRadius: 10, padding: '10px 11px', background: ok ? 'var(--ok-bg)' : 'var(--surface-2)' }}>
              <div className="row" style={{ justifyContent: 'space-between' }}><span style={{ fontSize: 11.5, fontWeight: 650 }}>{f.item}</span><Icon name={ok ? 'check-circle' : 'x-circle'} size={15} style={{ color: ok ? 'var(--ok)' : 'var(--text-3)' }} /></div>
              <div className="faint" style={{ fontSize: 10.5, marginTop: 4 }}>{ok ? (f.remark || 'OK') : 'Tap to mark OK'}</div>
            </div>
          );
        })}
      </div>

      {/* customer-witnessed calibration (WFX-06) */}
      <div className="card-body" style={{ borderTop: '1px solid var(--border)' }}>
        <label className="row" style={{ gap: 9, cursor: 'pointer' }} onClick={() => setWitness((w) => !w)}>
          <span style={{ width: 18, height: 18, borderRadius: 5, flex: 'none', border: `1.5px solid ${witness ? 'var(--ok)' : 'var(--border-2)'}`, background: witness ? 'var(--ok)' : '#fff', display: 'grid', placeItems: 'center' }}>{witness && <Icon name="check" size={12} style={{ color: '#fff' }} />}</span>
          <span style={{ fontSize: 12.5, fontWeight: 650 }}>Calibration witnessed by customer representative <span className="faint" style={{ fontWeight: 400 }}>· optional (WFX-06)</span></span>
        </label>
        {witness && (
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16, marginTop: 12 }}>
            <div>
              <div className="eyebrow" style={{ fontSize: 9.5 }}>Witness name &amp; designation</div>
              <input value={wname} onChange={(e) => setWname(e.target.value)} placeholder="e.g. H. Al Rashdi · HSE Officer" style={{ width: '100%', marginTop: 5, fontFamily: 'inherit', fontSize: 12.5, padding: '7px 10px', borderRadius: 8, border: '1.5px solid var(--border-2)', outline: 'none', boxSizing: 'border-box' }} />
            </div>
            <div>
              <div className="eyebrow" style={{ fontSize: 9.5 }}>Signature</div>
              <div style={{ marginTop: 5, height: 34, borderBottom: '1px solid var(--border-2)', display: 'flex', alignItems: 'flex-end', paddingBottom: 4 }}>
                <span style={{ fontFamily: 'cursive', color: 'var(--primary-700)', opacity: wname ? .8 : .4, fontSize: 15 }}>{wname ? '✒ ' + wname.split(' ')[0] : 'signed on collection'}</span>
              </div>
            </div>
          </div>
        )}
      </div>

      <div className="card-body" style={{ borderTop: '1px solid var(--border)' }}>
        <div className="row" style={{ justifyContent: 'space-between', padding: '4px 2px 12px' }}>
          <div className="row" style={{ gap: 10 }}>
            <span className="kpi-ico" style={{ width: 34, height: 34, background: overall ? 'var(--ok-bg)' : 'var(--warn-bg)', color: overall ? 'var(--ok)' : 'var(--warn)' }}><Icon name={overall ? 'check-circle' : 'alert'} size={18} /></span>
            <div><div style={{ fontWeight: 750, fontSize: 14 }}>Computed result: {overall ? 'PASS' : 'Review needed'}</div><div className="faint" style={{ fontSize: 11.5 }}>Expanded uncertainty {cfg.mu} (k=2) · decision rule: simple acceptance</div></div>
          </div>
          <span className="badge b-ai" style={{ fontSize: 11.5 }}><Icon name="sparkles" size={12} />AI drift check {overall ? 'clear' : 'flagged'}</span>
        </div>
        <AINote title={overall ? 'All test points within method acceptance criteria' : 'One or more readings outside tolerance'} clause="§7.6">
          {overall ? 'Result computes to Pass. Expanded uncertainty is attached from the method budget; submit locks the worksheet for independent review.' : 'Adjust the instrument and record as-left values, or record a fail result and raise an NCR — the worksheet cannot pass review while out of tolerance.'}
        </AINote>
      </div>
    </div>
  );
}
