/* =====================================================================
   AI-COS — Certificate Management + ISO 17025 detail + QR verify
   Layout mirrors ADAM-QMS-L4-F-005 Calibration Certificate Template.
   ===================================================================== */
const MULTI_MODELS = ['MSA Altair 4XR', 'Ventis Pro5', 'Ind. Scientific Ventis MX4', 'Honeywell GasAlertMicro 5', 'BW MicroClip XL'];
function certKind(ct) { return ct.bump ? 'bump' : MULTI_MODELS.includes(ct.model) ? 'multi' : 'h2s'; }
function certResults(kind) {
  if (kind === 'multi') return {
    cols: ['Gas', 'Applied', 'Expected', 'Actual', 'Tolerance', 'Status'],
    rows: [['LEL', '50 %LEL', '50 %LEL', '49 %LEL', '±5%', 1], ['O₂', '20.9 %vol', '20.9 %vol', '20.9 %vol', '±0.5%', 1], ['CO', '50 ppm', '50 ppm', '48 ppm', '±10%', 1], ['H₂S', '25 ppm', '25 ppm', '24.6 ppm', '±10%', 1]],
  };
  if (kind === 'bump') return {
    cols: ['Challenge', 'Applied', 'Response', 'Alarm', 'Status'],
    rows: [['H₂S bump', '25 ppm', '23.8 ppm', 'Activated', 1], ['Alarm low', '10 ppm', '—', 'Activated', 1], ['Alarm high', '15 ppm', '—', 'Activated', 1]],
  };
  return {
    cols: ['Test description', 'Applied', 'Expected', 'Actual', 'Tolerance', 'Status'],
    rows: [['Fresh Air Zero Check', '0 ppm', '0 ppm', '0.0 ppm', '±2 ppm', 1], ['Span Calibration', '25 ppm H₂S', '25 ppm', '24.3 ppm', '±10%', 1], ['Low Alarm Test', '10 ppm', 'Alarm', 'Activated', 'N/A', 1], ['High Alarm Test', '15 ppm', 'Alarm', 'Activated', 'N/A', 1]],
  };
}

