Catalyst / admin/Strike 14.8 GB / 57.8 GB 40.0 GB free
Help Sign in

admin / Strike

public

Web-Based UK Cyber Compliance Tool with Reporting

Code Issues Pull requests Pipelines Packages Security Insights Wiki Settings
Strike / strikexi-v2 / frontend / js / app.js 37951 B · main
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
/* StrikeXi SPA — vanilla JS, no build step required. */
const APP_BUILD = "2.0.0";
console.log("StrikeXi SPA build", APP_BUILD, "loaded");
// Surface any uncaught error visibly so a silent failure can't make the UI
// look "dead" (buttons doing nothing).
window.addEventListener("error", (e) => {
  console.error("StrikeXi error:", e.message, e.filename + ":" + e.lineno);
});
window.addEventListener("unhandledrejection", (e) => {
  console.error("StrikeXi promise rejection:", e.reason);
});

const API = "/api";
let TOKEN = localStorage.getItem("strikexi_token") || null;
let USER = JSON.parse(localStorage.getItem("strikexi_user") || "null");
let CURRENT = null; // current assessment context

/* ---------- HTTP helper ---------- */
async function api(path, opts = {}) {
  const headers = opts.headers || {};
  if (TOKEN) headers["Authorization"] = "Bearer " + TOKEN;
  if (opts.json) {
    headers["Content-Type"] = "application/json";
    opts.body = JSON.stringify(opts.json);
    delete opts.json;
  }
  const res = await fetch(API + path, { ...opts, headers });
  if (res.status === 401) { logout(); throw new Error("Session expired"); }
  if (!res.ok) {
    let msg = "Request failed";
    try { msg = (await res.json()).detail || msg; } catch (e) {}
    throw new Error(msg);
  }
  const ct = res.headers.get("content-type") || "";
  return ct.includes("application/json") ? res.json() : res;
}

/* ---------- Auth ---------- */
let PENDING_MFA_TOKEN = null;

function finishLogin(data) {
  TOKEN = data.access_token;
  USER = {
    username: data.username, role: data.role,
    must_change_password: data.must_change_password,
    mfa_required: data.mfa_required, mfa_enabled: data.mfa_enabled,
    first_login_pending: data.first_login_pending,
  };
  localStorage.setItem("strikexi_token", TOKEN);
  localStorage.setItem("strikexi_user", JSON.stringify(USER));
  showApp();
}

/* ---------- Self-service signup ---------- */
const showSignup = document.getElementById("show-signup");
if (showSignup) showSignup.addEventListener("click", (e) => {
  e.preventDefault();
  document.getElementById("login-form").classList.add("hidden");
  document.getElementById("signup-form").classList.remove("hidden");
});
const signupCancel = document.getElementById("signup-cancel");
if (signupCancel) signupCancel.addEventListener("click", () => {
  document.getElementById("signup-form").classList.add("hidden");
  document.getElementById("login-form").classList.remove("hidden");
});
const signupForm = document.getElementById("signup-form");
if (signupForm) signupForm.addEventListener("submit", async (e) => {
  e.preventDefault();
  const errEl = document.getElementById("signup-error");
  errEl.style.color = ""; errEl.textContent = "";
  const pw = document.getElementById("su-password").value;
  const pw2 = document.getElementById("su-password2").value;
  if (pw !== pw2) { errEl.textContent = "Passwords do not match."; return; }
  const payload = {
    first_name: document.getElementById("su-firstname").value.trim(),
    surname: document.getElementById("su-surname").value.trim(),
    company_name: document.getElementById("su-company").value.trim(),
    email: document.getElementById("su-email").value.trim(),
    contact_number: document.getElementById("su-contact").value.trim(),
    username: document.getElementById("su-username").value.trim(),
    password: pw,
  };
  try {
    const res = await fetch(API + "/auth/signup", {
      method: "POST", headers: { "Content-Type": "application/json" },
      body: JSON.stringify(payload),
    });
    if (!res.ok) throw new Error((await res.json()).detail || "Signup failed");
    errEl.style.color = "#27ae60";
    errEl.textContent = "Account created! You can now sign in. You'll be asked to set up MFA on first login.";
    setTimeout(() => {
      document.getElementById("signup-form").classList.add("hidden");
      document.getElementById("login-form").classList.remove("hidden");
      document.getElementById("username").value = payload.username;
    }, 1600);
  } catch (err) { errEl.textContent = err.message; }
});

