/* =====================================================================
   AI-COS — ISO 17025 Technical Management cockpit
   ===================================================================== */
function ISOModule({ onNav }) {
  const DB = window.DB;
  const [tab, setTab] = useState('methods');
  const tabs = [['methods', 'Method control'], ['mu', 'Uncertainty budgets'], ['pt', 'Proficiency testing'], ['env', 'Environment'], ['trace', 'Traceability']];

  return (
    <div className="page page-wide rise">
      <div className="row" style={{ justifyContent: 'space-between', alignItems: 'flex-end', marginBottom: 16 }}>
        <div>
          <div className="h-page">ISO/IEC 17025 Technical Management</div>
          <div className="h-sub">Accreditation requirements made executable — methods, uncertainty, PT, environment &amp; traceability gate the workflow</div>
        </div>
        <Badge kind="ok" icon="shield">Compliant · last assessment passed</Badge>
      </div>

      <div className="tabs" style={{ marginBottom: 18 }}>
        {tabs.map(([id, label]) => <div key={id} className={`tab${tab === id ? ' on' : ''}`} onClick={() => setTab(id)}>{label}</div>)}
      </div>

      {tab === 'methods' && <MethodsTab />}
      {tab === 'mu' && <UncertaintyTab />}
      {tab === 'pt' && <PTTab onNav={onNav} />}
      {tab === 'env' && <EnvTab />}
      {tab === 'trace' && <div className="card card-pad" style={{ maxWidth: 640 }}><TraceChain ws={{ id: 'CL-CAL-26-04188', method: 'CAL-MD-014', methodRev: 'Rev 4' }} /></div>}
    </div>
  );
}

