/* =====================================================================
   AI-COS — Modules: Competency · HSE · PM · Field Service · Administration
   (data + codes from Al Duqum Al Masiya ENT real QMS register)
   ===================================================================== */

/* ---------------- Competency & Training --------------------------- */
function CompetencyModule({ onNav }) {
  const DB = window.DB;
  const [modal, setModal] = useState(false);
  const methods = DB.methods.filter((m) => m.id !== 'CAL-MD-016');
  const grantMap = { S: ['Sign', 'b-ok'], R: ['Review', 'b-info'], E: ['Execute', 'b-warn'], '-': ['—', 'b-neutral'] };
  return (
    <div className="page page-wide rise">
      <PageHead title="Competency &amp; Training" sub="Method-level authorization matrix · OEM certifications · ADAM-QSP-L2-P-009 · expiry auto-de-authorizes">
        <Btn icon="download" size="sm" onClick={() => window.toast('Training matrix (F-031) exported')}>Training matrix</Btn>
        <Btn variant="primary" icon="plus" onClick={() => setModal(true)}>New assessment</Btn>
      </PageHead>
      <div className="kpi-grid" style={{ gridTemplateColumns: 'repeat(4,1fr)', marginBottom: 16 }}>
        <Kpi label="Authorized personnel" value={DB.competency.length} icon="users" tone="ok" />
        <Kpi label="Expiring < 60 days" value={DB.competency.filter((c) => (c.exp - DB.TODAY) / 864e5 < 60).length} icon="clock" tone="warn" />
        <Kpi label="OEM certifications" value={9} icon="star" tone="info" />
        <Kpi label="Assessments due" value={2} icon="flag" tone="warn" />
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 320px', 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 }}>Competency matrix</div><span className="spacer" /><span className="faint" style={{ fontSize: 11 }}>Grants: execute · review · sign</span></div>
          <table className="tbl">
            <thead><tr><th>Person</th>{methods.map((m) => <th key={m.id} style={{ textAlign: 'center' }}>{m.id.replace('CAL-MD-', 'MD-').replace('BUMP-SOP-03', 'BUMP')}</th>)}<th>OEM</th><th>Auth. expiry</th></tr></thead>
            <tbody>
              {DB.competency.map((c) => {
                const s = DB.staffById(c.staff);
                return (
                  <tr key={c.staff} className="clickable" onClick={() => window.openDetail('person', c)}>
                    <td><div className="row" style={{ gap: 8 }}><Avatar id={c.staff} size="sm" /><div><div style={{ fontSize: 12.5, fontWeight: 650 }}>{s.name}</div><div className="cell-sub">{s.role}</div></div></div></td>
                    {methods.map((m) => { const g = c.grants[m.id] || '-'; const [lbl, cls] = grantMap[g]; return <td key={m.id} style={{ textAlign: 'center' }}><span className={`badge ${cls}`} style={{ minWidth: 28, justifyContent: 'center' }}>{g === '-' ? '—' : g}</span></td>; })}
                    <td className="faint" style={{ fontSize: 11.5 }}>{c.oem}</td>
                    <td><span style={{ fontSize: 12, fontWeight: 600, color: (c.exp - DB.TODAY) / 864e5 < 60 ? 'var(--warn)' : 'var(--text)' }}>{DB.rel(c.exp)}</span></td>
                  </tr>
                );
              })}
            </tbody>
          </table>
          <div className="card-body" style={{ borderTop: '1px solid var(--border)', display: 'flex', gap: 14 }}>
            {Object.entries(grantMap).filter(([k]) => k !== '-').map(([k, [lbl, cls]]) => <span key={k} className="row" style={{ gap: 6, fontSize: 11.5 }}><span className={`badge ${cls}`}>{k}</span>{lbl}</span>)}
          </div>
        </div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
          <div className="card card-pad">
            <div className="eyebrow" style={{ marginBottom: 10 }}>Authorizations expiring</div>
            {DB.competency.filter((c) => (c.exp - DB.TODAY) / 864e5 < 60).map((c) => (
              <div key={c.staff} className="lrow"><Avatar id={c.staff} size="sm" /><div style={{ flex: 1 }}><div style={{ fontSize: 12.5, fontWeight: 600 }}>{DB.staffById(c.staff).name}</div><div className="faint" style={{ fontSize: 11 }}>OEM cert · {c.oem}</div></div><Badge kind="warn">{DB.rel(c.exp)}</Badge></div>
            ))}
          </div>
          <AINote title="Expiry will remove an authorization" clause="CTY-02" action="Schedule renewal" onAction={() => window.toast('Renewal assessment scheduled', 'info')}>
            T. Bukhari's Ind. Scientific OEM cert expires soon — on expiry the system auto-removes his execute grant, blocking assignment until reassessed.
          </AINote>
        </div>
      </div>
      {modal && <FormModal title="New competency assessment" sub="ADAM-QMS-L4-F-008 · practical assessment record" icon="check-shield" fields={[
        { label: 'Person', type: 'select', options: DB.staff.map((s) => s.name) },
        { label: 'Method / asset class', type: 'select', options: methods.map((m) => `${m.id} — ${m.title}`) },
        { label: 'Grant level', type: 'select', options: ['Execute', 'Review', 'Sign'] },
        { label: 'Assessor', type: 'select', options: ['Sana Iqbal', 'Ahmed Al Habsi'] },
        { label: 'Outcome', type: 'select', options: ['Competent', 'Further training required'] },
        { label: 'Notes', type: 'textarea', full: true, placeholder: 'Assessment criteria & evidence…' },
      ]} onClose={() => setModal(false)} onSubmit={() => { setModal(false); window.toast('Assessment recorded — authorization updated'); }} wide />}
    </div>
  );
}