document.getElementById("login-form").addEventListener("submit", async (e) => {
  e.preventDefault();
  const errEl = document.getElementById("login-error");
  errEl.textContent = "";
  const body = new URLSearchParams();
  body.set("username", document.getElementById("username").value);
  body.set("password", document.getElementById("password").value);
  try {
    const res = await fetch(API + "/auth/login", { method: "POST", body });
    if (!res.ok) throw new Error((await res.json()).detail || "Login failed");
    const data = await res.json();
    if (data.mfa_required && data.mfa_token) {
      // Account uses MFA — show the second-factor step.
      PENDING_MFA_TOKEN = data.mfa_token;
      document.getElementById("login-form").classList.add("hidden");
      document.getElementById("mfa-form").classList.remove("hidden");
      document.getElementById("mfa-code").focus();
      return;
    }
    finishLogin(data);
  } catch (err) { errEl.textContent = err.message; }
});

document.getElementById("mfa-form").addEventListener("submit", async (e) => {
  e.preventDefault();
  const errEl = document.getElementById("mfa-error");
  errEl.textContent = "";
  try {
    const res = await fetch(API + "/auth/login/mfa", {
      method: "POST", headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ mfa_token: PENDING_MFA_TOKEN,
                             code: document.getElementById("mfa-code").value }),
    });
    if (!res.ok) throw new Error((await res.json()).detail || "Verification failed");
    finishLogin(await res.json());
  } catch (err) { errEl.textContent = err.message; }
});

document.getElementById("mfa-cancel").addEventListener("click", () => {
  PENDING_MFA_TOKEN = null;
  document.getElementById("mfa-form").classList.add("hidden");
  document.getElementById("login-form").classList.remove("hidden");
  document.getElementById("mfa-code").value = "";
});

function logout() {
  if (TOKEN) { api("/auth/logout", { method: "POST" }).catch(() => {}); }
  TOKEN = null; USER = null;
  localStorage.removeItem("strikexi_token");
  localStorage.removeItem("strikexi_user");
  document.getElementById("app-view").classList.add("hidden");
  document.getElementById("login-view").classList.remove("hidden");
  document.getElementById("mfa-form").classList.add("hidden");
  const sf = document.getElementById("signup-form");
  if (sf) sf.classList.add("hidden");
  document.getElementById("login-form").classList.remove("hidden");
}
document.getElementById("logout-btn").addEventListener("click", logout);

/* ---------- Navigation (event delegation: robust to re-renders) ---------- */
document.addEventListener("click", (ev) => {
  const el = ev.target.closest(".nav-item[data-view]");
  if (!el) return;
  ev.preventDefault();
  route(el.dataset.view);
});

async function showApp() {
  document.getElementById("login-view").classList.add("hidden");
  document.getElementById("app-view").classList.remove("hidden");
  // Always refresh identity from the server so a stale localStorage copy
  // (e.g. from an older build without role/MFA fields) can't hide menus or
  // break role gating.
  try {
    const me = await api("/auth/me");
    USER = { ...USER, ...me };
    localStorage.setItem("strikexi_user", JSON.stringify(USER));
  } catch (e) { /* if this fails, api() handles 401/logout */ }

  document.getElementById("user-chip").textContent = `${USER.username} (${USER.role})`;
  // Stamp the running build into the sidebar so it's obvious which JS is live.
  const brand = document.querySelector("#app-view .sidebar .brand");
  if (brand && !brand.querySelector(".build-tag")) {
    brand.insertAdjacentHTML("beforeend",
      `<div class="build-tag" style="font-size:10px;color:#5cb3ff;font-weight:400">build ${APP_BUILD}</div>`);
  }
  // Hide admin-only nav for non-admins.
  const isAdmin = USER.role === "admin";
  document.querySelectorAll(".nav-admin").forEach(el =>
    el.style.display = isAdmin ? "" : "none");
  // Force password change before anything else.
  if (USER.must_change_password) {
    route("account");
    return;
  }
  // Enforce MFA enrolment on first login (self-service signups) or whenever an
  // admin requires MFA that hasn't been set up yet.
  if (USER.mfa_required && !USER.mfa_enabled) {
    route("account");
    return;
  }
  route("dashboard");
}

function route(view) {
  const titles = { dashboard: "Dashboard", new: "New Assessment", audit: "Audit Log",
                   users: "User Administration", account: "My Account",
                   run: "Assessment", results: "Results" };
  document.getElementById("page-title").textContent = titles[view] || "StrikeXi";
  document.querySelectorAll(".nav-item").forEach((n) => n.classList.remove("active"));
  const navEl = document.querySelector(`.nav-item[data-view="${view}"]`);
  if (navEl) navEl.classList.add("active");
  if (view === "dashboard") renderDashboard();
  else if (view === "new") renderNew();
  else if (view === "audit") renderAudit();
  else if (view === "users") renderUsers();
  else if (view === "account") renderAccount();
}

const content = () => document.getElementById("content");
const badgeFor = (s) => s >= 60 ? "green" : (s >= 40 ? "amber" : "red");
const esc = (s) => (s || "").replace(/[&<>"]/g, c => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" }[c]));

