/* educator-compliance.jsx — the Compliance tab: ISO 9001, ISO 27002,
   candidate evaluations and incident management.

   Read-only views over the registers in compliance-data.js. Nothing is stored
   or edited here; when the registers move to D1 only the data file changes.
   Every screen honours the demo switch — with demo content off the registers
   show an empty state, because what they hold today is example data. */

/* ── shared bits ── */

const CMP_TAG_CLASS = {
  "Implemented":"green", "Closed":"green", "Treated":"green", "Resolved":"green", "Passed":"green",
  "In progress":"blue", "In treatment":"blue",
  "Overdue":"red", "Failed":"red",
};
function CmpTag({ s }) {
  return <span className={"tag " + (CMP_TAG_CLASS[s] || "")}>{s}</span>;
}

const CMP_PRI = {
  P1:{ bg:"#ffebee", ic:"#c62828" }, P2:{ bg:"#fff3e0", ic:"#e65100" },
  P3:{ bg:"var(--vh-blue-50)", ic:"var(--vh-blue-600)" }, P4:{ bg:"var(--chip)", ic:"var(--ink-2)" },
};
function CmpPri({ p }) {
  const c = CMP_PRI[p] || CMP_PRI.P4;
  return <span style={{ display:"inline-flex", alignItems:"center", justifyContent:"center", minWidth:32, padding:"3px 8px", borderRadius:7, background:c.bg, color:c.ic, fontFamily:"var(--display)", fontWeight:800, fontSize:11.5 }}>{p}</span>;
}

function CmpHead({ title, sub, right }) {
  return (
    <div className="between" style={{ marginBottom:22 }}>
      <div className="page-head" style={{ marginBottom:0 }}>
        <h1>{title}</h1>
        <p>{sub}</p>
      </div>
      {right}
    </div>
  );
}

/* Card wrapper with a caps title — used for every register block. */
function CmpBlock({ title, note, right, children, pad = true }) {
  return (
    <div className="card" style={{ marginBottom:18, overflow:"hidden" }}>
      <div className="between" style={{ padding:"18px 22px", borderBottom:"1px solid var(--line)" }}>
        <div>
          <div style={{ fontFamily:"var(--display)", fontWeight:700, fontSize:15.5 }}>{title}</div>
          {note && <div style={{ fontSize:12.5, color:"var(--ink-3)", marginTop:3 }}>{note}</div>}
        </div>
        {right}
      </div>
      {/* registers are wide — let the table scroll inside the card instead of the page */}
      <div className="scroll" style={{ padding: pad ? "4px 0" : 0, overflowX:"auto" }}>{children}</div>
    </div>
  );
}

function CmpStats({ items }) {
  return (
    <div className="stat-grid">
      {items.map(s => (
        <div key={s.label} className="card stat-card" onClick={s.onClick}
          style={{ cursor:s.onClick ? "pointer" : "default", transition:"box-shadow .14s" }}
          onMouseEnter={e => { if (s.onClick) e.currentTarget.style.boxShadow = "var(--shadow-md)"; }}
          onMouseLeave={e => { e.currentTarget.style.boxShadow = ""; }}>
          <div className="between" style={{ marginBottom:12 }}>
            <div className="eyebrow">{s.label}</div>
            <div className="stat-ico" style={{ background:s.bg }}><Icon name={s.icon} size={17} style={{ color:s.ic }}/></div>
          </div>
          <div className="kpi" style={{ fontSize:30, color:s.warn ? "#c62828" : undefined }}>{s.val}</div>
          {s.sub && <div style={{ fontSize:12.5, color:"var(--ink-3)", marginTop:6 }}>{s.sub}</div>}
        </div>
      ))}
    </div>
  );
}