/* ---------------- HSE Management ---------------------------------- */
function HSEModule({ onNav }) {
  const DB = window.DB;
  const [tab, setTab] = useState('incidents');
  const [modal, setModal] = useState(false);
  const tabs = [['incidents', 'Incidents & near-miss'], ['risk', 'Risk assessments'], ['ptw', 'Permit to work'], ['toolbox', 'Toolbox talks & observations'], ['drills', 'Drills & training'], ['sds', 'SDS register']];
  return (
    <div className="page page-wide rise">
      <PageHead title="HSE Management" sub="Incidents · risk assessments · PTW · SDS — feeding the same CAPA improvement loop">
        <Btn icon="filter" size="sm" onClick={() => window.toast('Filters applied', 'info')}>Filter</Btn>
        <Btn variant="primary" icon="plus" onClick={() => setModal(true)}>Report incident</Btn>
      </PageHead>
      <div className="kpi-grid" style={{ gridTemplateColumns: 'repeat(4,1fr)', marginBottom: 16 }}>
        <Kpi label="Open incidents" value={DB.hseIncidents.filter((i) => i.status !== 'Closed').length} icon="helmet" tone="warn" />
        <Kpi label="Days since LTI" value={184} icon="check-circle" tone="ok" delta="no lost-time injury" />
        <Kpi label="Active permits" value={DB.ptw.filter((p) => p.status === 'Active').length} icon="flag" tone="info" />
        <Kpi label="SDS review due" value={DB.sds.filter((s) => s.review <= DB.TODAY).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 === 'incidents' && (
        <div className="card"><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>
      )}
      {tab === 'risk' && (
        <div className="card"><table className="tbl">
          <thead><tr><th>Ref</th><th>Area / task</th><th>Controls</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: 12 }}>{r.id}</td><td style={{ fontSize: 12.5, fontWeight: 600 }}>{r.area}</td>
              <td className="faint" style={{ fontSize: 12 }}>{r.controls}</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>
      )}
      {tab === 'ptw' && (
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2,1fr)', gap: 14 }}>
          {DB.ptw.map((p) => (
            <div key={p.id} className="card card-pad hover-lift" style={{ cursor: 'pointer' }} onClick={() => window.openDetail('ptw', p)}>
              <div className="row" style={{ justifyContent: 'space-between' }}><span className="mono cell-strong">{p.id}</span><StatusBadge status={p.status} /></div>
              <div style={{ fontSize: 13.5, fontWeight: 650, marginTop: 8 }}>{p.job}</div>
              <div className="row" style={{ gap: 14, marginTop: 8 }}><span className="tag">{p.type}</span><span className="faint" style={{ fontSize: 11.5 }}><Icon name="clock" size={11} /> {p.validity}</span></div>
            </div>
          ))}
        </div>
      )}
      {tab === 'toolbox' && (
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16, alignItems: 'start' }}>
          <div className="card">
            <div className="card-head"><Icon name="users" size={16} style={{ color: 'var(--primary-600)' }} /><div className="h-sec" style={{ fontSize: 14 }}>Toolbox talks</div><span className="spacer" /><Btn size="sm" variant="ghost" icon="plus" onClick={() => window.toast('Toolbox talk record opened', 'info')}>Record talk</Btn></div>
            <table className="tbl">
              <thead><tr><th>Ref</th><th>Topic</th><th>Delivered by</th><th>Date</th><th className="num">Attended</th></tr></thead>
              <tbody>{DB.toolboxTalks.map((t) => (
                <tr key={t.id}><td className="mono cell-strong" style={{ fontSize: 11.5 }}>{t.id}</td><td style={{ fontSize: 12.5 }}>{t.topic}</td><td><Avatar id={t.by} size="sm" /></td><td className="faint">{DB.fmt(t.date)}</td><td className="num"><Badge kind="info">{t.attendees}</Badge></td></tr>
              ))}</tbody>
            </table>
          </div>
          <div className="card">
            <div className="card-head"><Icon name="flag" size={16} style={{ color: 'var(--warn)' }} /><div className="h-sec" style={{ fontSize: 14 }}>Safety observations</div><span className="spacer" /><Btn size="sm" variant="ghost" icon="plus" onClick={() => window.toast('Observation logged · trends updated', 'info')}>Log observation</Btn></div>
            <table className="tbl">
              <thead><tr><th>Ref</th><th>Observation</th><th>Type</th><th>By</th><th>Status</th></tr></thead>
              <tbody>{DB.safetyObservations.map((o) => (
                <tr key={o.id}><td className="mono cell-strong" style={{ fontSize: 11.5 }}>{o.id}</td><td style={{ fontSize: 12 }}>{o.obs}</td><td><Badge kind={o.type === 'Positive' ? 'ok' : o.type === 'Unsafe act' ? 'bad' : 'warn'}>{o.type}</Badge></td><td><Avatar id={o.by} size="sm" /></td><td><StatusBadge status={o.status} /></td></tr>
              ))}</tbody>
            </table>
          </div>
        </div>
      )}
      {tab === 'drills' && (
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16, alignItems: 'start' }}>
          <div className="card">
            <div className="card-head"><Icon name="alert" size={16} style={{ color: 'var(--primary-600)' }} /><div className="h-sec" style={{ fontSize: 14 }}>Emergency drills</div><span className="spacer" /><Btn size="sm" variant="ghost" icon="plus" onClick={() => window.toast('Drill record opened', 'info')}>Record drill</Btn></div>
            <table className="tbl">
              <thead><tr><th>Ref</th><th>Scenario</th><th>Date</th><th className="num">Part.</th><th>Outcome</th></tr></thead>
              <tbody>{DB.drills.map((d) => (
                <tr key={d.id}><td className="mono cell-strong" style={{ fontSize: 11.5 }}>{d.id}</td><td style={{ fontSize: 12.5 }}>{d.type}</td><td className="faint">{DB.fmt(d.date)}</td><td className="num">{d.participants}</td><td><Badge kind={d.outcome === 'Satisfactory' ? 'ok' : 'warn'}>{d.outcome}</Badge></td></tr>
              ))}</tbody>
            </table>
          </div>
          <div className="card">
            <div className="card-head"><Icon name="check-shield" size={16} style={{ color: 'var(--ok)' }} /><div className="h-sec" style={{ fontSize: 14 }}>HSE training records</div><span className="spacer" /><span className="faint" style={{ fontSize: 11 }}>links to Competency</span></div>
            <table className="tbl">
              <thead><tr><th>Course</th><th>Staff</th><th>Provider</th><th>Expiry</th><th>Status</th></tr></thead>
              <tbody>{DB.hseTraining.map((h) => (
                <tr key={h.id}><td style={{ fontSize: 12.5, fontWeight: 600 }}>{h.course}</td><td><div className="row" style={{ gap: 6 }}><Avatar id={h.staff} size="sm" /><span style={{ fontSize: 12 }}>{DB.staffById(h.staff).name.split(' ')[0]}</span></div></td><td className="faint" style={{ fontSize: 12 }}>{h.provider}</td><td><span style={{ fontWeight: 600, color: h.exp <= DB.TODAY ? 'var(--bad)' : (h.exp - DB.TODAY) / 864e5 < 90 ? 'var(--warn)' : 'var(--text)' }}>{DB.rel(h.exp)}</span></td><td><Badge kind={h.status === 'Valid' ? 'ok' : h.status === 'Expired' ? 'bad' : 'warn'} dot={h.status !== 'Valid'}>{h.status}</Badge></td></tr>
              ))}</tbody>
            </table>
          </div>
        </div>
      )}
      {tab === 'sds' && (
        <div className="card"><table className="tbl">
          <thead><tr><th>SDS</th><th>Chemical</th><th>Supplier</th><th>Next review</th><th></th></tr></thead>
          <tbody>{DB.sds.map((s) => (
            <tr key={s.id} className="clickable" onClick={() => window.openDetail('sds', s)}><td className="mono cell-strong" style={{ fontSize: 12 }}>{s.id}</td><td style={{ fontSize: 12.5 }}>{s.chemical}</td><td className="faint">{s.supplier}</td>
              <td><span style={{ fontWeight: 600, color: s.review <= DB.TODAY ? 'var(--bad)' : 'var(--text)' }}>{DB.rel(s.review)}</span></td>
              <td><button className="icon-btn" style={{ width: 30, height: 30 }} onClick={(e) => { e.stopPropagation(); window.toast(`${s.id} datasheet opened`, 'info'); }}><Icon name="download" size={14} /></button></td></tr>))}</tbody>
        </table></div>
      )}
      {modal && <FormModal title="Report incident / near-miss" sub="ADAM-QMS-L4-F-012 · routes to shared CAPA loop" icon="helmet" fields={[
        { label: 'Type', type: 'select', options: ['Near miss', 'Incident', 'Unsafe condition', 'Observation'] },
        { label: 'Severity', type: 'select', options: ['Low', 'Medium', 'High'] },
        { label: 'Location', type: 'select', options: ['Lab', 'Gas store', 'Field site', 'Office'] },
        { label: 'Date / time', type: 'date' },
        { label: 'Description', type: 'textarea', full: true, placeholder: 'What happened, immediate actions taken…' },
      ]} onClose={() => setModal(false)} onSubmit={() => { setModal(false); window.toast('Incident logged — CAPA opened in shared register'); }} wide />}
    </div>
  );
}