/* ---------- Dashboard ---------- */
async function renderDashboard() {
  content().innerHTML = `<div class="card"><p class="muted">Loading assessments…</p></div>`;
  try {
    const list = await api("/assessments");
    if (!list.length) {
      content().innerHTML = `<div class="card"><p>No assessments yet.</p>
        <button class="btn btn-primary" style="width:auto" onclick="route('new')">Start your first assessment</button></div>`;
      return;
    }
    const isAdmin = USER.role === "admin";
    const rows = list.map(a => {
      let acts = `<button class="btn btn-ghost btn-sm" onclick="openAssessment('${a.id}')">${a.status === 'completed' ? 'Review' : 'Resume'}</button>`;
      if (isAdmin)
        acts += ` <button class="btn btn-ghost btn-sm" style="color:#e74c3c" onclick="deleteAssessment('${a.id}','${esc(a.organisation_name)}')">Delete</button>`;
      return `
      <tr>
        <td><b>${esc(a.organisation_name)}</b></td>
        <td>${a.assessment_date}</td>
        <td>${a.status === "completed"
            ? `<span class="badge ${badgeFor(a.overall_score)}">${a.overall_score ?? 0}/100</span>`
            : `<span class="badge grey">In progress</span>`}</td>
        <td><span class="badge ${a.status === 'completed' ? 'green' : 'amber'}">${a.status}</span></td>
        <td class="row-actions">${acts}</td>
      </tr>`;}).join("");
    content().innerHTML = `<div class="card">
      <table><thead><tr><th>Organisation</th><th>Date</th><th>Score</th><th>Status</th><th></th></tr></thead>
      <tbody>${rows}</tbody></table></div>`;
  } catch (e) { content().innerHTML = `<div class="card error">${e.message}</div>`; }
}

async function deleteAssessment(id, org) {
  if (!confirm(`Delete the assessment for "${org}"? This permanently removes its answers, scores and roadmap and cannot be undone.`)) return;
  try { await api("/assessments/" + id, { method: "DELETE" }); renderDashboard(); }
  catch (e) { alert(e.message); }
}

/* ---------- New assessment ---------- */
function renderNew() {
  content().innerHTML = `<div class="card" style="max-width:520px">
    <label>Organisation name</label>
    <input id="new-org" placeholder="e.g. Acme Water Utilities" />
    <label>Date of assessment</label>
    <input id="new-date" type="date" value="${new Date().toISOString().slice(0,10)}" />
    <button class="btn btn-primary" style="width:auto;margin-top:18px" id="create-btn">Create &amp; begin</button>
    <div class="error" id="new-error"></div>
  </div>`;
  document.getElementById("create-btn").addEventListener("click", async () => {
    const org = document.getElementById("new-org").value.trim();
    if (!org) { document.getElementById("new-error").textContent = "Organisation name is required"; return; }
    try {
      const a = await api("/assessments", { method: "POST", json: {
        organisation_name: org, assessment_date: document.getElementById("new-date").value } });
      openAssessment(a.id);
    } catch (e) { document.getElementById("new-error").textContent = e.message; }
  });
}

/* ---------- Run / resume assessment ---------- */
async function openAssessment(id) {
  document.getElementById("page-title").textContent = "Assessment";
  document.querySelectorAll(".nav-item").forEach(n => n.classList.remove("active"));
  content().innerHTML = `<div class="card"><p class="muted">Loading…</p></div>`;
  try {
    const [catalogue, assessment] = await Promise.all([
      api("/catalogue"), api("/assessments/" + id)
    ]);
    CURRENT = { id, assessment, catalogue, answers: { ...assessment.answers } };
    if (assessment.status === "completed") return renderResults(id);
    renderQuestionnaire();
  } catch (e) { content().innerHTML = `<div class="card error">${e.message}</div>`; }
}