function MethodsTab() {
  const DB = window.DB;
  return (
    <div style={{ display: 'grid', gridTemplateColumns: '1fr 320px', gap: 16, alignItems: 'start' }}>
      <div className="card">
        <div className="card-head"><Icon name="flask" size={16} style={{ color: 'var(--primary-600)' }} /><div className="h-sec" style={{ fontSize: 14 }}>Controlled calibration methods</div><span className="spacer" /><Btn variant="primary" icon="plus" size="sm" onClick={() => window.openForm({ title: 'New calibration method', sub: 'Drafted as controlled document; needs validation (LAB-01)', icon: 'flask', fields: [{ label: 'Method code', type: 'text', placeholder: 'CAL-MD-0XX' }, { label: 'Title', type: 'text', full: true }, { label: 'Points', type: 'select', options: ['2-point (zero/span)', '3-point', 'Challenge + alarm'] }, { label: 'Owner', type: 'select', options: window.DB.staff.map((s) => s.name) }, { label: 'Acceptance criteria', type: 'text', full: true, placeholder: 'e.g. ±10% of applied' }], submitLabel: 'Create draft', done: 'Method drafted · awaiting validation evidence' })}>New method</Btn></div>
        <table className="tbl">
          <thead><tr><th>Method</th><th>Title</th><th>Rev</th><th>Points</th><th>Validated</th><th>MU budget</th><th>Status</th></tr></thead>
          <tbody>
            {DB.methods.map((m) => (
              <tr key={m.id} className="clickable" onClick={() => window.openDetail('method', m)}>
                <td className="mono cell-strong" style={{ fontSize: 12 }}>{m.id}</td>
                <td style={{ fontSize: 12.5 }}>{m.title}</td>
                <td><Badge kind={m.status === 'Active' ? 'ink' : 'warn'}>{m.rev}</Badge></td>
                <td className="faint" style={{ fontSize: 11.5 }}>{m.points}</td>
                <td>{m.validated ? <Icon name="check-circle" size={16} style={{ color: 'var(--ok)' }} /> : <Icon name="clock" size={16} style={{ color: 'var(--warn)' }} />}</td>
                <td>{m.mu ? <Badge kind="ok">Linked</Badge> : <span className="faint">—</span>}</td>
                <td><StatusBadge status={m.status} /></td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
        <div className="card card-pad">
          <div className="eyebrow" style={{ marginBottom: 10 }}>Method lifecycle</div>
          {['Draft', 'Validated', 'Active', 'Obsolete'].map((s, i) => (
            <div key={s} className="row" style={{ gap: 10, padding: '6px 0' }}>
              <span style={{ width: 22, height: 22, borderRadius: '50%', flex: 'none', display: 'grid', placeItems: 'center', fontSize: 10, fontWeight: 700, background: i < 3 ? 'var(--ok)' : '#eef1f6', color: i < 3 ? '#fff' : 'var(--text-3)' }}>{i + 1}</span>
              <span style={{ fontSize: 12.5, fontWeight: 600 }}>{s}</span>
              {i < 3 && <Badge kind="neutral" style={{ marginLeft: 'auto' }}>—</Badge>}
            </div>
          ))}
          <div className="ai-note" style={{ marginTop: 12, 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="lock" size={14} /></span>
            <div style={{ fontSize: 11.5 }}>Each worksheet binds to a specific method revision. In-flight jobs finish on their bound revision; new jobs use the current one.</div>
          </div>
        </div>
        <AINote title="SO₂ method ready to validate" clause="LAB-02" action="Open validation">
          CAL-MD-016 has validation runs complete. Attach the uncertainty budget to set it Active.
        </AINote>
      </div>
    </div>
  );
}

function UncertaintyTab() {
  const b = window.DB.uncertaintyBudget;
  return (
    <div style={{ display: 'grid', gridTemplateColumns: '1fr 300px', gap: 16, alignItems: 'start' }}>
      <div className="card">
        <div className="card-head"><Icon name="gauge" size={16} style={{ color: 'var(--primary-600)' }} /><div><div className="h-sec" style={{ fontSize: 14 }}>Uncertainty budget · {b.method}</div><div className="faint" style={{ fontSize: 11.5 }}>{b.range}</div></div></div>
        <table className="tbl">
          <thead><tr><th>Component</th><th className="num">Value</th><th>Distribution</th><th className="num">Divisor</th><th className="num">uᵢ</th></tr></thead>
          <tbody>
            {b.components.map((c, i) => (
              <tr key={i}>
                <td style={{ fontSize: 12.5 }}>{c.src}</td>
                <td className="num mono">{c.val}</td>
                <td><span className="tag">{c.dist}</span></td>
                <td className="num mono faint">{c.div}</td>
                <td className="num mono cell-strong">{c.u}</td>
              </tr>
            ))}
          </tbody>
        </table>
        <div className="card-body" style={{ borderTop: '1px solid var(--border)', display: 'grid', gridTemplateColumns: 'repeat(3,1fr)', gap: 12 }}>
          <Stat label="Combined uncertainty uc" value={b.combined} unit="ppm" />
          <Stat label="Coverage factor k" value={b.k.toFixed(1)} />
          <Stat label="Expanded U" value={`±${b.expanded}`} unit="ppm" strong />
        </div>
      </div>
      <div className="card card-pad">
        <div className="eyebrow" style={{ marginBottom: 12 }}>Contribution to uc²</div>
        {b.components.map((c, i) => {
          const sumsq = b.components.reduce((a, x) => a + x.u * x.u, 0);
          const pct = Math.round((c.u * c.u / sumsq) * 100);
          return (
            <div key={i} style={{ marginBottom: 11 }}>
              <div className="row" style={{ justifyContent: 'space-between', fontSize: 11.5, marginBottom: 3 }}><span className="muted">{c.src.split('(')[0]}</span><b>{pct}%</b></div>
              <Bar pct={pct} color={['#2f6fed', '#15a06b', '#c9820a', '#7a5bff', '#df463c'][i]} />
            </div>
          );
        })}
        <div className="faint" style={{ fontSize: 11, marginTop: 6 }}>Printed on certificates per ISO 17025 §7.6, with the stated decision rule.</div>
      </div>
    </div>
  );
}
function Stat({ label, value, unit, strong }) {
  return <div><div className="eyebrow" style={{ fontSize: 9.5 }}>{label}</div><div style={{ fontSize: strong ? 22 : 19, fontWeight: 800, letterSpacing: '-.5px', marginTop: 3, color: strong ? 'var(--primary-700)' : 'var(--ink)' }} className="mono">{value}{unit && <span style={{ fontSize: 12, color: 'var(--text-3)', marginLeft: 3 }}>{unit}</span>}</div></div>;
}

function PTTab({ onNav }) {
  const DB = window.DB;
  return (
    <div style={{ display: 'grid', gridTemplateColumns: '1fr 320px', gap: 16, alignItems: 'start' }}>
      <div className="card">
        <div className="card-head"><Icon name="trend" size={16} style={{ color: 'var(--primary-600)' }} /><div className="h-sec" style={{ fontSize: 14 }}>Proficiency testing &amp; ILC</div><span className="spacer" /><Btn variant="primary" icon="plus" size="sm" onClick={() => window.openForm({ title: 'Record proficiency test', sub: 'Unsatisfactory results auto-open an NCR (LAB-04)', icon: 'trend', fields: [{ label: 'Provider', type: 'select', options: ['LGC Standards', 'NEL / TÜV'] }, { label: 'Scheme', type: 'text' }, { label: 'Parameter', type: 'text', placeholder: 'e.g. H₂S 25 ppm' }, { label: 'Date', type: 'date' }, { label: 'z-score', type: 'number' }, { label: 'Evaluation', type: 'select', options: ['Satisfactory', 'Questionable', 'Unsatisfactory'] }], submitLabel: 'Record PT', done: 'PT participation recorded' })}>Record PT</Btn></div>
        <table className="tbl">
          <thead><tr><th>PT №</th><th>Provider / scheme</th><th>Parameter</th><th>Date</th><th className="num">z-score</th><th>Result</th></tr></thead>
          <tbody>
            {DB.ptRecords.map((p) => (
              <tr key={p.id} className="clickable" onClick={() => window.openDetail('pt', p)}>
                <td className="mono cell-strong" style={{ fontSize: 12 }}>{p.id}</td>
                <td><div style={{ fontSize: 12.5, fontWeight: 600 }}>{p.provider}</div><div className="cell-sub">{p.scheme}</div></td>
                <td className="mono" style={{ fontSize: 12 }}>{p.param}</td>
                <td className="faint">{DB.fmt(p.date)}</td>
                <td className="num"><span className="mono" style={{ fontWeight: 700, color: Math.abs(p.z) > 2 ? 'var(--warn)' : 'var(--ok)' }}>{p.z.toFixed(1)}</span></td>
                <td>{p.result === 'Satisfactory' ? <Badge kind="ok" icon="check">Satisfactory</Badge> : <Badge kind="warn">{p.result} → {p.capa}</Badge>}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
        <div className="card card-pad" style={{ textAlign: 'center' }}>
          <Ring value={96} size={120} color="var(--ok)"><div><div style={{ fontSize: 26, fontWeight: 800 }}>96%</div><div className="faint" style={{ fontSize: 10.5 }}>satisfactory</div></div></Ring>
          <div className="muted" style={{ fontSize: 12, marginTop: 8 }}>3 schemes participated YTD · 1 questionable under CAPA</div>
        </div>
        <AINote title="z-score 2.3 on CO — possible bias" clause="AIX-03" action="Open CAPA-26-014" onAction={() => onNav('qms')}>
          PT result correlates with the CO drift trend on 3 monitors. AI suggests checking reference cylinder CYL-2452 against a second standard.
        </AINote>
      </div>
    </div>
  );
}

function EnvTab() {
  const DB = window.DB;
  const series = DB.envSeries;
  return (
    <div style={{ display: 'grid', gridTemplateColumns: '1fr 300px', gap: 16, alignItems: 'start' }}>
      <div className="card">
        <div className="card-head"><Icon name="thermometer" size={16} style={{ color: 'var(--primary-600)' }} /><div className="h-sec" style={{ fontSize: 14 }}>Continuous environmental monitoring</div><span className="spacer" /><Badge kind="ok" dot>Within limits</Badge></div>
        <div className="card-body">
          <div className="row" style={{ gap: 22, marginBottom: 16 }}>
            <EnvBig icon="thermometer" label="Temperature" value="22.4" unit="°C" lim="18–25 °C" pct={62} />
            <EnvBig icon="droplet" label="Humidity" value="47" unit="%RH" lim="30–60 %" pct={47} />
            <EnvBig icon="gauge" label="Pressure" value="1009" unit="hPa" lim="±30 hPa" pct={55} />
          </div>
          <EnvChart series={series} />
        </div>
      </div>
      <div className="card card-pad">
        <div className="eyebrow" style={{ marginBottom: 10 }}>Method-defined gating</div>
        <div className="gate pass" style={{ marginBottom: 10 }}><span className="gate-ico" style={{ background: 'var(--ok-bg)', color: 'var(--ok)' }}><Icon name="check-circle" size={17} /></span><div><div className="gate-title" style={{ fontSize: 12.5 }}>Within method limits</div><div className="gate-desc">Worksheets may execute</div></div></div>
        <div className="muted" style={{ fontSize: 12, lineHeight: 1.6 }}>Each method defines acceptable T/RH/pressure ranges. Out-of-range conditions <b>warn or block</b> worksheet execution per the method's criticality (ISO 17025 §6.3) — and the readings are retained with the worksheet.</div>
        <div className="ai-note" style={{ marginTop: 14 }}>
          <span className="ai-badge-ico"><Icon name="sparkles" size={14} fill /></span>
          <div style={{ fontSize: 11.5 }}><span className="ai-label">AI</span><div style={{ marginTop: 2 }}>Predicted afternoon temperature rise (HVAC cycle) may approach the 25 °C limit ~14:30. No action needed yet.</div></div>
        </div>
      </div>
    </div>
  );
}
function EnvBig({ icon, label, value, unit, lim, pct }) {
  return (
    <div style={{ flex: 1 }}>
      <div className="row" style={{ gap: 6, color: 'var(--text-2)', fontSize: 12, fontWeight: 600, marginBottom: 5 }}><Icon name={icon} size={14} />{label}</div>
      <div style={{ fontSize: 26, fontWeight: 800, letterSpacing: '-1px' }}>{value}<span style={{ fontSize: 13, color: 'var(--text-3)', marginLeft: 3 }}>{unit}</span></div>
      <div style={{ margin: '7px 0 4px' }}><Bar pct={pct} color="var(--ok)" /></div>
      <div className="faint" style={{ fontSize: 11 }}>Limit {lim}</div>
    </div>
  );
}
function EnvChart({ series }) {
  const w = 560, h = 120, pad = 4;
  const temps = series.map((s) => s.temp), rhs = series.map((s) => s.rh);
  const tmin = 18, tmax = 26;
  const tx = (i) => (i / (series.length - 1)) * w;
  const ty = (v) => h - pad - ((v - tmin) / (tmax - tmin)) * (h - pad * 2);
  const tpts = series.map((s, i) => `${tx(i)},${ty(s.temp)}`).join(' ');
  const limitY = ty(25);
  return (
    <svg viewBox={`0 0 ${w} ${h}`} style={{ width: '100%', height: 150 }} preserveAspectRatio="none">
      <line x1="0" y1={limitY} x2={w} y2={limitY} stroke="var(--warn)" strokeWidth="1" strokeDasharray="4 4" vectorEffect="non-scaling-stroke" />
      <defs><linearGradient id="tg" x1="0" y1="0" x2="0" y2="1"><stop offset="0" stopColor="rgba(47,111,237,.2)" /><stop offset="1" stopColor="rgba(47,111,237,0)" /></linearGradient></defs>
      <polygon points={`0,${h} ${tpts} ${w},${h}`} fill="url(#tg)" />
      <polyline points={tpts} fill="none" stroke="var(--primary-600)" strokeWidth="1.8" vectorEffect="non-scaling-stroke" />
    </svg>
  );
}

window.ISOModule = ISOModule;