/* ---------------- Laboratory Equipment PM ------------------------- */
function PMModule({ onNav }) {
  const DB = window.DB;
  const [modal, setModal] = useState(false);
  return (
    <div className="page page-wide rise">
      <PageHead title="Laboratory Equipment PM" sub="Preventive maintenance for benches, docking stations &amp; reference instruments — overdue PM blocks the equipment in worksheets">
        <Btn icon="download" size="sm" onClick={() => window.toast('PM compliance report exported')}>Report</Btn>
        <Btn variant="primary" icon="plus" onClick={() => setModal(true)}>New work order</Btn>
      </PageHead>
      <div className="kpi-grid" style={{ gridTemplateColumns: 'repeat(4,1fr)', marginBottom: 16 }}>
        <Kpi label="Open work orders" value={DB.pmOrders.filter((p) => p.status === 'Open').length} icon="wrench" tone="info" />
        <Kpi label="Overdue" value={DB.pmOrders.filter((p) => p.status === 'Overdue').length} icon="alert" tone="bad" delta="blocks equipment" />
        <Kpi label="Equipment uptime" value="98.6%" icon="trend" tone="ok" delta="+0.4%" deltaDir="up" />
        <Kpi label="PM compliance" value="94%" icon="check-circle" tone="ok" />
      </div>
      <div className="card">
        <div className="card-head"><Icon name="wrench" size={16} style={{ color: 'var(--primary-600)' }} /><div className="h-sec" style={{ fontSize: 14 }}>PM work orders</div></div>
        <table className="tbl">
          <thead><tr><th>Work order</th><th>Equipment</th><th>Task</th><th>Criticality</th><th>Assignee</th><th>Due</th><th>Status</th></tr></thead>
          <tbody>{DB.pmOrders.map((p) => (
            <tr key={p.id} className="clickable" onClick={() => window.openDetail('pm', p)}>
              <td className="mono cell-strong" style={{ fontSize: 12 }}>{p.id}</td><td style={{ fontSize: 12.5, fontWeight: 600 }}>{p.equip}</td>
              <td className="faint" style={{ fontSize: 12 }}>{p.task}</td>
              <td><Badge kind={p.crit === 'Critical' ? 'bad' : p.crit === 'High' ? 'warn' : 'neutral'}>{p.crit}</Badge></td>
              <td><Avatar id={p.assignee} size="sm" /></td>
              <td><span style={{ fontWeight: 600, color: p.status === 'Overdue' ? 'var(--bad)' : 'var(--text)' }}>{DB.rel(p.due)}</span></td>
              <td><StatusBadge status={p.status} /></td>
            </tr>))}</tbody>
        </table>
        <div className="card-body" style={{ borderTop: '1px solid var(--border)' }}>
          <div className="gate block"><span className="gate-ico" style={{ background: 'var(--bad-bg)', color: 'var(--bad)' }}><Icon name="x-circle" size={18} /></span>
            <div><div className="gate-title">DOCK-001 PM overdue — equipment gated</div><div className="gate-desc">Overdue critical PM blocks the docking station from worksheet selection until serviced (PM-04).</div></div>
            <Btn size="sm" variant="ghost" style={{ marginLeft: 'auto' }} onClick={() => window.toast('Work order PM-WO-088 assigned to R. Al Maashari')}>Resolve</Btn>
          </div>
        </div>
      </div>
      {modal && <FormModal title="New PM work order" icon="wrench" fields={[
        { label: 'Equipment', type: 'select', options: DB.labAssets.slice(0, 12).map((a) => `${a.id} — ${a.name}`) },
        { label: 'Task', type: 'text', placeholder: 'e.g. Quarterly service' },
        { label: 'Frequency', type: 'select', options: ['Monthly', 'Quarterly', '6-monthly', 'Annual'] },
        { label: 'Assignee', type: 'select', options: DB.staff.map((s) => s.name) },
      ]} onClose={() => setModal(false)} onSubmit={() => { setModal(false); window.toast('PM work order created'); }} wide />}
    </div>
  );
}