function renderQuestionnaire() {
  const { catalogue, assessment, answers } = CURRENT;
  let html = `<div class="card"><h2 style="margin-top:0">${esc(assessment.organisation_name)}</h2>
    <p class="muted">Answer each question. You can save & pause at any time.</p>`;
  catalogue.forEach(obj => {
    html += `<div class="objective-head">Objective ${obj.id}: ${esc(obj.title)}</div>`;
    if (obj.description) html += `<div class="objective-desc">${esc(obj.description)}</div>`;
    obj.principles.forEach(pr => {
      if (!pr.questions.length) return;
      html += `<div class="principle-head">${pr.id}${esc(pr.title)}</div>`;
      if (pr.description) html += `<div class="principle-desc">${esc(pr.description)}</div>`;
      pr.questions.forEach(q => {
        const opts = q.options.map(o => `
          <div class="opt ${answers[q.id] === o.id ? 'selected' : ''}"
               data-q="${q.id}" data-o="${o.id}">${esc(o.label)} (${o.score})</div>`).join("");
        const context = q.guidance ? `<div class="q-context"><b>CAF context:</b> ${esc(q.guidance)}</div>` : "";
        html += `<div class="q-block">
          <div class="q-meta">${q.code} · weight ${q.weight}</div>
          <div class="q-text">${esc(q.text)}</div>
          ${context}
          <div class="opts">${opts}</div></div>`;
      });
    });
  });
  html += `<div class="row-actions" style="margin-top:18px">
      <button class="btn btn-ghost" id="save-btn">💾 Save &amp; pause</button>
      <button class="btn btn-success" id="complete-btn">✓ Complete &amp; score</button>
    </div><div class="error" id="run-error"></div></div>`;
  content().innerHTML = html;

  content().querySelectorAll(".opt").forEach(el => el.addEventListener("click", () => {
    const q = el.dataset.q;
    content().querySelectorAll(`.opt[data-q="${q}"]`).forEach(x => x.classList.remove("selected"));
    el.classList.add("selected");
    CURRENT.answers[q] = el.dataset.o;
  }));

  document.getElementById("save-btn").addEventListener("click", () => saveAnswers(false));
  document.getElementById("complete-btn").addEventListener("click", () => saveAnswers(true));
}

async function saveAnswers(complete) {
  const errEl = document.getElementById("run-error");
  const answers = Object.entries(CURRENT.answers).map(([question_id, option_id]) => ({ question_id, option_id }));
  if (complete && !answers.length) { errEl.textContent = "Answer at least one question first."; return; }
  try {
    await api(`/assessments/${CURRENT.id}/answers`, { method: "PUT", json: { answers } });
    if (!complete) { errEl.style.color = "#27ae60"; errEl.textContent = "Saved. You can resume later."; return; }
    await api(`/assessments/${CURRENT.id}/complete`, { method: "POST" });
    renderResults(CURRENT.id);
  } catch (e) { errEl.textContent = e.message; }
}