/* Demo content off → the registers hold nothing real yet, so say so. */
function CmpEmpty({ what }) {
  return (
    <div className="card" style={{ padding:"44px 20px", textAlign:"center", color:"var(--ink-3)" }}>
      <Icon name="shield" size={30} style={{ color:"var(--line)", marginBottom:10 }}/>
      <div style={{ fontSize:14 }}>The {what} holds example data only. It is hidden while “Visualise demo content” is off — turn it on in the Style Tailor to preview it.</div>
    </div>
  );
}

/* ── OVERVIEW ── */

function ComplianceOverview({ go }) {
  const demo = useDemoMode();
  const openInc = INCIDENTS.filter(i => i.status === "Open" || i.status === "In progress");
  const openCapa = Q_CAPA.filter(c => c.status !== "Closed");
  const ctrlTotal = SEC_THEMES.reduce((s,t) => s + t.total, 0);
  const ctrlDone = SEC_THEMES.reduce((s,t) => s + t.implemented, 0);
  const cand = EVAL_COURSES.reduce((s,c) => s + c.candidates, 0);
  const passed = EVAL_COURSES.reduce((s,c) => s + c.passed, 0);
  const passRate = Math.round(passed / cand * 100);
  const missed = Q_OBJECTIVES.filter(o => o.value < o.target);

  /* one list of everything that is over its date or outside the norm */
  const attention = [
    ...Q_CAPA.filter(c => c.status === "Overdue").map(c => ({ icon:"wand", ic:"#c62828", bg:"#ffebee", text:c.id + " — " + c.desc, meta:"Due " + c.due, to:"iso9001" })),
    ...missed.map(o => ({ icon:"bars", ic:"#e65100", bg:"#fff3e0", text:o.label + " below target", meta:o.value + o.unit + " vs " + o.target + o.unit, to:"iso9001" })),
    ...SEC_RISKS.filter(r => r.status === "Open").map(r => ({ icon:"shield", ic:"#e65100", bg:"#fff3e0", text:r.id + " — " + r.risk, meta:"Untreated · score " + r.score, to:"iso27002" })),
    ...openInc.map(i => ({ icon:"ticket", ic:"var(--vh-blue-600)", bg:"var(--vh-blue-50)", text:i.id + " — " + i.title, meta:i.pri + " · " + i.status, to:"incidents" })),
  ];

  return (
    <div>
      <CmpHead title="Compliance" sub="Quality, information security, candidate results and incidents in one place."
        right={<span className="tag blue"><Icon name="calendar" size={13}/>Q3 2026</span>}/>
      {!demo ? <CmpEmpty what="compliance register"/> : (
        <div>
          <CmpStats items={[
            { label:"Open incidents",   val:openInc.length, sub:openInc.filter(i=>i.pri==="P1"||i.pri==="P2").length + " at P1–P2", icon:"ticket",      bg:"var(--vh-blue-50)", ic:"var(--vh-blue-500)", onClick:()=>go("incidents") },
            { label:"Controls in place",val:Math.round(ctrlDone/ctrlTotal*100)+"%", sub:ctrlDone + " of " + ctrlTotal + " ISO 27002 controls", icon:"lock", bg:"#e8f5e9", ic:"#2e7d32", onClick:()=>go("iso27002") },
            { label:"Candidate pass rate", val:passRate+"%", sub:passed + " of " + cand + " candidates", icon:"cert",    bg:"#fff8e1",           ic:"#f57f17",            onClick:()=>go("evaluations") },
            { label:"Open actions",     val:openCapa.length, sub:Q_CAPA.filter(c=>c.status==="Overdue").length + " past due", warn:Q_CAPA.some(c=>c.status==="Overdue"), icon:"wand", bg:"#ffebee", ic:"#c62828", onClick:()=>go("iso9001") },
          ]}/>

          <div style={{ display:"grid", gridTemplateColumns:"1.35fr 1fr", gap:18, alignItems:"start" }}>
            <CmpBlock title="Needs attention" note="Everything past its date or outside the agreed norm.">
              {attention.map((a,i) => (
                <div key={i} onClick={()=>go(a.to)} style={{ display:"flex", alignItems:"flex-start", gap:12, padding:"13px 22px", borderBottom: i < attention.length-1 ? "1px solid var(--line-2)" : "none", cursor:"pointer" }}>
                  <div className="act-dot" style={{ background:a.bg }}><Icon name={a.icon} size={15} style={{ color:a.ic }}/></div>
                  <div style={{ flex:1, minWidth:0 }}>
                    <div style={{ fontSize:13.5, fontWeight:600, color:"var(--ink)" }}>{a.text}</div>
                    <div style={{ fontSize:12, color:"var(--ink-3)", marginTop:2 }}>{a.meta}</div>
                  </div>
                  <Icon name="arrowR" size={14} style={{ color:"var(--ink-3)", flexShrink:0, marginTop:3 }}/>
                </div>
              ))}
            </CmpBlock>

            <CmpBlock title="Recent activity">
              <div style={{ padding:"4px 22px" }}>
                {COMP_ACTIVITY.map((a,i) => (
                  <div key={i} className="act-item">
                    <div className="act-dot" style={{ background:a.bg }}><Icon name={a.icon} size={15} style={{ color:a.ic }}/></div>
                    <div style={{ flex:1 }}>
                      <div style={{ fontSize:13.5, color:"var(--ink)" }}>{a.text}</div>
                      <div style={{ fontSize:11.5, color:"var(--ink-3)", marginTop:2 }}>{a.time}</div>
                    </div>
                  </div>
                ))}
              </div>
            </CmpBlock>
          </div>

          <div className="card" style={{ padding:"16px 22px", display:"flex", alignItems:"center", gap:12, marginTop:4 }}>
            <Icon name="eye" size={17} style={{ color:"var(--vh-blue-500)", flexShrink:0 }}/>
            <div style={{ fontSize:13, color:"var(--ink-2)" }}>
              Personal-data handling per feature lives in <b>System → Features</b>, where every feature carries its data category and compliance note.
            </div>
            <button className="btn btn-outline btn-sm" style={{ marginLeft:"auto", flexShrink:0 }} onClick={()=>go("features")}>Open Features</button>
          </div>
        </div>
      )}
    </div>
  );
}