/* ---------------- Mobile Field Service ---------------------------- */
function FieldModule({ onNav }) {
  const DB = window.DB;
  const statusColor = { 'On site': 'ok', 'En route': 'info', 'Synced': 'neutral' };
  return (
    <div className="page page-wide rise">
      <PageHead title="Mobile Field Service" sub="On-site calibration under the same standards gates · offline job packs · GPS, photo &amp; signature evidence">
        <Btn icon="refresh" size="sm" onClick={() => window.toast('Syncing field devices…', 'info')}>Sync devices</Btn>
        <Btn variant="primary" icon="plus" onClick={() => window.toast('Field job dispatched to technician tablet')}>Dispatch field job</Btn>
      </PageHead>
      <div className="kpi-grid" style={{ gridTemplateColumns: 'repeat(4,1fr)', marginBottom: 16 }}>
        <Kpi label="Active field jobs" value={DB.fieldJobs.length} icon="truck" tone="info" />
        <Kpi label="On site now" value={DB.fieldJobs.filter((f) => f.status === 'On site').length} icon="pin" tone="ok" />
        <Kpi label="Offline packs" value={DB.fieldJobs.filter((f) => f.offline).length} icon="download" tone="warn" delta="encrypted local store" />
        <Kpi label="Items synced today" value={DB.fieldJobs.reduce((a, f) => a + f.synced, 0)} icon="refresh" tone="ok" />
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 340px', gap: 16, alignItems: 'start' }}>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
          {DB.fieldJobs.map((f) => {
            const c = DB.custById(f.customer);
            return (
              <div key={f.id} className="card card-pad hover-lift" style={{ cursor: 'pointer' }} onClick={() => window.openDetail('fieldjob', f)}>
                <div className="row" style={{ gap: 12 }}>
                  <span className="avatar" style={{ background: c.color, borderRadius: 10 }}>{c.short}</span>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div className="row" style={{ gap: 8 }}><span className="mono cell-strong" style={{ fontSize: 12.5 }}>{f.id}</span><Badge kind={statusColor[f.status]} dot>{f.status}</Badge>{f.offline && <Badge kind="warn">Offline</Badge>}</div>
                    <div style={{ fontSize: 12.5, fontWeight: 600, marginTop: 3 }}>{f.site}</div>
                    <div className="row" style={{ gap: 14, marginTop: 5 }}>
                      <span className="faint" style={{ fontSize: 11.5 }}><Icon name="pin" size={11} /> {f.gps}</span>
                      <span className="faint" style={{ fontSize: 11.5 }}><Avatar id={f.tech} size="sm" /></span>
                      <span className="faint" style={{ fontSize: 11.5 }}>{f.items} items · {f.synced} synced</span>
                    </div>
                  </div>
                  <div style={{ textAlign: 'right' }}><div style={{ width: 60 }}><Bar pct={(f.synced / f.items) * 100} color="var(--ok)" /></div><div className="faint" style={{ fontSize: 10.5, marginTop: 4 }}>{Math.round((f.synced / f.items) * 100)}% synced</div></div>
                </div>
              </div>
            );
          })}
          <div className="card card-pad" style={{ background: 'var(--surface-2)' }}>
            <div className="row" style={{ gap: 9 }}><Icon name="shield" size={15} style={{ color: 'var(--primary-600)' }} /><b style={{ fontSize: 13 }}>Field work changes the location, not the rules</b></div>
            <div className="muted" style={{ fontSize: 12, marginTop: 5 }}>The same authorization, standards-validity and environment gates apply on the tablet. Sync is idempotent with conflict detection; no silent overwrite.</div>
          </div>
        </div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
          <div className="card" style={{ overflow: 'hidden' }}>
            <div className="card-head"><Icon name="pin" size={15} style={{ color: 'var(--primary-600)' }} /><div className="h-sec" style={{ fontSize: 13.5 }}>Live locations</div></div>
            <div style={{ height: 220, position: 'relative', background: 'linear-gradient(135deg,#eef3fb,#e3ebf6)' }}>
              <div style={{ position: 'absolute', inset: 0, backgroundImage: 'linear-gradient(rgba(47,111,237,.08) 1px,transparent 1px),linear-gradient(90deg,rgba(47,111,237,.08) 1px,transparent 1px)', backgroundSize: '28px 28px' }} />
              {[[30, 40, 'ok'], [62, 28, 'info'], [48, 70, 'neutral']].map(([x, y, t], i) => (
                <div key={i} style={{ position: 'absolute', left: `${x}%`, top: `${y}%`, transform: 'translate(-50%,-50%)' }}>
                  <span style={{ width: 16, height: 16, borderRadius: '50%', background: `var(--${t === 'neutral' ? 'text-3' : t})`, display: 'block', border: '3px solid #fff', boxShadow: 'var(--sh)' }} />
                </div>
              ))}
              <div style={{ position: 'absolute', bottom: 10, left: 12, fontSize: 10.5, color: 'var(--text-3)', fontWeight: 600 }}>Sultanate of Oman · 3 active</div>
            </div>
          </div>
          <AINote title="Sync conflict queued for supervisor" clause="NFR-13" action="Resolve conflict" onAction={() => window.toast('Conflict queue opened', 'info')}>
            FJ-26-019 has a worksheet edited on two devices. Single-owner sync flagged it — no data lost, awaiting supervisor decision.
          </AINote>
        </div>
      </div>
    </div>
  );
}