/* ---------- Results + roadmap ---------- */
async function renderResults(id) {
  document.getElementById("page-title").textContent = "Results";
  content().innerHTML = `<div class="card"><p class="muted">Loading results…</p></div>`;
  try {
    const [a, roadmap, riskData] = await Promise.all([
      api("/assessments/" + id), api(`/assessments/${id}/roadmap`),
      api(`/assessments/${id}/risk`)
    ]);
    CURRENT = { id, assessment: a };
    const objs = a.objective_scores || {};
    const objBoxes = ["A","B","C","D"].map(o => {
      const s = objs[o];
      return `<div class="score-box">
        <div class="score-num" style="color:${s==null?'#999':(s>=60?'#27ae60':s>=40?'#f39c12':'#e74c3c')}">${s==null?'—':Math.round(s)}</div>
        <div class="score-label">Objective ${o}</div></div>`;
    }).join("");

    const steps = roadmap.length ? roadmap.map((r,i) => `
      <div class="roadmap-step">
        <span class="num">Step ${i+1}.</span> <b>${esc(r.title)}</b>
        <div style="margin:6px 0">
          <span class="badge grey">Objective ${esc(r.objective_id)}</span>
          <span class="badge grey">Principle ${esc(r.principle_id)}${esc(r.principle_title)}</span>
          <span class="badge ${badgeFor(r.principle_score)}">Current: ${Math.round(r.principle_score)}/100</span>
          <span class="badge grey">Effort: ${esc(r.effort)}</span>
        </div>
        <div class="muted" style="margin-top:4px"><b>Mitigation:</b> ${esc(r.detail)}</div>
      </div>`).join("")
      : `<p class="muted">No remediation actions triggered — all principles met the threshold. 🎉</p>`;

    const riskColour = (lvl) => ({ Critical:'#c0392b', High:'#e67e22', Medium:'#f1c40f', Low:'#27ae60' }[lvl] || '#7b8a9a');
    const objRiskRows = (riskData.objective_risks || []).map(o => `<tr>
        <td><b>${esc(o.objective_id)}</b></td><td>${esc(o.title)}</td>
        <td>${Math.round(o.score)}/100</td>
        <td><span class="badge" style="background:${riskColour(o.risk_level)};color:#fff">${esc(o.risk_level)}</span></td></tr>`).join("");
    const keyRiskRows = (riskData.key_risks || []).map((k,i) => `<tr>
        <td>${i+1}</td><td>${esc(k.objective_id)}</td>
        <td><b>${esc(k.principle_id)}</b> — ${esc(k.principle_title)}</td>
        <td>${Math.round(k.score)}/100</td>
        <td><span class="badge" style="background:${riskColour(k.risk_level)};color:#fff">${esc(k.risk_level)}</span></td></tr>`).join("");
    const c = riskData.counts || {};
    const riskSection = `<div class="card">
        <h2 style="margin-top:0">Risk Assessment Summary</h2>
        <p class="muted">Derived from your assessment responses — lower maturity means higher residual cyber risk.</p>
        <div class="score-grid" style="align-items:center">
          <div class="score-box" style="background:${riskColour(riskData.overall_risk)}1a">
            <div class="score-num" style="color:${riskColour(riskData.overall_risk)};font-size:24px">${esc(riskData.overall_risk)}</div>
            <div class="score-label">Overall residual risk</div></div>
          <div style="flex:2;min-width:240px;color:#41536b;font-size:13px;line-height:1.5">${esc(riskData.narrative)}</div>
        </div>
        <div style="margin-top:14px">
          <span class="badge" style="background:#c0392b;color:#fff">Critical: ${c.Critical||0}</span>
          <span class="badge" style="background:#e67e22;color:#fff">High: ${c.High||0}</span>
          <span class="badge" style="background:#f1c40f;color:#fff">Medium: ${c.Medium||0}</span>
          <span class="badge" style="background:#27ae60;color:#fff">Low: ${c.Low||0}</span>
        </div>
        <h3 style="color:#16324f;margin-bottom:4px">Risk by objective</h3>
        <table><thead><tr><th>Objective</th><th>Title</th><th>Score</th><th>Risk level</th></tr></thead>
        <tbody>${objRiskRows}</tbody></table>
        <h3 style="color:#16324f;margin-bottom:4px">Key risk areas</h3>
        <table><thead><tr><th>#</th><th>Objective</th><th>Principle</th><th>Score</th><th>Risk level</th></tr></thead>
        <tbody>${keyRiskRows}</tbody></table>
      </div>`;

    const ps = a.principle_scores || [];
    const breakdown = ps.length ? `<div class="card">
        <h2 style="margin-top:0">Assessment Summary &amp; Breakdown</h2>
        <table><thead><tr><th>Objective</th><th>Principle</th><th>Score</th><th>Status</th></tr></thead>
        <tbody>${ps.map(r => `<tr>
          <td>${esc(r.objective_id)}</td>
          <td><b>${esc(r.principle_id)}</b> — ${esc(r.principle_title)}</td>
          <td><span class="badge ${badgeFor(r.score)}">${Math.round(r.score)}/100</span></td>
          <td>${r.score < 70 ? '<span class="badge red">Needs improvement</span>' : '<span class="badge green">On track</span>'}</td>
        </tr>`).join("")}</tbody></table></div>` : "";

    content().innerHTML = `
      <div class="card">
        <h2 style="margin-top:0">${esc(a.organisation_name)}${a.assessment_date}</h2>
        <div class="score-grid">
          <div class="score-box" style="background:#eaf3fd">
            <div class="score-num" style="color:#2e86de">${a.overall_score==null?'—':Math.round(a.overall_score)}</div>
            <div class="score-label">Overall maturity</div></div>
          ${objBoxes}
        </div>
      </div>
      ${riskSection}
      ${breakdown}
      <div class="card">
        <h2 style="margin-top:0">Actionable Maturity Roadmap</h2>
        ${steps}
      </div>
      <div class="card">
        <div class="row-actions">
          <button class="btn btn-success" id="pdf-btn">📄 Export PDF report</button>
          <button class="btn btn-ghost" onclick="route('dashboard')">← Back to dashboard</button>
        </div>
      </div>`;
    document.getElementById("pdf-btn").addEventListener("click", () => openReportModal(a));
  } catch (e) { content().innerHTML = `<div class="card error">${e.message}</div>`; }
}

/* ---------- PDF report modal ---------- */
function openReportModal(a) {
  document.getElementById("report-org").value = a.organisation_name;
  document.getElementById("report-date").value = a.assessment_date;
  document.getElementById("report-modal").classList.remove("hidden");
}
document.getElementById("report-cancel").addEventListener("click", () =>
  document.getElementById("report-modal").classList.add("hidden"));

document.getElementById("report-generate").addEventListener("click", async () => {
  const org = document.getElementById("report-org").value;
  const adate = document.getElementById("report-date").value;
  try {
    await api(`/assessments/${CURRENT.id}/report`, { method: "POST",
      json: { organisation_name: org, assessment_date: adate } });
    // Trigger download
    const res = await api(`/assessments/${CURRENT.id}/report/download`);
    const blob = await res.blob();
    const url = URL.createObjectURL(blob);
    const link = document.createElement("a");
    link.href = url; link.download = `StrikeXi_Report_${org}.pdf`;
    link.click(); URL.revokeObjectURL(url);
    document.getElementById("report-modal").classList.add("hidden");
  } catch (e) { alert(e.message); }
});