/* ── ISO 9001 · QUALITY ── */

function ISO9001Screen() {
  const demo = useDemoMode();
  const met = Q_OBJECTIVES.filter(o => o.value >= o.target).length;

  return (
    <div>
      <CmpHead title="ISO 9001 · Quality" sub="Quality objectives, internal audits and the corrective-action register."
        right={<span className="tag green"><Icon name="checkCircle" size={13}/>{met} of {Q_OBJECTIVES.length} objectives met</span>}/>
      {!demo ? <CmpEmpty what="quality register"/> : (
        <div>
          <CmpBlock title="Quality objectives" note="Measured against the norms in the quality plan — Q3 2026." pad={false}>
            <div style={{ display:"grid", gridTemplateColumns:"repeat(3,1fr)" }}>
              {Q_OBJECTIVES.map((o,i) => {
                const ok = o.value >= o.target;
                const pct = Math.min(100, Math.round(o.value / o.target * 100));
                return (
                  <div key={o.id} style={{ padding:"18px 22px", borderRight:(i%3)<2 ? "1px solid var(--line-2)" : "none", borderBottom: i < Q_OBJECTIVES.length-3 ? "1px solid var(--line-2)" : "none" }}>
                    <div className="between" style={{ marginBottom:9 }}>
                      <div style={{ fontSize:13, fontWeight:600, color:"var(--ink-2)" }}>{o.label}</div>
                      <Icon name={ok ? "checkCircle" : "bell"} size={16} style={{ color: ok ? "#2e7d32" : "#e65100", flexShrink:0 }}/>
                    </div>
                    <div style={{ display:"flex", alignItems:"baseline", gap:7, marginBottom:9 }}>
                      <span className="kpi" style={{ fontSize:26, color: ok ? "var(--ink)" : "#c62828" }}>{o.value}{o.unit}</span>
                      <span style={{ fontSize:12, color:"var(--ink-3)" }}>target {o.target}{o.unit}</span>
                    </div>
                    <Bar pct={pct} cls={ok ? "green" : ""}/>
                    <div style={{ fontSize:11.5, color:"var(--ink-3)", marginTop:8 }}>{o.owner}</div>
                  </div>
                );
              })}
            </div>
          </CmpBlock>

          <CmpBlock title="Internal audits" note="Findings by weight: major, minor and observation." pad={false}>
            <table className="tbl">
              <thead><tr><th>Audit</th><th>Date</th><th>Scope</th><th>Auditor</th><th style={{ textAlign:"center" }}>Major</th><th style={{ textAlign:"center" }}>Minor</th><th style={{ textAlign:"center" }}>Obs.</th><th>Status</th></tr></thead>
              <tbody>
                {Q_AUDITS.map(a => (
                  <tr key={a.id}>
                    <td style={{ fontWeight:700, whiteSpace:"nowrap" }}>{a.id}</td>
                    <td style={{ whiteSpace:"nowrap", color:"var(--ink-2)" }}>{a.date}</td>
                    <td>{a.scope}</td>
                    <td style={{ color:"var(--ink-2)", whiteSpace:"nowrap" }}>{a.auditor}</td>
                    <td style={{ textAlign:"center", fontWeight:700, color: a.major ? "#c62828" : "var(--ink-3)" }}>{a.major === null ? "—" : a.major}</td>
                    <td style={{ textAlign:"center", color: a.minor ? "#e65100" : "var(--ink-3)" }}>{a.minor === null ? "—" : a.minor}</td>
                    <td style={{ textAlign:"center", color:"var(--ink-3)" }}>{a.obs === null ? "—" : a.obs}</td>
                    <td><CmpTag s={a.status}/></td>
                  </tr>
                ))}
              </tbody>
            </table>
          </CmpBlock>

          <CmpBlock title="Corrective and preventive actions" note="Every action traces back to the audit, complaint or incident that raised it." pad={false}>
            <table className="tbl">
              <thead><tr><th>Action</th><th>Source</th><th>Description</th><th>Owner</th><th>Due</th><th>Status</th></tr></thead>
              <tbody>
                {Q_CAPA.map(c => (
                  <tr key={c.id}>
                    <td style={{ fontWeight:700, whiteSpace:"nowrap" }}>{c.id}</td>
                    <td style={{ whiteSpace:"nowrap" }}>
                      <span style={{ fontSize:12.5, color:"var(--ink-2)" }}>{c.source}</span>
                      <div style={{ fontSize:11, color:"var(--ink-3)", marginTop:2 }}>{c.link}</div>
                    </td>
                    <td style={{ maxWidth:420 }}>{c.desc}</td>
                    <td style={{ color:"var(--ink-2)", whiteSpace:"nowrap" }}>{c.owner}</td>
                    <td style={{ whiteSpace:"nowrap", color: c.status === "Overdue" ? "#c62828" : "var(--ink-2)", fontWeight: c.status === "Overdue" ? 700 : 400 }}>{c.due}</td>
                    <td><CmpTag s={c.status}/></td>
                  </tr>
                ))}
              </tbody>
            </table>
          </CmpBlock>
        </div>
      )}
    </div>
  );
}

