/* =====================================================================
   AI-COS — Supporting modules (part 1):
   Standards & Cylinders · Equipment & Assets · CRM · Scheduling · QMS
   ===================================================================== */
function PageHead({ title, sub, children }) {
  return (
    <div className="row" style={{ justifyContent: 'space-between', alignItems: 'flex-end', marginBottom: 18 }}>
      <div><div className="h-page">{title}</div><div className="h-sub">{sub}</div></div>
      <div className="row" style={{ gap: 8 }}>{children}</div>
    </div>
  );
}
function pressurePct(c) { return Math.round((c.pressure / c.p0) * 100); }

/* ---------------- Standards & Cylinders ---------------------------- */
function CylindersModule({ onNav }) {
  const DB = window.DB;
  const [tab, setTab] = useState('cyl');
  return (
    <div className="page page-wide rise">
      <PageHead title="Reference Standards &amp; Cylinders" sub="Calibration gases, reference instruments &amp; the lab asset register — validity hard-gates the worksheet (ISO 17025 §6.4/6.5)">
        <Btn icon="filter" size="sm" onClick={() => window.toast('Filters applied', 'info')}>Filter</Btn><Btn variant="primary" icon="plus" onClick={() => window.openForm({ title: 'Record cylinder GRN', sub: 'Goods receipt — activation requires supplier certificate (CYL-01)', icon: 'cylinder', fields: [{ label: 'Gas mixture', type: 'text', placeholder: 'e.g. H₂S in N₂' }, { label: 'Certified concentration', type: 'text', placeholder: '25 ppm' }, { label: 'Lot / cylinder no.', type: 'text' }, { label: 'Supplier', type: 'select', options: ['Air Products', 'BOC Linde'] }, { label: 'Fill date', type: 'date' }, { label: 'Expiry date', type: 'date' }, { label: 'Initial pressure (psi)', type: 'number', value: '2000' }, { label: 'Supplier certificate', type: 'text', placeholder: 'Attach / ref' }], submitLabel: 'Activate cylinder', done: 'GRN recorded · cylinder activated for compatible models' })}>Record GRN</Btn>
      </PageHead>

      <div className="kpi-grid" style={{ gridTemplateColumns: 'repeat(4,1fr)', marginBottom: 16 }}>
        <Kpi label="Active cylinders" value={DB.cylinders.filter(c => c.status === 'Active').length} icon="cylinder" tone="ok" />
        <Kpi label="Low pressure" value={DB.cylinders.filter(c => c.status === 'Low pressure').length} icon="gauge" tone="warn" delta="reorder suggested" />
        <Kpi label="Expired · blocked" value={DB.cylinders.filter(c => c.status === 'Expired').length} icon="x-circle" tone="bad" delta="hard-blocked" />
        <Kpi label="Reference instruments" value={DB.labAssets.filter(a => a.category === 'Reference' || a.category === 'Environmental').length} icon="gauge" tone="info" />
      </div>

      <div className="tabs" style={{ marginBottom: 16 }}>
        {[['cyl', 'Calibration gas cylinders'], ['ref', 'Reference instruments'], ['reg', 'Lab asset register']].map(([id, l]) => <div key={id} className={`tab${tab === id ? ' on' : ''}`} onClick={() => setTab(id)}>{l}</div>)}
      </div>

      {tab === 'cyl' && (
        <div className="card">
          <table className="tbl">
            <thead><tr><th>Cylinder</th><th>Mixture</th><th>Concentration</th><th>Lot</th><th>Supplier</th><th>Pressure</th><th>Expiry</th><th>Status</th></tr></thead>
            <tbody>
              {DB.cylinders.map((c) => {
                const pct = pressurePct(c);
                return (
                  <tr key={c.id} className="clickable" onClick={() => window.openDetail('cylinder', c)}>
                    <td className="mono cell-strong" style={{ fontSize: 12 }}>{c.id}</td>
                    <td style={{ fontSize: 12.5 }}>{c.mix}</td>
                    <td className="mono" style={{ fontSize: 12 }}>{c.conc}</td>
                    <td className="mono faint" style={{ fontSize: 11.5 }}>{c.lot}</td>
                    <td className="faint" style={{ fontSize: 12 }}>{c.supplier}</td>
                    <td style={{ width: 120 }}><div className="row" style={{ gap: 7 }}><div style={{ width: 56 }}><Bar pct={pct} color={pct < 25 ? 'var(--bad)' : pct < 50 ? 'var(--warn)' : 'var(--ok)'} /></div><span className="mono faint" style={{ fontSize: 11 }}>{c.pressure}</span></div></td>
                    <td><span style={{ fontSize: 12, fontWeight: 600, color: c.exp <= DB.TODAY ? 'var(--bad)' : (c.exp - DB.TODAY) / 864e5 < 30 ? 'var(--warn)' : 'var(--text)' }}>{DB.fmt(c.exp)}</span></td>
                    <td><StatusBadge status={c.status} /></td>
                  </tr>
                );
              })}
            </tbody>
          </table>
          <div className="card-body" style={{ borderTop: '1px solid var(--border)' }}>
            <AINote title="CYL-2455 (SO₂) expired — auto-blocked from selection" clause="CYL-03" action="Suggest reorder">
              An expired calibration gas invalidates results. The cylinder is hard-blocked from every worksheet; 1 low-pressure cylinder (CYL-2454) is approaching the reorder threshold.
            </AINote>
          </div>
        </div>
      )}

      {(tab === 'ref' || tab === 'reg') && (
        <div className="card">
          <table className="tbl">
            <thead><tr><th>Asset ID</th><th>Name</th><th>Category</th><th>Serial</th><th>Location</th><th>Criticality</th><th>Next cal due</th><th>Status</th></tr></thead>
            <tbody>
              {DB.labAssets.filter((a) => tab === 'reg' ? true : (a.category === 'Reference' || a.category === 'Environmental')).map((a) => (
                <tr key={a.id} className="clickable" onClick={() => window.openDetail('labasset', a)}>
                  <td className="mono cell-strong" style={{ fontSize: 12 }}>{a.id}</td>
                  <td style={{ fontSize: 12.5 }}>{a.name}</td>
                  <td><span className="tag">{a.category}</span></td>
                  <td className="mono faint" style={{ fontSize: 11.5 }}>{a.serial}</td>
                  <td className="faint" style={{ fontSize: 12 }}><span className="row" style={{ gap: 5 }}><Icon name="pin" size={12} />{a.location}</span></td>
                  <td><Badge kind={a.criticality === 'Critical' ? 'bad' : a.criticality === 'High' ? 'warn' : 'neutral'}>{a.criticality}</Badge></td>
                  <td><span style={{ fontSize: 12, fontWeight: 600, color: a.status === 'Overdue' ? 'var(--bad)' : a.status === 'Due soon' ? 'var(--warn)' : 'var(--text)' }}>{DB.fmt(a.due)} · {a.dueRel}</span></td>
                  <td><StatusBadge status={a.status} /></td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}
    </div>
  );
}

/* ---------------- Equipment & Assets (customer monitors) ----------- */
function AssetsModule({ onNav }) {
  const DB = window.DB;
  const [cust, setCust] = useState('All');
  const list = DB.monitors.filter((m) => cust === 'All' || m.customer === cust);
  return (
    <div className="page page-wide rise">
      <PageHead title="Equipment &amp; Assets" sub="Customer gas monitors · sensor-level configuration · firmware &amp; battery history · QR asset labels">
        <Btn icon="qr" size="sm" onClick={() => window.toast('Camera scanner ready — scan asset QR', 'info')}>Scan asset</Btn><Btn variant="primary" icon="plus" onClick={() => window.openForm({ title: 'Register equipment', sub: 'New asset — interval defaults from category (EQ)', icon: 'cpu', fields: [{ label: 'Serial number', type: 'text' }, { label: 'Asset ID', type: 'text', placeholder: 'auto if blank' }, { label: 'Manufacturer / model', type: 'select', options: window.DB.models }, { label: 'Category', type: 'select', options: ['Portable monitor', 'Fixed detector', 'Sampling pump'] }, { label: 'Customer', type: 'select', options: window.DB.customers.map((c) => c.name) }, { label: 'Calibration interval', type: 'select', options: ['6 months', '12 months'] }, { label: 'Sensor configuration', type: 'text', full: true, placeholder: 'H₂S / CO / O₂ / LEL' }], submitLabel: 'Register', done: 'Equipment registered · interval set from category' })}>Register equipment</Btn>
      </PageHead>
      <div className="kpi-grid" style={{ gridTemplateColumns: 'repeat(4,1fr)', marginBottom: 16 }}>
        <Kpi label="Monitors under management" value="1,247" icon="cpu" tone="info" delta="across 8 customers" />
        <Kpi label="In calibration" value={DB.monitors.filter(m => m.status === 'In calibration').length} icon="workflow" tone="info" />
        <Kpi label="Due within 30 days" value={DB.monitors.filter(m => m.status === 'Due soon').length} icon="clock" tone="warn" />
        <Kpi label="Overdue" value={DB.monitors.filter(m => m.status === 'Overdue').length} icon="alert" tone="bad" />
      </div>
      <div className="card">
        <div className="card-head">
          <div className="h-sec" style={{ fontSize: 14 }}>Asset register</div><span className="spacer" />
          <select value={cust} onChange={(e) => setCust(e.target.value)} style={{ fontFamily: 'inherit', fontSize: 12.5, padding: '7px 11px', borderRadius: 9, border: '1px solid var(--border-2)', background: 'var(--surface)', fontWeight: 600 }}>
            <option value="All">All customers</option>
            {DB.customers.map((c) => <option key={c.id} value={c.id}>{c.name}</option>)}
          </select>
        </div>
        <table className="tbl">
          <thead><tr><th>Asset ID</th><th>Model</th><th>Serial</th><th>Sensors</th><th>Customer</th><th>Last cal</th><th>Next due</th><th>Status</th></tr></thead>
          <tbody>
            {list.slice(0, 16).map((m) => {
              const c = DB.custById(m.customer);
              return (
                <tr key={m.id} className="clickable" onClick={() => window.openDetail('asset', m)}>
                  <td className="mono cell-strong" style={{ fontSize: 12 }}>{m.id}</td>
                  <td style={{ fontSize: 12.5 }}>{m.model}</td>
                  <td className="mono faint" style={{ fontSize: 11.5 }}>{m.serial}</td>
                  <td><div className="row wrap" style={{ gap: 4 }}>{m.sensors.map((s) => <span key={s} className="tag" style={{ padding: '1px 6px', fontSize: 10.5 }}>{s}</span>)}</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="faint" style={{ fontSize: 12 }}>{DB.fmt(m.last)}</td>
                  <td><span style={{ fontSize: 12, fontWeight: 600, color: m.status === 'Overdue' ? 'var(--bad)' : m.status === 'Due soon' ? 'var(--warn)' : 'var(--text)' }}>{m.dueRel}</span></td>
                  <td><StatusBadge status={m.status} /></td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    </div>
  );
}

/* ---------------- CRM & Contracts ---------------------------------- */
function CRMModule({ onNav }) {
  const DB = window.DB;
  const [tab, setTab] = useState('customers');
  const tabs = [['customers', 'Customers'], ['quotations', 'Quotations'], ['contracts', 'Contracts / AMC'], ['prequal', 'Prequalification']];
  const qStatus = { Accepted: 'ok', Sent: 'info', Draft: 'neutral', Rejected: 'bad' };
  return (
    <div className="page page-wide rise">
      <PageHead title="CRM &amp; Contracts" sub="Customers · prequalification · quotations · AMC contracts that auto-drive scheduling">
        <Btn icon="receipt" size="sm" onClick={() => window.openForm({ title: 'New quotation', sub: 'Converts to job or AMC on acceptance (CRM-03)', icon: 'receipt', fields: [{ label: 'Customer', type: 'select', options: window.DB.customers.map((c) => c.name) }, { label: 'Validity (days)', type: 'number', value: '30' }, { label: 'Scope / title', type: 'text', full: true, placeholder: 'e.g. 40 monitors — annual calibration' }, { label: 'No. of items', type: 'number' }, { label: 'Estimated value (OMR)', type: 'number' }], submitLabel: 'Create quotation', done: 'Quotation created (Draft)' })}>New quotation</Btn><Btn variant="primary" icon="plus" onClick={() => window.openForm({ title: 'New AMC contract', sub: 'Covered assets auto-planned across the period', icon: 'briefcase', fields: [{ label: 'Customer', type: 'select', options: window.DB.customers.map((c) => c.name) }, { label: 'Covered assets', type: 'number' }, { label: 'Frequency', type: 'select', options: ['6-monthly', 'Quarterly', 'Annual'] }, { label: 'Annual value (OMR)', type: 'number' }, { label: 'Contract period', type: 'text', full: true, placeholder: 'Jan–Dec 2026' }], submitLabel: 'Create contract', done: 'Contract created · covered assets auto-planned' })}>New contract</Btn>
      </PageHead>
      <div className="kpi-grid" style={{ gridTemplateColumns: 'repeat(4,1fr)', marginBottom: 16 }}>
        <Kpi label="Active customers" value={DB.customers.length} icon="building" tone="info" />
        <Kpi label="Open quotations" value={DB.quotations.filter((q) => q.status === 'Sent' || q.status === 'Draft').length} icon="receipt" tone="warn" delta="awaiting decision" />
        <Kpi label="AMC contracts" value={DB.contracts.length} icon="briefcase" tone="ok" />
        <Kpi label="Prequal. expiring" value={DB.customers.filter((c) => (c.prequalExp - DB.TODAY) / 864e5 < 90).length} icon="alert" tone="bad" />
      </div>
      <div className="tabs" style={{ marginBottom: 16 }}>{tabs.map(([id, l]) => <div key={id} className={`tab${tab === id ? ' on' : ''}`} onClick={() => setTab(id)}>{l}</div>)}</div>

      {tab === 'customers' && (
        <div className="card">
          <div className="card-head"><Icon name="building" size={16} style={{ color: 'var(--primary-600)' }} /><div className="h-sec" style={{ fontSize: 14 }}>Customers</div></div>
          <table className="tbl">
            <thead><tr><th>Customer</th><th>Sector</th><th>Assets</th><th>Tier</th><th>Prequalification</th><th></th></tr></thead>
            <tbody>
              {DB.customers.map((c) => (
                <tr key={c.id} className="clickable" onClick={() => window.openDetail('customer', c)}>
                  <td><CustChip id={c.id} sub /></td>
                  <td className="faint" style={{ fontSize: 12 }}>{c.sector}</td>
                  <td className="num mono">{c.assets}</td>
                  <td><span className="tag">{c.tier}</span></td>
                  <td>{c.prequal === 'Approved' ? <Badge kind="ok" dot>Approved</Badge> : c.prequal === 'Renewal due' ? <Badge kind="warn" dot>Renewal {DB.rel(c.prequalExp)}</Badge> : <Badge kind="info" dot>{c.prequal}</Badge>}</td>
                  <td><Icon name="chevR" size={16} style={{ color: 'var(--text-3)' }} /></td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}

      {tab === 'quotations' && (
        <div className="card">
          <div className="card-head"><Icon name="receipt" size={16} style={{ color: 'var(--primary-600)' }} /><div className="h-sec" style={{ fontSize: 14 }}>Quotations &amp; proposals</div></div>
          <table className="tbl">
            <thead><tr><th>Quotation №</th><th>Customer</th><th>Scope</th><th className="num">Value (OMR)</th><th>Valid until</th><th>Status</th><th></th></tr></thead>
            <tbody>
              {DB.quotations.map((q) => { const c = DB.custById(q.customer); return (
                <tr key={q.id} className="clickable" onClick={() => window.openDetail('quotation', q)}>
                  <td className="mono cell-strong" style={{ fontSize: 12 }}>{q.id}</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 style={{ fontSize: 12.5, maxWidth: 260 }}>{q.title}</td>
                  <td className="num mono cell-strong">{q.value.toLocaleString()}</td>
                  <td><span style={{ fontWeight: 600, color: q.validity <= DB.TODAY ? 'var(--bad)' : 'var(--text)' }}>{DB.rel(q.validity)}</span></td>
                  <td><Badge kind={qStatus[q.status]} dot>{q.status}</Badge></td>
                  <td><Icon name="chevR" size={16} style={{ color: 'var(--text-3)' }} /></td>
                </tr>
              ); })}
            </tbody>
          </table>
        </div>
      )}

      {tab === 'contracts' && (
        <div className="card">
          <div className="card-head"><Icon name="briefcase" size={16} style={{ color: 'var(--primary-600)' }} /><div className="h-sec" style={{ fontSize: 14 }}>Service agreements / AMC</div></div>
          <table className="tbl">
            <thead><tr><th>Contract №</th><th>Customer</th><th>Assets</th><th>Frequency</th><th className="num">Annual value</th><th>Renewal</th><th>Status</th><th></th></tr></thead>
            <tbody>
              {DB.contracts.map((ct) => { const c = DB.custById(ct.customer); return (
                <tr key={ct.id} className="clickable" onClick={() => window.openDetail('contract', ct)}>
                  <td className="mono cell-strong" style={{ fontSize: 12 }}>{ct.id}</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="num mono">{ct.assets}</td><td className="faint" style={{ fontSize: 12 }}>{ct.freq}</td>
                  <td className="num mono cell-strong">{ct.value.toLocaleString()}</td>
                  <td>{DB.rel(ct.renew)}</td>
                  <td><StatusBadge status={ct.status} /></td>
                  <td><Icon name="chevR" size={16} style={{ color: 'var(--text-3)' }} /></td>
                </tr>
              ); })}
            </tbody>
          </table>
        </div>
      )}

      {tab === 'prequal' && (
        <div className="card">
          <div className="card-head"><Icon name="check-shield" size={16} style={{ color: 'var(--primary-600)' }} /><div className="h-sec" style={{ fontSize: 14 }}>Client approval &amp; prequalification</div></div>
          <table className="tbl">
            <thead><tr><th>Customer</th><th>Status</th><th>Expiry</th><th>Documents</th><th></th></tr></thead>
            <tbody>
              {DB.customers.map((c) => (
                <tr key={c.id} className="clickable" onClick={() => window.openDetail('customer', c)}>
                  <td><CustChip id={c.id} /></td>
                  <td>{c.prequal === 'Approved' ? <Badge kind="ok" dot>Approved</Badge> : c.prequal === 'Renewal due' ? <Badge kind="warn" dot>Renewal due</Badge> : <Badge kind="info" dot>{c.prequal}</Badge>}</td>
                  <td><span style={{ fontWeight: 600, color: (c.prequalExp - DB.TODAY) / 864e5 < 60 ? 'var(--warn)' : 'var(--text)' }}>{DB.fmt(c.prequalExp)} · {DB.rel(c.prequalExp)}</span></td>
                  <td><span className="tag"><Icon name="documents" size={11} /> Vendor registration</span></td>
                  <td><Icon name="chevR" size={16} style={{ color: 'var(--text-3)' }} /></td>
                </tr>
              ))}
            </tbody>
          </table>
          <div className="card-body" style={{ borderTop: '1px solid var(--border)' }}>
            <AINote title="2 contracts need renewal outreach" clause="AIX-01" action="Generate outreach list" onAction={() => onNav('schedule')}>
              Vale AMC renews in ~1 month and prequalification expires soon. AI drafted a renewal email and a covered-asset summary.
            </AINote>
          </div>
        </div>
      )}
    </div>
  );
}

/* ---------------- Scheduling -------------------------------------- */
function ScheduleModule({ onNav, openJob }) {
  const DB = window.DB;
  const [tab, setTab] = useState('overview');
  const days = ['Mon', 'Tue', 'Wed', 'Thu', 'Sat', 'Sun'];
  const dueSoon = DB.monitors.filter((m) => m.status === 'Due soon');
  const overdue = DB.monitors.filter((m) => m.status === 'Overdue');
  const tabs = [['overview', 'Overview'], ['upcoming', 'Upcoming plan'], ['overdue', 'Overdue & escalation'], ['amc', 'AMC plan']];
  const planRow = (m, esc) => { const c = DB.custById(m.customer); return (
    <tr key={m.id} className="clickable" onClick={() => window.openDetail('asset', m)}>
      <td className="mono cell-strong" style={{ fontSize: 12 }}>{m.id}</td>
      <td style={{ fontSize: 12.5 }}>{m.model}</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="faint">{DB.fmt(m.last)}</td>
      <td><span style={{ fontWeight: 600, color: m.status === 'Overdue' ? 'var(--bad)' : 'var(--warn)' }}>{DB.fmt(m.due)} · {m.dueRel}</span></td>
      {esc ? <td><Badge kind="bad" dot>Escalated</Badge></td> : <td><StatusBadge status={m.status} /></td>}
      <td><Btn size="sm" variant="ghost" onClick={(e) => { e.stopPropagation(); window.toast(`Reminder sent for ${m.id}`, 'info'); }}>Remind</Btn></td>
    </tr>
  ); };
  return (
    <div className="page page-wide rise">
      <PageHead title="Calibration Scheduling" sub="Due-date engine · AMC-driven planning · reminders, overdue alerts &amp; escalation">
        <Btn icon="download" size="sm" onClick={() => window.toast('Calibration plan exported (XLSX)')}>Export plan</Btn><Btn variant="primary" icon="bell" onClick={() => window.toast('Reminder run complete · 326 notifications sent', 'info')}>Run reminders</Btn>
      </PageHead>
      <div className="kpi-grid" style={{ gridTemplateColumns: 'repeat(4,1fr)', marginBottom: 16 }}>
        <Kpi label="Due this week" value={42} icon="calendar" tone="info" />
        <Kpi label="Overdue" value={11} icon="alert" tone="bad" delta="escalated to Lab Manager" />
        <Kpi label="AMC auto-planned" value={188} icon="refresh" tone="ok" delta="no manual entry" />
        <Kpi label="Reminders sent (Jun)" value={326} icon="bell" tone="info" delta="email · SMS Phase 2" />
      </div>
      <div className="tabs" style={{ marginBottom: 16 }}>{tabs.map(([id, l]) => <div key={id} className={`tab${tab === id ? ' on' : ''}`} onClick={() => setTab(id)}>{l}</div>)}</div>

      {tab === 'overview' && (
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 340px', gap: 16, alignItems: 'start' }}>
          <div className="card">
            <div className="card-head"><Icon name="calendar" size={16} style={{ color: 'var(--primary-600)' }} /><div className="h-sec" style={{ fontSize: 14 }}>Due-date heatmap · next 6 weeks</div></div>
            <div className="card-body">
              <div style={{ display: 'grid', gridTemplateColumns: 'auto repeat(6,1fr)', gap: 6 }}>
                <div></div>
                {['W23', 'W24', 'W25', 'W26', 'W27', 'W28'].map(w => <div key={w} className="faint" style={{ fontSize: 10.5, textAlign: 'center', fontWeight: 700 }}>{w}</div>)}
                {days.map((d, ri) => (
                  <React.Fragment key={d}>
                    <div className="faint" style={{ fontSize: 10.5, fontWeight: 700, display: 'grid', alignItems: 'center' }}>{d}</div>
                    {Array.from({ length: 6 }).map((_, ci) => {
                      const v = (ri * 7 + ci * 3 + 2) % 11;
                      const lvl = v > 8 ? 3 : v > 5 ? 2 : v > 2 ? 1 : 0;
                      const bg = ['#eef1f6', '#cfe0fb', '#7aa8f5', '#2f6fed'][lvl];
                      return <div key={ci} title={`${v} due`} onClick={() => v && setTab('upcoming')} style={{ height: 30, borderRadius: 7, background: bg, display: 'grid', placeItems: 'center', fontSize: 10.5, fontWeight: 700, color: lvl > 1 ? '#fff' : 'var(--text-2)', cursor: 'pointer' }}>{v || ''}</div>;
                    })}
                  </React.Fragment>
                ))}
              </div>
              <div className="row" style={{ gap: 6, marginTop: 14, justifyContent: 'flex-end' }}>
                <span className="faint" style={{ fontSize: 10.5 }}>Fewer</span>
                {['#eef1f6', '#cfe0fb', '#7aa8f5', '#2f6fed'].map(b => <span key={b} style={{ width: 14, height: 14, borderRadius: 4, background: b }} />)}
                <span className="faint" style={{ fontSize: 10.5 }}>More</span>
              </div>
            </div>
          </div>
          <div className="card">
            <div className="card-head"><Icon name="alert" size={15} style={{ color: 'var(--warn)' }} /><div className="h-sec" style={{ fontSize: 13.5 }}>Overdue &amp; due-soon</div></div>
            <div className="card-body" style={{ paddingTop: 4, paddingBottom: 4, maxHeight: 360, overflowY: 'auto' }}>
              {overdue.concat(dueSoon).slice(0, 9).map((m) => {
                const c = DB.custById(m.customer);
                return (
                  <div key={m.id} className="lrow" style={{ cursor: 'pointer' }} onClick={() => window.openDetail('asset', m)}>
                    <span className="avatar avatar-sm" style={{ background: c.color, borderRadius: 6 }}>{c.short}</span>
                    <div style={{ flex: 1 }}><div className="mono" style={{ fontSize: 11.5, fontWeight: 650 }}>{m.id}</div><div className="faint" style={{ fontSize: 11 }}>{m.model}</div></div>
                    <Badge kind={m.status === 'Overdue' ? 'bad' : 'warn'}>{m.dueRel}</Badge>
                  </div>
                );
              })}
            </div>
          </div>
        </div>
      )}

      {tab === 'upcoming' && (
        <div className="card">
          <div className="card-head"><Icon name="calendar" size={16} style={{ color: 'var(--primary-600)' }} /><div className="h-sec" style={{ fontSize: 14 }}>Upcoming calibration plan</div></div>
          <table className="tbl"><thead><tr><th>Asset</th><th>Model</th><th>Customer</th><th>Last cal</th><th>Next due</th><th>Status</th><th></th></tr></thead>
            <tbody>{dueSoon.concat(DB.monitors.filter((m) => m.status === 'Active')).slice(0, 14).map((m) => planRow(m, false))}</tbody></table>
        </div>
      )}
      {tab === 'overdue' && (
        <div className="card">
          <div className="card-head"><Icon name="alert" size={16} style={{ color: 'var(--bad)' }} /><div className="h-sec" style={{ fontSize: 14 }}>Overdue — escalated to Lab Manager</div></div>
          <table className="tbl"><thead><tr><th>Asset</th><th>Model</th><th>Customer</th><th>Last cal</th><th>Was due</th><th>Escalation</th><th></th></tr></thead>
            <tbody>{overdue.length ? overdue.map((m) => planRow(m, true)) : <tr><td colSpan="7" className="faint" style={{ textAlign: 'center', padding: 20 }}>No overdue items 🎉</td></tr>}</tbody></table>
        </div>
      )}
      {tab === 'amc' && (
        <div className="card">
          <div className="card-head"><Icon name="refresh" size={16} style={{ color: 'var(--primary-600)' }} /><div className="h-sec" style={{ fontSize: 14 }}>AMC-driven auto-plan</div><span className="spacer" /><span className="faint" style={{ fontSize: 11.5 }}>Covered equipment planned across the contract period</span></div>
          <table className="tbl"><thead><tr><th>Contract</th><th>Customer</th><th>Covered assets</th><th>Frequency</th><th>Next cycle</th><th></th></tr></thead>
            <tbody>{DB.contracts.map((ct) => { const c = DB.custById(ct.customer); return (
              <tr key={ct.id} className="clickable" onClick={() => window.openDetail('contract', ct)}>
                <td className="mono cell-strong" style={{ fontSize: 12 }}>{ct.id}</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="num mono">{ct.assets}</td><td className="faint" style={{ fontSize: 12 }}>{ct.freq}</td>
                <td>{DB.rel(ct.renew)}</td><td><Icon name="chevR" size={16} style={{ color: 'var(--text-3)' }} /></td>
              </tr>
            ); })}</tbody></table>
        </div>
      )}
    </div>
  );
}

/* ---------------- QMS Registers (NCR/CAPA · MR · Incidents · Audits) - */
function QMSModule({ onNav }) {
  const DB = window.DB;
  const [tab, setTab] = useState('capa');
  const tabs = [['capa', 'NCR / CAPA'], ['mr', 'Management review'], ['incidents', 'Incidents & complaints'], ['audits', 'Audits & risk']];
  const latestMR = DB.managementReviews.find((m) => m.status === 'Closed') || DB.managementReviews[0];
  return (
    <div className="page page-wide rise">
      <PageHead title="QMS &amp; Compliance Registers" sub="NCR · CAPA · management review · incidents · audits & risk — one improvement loop for the whole system">
        <Btn icon="filter" size="sm" onClick={() => window.toast('Filters applied', 'info')}>Filter</Btn><Btn variant="primary" icon="plus" onClick={() => window.openForm({ title: 'Raise NCR', sub: 'Opens in the shared improvement register (CMP)', icon: 'flag', fields: [{ label: 'Source', type: 'select', options: ['Internal audit', 'Proficiency testing', 'Complaint', 'HSE incident', 'Document control', 'Other'] }, { label: 'Severity', type: 'select', options: ['Minor', 'Major'] }, { label: 'Linked job / certificate', type: 'text', placeholder: 'optional' }, { label: 'Owner', type: 'select', options: window.DB.staff.map((s) => s.name) }, { label: 'Description', type: 'textarea', full: true, placeholder: 'Nonconformity detail & containment…' }], submitLabel: 'Raise NCR', done: 'NCR raised · added to shared register' })}>Raise NCR</Btn>
      </PageHead>
      <div className="kpi-grid" style={{ gridTemplateColumns: 'repeat(5,1fr)', marginBottom: 16 }}>
        <Kpi label="Open NCRs" value={6} icon="flag" tone="warn" />
        <Kpi label="CAPAs in progress" value={4} icon="refresh" tone="info" />
        <Kpi label="Overdue actions" value={2} icon="alert" tone="bad" />
        <Kpi label="Open complaints" value={DB.complaints.filter((c) => c.status !== 'Resolved').length} icon="chat" tone="info" />
        <Kpi label="On-time closure" value="88%" icon="trend" tone="ok" delta="+6%" deltaDir="up" />
      </div>
      <div className="tabs" style={{ marginBottom: 16 }}>{tabs.map(([id, l]) => <div key={id} className={`tab${tab === id ? ' on' : ''}`} onClick={() => setTab(id)}>{l}</div>)}</div>

      {tab === 'capa' && (
        <div className="card">
          <div className="card-head"><Icon name="check-shield" size={16} style={{ color: 'var(--primary-600)' }} /><div className="h-sec" style={{ fontSize: 14 }}>NCR / CAPA register</div><span className="spacer" /><Badge kind="ai" icon="sparkles">AI root-cause suggestions</Badge></div>
          <table className="tbl">
            <thead><tr><th>ID</th><th>Title</th><th>Source</th><th>Severity</th><th>Owner</th><th>Stage</th><th>Due</th><th>Status</th></tr></thead>
            <tbody>
              {DB.capa.map((x) => (
                <tr key={x.id} className="clickable" onClick={() => window.openDetail('capa', x)}>
                  <td className="mono cell-strong" style={{ fontSize: 12 }}>{x.id}</td>
                  <td style={{ fontSize: 12.5, maxWidth: 280 }}>{x.title}</td>
                  <td><span className="tag">{x.source}</span></td>
                  <td><Badge kind={x.severity === 'Major' ? 'bad' : 'warn'}>{x.severity}</Badge></td>
                  <td><Avatar id={x.owner} size="sm" /></td>
                  <td className="faint" style={{ fontSize: 12 }}>{x.stage}</td>
                  <td><span style={{ fontSize: 12, fontWeight: 600, color: x.due < DB.TODAY && x.status !== 'Closed' ? 'var(--bad)' : 'var(--text)' }}>{DB.rel(x.due)}</span></td>
                  <td><StatusBadge status={x.status} /></td>
                </tr>
              ))}
            </tbody>
          </table>
          <div className="card-body" style={{ borderTop: '1px solid var(--border)' }}>
            <AINote title="Recurring theme detected across 3 NCRs" clause="AIX-03" action="Draft systemic CAPA">
              Cylinder-validity and template-revision findings cluster around the gas-store handover. AI suggests a single systemic CAPA and a candidate root cause for review.
            </AINote>
          </div>
        </div>
      )}

      {tab === 'mr' && (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
          <div className="card">
            <div className="card-head"><Icon name="check-shield" size={16} style={{ color: 'var(--primary-600)' }} /><div className="h-sec" style={{ fontSize: 14 }}>Management review register</div><span className="faint" style={{ fontSize: 11, marginLeft: 8 }}>ISO 9001 §9.3 · ISO 17025 §8.9 · ADAM-QSP-L2-P-008</span><span className="spacer" /><Btn size="sm" variant="primary" icon="plus" onClick={() => window.toast('Management review scheduled · agenda circulated', 'info')}>Schedule review</Btn></div>
            <table className="tbl">
              <thead><tr><th>Ref</th><th>Review</th><th>Date</th><th>Chair</th><th>Attendees</th><th className="num">Actions</th><th>Status</th></tr></thead>
              <tbody>{DB.managementReviews.map((m) => (
                <tr key={m.id}><td className="mono cell-strong" style={{ fontSize: 12 }}>{m.id}</td><td style={{ fontSize: 12.5 }}>{m.title}</td><td className="faint">{DB.fmt(m.date)}</td><td><Avatar id={m.chair} size="sm" /></td>
                  <td><div className="row" style={{ gap: -4 }}>{m.attendees.slice(0, 4).map((a, i) => <span key={i} style={{ marginLeft: i ? -6 : 0 }}><Avatar id={a} size="sm" /></span>)}</div></td>
                  <td className="num">{m.actions ? <Badge kind={m.open ? 'warn' : 'ok'}>{m.open ? `${m.open} open` : `${m.actions} ✓`}</Badge> : <span className="faint">—</span>}</td>
                  <td><StatusBadge status={m.status} /></td></tr>
              ))}</tbody>
            </table>
          </div>
          {/* Management review pack (MCR report) */}
          <div className="card">
            <div className="card-head"><Icon name="documents" size={16} style={{ color: 'var(--primary-600)' }} /><div className="h-sec" style={{ fontSize: 14 }}>Management review pack — {latestMR.title}</div><span className="spacer" /><Btn size="sm" variant="ghost" icon="download" onClick={() => window.toast(`${latestMR.id} management review pack exported (PDF)`)}>Download pack</Btn></div>
            <div className="card-body" style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 20 }}>
              <div>
                <div className="eyebrow" style={{ fontSize: 9.5, marginBottom: 8 }}>Inputs reviewed (§9.3.2)</div>
                {latestMR.inputs.map((inp, i) => (
                  <div key={i} className="row" style={{ gap: 9, padding: '6px 0', fontSize: 12.5 }}><Icon name="check-circle" size={15} style={{ color: 'var(--ok)', flex: 'none' }} />{inp}</div>
                ))}
              </div>
              <div>
                <div className="eyebrow" style={{ fontSize: 9.5, marginBottom: 8 }}>Outputs & decisions (§9.3.3)</div>
                {latestMR.outputs.map((o, i) => (
                  <div key={i} className="row" style={{ gap: 9, padding: '6px 0', fontSize: 12.5 }}><Icon name="arrowR" size={14} style={{ color: 'var(--primary-600)', flex: 'none' }} />{o}</div>
                ))}
                <div className="row" style={{ gap: 14, marginTop: 12, paddingTop: 10, borderTop: '1px solid var(--border)' }}>
                  <span className="faint" style={{ fontSize: 12 }}>Actions raised <b style={{ color: 'var(--text)' }}>{latestMR.actions}</b></span>
                  <span className="faint" style={{ fontSize: 12 }}>Open <b style={{ color: latestMR.open ? 'var(--warn)' : 'var(--ok)' }}>{latestMR.open}</b></span>
                  <span className="faint" style={{ fontSize: 12 }}>Chaired by <b style={{ color: 'var(--text)' }}>{DB.staffById(latestMR.chair).name}</b></span>
                </div>
              </div>
            </div>
          </div>
        </div>
      )}

      {tab === 'incidents' && (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
          <div className="card">
            <div className="card-head"><Icon name="helmet" size={16} style={{ color: 'var(--warn)' }} /><div className="h-sec" style={{ fontSize: 14 }}>Incident & near-miss register</div><span className="spacer" /><Btn size="sm" variant="ghost" icon="download" onClick={() => window.toast('HSE incident report generated (PDF)')}>Incident report</Btn><Btn size="sm" variant="primary" icon="plus" onClick={() => window.openForm({ title: 'Report incident / near-miss', sub: 'ADAM-QMS-L4-F-012 · routes to the shared CAPA loop', icon: 'helmet', fields: [{ label: 'Type', type: 'select', options: ['Near miss', 'Incident', 'Property damage'] }, { label: 'Severity', type: 'select', options: ['Low', 'Medium', 'High'] }, { label: 'Location', type: 'text' }, { label: 'Date & time', type: 'datetime-local' }, { label: 'Description', type: 'textarea', full: true, placeholder: 'What happened, immediate action taken…' }], submitLabel: 'Submit report', done: 'Incident reported · CAPA loop opened' })}>Report incident</Btn></div>
            <table className="tbl">
              <thead><tr><th>Ref</th><th>Type</th><th>Description</th><th>Date</th><th>Severity</th><th>Linked CAPA</th><th>Status</th></tr></thead>
              <tbody>{DB.hseIncidents.map((x) => (
                <tr key={x.id} className="clickable" onClick={() => window.openDetail('hse', x)}>
                  <td className="mono cell-strong" style={{ fontSize: 12 }}>{x.id}</td>
                  <td><Badge kind={x.type === 'Incident' ? 'bad' : 'warn'}>{x.type}</Badge></td>
                  <td style={{ fontSize: 12.5 }}>{x.title}</td><td className="faint">{DB.fmt(x.date)}</td>
                  <td><Badge kind={x.severity === 'Medium' ? 'warn' : 'neutral'}>{x.severity}</Badge></td>
                  <td>{x.capa ? <span className="mono" style={{ fontSize: 11.5, color: 'var(--primary-700)' }}>{x.capa}</span> : <span className="faint">—</span>}</td>
                  <td><StatusBadge status={x.status} /></td>
                </tr>))}</tbody>
            </table>
          </div>
          <div className="card">
            <div className="card-head"><Icon name="chat" size={16} style={{ color: 'var(--primary-600)' }} /><div className="h-sec" style={{ fontSize: 14 }}>Customer complaints</div><span className="faint" style={{ fontSize: 11, marginLeft: 8 }}>ISO 17025 §7.9</span></div>
            <table className="tbl">
              <thead><tr><th>Ref</th><th>Customer</th><th>Subject</th><th>Date</th><th>Linked CAPA</th><th>Status</th></tr></thead>
              <tbody>{DB.complaints.map((c) => { const cu = DB.custById(c.customer); return (
                <tr key={c.id}><td className="mono cell-strong" style={{ fontSize: 12 }}>{c.id}</td><td><div className="row" style={{ gap: 7 }}><span className="avatar avatar-sm" style={{ background: cu.color, borderRadius: 6 }}>{cu.short}</span>{cu.short}</div></td><td style={{ fontSize: 12.5 }}>{c.subject}</td><td className="faint">{DB.fmt(c.date)}</td><td>{c.capa ? <span className="mono" style={{ fontSize: 11.5, color: 'var(--primary-700)' }}>{c.capa}</span> : <span className="faint">—</span>}</td><td><StatusBadge status={c.status} /></td></tr>
              ); })}</tbody>
            </table>
          </div>
        </div>
      )}

      {tab === 'audits' && (
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16, alignItems: 'start' }}>
          <div className="card">
            <div className="card-head"><Icon name="check-shield" size={16} style={{ color: 'var(--primary-600)' }} /><div className="h-sec" style={{ fontSize: 14 }}>Internal audits</div><span className="spacer" /><Badge kind="neutral">ADAM-QSP-L2-P-004</Badge></div>
            <table className="tbl">
              <thead><tr><th>Ref</th><th>Scope</th><th>Date</th><th>Auditor</th><th className="num">Findings</th><th>Status</th></tr></thead>
              <tbody>{DB.internalAudits.map((a) => (
                <tr key={a.id}><td className="mono cell-strong" style={{ fontSize: 11.5 }}>{a.id}</td><td style={{ fontSize: 12 }}>{a.scope}</td><td className="faint">{DB.fmt(a.date)}</td><td><Avatar id={a.auditor} size="sm" /></td><td className="num">{a.findings}{a.major ? <span style={{ color: 'var(--bad)' }}> ({a.major} maj)</span> : ''}</td><td><StatusBadge status={a.status} /></td></tr>
              ))}</tbody>
            </table>
          </div>
          <div className="card">
            <div className="card-head"><Icon name="alert" size={16} style={{ color: 'var(--warn)' }} /><div className="h-sec" style={{ fontSize: 14 }}>Risk & opportunity register</div></div>
            <table className="tbl">
              <thead><tr><th>Ref</th><th>Area / task</th><th>Next review</th><th>Status</th></tr></thead>
              <tbody>{DB.riskAssessments.map((r) => (
                <tr key={r.id} className="clickable" onClick={() => window.openDetail('risk', r)}><td className="mono cell-strong" style={{ fontSize: 11.5 }}>{r.id}</td><td style={{ fontSize: 12, fontWeight: 600 }}>{r.area}</td><td><span style={{ fontWeight: 600, color: r.review <= DB.TODAY ? 'var(--bad)' : 'var(--text)' }}>{DB.rel(r.review)}</span></td><td><StatusBadge status={r.status} /></td></tr>
              ))}</tbody>
            </table>
          </div>
        </div>
      )}
    </div>
  );
}

Object.assign(window, { CylindersModule, AssetsModule, CRMModule, ScheduleModule, QMSModule, PageHead });