/* ---------- Audit log ---------- */
async function renderAudit() {
  content().innerHTML = `<div class="card"><p class="muted">Loading audit log…</p></div>`;
  try {
    const logs = await api("/audit?limit=300");
    const rows = logs.map(l => `<tr>
      <td>${new Date(l.ts).toLocaleString()}</td>
      <td>${esc(l.username) || '—'}</td>
      <td><span class="badge ${l.action.includes('FAILED') ? 'red' : 'grey'}">${esc(l.action)}</span></td>
      <td class="muted">${esc(l.detail) || ''}</td>
      <td class="muted">${esc(l.ip_address) || ''}</td></tr>`).join("");
    content().innerHTML = `<div class="card"><table>
      <thead><tr><th>Timestamp</th><th>User</th><th>Action</th><th>Detail</th><th>IP</th></tr></thead>
      <tbody>${rows}</tbody></table></div>`;
  } catch (e) { content().innerHTML = `<div class="card error">${e.message}</div>`; }
}

/* ===================================================================== */
/* User administration (admin)                                           */
/* ===================================================================== */
async function renderUsers() {
  content().innerHTML = `<div class="card"><p class="muted">Loading users…</p></div>`;
  try {
    const users = await api("/users");
    const rows = users.map(u => {
      const self = u.username.toLowerCase() === USER.username.toLowerCase();
      const roleBadge = u.role === "admin"
        ? '<span class="badge amber">admin</span>'
        : (u.role === "user"
            ? '<span class="badge grey">user</span>'
            : '<span class="badge grey">assessor</span>');
      const originBadge = u.signup_origin === "self_service"
        ? '<span class="badge" style="background:#eaf3fd;color:#2e86de">Self-service signup</span>'
        : '<span class="badge grey">Admin created</span>';
      const statusBadge = u.is_active
        ? '<span class="badge green">active</span>'
        : '<span class="badge red">disabled</span>';
      let mfaBadge = u.mfa_enabled
        ? '<span class="badge green">on</span>'
        : '<span class="badge grey">off</span>';
      if (u.mfa_required) mfaBadge += ' <span class="badge amber">required</span>';
      const contact = [u.company_name, u.email, u.contact_number].filter(Boolean).map(esc).join(' · ');
      let acts = `<button class="btn btn-ghost btn-sm" onclick="openEditUser('${u.id}')">Edit</button>`;
      if (u.mfa_enabled || u.mfa_required)
        acts += ` <button class="btn btn-ghost btn-sm" onclick="resetUserMfa('${u.id}','${esc(u.username)}')">Reset MFA</button>`;
      if (!self)
        acts += ` <button class="btn btn-ghost btn-sm" style="color:#e74c3c" onclick="deleteUser('${u.id}','${esc(u.username)}')">Delete</button>`;
      return `<tr>
        <td><b>${esc(u.username)}</b>${self ? ' <span class="muted">(you)</span>' : ''}<div class="muted">${esc(u.full_name || '')}</div>${contact ? `<div class="muted" style="font-size:11px">${contact}</div>` : ''}</td>
        <td>${roleBadge}</td><td>${originBadge}</td><td>${statusBadge}</td><td>${mfaBadge}</td>
        <td class="muted">${u.last_login ? new Date(u.last_login).toLocaleString() : '—'}</td>
        <td class="row-actions">${acts}</td></tr>`;
    }).join("");
    content().innerHTML = `
      <div class="card">
        <h2 style="margin-top:0">Add user</h2>
        <div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(180px,1fr));gap:12px">
          <div><label>Username</label><input id="nu-username" autocomplete="off" /></div>
          <div><label>Full name</label><input id="nu-fullname" autocomplete="off" /></div>
          <div><label>Temporary password</label><input id="nu-password" placeholder="min 8 chars" /></div>
          <div><label>Role</label><select id="nu-role"><option value="assessor">assessor</option><option value="user">user</option><option value="admin">admin</option></select></div>
        </div>
        <label style="margin-top:12px"><input type="checkbox" id="nu-mfa" style="width:auto" /> Require MFA (force enrolment at next login)</label>
        <label><input type="checkbox" id="nu-chg" checked style="width:auto" /> Require password change at first login</label>
        <button class="btn btn-primary" style="width:auto;margin-top:14px" id="nu-create">Create user</button>
        <div class="error" id="nu-error"></div>
      </div>
      <div class="card">
        <div class="row-actions" style="justify-content:space-between;align-items:center">
          <h2 style="margin:0">Users</h2>
          <div class="row-actions">
            <button class="btn btn-ghost btn-sm" onclick="downloadUsersReport('csv')">⬇ Export CSV</button>
            <button class="btn btn-ghost btn-sm" onclick="downloadUsersReport('pdf')">📄 Export PDF</button>
          </div>
        </div>
        <table><thead><tr><th>User</th><th>Role</th><th>Account type</th><th>Status</th><th>MFA</th><th>Last login</th><th></th></tr></thead>
        <tbody>${rows}</tbody></table>
      </div>`;
    document.getElementById("nu-create").addEventListener("click", createUser);
    window._users = users;
  } catch (e) { content().innerHTML = `<div class="card error">${e.message}</div>`; }
}

