/* =====================================================================
   AI-COS — Supporting modules (part 2):
   Inventory · Finance · Document Control · Reporting · AI Intelligence
   ===================================================================== */

/* ---------------- Inventory & Spare Parts ------------------------- */
function InventoryModule({ onNav }) {
  const DB = window.DB;
  return (
    <div className="page page-wide rise">
      <PageHead title="Inventory &amp; Spare Parts" sub="Sensors · filters · batteries · consumables — GRN, batch/lot traceability, min-stock alerts">
        <Btn icon="box" size="sm" onClick={() => window.openForm({ title: 'Record goods receipt (GRN)', icon: 'box', fields: [{ label: 'Item', type: 'select', options: window.DB.inventory.map((i) => i.name) }, { label: 'Quantity', type: 'number' }, { label: 'Batch / lot', type: 'text' }, { label: 'Vendor', type: 'select', options: ['Dräger', 'Honeywell', 'MSA', 'Generic'] }, { label: 'Expiry (if any)', type: 'date' }, { label: 'Supplier certificate', type: 'text', placeholder: 'ref' }], submitLabel: 'Receive', done: 'Goods receipt recorded' })}>GRN</Btn><Btn variant="primary" icon="plus" onClick={() => window.openForm({ title: 'Issue stock to job', icon: 'box', fields: [{ label: 'Item', type: 'select', options: window.DB.inventory.map((i) => i.name) }, { label: 'Job', type: 'select', options: window.DB.jobs.map((j) => j.id) }, { label: 'Quantity', type: 'number' }, { label: 'Batch / lot', type: 'text' }, { label: 'Technician', type: 'select', options: window.DB.staff.map((s) => s.name) }], submitLabel: 'Issue', done: 'Stock issued · lot traced to job & equipment' })}>Issue to job</Btn>
      </PageHead>
      <div className="kpi-grid" style={{ gridTemplateColumns: 'repeat(4,1fr)', marginBottom: 16 }}>
        <Kpi label="SKUs tracked" value={64} icon="box" tone="info" />
        <Kpi label="Below minimum" value={DB.inventory.filter(i => i.status === 'Low').length} icon="alert" tone="warn" delta="reorder suggested" />
        <Kpi label="Stock value" value="6.2K" unit="OMR" icon="receipt" tone="info" />
        <Kpi label="Lots traceable" value="100%" icon="link" tone="ok" delta="recall-ready" />
      </div>
      <div className="card">
        <div className="card-head"><Icon name="box" size={16} style={{ color: 'var(--primary-600)' }} /><div className="h-sec" style={{ fontSize: 14 }}>Item master</div></div>
        <table className="tbl">
          <thead><tr><th>Item</th><th>Name</th><th>Category</th><th>On hand</th><th>Min</th><th>Vendor</th><th>Batch/lot</th><th>Status</th></tr></thead>
          <tbody>
            {DB.inventory.map((it) => (
              <tr key={it.id} className="clickable" onClick={() => window.openDetail('inventory', it)}>
                <td className="mono cell-strong" style={{ fontSize: 12 }}>{it.id}</td>
                <td style={{ fontSize: 12.5 }}>{it.name}</td>
                <td><span className="tag">{it.cat}</span></td>
                <td style={{ width: 120 }}><div className="row" style={{ gap: 7 }}><div style={{ width: 50 }}><Bar pct={Math.min(100, (it.qty / (it.min * 2)) * 100)} color={it.status === 'Low' ? 'var(--warn)' : 'var(--ok)'} /></div><b className="mono">{it.qty}</b> <span className="faint">{it.uom}</span></div></td>
                <td className="num mono faint">{it.min}</td>
                <td className="faint" style={{ fontSize: 12 }}>{it.vendor}</td>
                <td className="mono faint" style={{ fontSize: 11.5 }}>{it.batch}</td>
                <td><StatusBadge status={it.status} /></td>
              </tr>
            ))}
          </tbody>
        </table>
        <div className="card-body" style={{ borderTop: '1px solid var(--border)' }}>
          <AINote title="2 items below minimum · sensor failure predicted" clause="AIX-07" action="Create purchase request">
            CO sensors and Li-ion packs are low. AI predicts 3 H₂S sensor replacements next cycle from age + drift — pre-stocking avoids job delays.
          </AINote>
        </div>
      </div>
    </div>
  );
}