/* ── ISO 27002 · SECURITY ── */

function ISO27002Screen() {
  const demo = useDemoMode();
  const [theme, setTheme] = useState("all");
  const rows = theme === "all" ? SEC_CONTROLS : SEC_CONTROLS.filter(c => c.theme === theme);
  const total = SEC_THEMES.reduce((s,t) => s + t.total, 0);
  const done = SEC_THEMES.reduce((s,t) => s + t.implemented, 0);

  return (
    <div>
      <CmpHead title="ISO 27002 · Information security" sub="Control implementation across the four themes, plus the risk register."
        right={<span className="tag blue"><Icon name="lock" size={13}/>{done} of {total} controls implemented</span>}/>
      {!demo ? <CmpEmpty what="security register"/> : (
        <div>
          <div className="stat-grid">
            {SEC_THEMES.map(t => {
              const pct = Math.round(t.implemented / t.total * 100);
              return (
                <div key={t.id} className="card stat-card">
                  <div className="between" style={{ marginBottom:12 }}>
                    <div className="eyebrow">{t.label}</div>
                    <div className="stat-ico" style={{ background:t.bg }}><Icon name={t.icon} size={17} style={{ color:t.color }}/></div>
                  </div>
                  <div style={{ display:"flex", alignItems:"baseline", gap:6, marginBottom:10 }}>
                    <span className="kpi" style={{ fontSize:28 }}>{t.implemented}</span>
                    <span style={{ fontSize:13, color:"var(--ink-3)" }}>/ {t.total} controls</span>
                  </div>
                  <Bar pct={pct} cls={pct >= 80 ? "green" : ""}/>
                  <div style={{ fontSize:11.5, color:"var(--ink-3)", marginTop:8 }}>
                    {t.progress} in progress · {t.planned} planned · clause {t.clause}
                  </div>
                </div>
              );
            })}
          </div>

          <CmpBlock title="Control register" note="The controls with activity this cycle — the full Statement of Applicability holds all 93." pad={false}
            right={
              <div style={{ display:"flex", gap:7, flexWrap:"wrap" }}>
                <span className={"filter-chip" + (theme === "all" ? " on" : "")} onClick={()=>setTheme("all")}>All</span>
                {SEC_THEMES.map(t => (
                  <span key={t.id} className={"filter-chip" + (theme === t.id ? " on" : "")} onClick={()=>setTheme(t.id)}>{t.label}</span>
                ))}
              </div>
            }>
            <table className="tbl">
              <thead><tr><th style={{ width:70 }}>Clause</th><th>Control</th><th>Theme</th><th>Status</th><th>Owner</th><th>Last review</th></tr></thead>
              <tbody>
                {rows.map(c => {
                  const th = SEC_THEMES.find(t => t.id === c.theme) || {};
                  return (
                    <tr key={c.clause}>
                      <td style={{ fontFamily:"var(--display)", fontWeight:800, color:th.color }}>{c.clause}</td>
                      <td style={{ fontWeight:600 }}>{c.name}</td>
                      <td><span className="tag" style={{ background:th.bg, color:th.color }}>{th.label}</span></td>
                      <td><CmpTag s={c.status}/></td>
                      <td style={{ color:"var(--ink-2)", whiteSpace:"nowrap" }}>{c.owner}</td>
                      <td style={{ color:"var(--ink-3)", whiteSpace:"nowrap" }}>{c.review}</td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </CmpBlock>

          <CmpBlock title="Risk register" note="Score is likelihood × impact, each on a 1–4 scale." pad={false}>
            <table className="tbl">
              <thead><tr><th>Risk</th><th>Likelihood</th><th>Impact</th><th style={{ textAlign:"center" }}>Score</th><th>Treatment</th><th>Owner</th><th>Status</th></tr></thead>
              <tbody>
                {SEC_RISKS.map(r => (
                  <tr key={r.id}>
                    <td style={{ maxWidth:300 }}>
                      <div style={{ fontWeight:600 }}>{r.risk}</div>
                      <div style={{ fontSize:11.5, color:"var(--ink-3)", marginTop:2 }}>{r.id}</div>
                    </td>
                    <td style={{ color:"var(--ink-2)" }}>{r.like}</td>
                    <td style={{ color:"var(--ink-2)" }}>{r.impact}</td>
                    <td style={{ textAlign:"center" }}>
                      <span style={{ display:"inline-grid", placeItems:"center", width:30, height:26, borderRadius:7, fontFamily:"var(--display)", fontWeight:800, fontSize:13,
                        background: r.score >= 12 ? "#ffebee" : r.score >= 9 ? "#fff3e0" : "var(--surface-3)",
                        color:      r.score >= 12 ? "#c62828" : r.score >= 9 ? "#e65100" : "var(--ink-2)" }}>{r.score}</span>
                    </td>
                    <td style={{ maxWidth:300, color:"var(--ink-2)" }}>{r.treat}</td>
                    <td style={{ color:"var(--ink-2)", whiteSpace:"nowrap" }}>{r.owner}</td>
                    <td><CmpTag s={r.status}/></td>
                  </tr>
                ))}
              </tbody>
            </table>
          </CmpBlock>
        </div>
      )}
    </div>
  );
}

/* ── CANDIDATE EVALUATIONS ── */

function EvaluationsScreen() {
  const demo = useDemoMode();
  const [course, setCourse] = useState("all");
  const cand = EVAL_COURSES.reduce((s,c) => s + c.candidates, 0);
  const passed = EVAL_COURSES.reduce((s,c) => s + c.passed, 0);
  const avg = (EVAL_COURSES.reduce((s,c) => s + c.avg * c.candidates, 0) / cand).toFixed(1);
  const sat = (EVAL_COURSES.reduce((s,c) => s + c.sat * c.candidates, 0) / cand).toFixed(1);
  const log = course === "all" ? EVAL_LOG : EVAL_LOG.filter(e => e.course === course);

  return (
    <div>
      <CmpHead title="Candidate evaluations" sub="Exam results and candidate satisfaction per course, and the evaluation log."
        right={<span className="tag blue"><Icon name="calendar" size={13}/>2026 to date</span>}/>
      {!demo ? <CmpEmpty what="evaluation register"/> : (
        <div>
          <CmpStats items={[
            { label:"Candidates",        val:cand,                                     sub:"exams sat this year", icon:"users",  bg:"var(--vh-blue-50)", ic:"var(--vh-blue-500)" },
            { label:"Pass rate",         val:Math.round(passed/cand*100)+"%",           sub:passed + " passed",    icon:"cert",   bg:"#e8f5e9",           ic:"#2e7d32" },
            { label:"Average score",     val:avg,                                      sub:"pass mark 65",        icon:"bars",   bg:"#fff3e0",           ic:"#e65100" },
            { label:"Satisfaction",      val:sat,                                      sub:"candidate rating out of 5", icon:"star", bg:"#fff8e1",     ic:"#f57f17" },
          ]}/>

          <CmpBlock title="Results per course" pad={false}>
            <table className="tbl">
              <thead><tr><th>Course</th><th style={{ textAlign:"center" }}>Candidates</th><th style={{ width:220 }}>Pass rate</th><th style={{ textAlign:"center" }}>Avg score</th><th style={{ textAlign:"center" }}>Satisfaction</th></tr></thead>
              <tbody>
                {EVAL_COURSES.map(c => {
                  const pct = Math.round(c.passed / c.candidates * 100);
                  return (
                    <tr key={c.course}>
                      <td>
                        <div style={{ display:"flex", alignItems:"center", gap:11 }}>
                          <div style={{ width:32, height:32, borderRadius:9, background:c.color, display:"grid", placeItems:"center", flexShrink:0 }}>
                            <Icon name={c.icon} size={16} style={{ color:"#fff" }}/>
                          </div>
                          <span style={{ fontWeight:600 }}>{c.course}</span>
                        </div>
                      </td>
                      <td style={{ textAlign:"center", color:"var(--ink-2)" }}>{c.candidates}</td>
                      <td>
                        <div style={{ display:"flex", alignItems:"center", gap:10 }}>
                          <Bar pct={pct} cls={pct >= 85 ? "green" : ""}/>
                          <span style={{ fontFamily:"var(--display)", fontWeight:700, fontSize:13, width:34, textAlign:"right", color: pct >= 85 ? "#2e7d32" : pct >= 75 ? "var(--ink)" : "#c62828" }}>{pct}%</span>
                        </div>
                      </td>
                      <td style={{ textAlign:"center", fontWeight:600 }}>{c.avg}</td>
                      <td style={{ textAlign:"center", color:"var(--ink-2)" }}>{c.sat.toFixed(1)} ★</td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </CmpBlock>

          <CmpBlock title="Evaluation log" note="Individual candidate results, most recent first." pad={false}
            right={
              <select value={course} onChange={e=>setCourse(e.target.value)}
                style={{ padding:"8px 12px", borderRadius:9, border:"1px solid var(--line)", background:"var(--surface)", color:"var(--ink)", fontSize:13, fontWeight:600 }}>
                <option value="all">All courses</option>
                {EVAL_COURSES.map(c => <option key={c.course} value={c.course}>{c.course}</option>)}
              </select>
            }>
            <table className="tbl">
              <thead><tr><th>Candidate</th><th>Course</th><th>Exam date</th><th style={{ textAlign:"center" }}>Score</th><th>Result</th><th style={{ textAlign:"center" }}>Rating</th><th>Evaluated by</th></tr></thead>
              <tbody>
                {log.map((e,i) => (
                  <tr key={i}>
                    <td>
                      <div style={{ display:"flex", alignItems:"center", gap:10 }}>
                        <Av initials={e.ini} size={30}/>
                        <span style={{ fontWeight:600 }}>{e.cand}</span>
                      </div>
                    </td>
                    <td style={{ color:"var(--ink-2)" }}>{e.course}</td>
                    <td style={{ color:"var(--ink-2)", whiteSpace:"nowrap" }}>{e.date}</td>
                    <td style={{ textAlign:"center", fontFamily:"var(--display)", fontWeight:800, color: e.score >= 65 ? "var(--ink)" : "#c62828" }}>{e.score}</td>
                    <td><CmpTag s={e.result}/></td>
                    <td style={{ textAlign:"center", color:"var(--ink-2)" }}>{e.sat} ★</td>
                    <td style={{ color:"var(--ink-2)", whiteSpace:"nowrap" }}>{e.by}</td>
                  </tr>
                ))}
                {log.length === 0 && <tr><td colSpan={7} style={{ textAlign:"center", padding:"30px 0", color:"var(--ink-3)" }}>No evaluations for this course yet.</td></tr>}
              </tbody>
            </table>
          </CmpBlock>
        </div>
      )}
    </div>
  );
}

/* ── INCIDENT MANAGEMENT ── */

const INC_CATS = ["All", "Security", "Availability", "Data", "Exam integrity", "Service"];

function IncidentsScreen() {
  const demo = useDemoMode();
  const [cat, setCat] = useState("All");
  const open = INCIDENTS.filter(i => i.status === "Open" || i.status === "In progress");
  const done = INCIDENTS.filter(i => i.took !== null);
  const mttr = done.length ? (done.reduce((s,i) => s + i.took, 0) / done.length).toFixed(1) : "—";
  const withinSla = done.filter(i => i.took <= INC_SLA[i.pri]).length;
  const slaPct = done.length ? Math.round(withinSla / done.length * 100) : 0;
  const p1 = INCIDENTS.filter(i => i.pri === "P1").length;
  const rows = cat === "All" ? INCIDENTS : INCIDENTS.filter(i => i.cat === cat);
  const peak = Math.max.apply(null, INC_TREND.map(m => m.n));

  return (
    <div>
      <CmpHead title="Incident management" sub="Every incident with its priority, resolution time and SLA outcome."
        right={<span className="tag blue"><Icon name="calendar" size={13}/>2026 to date</span>}/>
      {!demo ? <CmpEmpty what="incident log"/> : (
        <div>
          <CmpStats items={[
            { label:"Open incidents", val:open.length, sub:open.map(i=>i.pri).join(", ") || "none", icon:"ticket", bg:"var(--vh-blue-50)", ic:"var(--vh-blue-500)" },
            { label:"Mean time to resolve", val:mttr + "h", sub:"across " + done.length + " closed", icon:"clock", bg:"#e8f5e9", ic:"#2e7d32" },
            { label:"Within SLA", val:slaPct + "%", sub:withinSla + " of " + done.length + " on target", warn:slaPct < 90, icon:"checkCircle", bg:slaPct < 90 ? "#ffebee" : "#e8f5e9", ic:slaPct < 90 ? "#c62828" : "#2e7d32" },
            { label:"P1 incidents", val:p1, sub:"highest priority, this year", icon:"bell", bg:"#fff3e0", ic:"#e65100" },
          ]}/>

          <CmpBlock title="Incidents per month" note="2026 to date.">
            <div style={{ display:"flex", alignItems:"flex-end", gap:14, padding:"14px 22px 6px", height:130 }}>
              {INC_TREND.map(m => (
                <div key={m.m} style={{ flex:1, display:"flex", flexDirection:"column", alignItems:"center", gap:7 }}>
                  <div style={{ fontFamily:"var(--display)", fontWeight:700, fontSize:12, color:"var(--ink-2)" }}>{m.n}</div>
                  <div title={m.n + " incidents"} style={{ width:"100%", maxWidth:44, height:Math.round(m.n / peak * 74) + 4, borderRadius:"6px 6px 0 0", background:"linear-gradient(180deg,var(--vh-blue-400),var(--vh-blue-500))" }}/>
                  <div style={{ fontSize:11.5, color:"var(--ink-3)" }}>{m.m}</div>
                </div>
              ))}
            </div>
          </CmpBlock>

          <CmpBlock title="Incident log" note="Resolution time is measured against the SLA for the priority: P1 4h, P2 8h, P3 24h, P4 72h." pad={false}
            right={
              <div style={{ display:"flex", gap:7, flexWrap:"wrap" }}>
                {INC_CATS.map(c => (
                  <span key={c} className={"filter-chip" + (cat === c ? " on" : "")} onClick={()=>setCat(c)}>{c}</span>
                ))}
              </div>
            }>
            <table className="tbl">
              <thead><tr><th>Incident</th><th>Date</th><th>Category</th><th style={{ textAlign:"center" }}>Priority</th><th>Status</th><th>Owner</th><th>Resolution</th><th>Action</th></tr></thead>
              <tbody>
                {rows.map(i => {
                  const breach = i.took !== null && i.took > INC_SLA[i.pri];
                  return (
                    <tr key={i.id}>
                      <td style={{ maxWidth:320 }}>
                        <div style={{ fontWeight:600 }}>{i.title}</div>
                        <div style={{ fontSize:11.5, color:"var(--ink-3)", marginTop:2 }}>{i.id} · reported by {i.by}</div>
                      </td>
                      <td style={{ color:"var(--ink-2)", whiteSpace:"nowrap" }}>{i.date}</td>
                      <td style={{ color:"var(--ink-2)", whiteSpace:"nowrap" }}>{i.cat}</td>
                      <td style={{ textAlign:"center" }}><CmpPri p={i.pri}/></td>
                      <td><CmpTag s={i.status}/></td>
                      <td style={{ color:"var(--ink-2)", whiteSpace:"nowrap" }}>{i.owner}</td>
                      <td style={{ whiteSpace:"nowrap" }}>
                        {i.took === null
                          ? <span style={{ color:"var(--ink-3)" }}>running · SLA {INC_SLA[i.pri]}h</span>
                          : <span style={{ fontWeight:700, color: breach ? "#c62828" : "#2e7d32" }}>
                              {i.took}h {breach ? "· SLA breached" : "· within SLA"}
                            </span>}
                      </td>
                      <td style={{ whiteSpace:"nowrap", fontSize:12, color:"var(--ink-3)" }}>{i.capa || "—"}</td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </CmpBlock>
        </div>
      )}
    </div>
  );
}

Object.assign(window, { ComplianceOverview, ISO9001Screen, ISO27002Screen, EvaluationsScreen, IncidentsScreen });