async function createUser() {
  const errEl = document.getElementById("nu-error");
  errEl.style.color = ""; errEl.textContent = "";
  try {
    await api("/users", { method: "POST", json: {
      username: document.getElementById("nu-username").value.trim(),
      full_name: document.getElementById("nu-fullname").value.trim() || null,
      password: document.getElementById("nu-password").value,
      role: document.getElementById("nu-role").value,
      mfa_required: document.getElementById("nu-mfa").checked,
      must_change_password: document.getElementById("nu-chg").checked,
    }});
    renderUsers();
  } catch (e) { errEl.textContent = e.message; }
}

function openEditUser(id) {
  const u = (window._users || []).find(x => x.id === id);
  if (!u) return;
  const html = `
    <div class="modal-bg" id="edit-modal">
      <div class="modal">
        <h3>Edit ${esc(u.username)}</h3>
        <label>Role</label>
        <select id="eu-role"><option value="assessor">assessor</option><option value="user">user</option><option value="admin">admin</option></select>
        <label style="margin-top:10px"><input type="checkbox" id="eu-active" style="width:auto" /> Account active</label>
        <label><input type="checkbox" id="eu-mfareq" style="width:auto" /> Require MFA</label>
        <label><input type="checkbox" id="eu-chg" style="width:auto" /> Require password change at next login</label>
        <label style="margin-top:10px">Reset password <span class="muted">(leave blank to keep)</span></label>
        <input id="eu-pw" placeholder="new password" />
        <div class="error" id="eu-error"></div>
        <div class="row-actions" style="justify-content:flex-end;margin-top:16px">
          <button class="btn btn-ghost btn-sm" onclick="document.getElementById('edit-modal').remove()">Cancel</button>
          <button class="btn btn-success btn-sm" id="eu-save">Save</button>
        </div>
      </div>
    </div>`;
  document.body.insertAdjacentHTML("beforeend", html);
  document.getElementById("eu-role").value = u.role;
  document.getElementById("eu-active").checked = u.is_active;
  document.getElementById("eu-mfareq").checked = u.mfa_required;
  document.getElementById("eu-chg").checked = u.must_change_password;
  document.getElementById("eu-save").addEventListener("click", async () => {
    const errEl = document.getElementById("eu-error");
    const body = {
      role: document.getElementById("eu-role").value,
      is_active: document.getElementById("eu-active").checked,
      mfa_required: document.getElementById("eu-mfareq").checked,
      must_change_password: document.getElementById("eu-chg").checked,
    };
    const pw = document.getElementById("eu-pw").value;
    if (pw) body.password = pw;
    try {
      await api("/users/" + id, { method: "PATCH", json: body });
      document.getElementById("edit-modal").remove();
      renderUsers();
    } catch (e) { errEl.textContent = e.message; }
  });
}

async function downloadUsersReport(fmt) {
  // fmt: 'csv' | 'pdf'
  try {
    const res = await api(`/users/report.${fmt}`);
    const blob = await res.blob();
    const url = URL.createObjectURL(blob);
    const link = document.createElement("a");
    link.href = url;
    link.download = `StrikeXi_Users_Report.${fmt}`;
    link.click();
    URL.revokeObjectURL(url);
  } catch (e) { alert(e.message); }
}

async function resetUserMfa(id, username) {
  if (!confirm(`Reset/disable MFA for ${username}? They will re-enrol if MFA is required.`)) return;
  try { await api(`/users/${id}/mfa/reset`, { method: "POST" }); renderUsers(); }
  catch (e) { alert(e.message); }
}

async function deleteUser(id, username) {
  if (!confirm(`Delete user ${username}? This cannot be undone.`)) return;
  try { await api("/users/" + id, { method: "DELETE" }); renderUsers(); }
  catch (e) { alert(e.message); }
}