/* ---------------- Finance & Billing ------------------------------- */
function FinanceModule({ onNav }) {
  const DB = window.DB;
  const [tab, setTab] = useState('invoices');
  return (
    <div className="page page-wide rise">
      <PageHead title="Finance &amp; Billing" sub="Quote-to-invoice · AMC billing · Oman VAT (5%) · payments &amp; per-client profitability">
        <Btn icon="download" size="sm" onClick={() => window.toast('Invoices exported to accounting (file)')}>Export to accounting</Btn><Btn variant="primary" icon="plus" onClick={() => window.openForm({ title: 'New invoice', sub: 'VAT 5% · gap-free numbering (FIN-01)', icon: 'receipt', fields: [{ label: 'Customer', type: 'select', options: window.DB.customers.map((c) => c.name) }, { label: 'Source', type: 'select', options: ['Completed job', 'AMC schedule'] }, { label: 'Amount net (OMR)', type: 'number' }, { label: 'VAT %', type: 'number', value: '5' }, { label: 'Payment terms', type: 'select', options: ['30 days net', '45 days net', 'On receipt'] }], submitLabel: 'Create invoice', done: 'Invoice drafted · VAT 5% · gap-free number assigned' })}>New invoice</Btn>
      </PageHead>
      <div className="kpi-grid" style={{ gridTemplateColumns: 'repeat(4,1fr)', marginBottom: 16 }}>
        <Kpi label="Invoiced (Jun)" value="18.4K" unit="OMR" icon="receipt" tone="info" delta="+8%" deltaDir="up" />
        <Kpi label="Outstanding" value="6.4K" unit="OMR" icon="clock" tone="warn" />
        <Kpi label="Overdue" value="1.6K" unit="OMR" icon="alert" tone="bad" delta="1 invoice" />
        <Kpi label="Collection rate" value="94%" icon="trend" tone="ok" delta="+3%" deltaDir="up" />
      </div>
      <div className="tabs" style={{ marginBottom: 16 }}>{[['invoices', 'Invoices'], ['payments', 'Payments & aging'], ['amc', 'AMC billing'], ['profit', 'Profitability']].map(([id, l]) => <div key={id} className={`tab${tab === id ? ' on' : ''}`} onClick={() => setTab(id)}>{l}</div>)}</div>

      {tab === 'invoices' && (
        <div className="card">
          <div className="card-head"><Icon name="receipt" size={16} style={{ color: 'var(--primary-600)' }} /><div className="h-sec" style={{ fontSize: 14 }}>Invoices</div><span className="spacer" /><span className="faint" style={{ fontSize: 12 }}>VAT-compliant · gap-free numbering · 3-decimal OMR</span></div>
          <table className="tbl">
            <thead><tr><th>Invoice №</th><th>Customer</th><th className="num">Amount (OMR)</th><th>VAT</th><th>Issued</th><th>Due</th><th>Status</th><th></th></tr></thead>
            <tbody>
              {DB.invoices.map((iv) => { const c = DB.custById(iv.customer); return (
                <tr key={iv.id} className="clickable" onClick={() => window.openDetail('invoice', iv)}>
                  <td className="mono cell-strong" style={{ fontSize: 12 }}>{iv.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 cell-strong">{iv.amount.toFixed(3)}</td>
                  <td className="faint">{iv.vat}%</td>
                  <td className="faint">{DB.fmt(iv.date)}</td>
                  <td><span style={{ fontWeight: 600, color: iv.status === 'Overdue' ? 'var(--bad)' : 'var(--text)' }}>{DB.fmt(iv.due)}</span></td>
                  <td><StatusBadge status={iv.status} /></td>
                  <td><Icon name="chevR" size={16} style={{ color: 'var(--text-3)' }} /></td>
                </tr>
              ); })}
            </tbody>
          </table>
        </div>
      )}

      {tab === 'payments' && (
        <div className="card">
          <div className="card-head"><Icon name="check-circle" size={16} style={{ color: 'var(--ok)' }} /><div className="h-sec" style={{ fontSize: 14 }}>Payments received</div></div>
          <table className="tbl">
            <thead><tr><th>Receipt №</th><th>Invoice</th><th>Customer</th><th className="num">Amount (OMR)</th><th>Date</th><th>Method</th></tr></thead>
            <tbody>
              {DB.payments.map((p) => { const c = DB.custById(p.customer); return (
                <tr key={p.id} className="clickable" onClick={() => window.toast(`${p.id} receipt opened`, 'info')}>
                  <td className="mono cell-strong" style={{ fontSize: 12 }}>{p.id}</td>
                  <td className="mono" style={{ fontSize: 11.5 }}>{p.invoice}</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 cell-strong">{p.amount.toFixed(3)}</td>
                  <td className="faint">{DB.fmt(p.date)}</td>
                  <td><span className="tag">{p.method}</span></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 billing schedule</div><span className="spacer" /><span className="faint" style={{ fontSize: 11.5 }}>Auto-generates draft invoices</span></div>
          <table className="tbl">
            <thead><tr><th>Contract</th><th>Customer</th><th>Frequency</th><th>Next billing</th><th className="num">Amount (OMR)</th><th>Status</th><th></th></tr></thead>
            <tbody>
              {DB.amcBilling.map((a) => { const c = DB.custById(a.customer); return (
                <tr key={a.id} className="clickable" onClick={() => window.openDetail('contract', DB.contracts.find((x) => x.id === a.id) || DB.contracts[0])}>
                  <td className="mono cell-strong" style={{ fontSize: 12 }}>{a.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="faint" style={{ fontSize: 12 }}>{a.freq}</td>
                  <td><span style={{ fontWeight: 600, color: a.status === 'Due' ? 'var(--bad)' : 'var(--text)' }}>{DB.fmt(a.next)} · {DB.rel(a.next)}</span></td>
                  <td className="num mono cell-strong">{a.amount.toFixed(3)}</td>
                  <td><Badge kind={a.status === 'Due' ? 'warn' : 'info'} dot>{a.status}</Badge></td>
                  <td><Btn size="sm" variant="ghost" onClick={(e) => { e.stopPropagation(); window.toast(`Draft invoice generated for ${a.id}`); }}>Generate</Btn></td>
                </tr>
              ); })}
            </tbody>
          </table>
        </div>
      )}

      {tab === 'profit' && (
        <div className="card">
          <div className="card-head"><Icon name="trend" size={16} style={{ color: 'var(--primary-600)' }} /><div className="h-sec" style={{ fontSize: 14 }}>Per-client profitability (YTD)</div></div>
          <table className="tbl">
            <thead><tr><th>Customer</th><th className="num">Revenue</th><th className="num">Cost</th><th className="num">Margin</th><th>Margin %</th><th className="num">Jobs</th></tr></thead>
            <tbody>
              {DB.profitability.map((p) => { const c = DB.custById(p.customer); const margin = p.revenue - p.cost; const pct = Math.round((margin / p.revenue) * 100); return (
                <tr key={p.customer} className="clickable" onClick={() => window.openDetail('customer', c)}>
                  <td><div className="row" style={{ gap: 6 }}><span className="avatar avatar-sm" style={{ background: c.color, borderRadius: 6 }}>{c.short}</span>{c.name.split(' ').slice(0, 2).join(' ')}</div></td>
                  <td className="num mono">{p.revenue.toLocaleString()}</td>
                  <td className="num mono faint">{p.cost.toLocaleString()}</td>
                  <td className="num mono cell-strong">{margin.toLocaleString()}</td>
                  <td style={{ width: 130 }}><div className="row" style={{ gap: 7 }}><div style={{ width: 60 }}><Bar pct={pct} color={pct > 30 ? 'var(--ok)' : pct > 15 ? 'var(--warn)' : 'var(--bad)'} /></div><b className="mono" style={{ fontSize: 12 }}>{pct}%</b></div></td>
                  <td className="num mono faint">{p.jobs}</td>
                </tr>
              ); })}
            </tbody>
          </table>
        </div>
      )}
    </div>
  );
}

/* ---------------- Document Control (ADAM real register) ----------- */
function DocsModule({ onNav }) {
  const DB = window.DB;
  const [tab, setTab] = useState('master');
  const [level, setLevel] = useState('All');
  const [modal, setModal] = useState(false);
  const levels = ['All', 'L1', 'L2', 'L3', 'L4'];
  const levelName = { L1: 'Policies & Manual', L2: 'Quality Procedures', L3: 'Technical', L4: 'Forms' };
  const list = DB.docReg.filter((d) => level === 'All' || d.level === level);
  const tabs = [['master', 'Master list'], ['ack', 'Read & acknowledge'], ['dcr', 'Change requests'], ['external', 'External documents']];
  const readers = DB.staff;
  const ackCell = (code, sid) => ((code.length * 7 + sid.charCodeAt(sid.length - 1) * 3) % 5) !== 0;
  return (
    <div className="page page-wide rise">
      <PageHead title="Document Control" sub="Controlled QMS documents · ADAM-QSP-L2-P-001 · approval workflow, revisions, obsolete control & read-acknowledgment">
        <Btn icon="download" size="sm" onClick={() => window.toast('Master list (F-022) exported to PDF')}>Master list</Btn>
        <Btn variant="primary" icon="plus" onClick={() => setModal(true)}>New document</Btn>
      </PageHead>
      <div className="kpi-grid" style={{ gridTemplateColumns: 'repeat(4,1fr)', marginBottom: 16 }}>
        <Kpi label="Controlled documents" value={DB.docReg.length} icon="documents" tone="info" delta="L1–L4 register" />
        <Kpi label="Published" value={DB.docReg.filter((d) => d.status === 'Published').length} icon="check-circle" tone="ok" />
        <Kpi label="Review overdue" value={DB.docReg.filter((d) => d.reviewDate <= DB.TODAY).length} icon="alert" tone="bad" />
        <Kpi label="Pending change requests" value={DB.docChangeRequests.filter((d) => d.status === 'Pending approval').length} icon="refresh" tone="warn" />
      </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 === 'master' && (
        <div className="card">
          <div className="card-head"><Icon name="documents" size={16} style={{ color: 'var(--primary-600)' }} /><div className="h-sec" style={{ fontSize: 14 }}>QMS document master list</div><span className="spacer" /><div className="seg">{levels.map((l) => <button key={l} className={level === l ? 'on' : ''} onClick={() => setLevel(l)}>{l}</button>)}</div></div>
          <table className="tbl">
            <thead><tr><th>Document code</th><th>Title</th><th>Type</th><th>Level</th><th>Ver</th><th>Owner</th><th>Next review</th><th>Ack.</th><th>Status</th></tr></thead>
            <tbody>{list.map((d) => (
              <tr key={d.code} className="clickable" onClick={() => window.openDetail('document', d)}>
                <td className="mono cell-strong" style={{ fontSize: 11.5 }}>{d.code}</td>
                <td style={{ fontSize: 12.5 }}>{d.title}</td>
                <td className="faint" style={{ fontSize: 11.5 }}>{d.type}</td>
                <td><Badge kind="neutral">{d.level}</Badge></td>
                <td><Badge kind="ink">{d.ver}</Badge></td>
                <td><Avatar id={d.owner} size="sm" /></td>
                <td><span style={{ fontSize: 12, fontWeight: 600, color: d.reviewDate <= DB.TODAY ? 'var(--bad)' : (d.reviewDate - DB.TODAY) / 864e5 < 30 ? 'var(--warn)' : 'var(--text)' }}>{d.reviewRel}</span></td>
                <td style={{ width: 88 }}><div className="row" style={{ gap: 6 }}><div style={{ width: 42 }}><Bar pct={d.ack} color={d.ack > 90 ? 'var(--ok)' : 'var(--warn)'} /></div><span className="faint" style={{ fontSize: 10.5 }}>{d.ack}%</span></div></td>
                <td><StatusBadge status={d.status} /></td>
              </tr>))}</tbody>
          </table>
        </div>
      )}
      {tab === 'ack' && (() => {
        const reqDocs = DB.docReg.filter((d) => d.level === 'L1' || d.level === 'L2');
        const pendingTotal = reqDocs.reduce((n, d) => n + readers.filter((s) => !ackCell(d.code, s.id)).length, 0);
        return (
          <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 }}>Distribution &amp; read-acknowledgment matrix</div>
              <span className="faint" style={{ fontSize: 11, marginLeft: 8 }}>— who must read each controlled document (DOC-04)</span>
              <span className="spacer" />
              {pendingTotal > 0 && <Badge kind="warn" dot>{pendingTotal} acknowledgments pending</Badge>}
              <Btn size="sm" variant="ghost" icon="bell" onClick={() => window.toast('Read-reminders sent to staff with pending acknowledgments', 'info')}>Remind pending</Btn>
            </div>
            <table className="tbl">
              <thead><tr><th>Controlled document</th>{readers.map((s) => <th key={s.id} style={{ textAlign: 'center' }} title={s.name}>{s.initials}</th>)}<th className="num">Ack.</th></tr></thead>
              <tbody>
                {reqDocs.map((d) => {
                  const cells = readers.map((s) => ackCell(d.code, s.id));
                  const pct = Math.round((cells.filter(Boolean).length / cells.length) * 100);
                  return (
                    <tr key={d.code} className="clickable" onClick={() => window.openDetail('document', d)}>
                      <td><div style={{ fontSize: 12.5, fontWeight: 650 }}>{d.title}</div><div className="mono faint" style={{ fontSize: 10.5 }}>{d.code} · {d.ver}</div></td>
                      {cells.map((ok, i) => <td key={i} style={{ textAlign: 'center' }}>{ok ? <Icon name="check" size={13} style={{ color: 'var(--ok)' }} /> : <span style={{ display: 'inline-block', width: 7, height: 7, borderRadius: '50%', background: 'var(--warn)' }} title="Pending read" />}</td>)}
                      <td className="num"><Badge kind={pct === 100 ? 'ok' : 'warn'}>{pct}%</Badge></td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
            <div className="card-body" style={{ borderTop: '1px solid var(--border)' }}>
              <div className="row" style={{ gap: 16, fontSize: 11.5, flexWrap: 'wrap' }}>
                <span className="row" style={{ gap: 6 }}><Icon name="check" size={12} style={{ color: 'var(--ok)' }} />Acknowledged</span>
                <span className="row" style={{ gap: 6 }}><span style={{ width: 7, height: 7, borderRadius: '50%', background: 'var(--warn)' }} />Pending read</span>
                <span className="faint">Only published versions require acknowledgment; a new revision resets the matrix and re-notifies assigned readers (DOC-02 / DOC-04).</span>
              </div>
            </div>
          </div>
        );
      })()}
      {tab === 'dcr' && (
        <div className="card">
          <div className="card-head"><Icon name="refresh" size={16} style={{ color: 'var(--primary-600)' }} /><div className="h-sec" style={{ fontSize: 14 }}>Document change requests (F-035)</div></div>
          <table className="tbl">
            <thead><tr><th>DCR</th><th>Document</th><th>Requested change</th><th>By</th><th>Date</th><th>Status</th></tr></thead>
            <tbody>{DB.docChangeRequests.map((d) => (
              <tr key={d.id} className="clickable" onClick={() => window.openDetail('dcr', d)}>
                <td className="mono cell-strong" style={{ fontSize: 12 }}>{d.id}</td><td className="mono" style={{ fontSize: 11.5 }}>{d.doc}</td>
                <td style={{ fontSize: 12.5 }}>{d.desc}</td><td><Avatar id={d.by} size="sm" /></td><td className="faint">{DB.fmt(d.date)}</td>
                <td><Badge kind={d.status === 'Pending approval' ? 'warn' : d.status === 'Approved' ? 'info' : 'ok'} dot>{d.status}</Badge></td>
              </tr>))}</tbody>
          </table>
        </div>
      )}
      {tab === 'external' && (
        <div className="card">
          <div className="card-head"><Icon name="link" size={16} style={{ color: 'var(--primary-600)' }} /><div className="h-sec" style={{ fontSize: 14 }}>External document register (F-036)</div></div>
          <table className="tbl">
            <thead><tr><th>Reference</th><th>Title</th><th>Source</th><th>Edition</th></tr></thead>
            <tbody>{DB.externalDocs.map((d) => (
              <tr key={d.code}><td className="mono cell-strong" style={{ fontSize: 12 }}>{d.code}</td><td style={{ fontSize: 12.5 }}>{d.title}</td><td><span className="tag">{d.source}</span></td><td className="faint">{d.ver}</td></tr>))}</tbody>
          </table>
        </div>
      )}
      {tab === 'master' && (
        <div style={{ marginTop: 16 }}>
          <AINote title="2 documents past their review date" clause="AIX-02" action="Notify owners" onAction={() => { window.toast('Review reminders sent to owners', 'info'); }}>
            Review dates impact audit readiness. AI can summarise changes since the last version for each reviewer.
          </AINote>
        </div>
      )}
      {modal && <FormModal title="New controlled document" sub="Draft → review → approve → publish" icon="documents" fields={[
        { label: 'Document code', type: 'text', placeholder: 'ADAM-QSP-L2-P-0XX' },
        { label: 'Level', type: 'select', options: ['L1 — Policy/Manual', 'L2 — Procedure', 'L3 — Technical', 'L4 — Form'] },
        { label: 'Title', type: 'text', full: true, placeholder: 'Document title' },
        { label: 'Owner', type: 'select', options: DB.staff.map((s) => s.name) },
        { label: 'Review frequency', type: 'select', options: ['Annual', '2-yearly', '3-yearly'] },
      ]} onClose={() => setModal(false)} onSubmit={() => { setModal(false); window.toast('Document created as Draft — sent for review'); }} wide />}
    </div>
  );
}

/* ---------------- Reporting --------------------------------------- */
function ReportsModule({ onNav }) {
  const cards = [
    ['Operational KPIs', 'chart', 'Turnaround, SLA, throughput, workload', 'var(--primary-600)', 'jobs'],
    ['Compliance dashboard', 'check-shield', 'NCR/CAPA, audit readiness, PT status', 'var(--ok)', 'qms'],
    ['Cylinder consumption', 'cylinder', 'Usage per gas type, reorder forecast', 'var(--warn)', 'cylinders'],
    ['Certificate register', 'certificate', 'Issued, superseded, by customer', 'var(--ai)', 'certs'],
    ['Financial summary', 'receipt', 'Invoiced, outstanding, profitability', 'var(--primary-600)', 'finance'],
    ['Asset due forecast', 'calendar', 'Due/overdue projection, AMC coverage', 'var(--bad)', 'schedule'],
    ['Management review pack', 'check-shield', 'ISO 9001 §9.3 inputs, outputs & actions', 'var(--ai)', 'qms'],
    ['HSE incident report', 'helmet', 'Incidents, near-miss, complaints & CAPA links', 'var(--warn)', 'hse'],
  ];
  return (
    <div className="page page-wide rise">
      <PageHead title="Reporting &amp; Dashboards" sub="Operational &amp; compliance KPIs · PDF/XLSX export · Power BI connector (Phase 3)">
        <Btn icon="download" size="sm" onClick={() => window.toast('Report scheduled · weekly email', 'info')}>Schedule report</Btn><Btn variant="primary" icon="plus" onClick={() => window.toast('Report builder opened', 'info')}>Build report</Btn>
      </PageHead>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3,1fr)', gap: 14 }}>
        {cards.map(([t, ic, d, col, target], i) => (
          <div key={i} className="card hover-lift card-pad" style={{ cursor: 'pointer' }} onClick={() => { window.toast(`${t} — opening`, 'info'); onNav(target); }}>
            <div className="row" style={{ justifyContent: 'space-between', marginBottom: 12 }}>
              <span className="kpi-ico" style={{ width: 38, height: 38, background: 'var(--bg)', color: col }}><Icon name={ic} size={19} /></span>
              <Icon name="ext" size={15} style={{ color: 'var(--text-3)' }} />
            </div>
            <div style={{ fontWeight: 750, fontSize: 14.5 }}>{t}</div>
            <div className="muted" style={{ fontSize: 12.5, marginTop: 3 }}>{d}</div>
            <div className="row" style={{ gap: 6, marginTop: 12 }}>
              <span className="tag"><Icon name="download" size={11} /> PDF</span><span className="tag">XLSX</span>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

/* ---------------- AI Intelligence overview ------------------------ */
function AIModule({ onNav }) {
  const DB = window.DB;
  const caps = [
    ['Audit-readiness scoring', 'Continuously computed from open items, expiries & overdue docs', 'check-shield', 'P1', 'var(--ok)'],
    ['Overdue-risk ranking', 'Ranks equipment & customers likely to miss due dates', 'trend', 'P1', 'var(--primary-600)'],
    ['CAPA suggestions', 'Recurring-issue detection & root-cause candidates', 'refresh', 'P1', 'var(--ai)'],
    ['Calibration drift analysis', 'Per-sensor as-found trend toward tolerance', 'gauge', 'P2', 'var(--warn)'],
    ['Sensor-failure prediction', 'Age + drift + repair history → proactive replacement', 'cpu', 'P2', 'var(--bad)'],
    ['Standards assistant', 'Answers ISO clause questions citing your own SOPs', 'documents', 'P2', 'var(--primary-600)'],
  ];
  return (
    <div className="page page-wide rise">
      <PageHead title="AI Compliance &amp; Calibration Intelligence" sub="Advisory · labelled · logged · human-confirmed — assistance at the point of work, never an autonomous record" />
      <div className="card card-pad" style={{ marginBottom: 16, background: 'linear-gradient(120deg, var(--ai-bg), #fff)', borderColor: 'var(--ai-line)' }}>
        <div className="row" style={{ gap: 14 }}>
          <span className="ai-badge-ico" style={{ width: 44, height: 44 }}><Icon name="sparkles" size={22} fill /></span>
          <div style={{ flex: 1 }}>
            <div style={{ fontWeight: 750, fontSize: 15 }}>Every AI output is a suggestion, not a decision</div>
            <div className="muted" style={{ fontSize: 12.5 }}>Predictions, flags and drafts require a human action to become records — and each is written to the audit trail with its rationale.</div>
          </div>
          <Btn variant="ai" icon="history" onClick={() => window.toast('AI decision log opened · every suggestion + outcome', 'ai')}>View AI audit log</Btn>
        </div>
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3,1fr)', gap: 14, marginBottom: 16 }}>
        {caps.map(([t, d, ic, ph, col], i) => (
          <div key={i} className="card hover-lift card-pad">
            <div className="row" style={{ justifyContent: 'space-between', marginBottom: 10 }}>
              <span className="kpi-ico" style={{ width: 36, height: 36, background: 'var(--bg)', color: col }}><Icon name={ic} size={18} /></span>
              <Badge kind="neutral">Phase {ph.replace('P', '')}</Badge>
            </div>
            <div style={{ fontWeight: 700, fontSize: 14 }}>{t}</div>
            <div className="muted" style={{ fontSize: 12, marginTop: 3 }}>{d}</div>
          </div>
        ))}
      </div>
      <div className="card">
        <div className="card-head"><Icon name="flag" size={15} style={{ color: 'var(--ai)' }} /><div className="h-sec" style={{ fontSize: 14 }}>Live signals</div></div>
        <div className="card-body" style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
          {DB.aiAlerts.map((a) => <AINote key={a.id} title={a.title} clause={a.clause} action={a.action} onAction={() => onNav('iso')}>{a.body}</AINote>)}
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { InventoryModule, FinanceModule, DocsModule, ReportsModule, AIModule });