function CertsModule({ onNav }) {
  const DB = window.DB;
  const [verify, setVerify] = useState(false);
  const [filter, setFilter] = useState('All');
  const filters = ['All', 'Valid', 'Superseded', 'Calibration', 'Bump test'];
  const list = DB.certificates.filter((c) => {
    if (filter === 'All') return true;
    if (filter === 'Bump test') return c.bump;
    if (filter === 'Calibration') return !c.bump;
    return c.status === filter;
  });
  return (
    <div className="page page-wide rise">
      <div className="row" style={{ justifyContent: 'space-between', alignItems: 'flex-end', marginBottom: 18 }}>
        <div>
          <div className="h-page">Certificates</div>
          <div className="h-sub">ISO 17025 §7.8 content · MU &amp; traceability · QR verification · supersession control</div>
        </div>
        <div className="row" style={{ gap: 8 }}>
          <Btn icon="qr" size="sm" onClick={() => setVerify(true)}>Verify a certificate</Btn>
          <Btn variant="ghost" icon="download" size="sm" onClick={() => window.toast('Certificate register exported (XLSX)')}>Export register</Btn>
        </div>
      </div>

      <div className="kpi-grid" style={{ gridTemplateColumns: 'repeat(4,1fr)', marginBottom: 16 }}>
        <Kpi label="Issued this month" value={312} icon="certificate" tone="ok" delta="+14%" deltaDir="up" />
        <Kpi label="Valid & verifiable" value="2,847" icon="check-shield" tone="info" />
        <Kpi label="Superseded" value={23} icon="history" tone="warn" />
        <Kpi label="QR verifications (Jun)" value="1,204" icon="qr" tone="info" delta="by customers & auditors" />
      </div>

      <div className="card">
        <div className="card-head">
          <div className="h-sec" style={{ fontSize: 14 }}>Certificate register</div>
          <span className="spacer" />
          <div className="seg">{filters.map((f) => <button key={f} className={filter === f ? 'on' : ''} onClick={() => setFilter(f)}>{f}</button>)}</div>
        </div>
        <table className="tbl">
          <thead><tr><th>Certificate №</th><th>Equipment</th><th>Customer</th><th>Method</th><th>Uncertainty</th><th>Result</th><th>Issued</th><th>Status</th><th></th></tr></thead>
          <tbody>
            {list.map((ct) => {
              const c = DB.custById(ct.customer);
              return (
                <tr key={ct.id} className="clickable" onClick={() => window.openDetail('cert', ct)}>
                  <td><span className="row" style={{ gap: 7 }}><span style={{ width: 26, height: 26, borderRadius: 7, background: ct.bump ? 'var(--warn-bg)' : 'var(--primary-50)', color: ct.bump ? 'var(--warn)' : 'var(--primary-600)', display: 'grid', placeItems: 'center', flex: 'none' }}><Icon name="certificate" size={14} /></span><span className="mono cell-strong" style={{ fontSize: 12 }}>{ct.id}</span></span></td>
                  <td><div style={{ fontSize: 12.5, fontWeight: 600 }}>{ct.model}</div><div className="cell-sub mono">{ct.monitor}</div></td>
                  <td><div className="row" style={{ gap: 6 }}><span className="avatar avatar-sm" style={{ background: c.color, borderRadius: 6 }}>{c.short}</span>{c.short}</div></td>
                  <td className="mono" style={{ fontSize: 11.5 }}>{ct.method}</td>
                  <td className="mono">{ct.mu}</td>
                  <td>{ct.result2 ? <Badge kind="warn">{ct.result}</Badge> : <Badge kind="ok" icon="check">Pass</Badge>}</td>
                  <td className="faint">{DB.fmt(ct.issued)}</td>
                  <td><StatusBadge status={ct.status} /></td>
                  <td><Icon name="chevR" size={16} style={{ color: 'var(--text-3)' }} /></td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>

      {verify && <VerifyModal onClose={() => setVerify(false)} />}
    </div>
  );
}

function CertDrawer({ ct, onClose }) {
  const DB = window.DB;
  const c = DB.custById(ct.customer);
  const kind = certKind(ct);
  const res = certResults(kind);
  const title = kind === 'bump' ? 'Bump Test Report' : kind === 'multi' ? 'Certificate of Calibration — Multi-Gas Monitor' : 'Certificate of Calibration — Portable H₂S Monitor';
  const procRef = kind === 'bump' ? 'ADAM-TECH-L3-P-006' : kind === 'multi' ? 'ADAM-TECH-L3-P-003' : 'ADAM-TECH-L3-P-004';
  const fields = [
    ['Certificate number', ct.id, 'mono'], ['Calibration date', DB.fmt(ct.issued)],
    ['Client name', c.name], ['Location', c.site],
    ['Instrument make / model', ct.model], ['Serial / Asset ID', ct.monitor, 'mono'],
    ['Sensor type', kind === 'multi' ? 'LEL / O₂ / CO / H₂S' : 'H₂S'], ['Measurement range', kind === 'multi' ? 'Multi' : '0–100 ppm'],
    ['Calibration gas / cylinder', kind === 'multi' ? '4-gas · CYL-2453' : '25 ppm H₂S · CYL-2451'], ['Gas expiry', DB.fmt(DB.addM(DB.TODAY, 4))],
    ['Expanded uncertainty', `${ct.mu} (k=2)`], ['Decision rule', 'Simple acceptance'],
    ['Ambient temp / humidity', '22.4 °C / 47 %RH'], ['Procedure ref.', procRef, 'mono'],
    ['Next calibration due', DB.fmt(DB.addM(ct.issued, 6))], ['Certificate expiry', DB.fmt(DB.addM(ct.issued, 6))],
  ];
  return (
    <Drawer open onClose={onClose} width={720}>
      <div className="drawer-head">
        <button className="icon-btn" onClick={onClose}><Icon name="chevR" size={17} /></button>
        <div style={{ flex: 1 }}>
          <div className="row" style={{ gap: 8 }}><span className="mono" style={{ fontWeight: 750, fontSize: 15 }}>{ct.id}</span><StatusBadge status={ct.status} /></div>
          <div className="faint" style={{ fontSize: 12 }}>{ct.model} · {ct.monitor}</div>
        </div>
        <Btn icon="download" size="sm" onClick={() => window.toast(`${ct.id}.pdf downloaded`)}>PDF</Btn>
        <Btn variant="primary" icon="ext" size="sm" onClick={() => window.toast('Opening verifiable certificate…', 'info')}>Open</Btn>
      </div>
      <div className="drawer-body" style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
        {/* certificate preview */}
        <div className="card" style={{ padding: 0, overflow: 'hidden' }}>
          <div style={{ background: 'linear-gradient(120deg,#0c2138,#163a5e)', color: '#fff', padding: '16px 22px', display: 'flex', alignItems: 'center', gap: 12 }}>
            <BrandMark size={38} light />
            <div style={{ flex: 1 }}><div style={{ fontWeight: 800, fontSize: 14 }}>{title}</div><div style={{ fontSize: 11, color: '#9fb4d0' }}>Al Duqum Al Masiya ENT · ISO/IEC 17025:2017 · ISO 9001:2015</div></div>
            <QRBox size={56} />
          </div>
          <div style={{ padding: 20 }}>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '11px 22px' }}>
              {fields.map(([k, v, cls], i) => (
                <div key={i}><div className="eyebrow" style={{ fontSize: 9 }}>{k}</div><div style={{ fontSize: 12.5, fontWeight: 650, marginTop: 2 }} className={cls === 'mono' ? 'mono' : ''}>{v}</div></div>
              ))}
            </div>
            <div className="divider" style={{ margin: '16px 0 12px' }} />
            <div className="eyebrow" style={{ fontSize: 9.5, marginBottom: 8 }}>Calibration results</div>
            <table className="tbl" style={{ fontSize: 12 }}>
              <thead><tr>{res.cols.map((c2) => <th key={c2} style={{ background: 'transparent', padding: '6px 10px' }}>{c2}</th>)}</tr></thead>
              <tbody>{res.rows.map((r, i) => (
                <tr key={i}>{r.map((cell, j) => j === r.length - 1
                  ? <td key={j} style={{ padding: '7px 10px' }}><Badge kind="ok" icon="check">Pass</Badge></td>
                  : <td key={j} className={j === 0 ? 'cell-strong' : 'mono'} style={{ padding: '7px 10px', fontSize: 11.5 }}>{cell}</td>)}</tr>
              ))}</tbody>
            </table>
            <div className="muted" style={{ fontSize: 11.5, marginTop: 12, lineHeight: 1.55, fontStyle: 'italic' }}>
              This is to certify that the above instrument has been calibrated using certified reference gas and calibrated equipment, and was found operating within acceptable tolerance limits at the time of calibration. Valid until the certificate expiry date, provided the instrument is maintained per manufacturer recommendations.
            </div>
            <div className="divider" style={{ margin: '14px 0' }} />
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3,1fr)', gap: 14 }}>
              {[['Calibrated by', ct.bump ? 'U-002' : 'U-003'], ['Reviewed by', 'U-002'], ['Approved by', ct.signatory]].map(([role, uid], i) => (
                <div key={i} style={{ border: '1px solid var(--border)', borderRadius: 9, padding: '10px 11px' }}>
                  <div className="eyebrow" style={{ fontSize: 8.5 }}>{role}</div>
                  <div className="row" style={{ gap: 7, marginTop: 6 }}><Avatar id={uid} size="sm" /><div style={{ fontSize: 11.5, fontWeight: 650 }}>{DB.staffById(uid).name}</div></div>
                  <div style={{ fontFamily: 'cursive', fontSize: 15, color: 'var(--primary-700)', marginTop: 6, opacity: .8 }}>✒ signed</div>
                </div>
              ))}
            </div>
          </div>
        </div>

        <div className="card card-pad"><TraceChain ws={{ id: ct.id, method: ct.method.split(' ')[0], methodRev: ct.method.split(' ').slice(1).join(' ') }} /></div>

        <div className="card">
          <div className="card-head"><Icon name="history" size={15} /><div className="h-sec" style={{ fontSize: 13.5 }}>Issuance lifecycle</div></div>
          <div className="card-body">
            {[['Composed & numbered', 'auto from worksheet'], ['Rendered & hashed', 'controlled template F-005 v4'], ['Published to portal', `${c.short} portal`], ['Emailed to customer', c.contact], ['Attached to dispatch', 'travels with equipment']].map(([t, s], i) => (
              <div key={i} className="lrow" style={{ padding: '9px 0' }}>
                <span style={{ width: 24, height: 24, borderRadius: '50%', background: 'var(--ok)', color: '#fff', display: 'grid', placeItems: 'center', flex: 'none' }}><Icon name="check" size={13} /></span>
                <div style={{ flex: 1 }}><span style={{ fontSize: 12.5, fontWeight: 600 }}>{t}</span> <span className="faint" style={{ fontSize: 11.5 }}>· {s}</span></div>
              </div>
            ))}
            {ct.status === 'Superseded' && <div className="ai-note" style={{ marginTop: 8, background: 'var(--warn-bg)', borderColor: 'var(--warn-line)' }}><span className="ai-badge-ico" style={{ color: 'var(--warn)' }}><Icon name="history" size={14} /></span><div style={{ fontSize: 11.5 }}>Superseded by a later issue. Original is immutable; QR verification returns <b>Superseded</b> and offers the current valid version.</div></div>}
          </div>
        </div>
      </div>
    </Drawer>
  );
}

/* ---- public QR verification ---- */
function VerifyModal({ onClose }) {
  const [done, setDone] = useState(false);
  useEffect(() => { const t = setTimeout(() => setDone(true), 900); return () => clearTimeout(t); }, []);
  return (
    <React.Fragment>
      <div className="scrim" onClick={onClose} />
      <div className="modal" style={{ width: 420, textAlign: 'center', padding: 28 }}>
        <button className="icon-btn" style={{ position: 'absolute', top: 14, right: 14 }} onClick={onClose}><Icon name="x" size={16} /></button>
        <div className="eyebrow">Public verification</div>
        {!done ? (
          <div style={{ padding: '28px 0' }}>
            <div className="spin" style={{ width: 30, height: 30, border: '3px solid var(--border)', borderTopColor: 'var(--primary-600)', borderRadius: '50%', margin: '0 auto' }} />
            <div className="faint" style={{ fontSize: 12.5, marginTop: 14 }}>Resolving QR token…</div>
          </div>
        ) : (
          <div className="rise">
            <div style={{ width: 54, height: 54, borderRadius: 15, background: 'var(--ok)', color: '#fff', display: 'grid', placeItems: 'center', margin: '14px auto 12px' }}><Icon name="check-shield" size={26} /></div>
            <div style={{ fontWeight: 800, fontSize: 18 }}>Certificate Valid</div>
            <div className="mono" style={{ fontSize: 13, marginTop: 4 }}>ADAM-CAL-26-04188</div>
            <div className="card" style={{ background: 'var(--surface-2)', padding: 14, marginTop: 16, textAlign: 'left' }}>
              {[['Equipment', 'Honeywell BW Ultra'], ['Customer', 'Petroleum Development Oman'], ['Issued', '6 Jun 2026'], ['Status', 'Valid']].map(([k, v], i) => (
                <div key={i} className="row" style={{ justifyContent: 'space-between', padding: '4px 0', fontSize: 12.5 }}><span className="faint">{k}</span><b>{v}</b></div>
              ))}
            </div>
            <div className="faint" style={{ fontSize: 11, marginTop: 12 }}>Public page exposes no other customer data (ISO 17025 §7.8 / CERT-05).</div>
          </div>
        )}
      </div>
      <style>{`@keyframes spin{to{transform:rotate(360deg)}}.spin{animation:spin .8s linear infinite}`}</style>
    </React.Fragment>
  );
}

window.CertsModule = CertsModule;