/* ===================================================================== */
/* My account (self-service password + MFA)                              */
/* ===================================================================== */
async function renderAccount() {
  let me;
  try { me = await api("/auth/me"); }
  catch (e) { content().innerHTML = `<div class="card error">${e.message}</div>`; return; }
  USER.must_change_password = me.must_change_password;
  USER.mfa_enabled = me.mfa_enabled;
  USER.mfa_required = me.mfa_required;

  const warn = me.must_change_password
    ? `<div class="card" style="border-left:4px solid #f39c12"><b>⚠ You must change your password before continuing.</b></div>` : "";
  const mfaWarn = (me.mfa_required && !me.mfa_enabled)
    ? `<div class="card" style="border-left:4px solid #f39c12"><b>⚠ An administrator requires MFA on your account. Please set it up below.</b></div>` : "";

  const mfaBlock = me.mfa_enabled
    ? `<p class="muted">MFA is <span class="badge green">enabled</span> on your account.</p>` +
      (me.mfa_required
        ? `<p class="muted">Your administrator requires MFA, so it cannot be disabled.</p>`
        : `<button class="btn btn-ghost" style="width:auto;color:#e74c3c" id="mfa-disable">Disable MFA</button>`)
    : `<p class="muted">MFA is <span class="badge grey">disabled</span>. Add an authenticator app for stronger security.</p>
       <button class="btn btn-primary" style="width:auto" id="mfa-start">Set up MFA</button>
       <div id="mfa-setup" style="margin-top:16px"></div>`;

  content().innerHTML = `
    ${warn}${mfaWarn}
    <div class="card">
      <h2 style="margin-top:0">Profile</h2>
      <p class="muted">Username: <b>${esc(me.username)}</b> &middot; Role:
        <span class="badge ${me.role === 'admin' ? 'amber' : 'grey'}">${esc(me.role)}</span></p>
    </div>
    <div class="card" style="max-width:480px">
      <h2 style="margin-top:0">🔑 Change password</h2>
      <label>Current password</label><input id="pw-cur" type="password" autocomplete="current-password" />
      <label>New password <span class="muted">(min 8 characters)</span></label><input id="pw-new" type="password" autocomplete="new-password" />
      <label>Confirm new password</label><input id="pw-new2" type="password" autocomplete="new-password" />
      <button class="btn btn-primary" style="width:auto;margin-top:14px" id="pw-save">Update password</button>
      <div class="error" id="pw-msg"></div>
    </div>
    <div class="card" style="max-width:480px">
      <h2 style="margin-top:0">🔐 Multi-factor authentication</h2>
      ${mfaBlock}
    </div>`;

  document.getElementById("pw-save").addEventListener("click", changeMyPassword);
  const startBtn = document.getElementById("mfa-start");
  if (startBtn) startBtn.addEventListener("click", startMyMfa);
  const disBtn = document.getElementById("mfa-disable");
  if (disBtn) disBtn.addEventListener("click", disableMyMfa);
  if (me.mfa_required && !me.mfa_enabled) startMyMfa();
}

async function changeMyPassword() {
  const msg = document.getElementById("pw-msg");
  msg.style.color = ""; msg.textContent = "";
  const a = document.getElementById("pw-new").value;
  const b = document.getElementById("pw-new2").value;
  if (a !== b) { msg.textContent = "New passwords do not match."; return; }
  try {
    await api("/users/me/password", { method: "POST", json: {
      current_password: document.getElementById("pw-cur").value, new_password: a } });
    USER.must_change_password = false;
    localStorage.setItem("strikexi_user", JSON.stringify(USER));
    msg.style.color = "#27ae60"; msg.textContent = "Password updated.";
    setTimeout(() => route("dashboard"), 900);
  } catch (e) { msg.textContent = e.message; }
}

async function startMyMfa() {
  try {
    const d = await api("/users/me/mfa/setup", { method: "POST" });
    const box = document.getElementById("mfa-setup");
    box.innerHTML = `
      <p class="muted">Scan this QR code with Google Authenticator, Authy, 1Password, etc.</p>
      <img src="${d.qr}" alt="MFA QR" style="width:180px;height:180px;border:1px solid #d4dde7;border-radius:8px" />
      <p class="muted">Or enter this secret manually:</p>
      <code style="display:block;background:#f4f8fc;padding:8px;border-radius:6px;word-break:break-all">${esc(d.secret)}</code>
      <label>Enter the 6-digit code to confirm</label>
      <input id="mfa-confirm-code" inputmode="numeric" placeholder="123456" style="max-width:200px" />
      <button class="btn btn-success" style="width:auto;margin-top:10px" id="mfa-confirm-btn">Confirm &amp; enable</button>
      <div class="error" id="mfa-confirm-msg"></div>`;
    document.getElementById("mfa-confirm-btn").addEventListener("click", confirmMyMfa);
  } catch (e) { alert(e.message); }
}

async function confirmMyMfa() {
  const msg = document.getElementById("mfa-confirm-msg");
  try {
    await api("/users/me/mfa/confirm", { method: "POST", json: {
      code: document.getElementById("mfa-confirm-code").value } });
    USER.mfa_enabled = true;
    USER.first_login_pending = false;
    localStorage.setItem("strikexi_user", JSON.stringify(USER));
    // First-login enrolment complete — drop the user into the app.
    if (!USER.must_change_password) { route("dashboard"); return; }
    renderAccount();
  } catch (e) { msg.textContent = e.message; }
}

async function disableMyMfa() {
  if (!confirm("Disable multi-factor authentication?")) return;
  try { await api("/users/me/mfa/disable", { method: "POST" }); renderAccount(); }
  catch (e) { alert(e.message); }
}

/* ---------- Boot ---------- */
if (TOKEN && USER) showApp();