/* ---------------- Administration & Security ----------------------- */
function AdminModule({ onNav }) {
  const DB = window.DB;
  const [tab, setTab] = useState('users');
  const tabs = [['users', 'Users & roles'], ['audit', 'Audit trail'], ['numbering', 'Numbering & templates'], ['integrations', 'Integrations']];
  const integrations = [
    ['Email & in-system notifications', 'Live', 'ok', 'P1'],
    ['SMS / WhatsApp gateway', 'Connected', 'ok', 'P2'],
    ['Docking station import (OEM)', 'Configured · 1 adapter', 'warn', 'P3'],
    ['Barcode / QR scanners', 'Camera-scan active', 'ok', 'P1'],
    ['Open REST API', 'Tokens issued · 3 clients', 'ok', 'P3'],
    ['Accounting export', 'File-based', 'warn', 'P2'],
  ];
  return (
    <div className="page page-wide rise">
      <PageHead title="Administration &amp; Security" sub="RBAC · immutable audit trail · master data · numbering schemes · integrations">
        <Btn icon="download" size="sm" onClick={() => window.toast('Audit trail exported (PDF)')}>Export audit</Btn>
        <Btn variant="primary" icon="plus" onClick={() => window.openForm({ title: 'Add user', sub: 'Role-based access with segregation of duties', icon: 'users', fields: [{ label: 'Full name', type: 'text' }, { label: 'Email', type: 'text', placeholder: 'name@aldam.om' }, { label: 'Role', type: 'select', options: window.DB.roles.map((r) => r.role) }, { label: 'Send invite', type: 'select', options: ['Yes — email now', 'No — create only'] }], submitLabel: 'Create user', done: 'User created · invite sent' })}>Add user</Btn>
      </PageHead>
      <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 === 'users' && (
        <div className="card"><div className="card-head"><Icon name="users" size={16} style={{ color: 'var(--primary-600)' }} /><div className="h-sec" style={{ fontSize: 14 }}>Roles &amp; access</div><span className="spacer" /><Badge kind="ok" icon="lock">Segregation of duties enforced</Badge></div>
          <table className="tbl">
            <thead><tr><th>Role</th><th>Users</th><th>Permissions</th><th>Restrictions</th></tr></thead>
            <tbody>{DB.roles.map((r) => (
              <tr key={r.role} className="clickable" onClick={() => window.openDetail('role', r)}>
                <td><span className="row" style={{ gap: 8 }}><span style={{ width: 9, height: 9, borderRadius: '50%', background: r.color }} /><b style={{ fontSize: 12.5 }}>{r.role}</b></span></td>
                <td className="num mono">{r.count}</td><td className="faint" style={{ fontSize: 12 }}>{r.perms}</td>
                <td className="faint" style={{ fontSize: 11.5 }}>{r.role === 'Technician' ? 'Cannot approve own work' : r.role === 'Sales / Accounts' ? 'No technical records' : '—'}</td>
              </tr>))}</tbody>
          </table>
        </div>
      )}
      {tab === 'audit' && (
        <div className="card"><div className="card-head"><Icon name="history" size={16} style={{ color: 'var(--primary-600)' }} /><div className="h-sec" style={{ fontSize: 14 }}>Audit trail</div><span className="spacer" /><span className="faint" style={{ fontSize: 11.5 }}>Immutable · every change logged</span></div>
          <table className="tbl">
            <thead><tr><th>Timestamp</th><th>User</th><th>Action</th><th>Entity</th></tr></thead>
            <tbody>{DB.auditLog.map((a, i) => (
              <tr key={i} className="clickable" onClick={() => window.openDetail('audit', a)}><td className="faint mono" style={{ fontSize: 11.5 }}>{a.ts}</td>
                <td>{a.user === 'system' ? <span className="tag"><Icon name="sparkles" size={11} /> System</span> : <div className="row" style={{ gap: 7 }}><Avatar id={a.user} size="sm" /><span style={{ fontSize: 12 }}>{DB.staffById(a.user)?.name.split(' ')[0]}</span></div>}</td>
                <td style={{ fontSize: 12.5 }}>{a.action}</td><td className="mono" style={{ fontSize: 11.5, color: 'var(--primary-700)' }}>{a.entity}</td></tr>))}</tbody>
          </table>
        </div>
      )}
      {tab === 'numbering' && (
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2,1fr)', gap: 14 }}>
          {[['Calibration certificate', 'ADAM-CAL-YY-NNNNN', 'Gap-free · sequential'], ['Bump test report', 'ADAM-BMP-YY-NNNNN', 'Separate series'], ['Job number', 'JOB-YY-NNNN', 'Per receipt'], ['Invoice', 'INV-YY-NNNN', 'Gap-free · VAT compliant'], ['NCR', 'CAPA-YY-NNN', 'Shared register'], ['Worksheet', 'WS-YY-NNNN', 'Bound to method rev']].map(([t, fmt, note], i) => (
            <div key={i} className="card card-pad">
              <div className="row" style={{ justifyContent: 'space-between' }}><span style={{ fontSize: 13, fontWeight: 700 }}>{t}</span><Btn size="sm" variant="ghost" onClick={() => window.toast(`${t} numbering edited`, 'info')}>Edit</Btn></div>
              <div className="mono" style={{ fontSize: 13, color: 'var(--primary-700)', marginTop: 8, background: 'var(--bg)', padding: '7px 10px', borderRadius: 8, border: '1px solid var(--border)' }}>{fmt}</div>
              <div className="faint" style={{ fontSize: 11.5, marginTop: 6 }}>{note}</div>
            </div>
          ))}
        </div>
      )}
      {tab === 'integrations' && (
        <div className="card"><table className="tbl">
          <thead><tr><th>Integration</th><th>Status</th><th>Phase</th><th></th></tr></thead>
          <tbody>{integrations.map(([t, s, k, ph], i) => (
            <tr key={i}><td style={{ fontSize: 12.5, fontWeight: 600 }}>{t}</td><td><Badge kind={k} dot>{s}</Badge></td><td><Badge kind="neutral">Phase {ph.replace('P', '')}</Badge></td>
              <td><Btn size="sm" variant="ghost" onClick={() => window.toast(`${t} settings opened`, 'info')}>Configure</Btn></td></tr>))}</tbody>
        </table></div>
      )}
    </div>
  );
}

Object.assign(window, { CompetencyModule, HSEModule, PMModule, FieldModule, AdminModule });
