"use client";
import { useEffect, useRef, useState } from "react";
import { questionSummary, groupedCosts } from "../lib/reports";
import InlineTest from "./InlineTest";
type R = Record<string, any>;
const date = (v: string) => (v ? new Date(v).toLocaleString() : "—");
const money = (v: any, c = "USD") =>
  v == null
    ? "Not recorded"
    : c + " " + Number(v).toFixed(8).replace(/0+$/, "").replace(/\.$/, "");
const plain = (v: any) =>
  String(v || "")
    .replace(/\u00a7\u00a7/g, "Sections ")
    .replace(/\u00a7/g, "Section ");
const values = (form: HTMLFormElement) => {
  const fd = new FormData(form),
    v: R = Object.fromEntries(fd);
  for (const key of ["documentIds"]) v[key] = fd.getAll(key);
  for (const key of ["setupConfirmed", "outcomeVerified"]) v[key] = fd.has(key);
  delete v.file;
  return v;
};
export default function Home() {
  const [data, setData] = useState<R | null>(null),
    [tab, setTab] = useState("My testing"),
    [modal, setModal] = useState<R | null>(null),
    [error, setError] = useState(""),
    [busy, setBusy] = useState(false),
    [search, setSearch] = useState(""),
    [area, setArea] = useState(""),
    [selected, setSelected] = useState<string[]>([]),
    [copied, setCopied] = useState(""),
    [saved, setSaved] = useState(""),
    [filters, setFilters] = useState<R>({}),
    [context, setContext] = useState({ oiName: "Jenny", channel: "Voice" }),
    [target, setTarget] = useState<R | null>(null),
    [expanded, setExpanded] = useState<string[]>([]);
  const draftTimer = useRef<ReturnType<typeof setTimeout> | null>(null),
    draftChain = useRef<Promise<any>>(Promise.resolve()),
    draftRevision = useRef(0),
    formRef = useRef<HTMLFormElement | null>(null);
  async function load() {
    try {
      const res = await fetch("/api/data", { cache: "no-store" });
      if (res.status === 401) {
        setData({ login: true });
        return;
      }
      const body = await res.json();
      if (!res.ok) throw Error(body.error);
      setData(body);
    } catch (e: any) {
      setError(e.message);
    }
  }
  useEffect(() => {
    load();
    const timer = setInterval(load, 30000);
    return () => clearInterval(timer);
  }, []);
  async function send(body: R, files?: File[]) {
    let request: RequestInit = { method: "POST" };
    if (files?.length) {
      const fd = new FormData();
      fd.set("data", JSON.stringify(body));
      files.forEach((f) => fd.append("file", f));
      request.body = fd;
    } else {
      request.headers = { "Content-Type": "application/json" };
      request.body = JSON.stringify(body);
    }
    const response = await fetch("/api/data", request),
      result = await response.json();
    if (!response.ok) throw Error(result.error);
    return result;
  }
  async function auth(e: any, action: string) {
    e.preventDefault();
    setBusy(true);
    setError("");
    try {
      const v = Object.fromEntries(new FormData(e.currentTarget));
      const r = await fetch("/api/auth", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ ...v, action }),
        }),
        b = await r.json();
      if (!r.ok) throw Error(b.error);
      await load();
    } catch (e: any) {
      setError(e.message);
    } finally {
      setBusy(false);
    }
  }
  const field = (
    label: string,
    name: string,
    value: any = "",
    required = false,
    type = "text",
  ) => (
    <label>
      {label}
      {type === "textarea" ? (
        <textarea name={name} defaultValue={plain(value)} required={required} />
      ) : (
        <input
          name={name}
          type={type}
          defaultValue={value ?? ""}
          required={required}
          min={type === "number" ? 0 : undefined}
          step={type === "number" ? "any" : undefined}
        />
      )}
    </label>
  );
  const select = (
    label: string,
    name: string,
    opts: string[],
    value?: string,
  ) => (
    <label>
      {label}
      <select name={name} defaultValue={value}>
        {opts.map((v) => (
          <option key={v}>{v}</option>
        ))}
      </select>
    </label>
  );
  if (!data)
    return (
      <main>
        <h1>OI Workforce Test Centre</h1>
        <p>{error || "Loading…"}</p>
      </main>
    );
  if (data.login || data.changePassword)
    return (
      <main className="login panel">
        <a className="brand loginbrand">
          OI<span>Workforce</span>
        </a>
        <h1>
          {data.changePassword ? "Choose your password" : "Test Centre sign in"}
        </h1>
        <p>
          {data.changePassword
            ? "Replace your temporary password. You will then sign in again."
            : "Use the account allocated by your administrator."}
        </p>
        {error && (
          <p role="alert" className="alert">
            {error}
          </p>
        )}
        <form
          onSubmit={(e) => auth(e, data.changePassword ? "password" : "login")}
        >
          {data.changePassword ? (
            <>
              {field("Current password", "current", "", true, "password")}
              {field(
                "New password (at least 12 characters)",
                "password",
                "",
                true,
                "password",
              )}
            </>
          ) : (
            <>
              {field("Email", "email", "", true, "email")}
              {field("Password", "password", "", true, "password")}
            </>
          )}
          <button disabled={busy} className="primary">
            {busy
              ? "Please wait…"
              : data.changePassword
                ? "Change password"
                : "Sign in"}
          </button>
        </form>
      </main>
    );
  const {
    user,
    questions,
    documents,
    runs,
    sessions,
    searches,
    issues,
    comments,
    events,
    users,
    drafts,
  } = data;
  const admin = user.role === "admin",
    technical = admin || user.role === "technical",
    ownSessions = sessions.filter((s: any) => s.user_id === user.id),
    active = ownSessions.find((s: any) => s.status === "Active");
  const badge = (v: string) => (
    <span className={"badge " + v.replaceAll(" ", "")}>
      {v === "Fail" ? "Failed" : v}
    </span>
  );
  const link = (f: any) => (
    <a href={"/api/files?id=" + f.id} key={f.id}>
      {f.filename || "Download file"}
    </a>
  );
  const doclinks = (docs: any[]) => (
    <ul className="doc-links">
      {docs.map((d) => (
        <li key={d.id + "-" + d.version}>
          <a href={"/api/files?id=" + d.fileId}>
            {d.code} · {d.title} · v{d.version}
          </a>
        </li>
      ))}
    </ul>
  );
  const linked = (q: any) =>
    (q.documentIds || [])
      .map((id: string) => documents.find((d: any) => d.id === id))
      .filter(Boolean);
  const ask = (q: any) => (
    <div className="ask-box">
      <h3>Ask the OI</h3>
      <p>{q.prompt}</p>
      <button
        type="button"
        onClick={async () => {
          try {
            await navigator.clipboard.writeText(q.prompt);
            setCopied(q.id);
          } catch {
            setError("Select and copy the question text.");
          }
        }}
      >
        {copied === q.id ? "Copied" : "Copy question"}
      </button>
    </div>
  );
  function open(v: R) {
    if (draftTimer.current) clearTimeout(draftTimer.current);
    setError("");
    setSaved("");
    setModal(v);
    draftRevision.current = v.draftRevision || 0;
  }
  function start(q: any, parent?: any, issue?: any) {
    setTarget({ questionId: q.id, parent, issue });
    setExpanded([q.id]);
    setTab("My testing");
    setSearch(q.id + " ");
    setArea("");
  }
  function captureDraft(form: HTMLFormElement) {
    if (modal?.action !== "run") return;
    const payload = { ...modal, ...values(form) };
    if (draftTimer.current) clearTimeout(draftTimer.current);
    setSaved("Saving draft…");
    draftTimer.current = setTimeout(() => {
      draftChain.current = draftChain.current
        .catch(() => {})
        .then(async () => {
          try {
            const r = await send({
              action: "draft",
              questionId: payload.questionId,
              payload,
              revision: draftRevision.current,
            });
            draftRevision.current = r.revision;
            setSaved(
              "Draft saved. Screenshots are saved with the final result.",
            );
          } catch (e: any) {
            setSaved("Draft not saved: " + e.message);
          }
        });
    }, 1500);
  }
  async function quick(body: R) {
    setBusy(true);
    setError("");
    try {
      await send(body);
      await load();
    } catch (e: any) {
      setError(e.message);
    } finally {
      setBusy(false);
    }
  }
  async function submit(e: any) {
    e.preventDefault();
    if (draftTimer.current) clearTimeout(draftTimer.current);
    setBusy(true);
    setError("");
    const form = e.currentTarget,
      body = { ...modal, ...values(form) };
    delete body.draftRevision;
    delete body.titleForDisplay;
    if (modal?.action === "search" && body.startedAt)
      body.startedAt = new Date(body.startedAt).toISOString();
    if (modal?.action === "question" && modal.version)
      body.version = Number(modal.version);
    if (modal?.action === "user") body.active = body.active === "true";
    if (modal?.action === "run" && !body.verdict) {
      setError("Choose a verdict.");
      setBusy(false);
      return;
    }
    const files = new FormData(form)
      .getAll("file")
      .filter((f) => f instanceof File && f.size) as File[];
    try {
      await draftChain.current;
      await send(body, files);
      setModal(null);
      setSaved("");
      await load();
    } catch (e: any) {
      setError(e.message);
    } finally {
      setBusy(false);
    }
  }
  const filteredRuns = runs.filter(
    (r: any) =>
      (!filters.tester || r.tester.id === filters.tester) &&
      (!filters.build || r.build === filters.build) &&
      (!filters.channel || r.channel === filters.channel) &&
      (!filters.environment || r.environment === filters.environment) &&
      (!filters.version || String(r.questionVersion) === filters.version) &&
      (!filters.from || r.created.slice(0, 10) >= filters.from) &&
      (!filters.to || r.created.slice(0, 10) <= filters.to),
  );
  const report = questionSummary(filteredRuns, questions, documents),
    decided = filteredRuns.filter((r: any) =>
      ["Pass", "Fail"].includes(r.verdict),
    ),
    costs = groupedCosts(filteredRuns, "run"),
    sc = searches.filter((s: any) =>
      filteredRuns.some((r: any) => r.id === s.runId),
    ),
    searchCosts = groupedCosts(sc, "search"),
    measured = sc.filter((s: any) => s.duration != null);
  const options = (k: string) =>
    [
      ...new Set(
        runs.map((r: any) => (k === "tester" ? r.tester.id : String(r[k]))),
      ),
    ].sort() as string[];
  const filterbar = (
    <div className="filters wrap">
      {["tester", "build", "channel", "environment", "version"].map((k) => (
        <label key={k}>
          {k === "version" ? "Question version" : k}
          <select
            aria-label={k}
            value={filters[k] || ""}
            onChange={(e) => setFilters({ ...filters, [k]: e.target.value })}
          >
            <option value="">All</option>
            {(k === "version"
              ? [...new Set(runs.map((r: any) => String(r.questionVersion)))]
              : options(k)
            ).map((v: any) => (
              <option key={v} value={v}>
                {k === "tester"
                  ? runs.find((r: any) => r.tester.id === v)?.tester.name
                  : v}
              </option>
            ))}
          </select>
        </label>
      ))}
      <label>
        From
        <input
          type="date"
          value={filters.from || ""}
          onChange={(e) => setFilters({ ...filters, from: e.target.value })}
        />
      </label>
      <label>
        To
        <input
          type="date"
          value={filters.to || ""}
          onChange={(e) => setFilters({ ...filters, to: e.target.value })}
        />
      </label>
      <button onClick={() => setFilters({})}>Clear filters</button>
    </div>
  );
  function exportFile() {
    const result = {
      exportedAt: data!.serverTime,
      user,
      questions,
      documents,
      runs: filteredRuns,
      searches: sc,
      sessions,
      issues,
      comments,
      events,
    };
    const b = new Blob([JSON.stringify(result, null, 2)], {
        type: "application/json",
      }),
      url = URL.createObjectURL(b),
      a = document.createElement("a");
    a.href = url;
    a.download = "oi-test-results.json";
    a.click();
    URL.revokeObjectURL(url);
  }
  const tabs = [
    "My testing",
    ...(technical ? ["Dashboard"] : []),
    "Question bank",
    "Test runs",
    "Documents",
    "Technical fixes",
    ...(admin ? ["People"] : []),
    "Activity",
  ];
  const testList = questions.filter(
    (q: any) =>
      (!area || q.area === area) &&
      [
        q.id,
        q.title,
        q.prompt,
        q.references,
        ...linked(q).map((d: any) => d.code + " " + d.title),
      ]
        .join(" ")
        .toLowerCase()
        .includes(search.toLowerCase()),
  );
  const searchesFor = (r: any) => (
    <>
      <h3>Individual searches</h3>
      {searches
        .filter((s: any) => s.runId === r.id)
        .map((s: any) => (
          <div className="measurement" key={s.id}>
            <b>{s.label}</b>
            <p>
              Started {s.startedAt ? date(s.startedAt) : "Not recorded"} ·{" "}
              {s.duration ?? "Not recorded"} seconds ·{" "}
              {money(s.costAmount, s.currency)} · {s.basis}
            </p>
            <p>{s.sources}</p>
            <small>
              {s.measurementSource} · Recorded {date(s.created)}
            </small>
          </div>
        ))}
      <button
        onClick={() =>
          open({
            action: "search",
            runId: r.id,
            currency: "USD",
            basis: "Not specified",
          })
        }
      >
        Add search measurement
      </button>
    </>
  );
  return (
    <div className="shell">
      <aside>
        <a className="brand" href="/">
          OI<span>Workforce</span>
        </a>
        <div className="workspace">TEST CENTRE</div>
        <nav>
          {tabs.map((t) => (
            <button
              key={t}
              className={tab === t ? "selected" : ""}
              onClick={() => {
                setTab(t);
                setSearch("");
                setError("");
              }}
            >
              {t}
            </button>
          ))}
        </nav>
        <div className="asidefoot">
          <strong>One shared test bank</strong>
          <p>Test as many questions as needed.</p>
          <small>{user.role}</small>
        </div>
      </aside>
      <div className="content">
        <header>
          <span>Quality & performance</span>
          <div className="identity">
            <span>{user.name}</span>
            <button onClick={load}>Refresh</button>
            <button
              onClick={async () => {
                await fetch("/api/auth", {
                  method: "POST",
                  headers: { "Content-Type": "application/json" },
                  body: JSON.stringify({ action: "logout" }),
                });
                setData({ login: true });
              }}
            >
              Sign out
            </button>
          </div>
        </header>
        <main>
          <div className="pagehead">
            <div>
              <p className="eyebrow">OI WORKFORCE / EVALUATION</p>
              <h1>{tab}</h1>
              <p className="muted">
                Last updated {date(data.serverTime)} · Refreshes every 30
                seconds
              </p>
            </div>
            <div className="actions">
              <button onClick={exportFile}>Export records</button>
              {admin && (
                <button
                  className="primary"
                  onClick={() => open({ action: "question" })}
                >
                  Add question
                </button>
              )}
            </div>
          </div>
          {error && (
            <p role="alert" className="alert">
              {error}
            </p>
          )}
          {tab === "Dashboard" && (
            <>
              {filterbar}
              <div className="verdict-totals">
                {["Pass", "Blocked", "Fail"].map((v) => (
                  <article className={"verdict-total " + v} key={v}>
                    <span>{v === "Fail" ? "Failed" : v}</span>
                    <strong>
                      {filteredRuns.filter((r: any) => r.verdict === v).length}
                    </strong>
                    <small>attempts</small>
                  </article>
                ))}
              </div>
              <div className="stats">
                {[
                  [
                    new Set(filteredRuns.map((r: any) => r.questionId)).size +
                      " / " +
                      questions.length,
                    "Questions tested",
                  ],
                  [
                    new Set(filteredRuns.map((r: any) => r.tester.id)).size,
                    "Testers",
                  ],
                  [
                    decided.length
                      ? Math.round(
                          (decided.filter((r: any) => r.verdict === "Pass")
                            .length /
                            decided.length) *
                            100,
                        ) + "%"
                      : "—",
                    "Attempt pass rate",
                  ],
                  [
                    issues.filter(
                      (i: any) => !["Resolved", "Merged"].includes(i.status),
                    ).length,
                    "Open issues (all)",
                  ],
                ].map(([v, l]) => (
                  <article key={l}>
                    <span>{l}</span>
                    <strong>{v}</strong>
                  </article>
                ))}
              </div>
              <section className="panel">
                <h2>Which questions cause problems?</h2>
                <p className="muted">
                  Latest attempt per tester within these filters. Mixed versions
                  and conditions can affect comparisons; narrow the filters.
                  Pass rate excludes Blocked and N/A.
                </p>
                <div className="buildtable">
                  <table>
                    <thead>
                      <tr>
                        <th>Question</th>
                        <th>Attempts</th>
                        <th>Testers</th>
                        <th>Latest results</th>
                        <th>Changed reference</th>
                      </tr>
                    </thead>
                    <tbody>
                      {report.map((q) => (
                        <tr key={q.id}>
                          <td>
                            <button
                              onClick={() => {
                                setTab("Test runs");
                                setSearch(q.id + " ");
                              }}
                            >
                              {q.id} · {q.title}
                            </button>
                          </td>
                          <td>{q.attempts}</td>
                          <td>{q.testers}</td>
                          <td>
                            <span className="fail-text">
                              {q.failed} of {q.testers} failed
                            </span>{" "}
                            · {q.passed} passed · {q.blocked} blocked
                          </td>
                          <td>
                            {q.needsRetest ? "Review / retest needed" : "—"}
                          </td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              </section>
              <section className="panel spaced">
                <h2>Recorded costs and search time</h2>
                <p className="muted">
                  Blank is not zero. Attempt costs and individual search costs
                  are separate and may overlap; do not add these tables
                  together. Different currencies are never added together. Check
                  notes for excluded charges.
                </p>
                {[
                  ["Attempt costs", costs],
                  ["Search costs", searchCosts],
                ].map(([name, groups]: any) => (
                  <div key={name}>
                    <h3>{name}</h3>
                    <div className="buildtable">
                      <table>
                        <thead>
                          <tr>
                            <th>Currency</th>
                            <th>Cost type</th>
                            <th>Covers</th>
                            <th>Measured</th>
                            <th>Total</th>
                            <th>Average</th>
                          </tr>
                        </thead>
                        <tbody>
                          {groups.map((g: any, i: number) => (
                            <tr key={i}>
                              <td>{g.currency}</td>
                              <td>{g.basis}</td>
                              <td>{g.scope}</td>
                              <td>{g.count}</td>
                              <td>{g.total.toFixed(8)}</td>
                              <td>{g.average.toFixed(8)}</td>
                            </tr>
                          ))}
                        </tbody>
                      </table>
                    </div>
                  </div>
                ))}
                <p>
                  Average measured search time:{" "}
                  {measured.length
                    ? (
                        measured.reduce(
                          (n: number, s: any) => n + Number(s.duration),
                          0,
                        ) / measured.length
                      ).toFixed(2) +
                      " seconds (" +
                      measured.length +
                      " measured)"
                    : "Not recorded"}
                </p>
              </section>
              <section className="panel spaced">
                <h2>Team sessions</h2>
                {sessions.map((s: any) => (
                  <details className="run" key={s.id}>
                    <summary>
                      <b>
                        {s.tester_name} · {s.title}
                      </b>
                      {badge(s.status)}
                    </summary>
                    <p>
                      Started {date(s.started_at)} · Finished{" "}
                      {s.finished_at ? date(s.finished_at) : "Not finished"} ·
                      Last activity {date(s.last_activity_at)}
                    </p>
                    <p>
                      {runs.filter((r: any) => r.sessionId === s.id).length}{" "}
                      attempts ·{" "}
                      {
                        new Set(
                          runs
                            .filter((r: any) => r.sessionId === s.id)
                            .map((r: any) => r.questionId),
                        ).size
                      }{" "}
                      distinct questions
                    </p>
                    {(data.sessionEvents || [])
                      .filter((e: any) => e.session_id === s.id)
                      .map((e: any) => (
                        <small key={e.id}>
                          {e.action} · {date(e.created_at)}
                        </small>
                      ))}
                  </details>
                ))}
              </section>
            </>
          )}
          {["Question bank", "My testing"].includes(tab) && (
            <>
              <div className="filters">
                <input
                  aria-label="Search questions"
                  placeholder="Search question, document or test ID"
                  value={search}
                  onChange={(e) => setSearch(e.target.value)}
                />
                <select
                  aria-label="Area"
                  value={area}
                  onChange={(e) => setArea(e.target.value)}
                >
                  <option value="">All areas</option>
                  {[...new Set(questions.map((q: any) => q.area))].map(
                    (a: any) => (
                      <option key={a}>{a}</option>
                    ),
                  )}
                </select>
              </div>
              <section className="testing-context">
                <p>
                  <b>
                    Ask the question → upload a screenshot → choose the result →
                    save.
                  </b>
                </p>
                <div className="formrow">
                  <label>
                    OI you are testing
                    <input
                      value={context.oiName}
                      onChange={(e) =>
                        setContext({ ...context, oiName: e.target.value })
                      }
                    />
                  </label>
                  <label>
                    How are you testing?
                    <select
                      value={context.channel}
                      onChange={(e) =>
                        setContext({ ...context, channel: e.target.value })
                      }
                    >
                      <option>Voice</option>
                      <option>Chat</option>
                      <option>API</option>
                    </select>
                  </label>
                </div>
                <small>
                  Sessions and timestamps are automatic. Test any number of
                  questions.
                </small>
              </section>
              {testList.map((q: any) => {
                const latest = runs.find(
                  (r: any) => r.questionId === q.id && r.tester.id === user.id,
                );
                return (
                  <details
                    className="panel question"
                    key={q.id}
                    open={expanded.includes(q.id)}
                    onToggle={(e) => {
                      const isOpen = e.currentTarget.open;
                      setExpanded((old) =>
                        isOpen
                          ? [...new Set([...old, q.id])]
                          : old.filter((id) => id !== q.id),
                      );
                    }}
                  >
                    <summary>
                      <div>
                        <span className="testid">
                          {q.id} · v{q.version} · {q.priority || "Normal"}
                        </span>
                        <strong>{q.title}</strong>
                        <small>{q.area}</small>
                      </div>
                      {badge(latest?.verdict || "Not tested")}
                    </summary>
                    <div className="questionbody">
                      {ask(q)}
                      <div className="expected-brief">
                        <b>Expected result</b>
                        <p>{q.expected}</p>
                      </div>
                      {expanded.includes(q.id) && (
                        <InlineTest
                          key={
                            q.id +
                            "-" +
                            context.oiName +
                            "-" +
                            context.channel +
                            "-" +
                            (target?.questionId === q.id
                              ? target?.parent?.id || "new"
                              : "new")
                          }
                          q={q}
                          user={user}
                          documents={documents}
                          draft={drafts.find((d: any) => d.questionId === q.id)}
                          context={context}
                          send={send}
                          load={load}
                          parent={
                            target?.questionId === q.id
                              ? target?.parent
                              : undefined
                          }
                          issue={
                            target?.questionId === q.id
                              ? target?.issue
                              : undefined
                          }
                        />
                      )}
                      <button
                        className="spaced"
                        onClick={() => {
                          setTab("Test runs");
                          setSearch(q.id + " ");
                        }}
                      >
                        View saved results for this question
                      </button>
                      <details className="reference-details">
                        <summary>Test guidance and reference documents</summary>
                        {q.setup && (
                          <>
                            <h3>Before you test</h3>
                            <p>{q.setup}</p>
                          </>
                        )}
                        <p>{q.checklist}</p>
                        {doclinks(linked(q))}
                        {q.references && (
                          <p className="muted">{plain(q.references)}</p>
                        )}
                        {admin && (
                          <button
                            onClick={() => open({ ...q, action: "question" })}
                          >
                            Edit question
                          </button>
                        )}
                      </details>
                    </div>
                  </details>
                );
              })}
            </>
          )}
          {tab === "Test runs" && (
            <>
              {filterbar}
              <section className="panel">
                <input
                  aria-label="Search test results"
                  placeholder="Search test ID, person, OI or actual result"
                  value={search}
                  onChange={(e) => setSearch(e.target.value)}
                />
                {filteredRuns
                  .filter((r: any) =>
                    [
                      r.questionId,
                      r.question.title,
                      r.tester.name,
                      r.oiName,
                      r.actual,
                    ]
                      .join(" ")
                      .toLowerCase()
                      .includes(search.toLowerCase().trim()),
                  )
                  .map((r: any) => (
                    <details className="run" key={r.id}>
                      <summary>
                        <b>
                          {r.questionId} · {r.question.title}
                        </b>
                        {badge(r.verdict)}
                        <small>
                          {r.tester.name} · {date(r.created)}
                        </small>
                      </summary>
                      <p>
                        {r.oiName} · {r.channel} · {r.build} · {r.environment} ·
                        Question v{r.questionVersion}
                      </p>
                      <h3>Actual result</h3>
                      <p>{r.actual}</p>
                      <h3>Evidence</h3>
                      <p>
                        {r.evidence || "See attachments"}
                        {r.reason ? " · " + r.reason : ""}
                      </p>
                      <div className="attachments">
                        {(r.attachments || []).map((f: any) => (
                          <a
                            key={f.id}
                            href={"/api/files?id=" + f.id + "&view=1"}
                            target="_blank"
                            rel="noreferrer"
                          >
                            <img
                              src={"/api/files?id=" + f.id + "&view=1"}
                              alt={f.filename}
                            />
                            <span>{f.filename}</span>
                          </a>
                        ))}
                      </div>
                      <h3>Reference versions used</h3>
                      {doclinks(r.documentSnapshot || [])}
                      <p>
                        Elapsed: {r.duration ?? "Not recorded"} seconds ·
                        Sources: {r.sourceCount ?? "Not recorded"} · Input
                        tokens: {r.inputTokens ?? "Not recorded"} · Output
                        tokens: {r.outputTokens ?? "Not recorded"}
                      </p>
                      <p>{r.sourcesChecked}</p>
                      <p>
                        Attempt cost: {money(r.costAmount, r.costCurrency)} ·{" "}
                        {r.costBasis} · Covers {r.costScope} · {r.costNotes}
                      </p>
                      {r.previousRunId && <p>Retest of {r.previousRunId}</p>}
                      {searchesFor(r)}
                      <h3>Discussion</h3>
                      {comments
                        .filter((c: any) => c.runId === r.id)
                        .map((c: any) => (
                          <p key={c.id}>
                            <b>{c.author}</b> · {date(c.created)}
                            <br />
                            {c.body}
                          </p>
                        ))}
                      <div className="actions spaced">
                        <button
                          onClick={() =>
                            open({ action: "comment", runId: r.id })
                          }
                        >
                          Add note
                        </button>
                        <button
                          onClick={() =>
                            start(
                              questions.find((q: any) => q.id === r.questionId),
                              r,
                              issues.find((i: any) => i.id === r.issueId),
                            )
                          }
                        >
                          Record retest
                        </button>
                        {technical && (
                          <button
                            onClick={() =>
                              open({
                                action: "linkIssue",
                                runId: r.id,
                                questionId: r.questionId,
                              })
                            }
                          >
                            Link to shared issue
                          </button>
                        )}
                      </div>
                    </details>
                  ))}
                {!filteredRuns.length && <p>No results in these filters.</p>}
              </section>
            </>
          )}
          {tab === "Documents" && (
            <section className="panel">
              <div className="pagehead">
                <div>
                  <h2>Document register</h2>
                  <p className="muted">
                    Use actual document codes. Replace the existing record to
                    preserve question links and earlier versions. Uploading here
                    does not train the OI.
                  </p>
                </div>
                {admin && (
                  <button
                    className="primary"
                    onClick={() => open({ action: "document" })}
                  >
                    Upload document
                  </button>
                )}
              </div>
              {documents.map((d: any) => (
                <details className="run" key={d.id}>
                  <summary>
                    <b>
                      {d.code} · {d.title}
                    </b>
                    <span>v{d.version}</span>
                  </summary>
                  <p>
                    {d.filename} · Updated {date(d.updated)}
                  </p>
                  {link({ id: d.fileId, filename: "Download current version" })}
                  {admin && (
                    <button onClick={() => open({ ...d, action: "document" })}>
                      Replace or change code
                    </button>
                  )}
                  <h3>Earlier versions</h3>
                  {doclinks(d.history || [])}
                </details>
              ))}
              {!documents.length && (
                <p>
                  Upload 01 to 011, rules, quick answers and other references.
                  Then use Edit question to link them.
                </p>
              )}
            </section>
          )}
          {tab === "Technical fixes" && (
            <div className="issuelist">
              {issues.map((i: any) => (
                <section className="panel" key={i.id}>
                  <div className="issuetop">
                    <b>
                      {i.id} · {i.priority}
                    </b>
                    {badge(i.status)}
                  </div>
                  <h2>
                    {i.questionId} · {i.title}
                  </h2>
                  <p>
                    Owner: {i.owner || "Unassigned"} · {i.linkedRuns.length}{" "}
                    linked attempts
                  </p>
                  <p>{i.fix || "Investigation not recorded yet."}</p>
                  {i.fixBuild && <p>Fixed build: {i.fixBuild}</p>}
                  {i.mergedInto && <p>Consolidated into {i.mergedInto}</p>}
                  <div className="actions">
                    {technical && i.status !== "Merged" && (
                      <button onClick={() => open({ ...i, action: "issue" })}>
                        Update fix
                      </button>
                    )}
                    <button
                      onClick={() => {
                        setTab("Test runs");
                        setSearch(i.questionId + " ");
                      }}
                    >
                      View attempts
                    </button>
                    {technical && i.status !== "Merged" && (
                      <button
                        onClick={() =>
                          open({
                            action: "mergeIssue",
                            id: i.id,
                            questionId: i.questionId,
                          })
                        }
                      >
                        Consolidate duplicate
                      </button>
                    )}
                    {i.status === "Ready for retest" && (
                      <button
                        className="primary"
                        onClick={() =>
                          start(
                            questions.find((q: any) => q.id === i.questionId),
                            runs.find((r: any) => i.linkedRuns.includes(r.id)),
                            i,
                          )
                        }
                      >
                        Retest
                      </button>
                    )}
                  </div>
                </section>
              ))}
              {!issues.length && <p>No technical issues yet.</p>}
            </div>
          )}
          {tab === "People" && (
            <section className="panel">
              <h2>Allocate access</h2>
              <p>
                Users must change their temporary password on first sign-in.
                Share temporary passwords through your agreed secure channel;
                this app does not send emails.
              </p>
              <button
                className="primary"
                onClick={() => open({ action: "user" })}
              >
                Add user
              </button>
              {users.map((u: any) => (
                <div className="queue" key={u.id}>
                  <div>
                    <b>{u.name}</b>
                    <small>
                      {u.email} · {u.role} · {u.active ? "Active" : "Disabled"}
                    </small>
                  </div>
                  <button onClick={() => open({ ...u, action: "user" })}>
                    Manage
                  </button>
                </div>
              ))}
            </section>
          )}
          {tab === "Activity" && (
            <section className="panel">
              {events.map((e: any) => (
                <div className="recent" key={e.id}>
                  <div>
                    <b>{e.type}</b>
                    <p>{e.detail}</p>
                    <small>
                      {e.actor?.name || "System"} · {date(e.created)} ·{" "}
                      {e.target}
                    </small>
                  </div>
                </div>
              ))}
            </section>
          )}
        </main>
      </div>
      {modal && (
        <div className="overlay">
          <section
            role="dialog"
            aria-modal="true"
            aria-label="Record information"
            className="dialog"
          >
            <div className="dialoghead">
              <h2>
                {
                  (
                    {
                      run: "Record test",
                      session: "Start session",
                      question: "Question details",
                      document: "Upload document",
                      search: "Search measurement",
                      issue: "Technical update",
                      comment: "Add note",
                      user: "Allocate access",
                      linkIssue: "Link evidence to issue",
                      mergeIssue: "Consolidate duplicate issue",
                    } as R
                  )[modal.action]
                }
              </h2>
              <button
                type="button"
                disabled={busy}
                onClick={async () => {
                  if (draftTimer.current && formRef.current) {
                    clearTimeout(draftTimer.current);
                    if (modal.action === "run") {
                      const payload = { ...modal, ...values(formRef.current) };
                      await draftChain.current;
                      try {
                        await send({
                          action: "draft",
                          questionId: modal.questionId,
                          payload,
                          revision: draftRevision.current,
                        });
                      } catch (e: any) {
                        setError(e.message);
                        return;
                      }
                    }
                  }
                  setModal(null);
                  await load();
                }}
                aria-label="Close"
              >
                ✕
              </button>
            </div>
            <form
              ref={formRef}
              onSubmit={submit}
              onChange={(e) => captureDraft(e.currentTarget)}
            >
              {error && (
                <p role="alert" className="alert">
                  {error}
                </p>
              )}

              {modal.action === "question" && (
                <>
                  {field("Title", "title", modal.title, true)}
                  {field(
                    "Area",
                    "area",
                    modal.area || "Additional tests",
                    true,
                  )}
                  {field(
                    "Ask the OI",
                    "prompt",
                    modal.prompt,
                    true,
                    "textarea",
                  )}
                  {field(
                    "Before you test",
                    "setup",
                    modal.setup,
                    false,
                    "textarea",
                  )}
                  {field(
                    "Expected result",
                    "expected",
                    modal.expected,
                    true,
                    "textarea",
                  )}
                  {field(
                    "How to judge this test",
                    "checklist",
                    modal.checklist,
                    false,
                    "textarea",
                  )}
                  {select(
                    "Impact if it fails",
                    "priority",
                    ["Normal", "Critical", "High", "Low"],
                    modal.priority,
                  )}
                  <fieldset className="document-choices">
                    <legend>Link live document records</legend>
                    {documents.map((d: any) => (
                      <label key={d.id}>
                        <input
                          type="checkbox"
                          name="documentIds"
                          value={d.id}
                          defaultChecked={(modal.documentIds || []).includes(
                            d.id,
                          )}
                        />
                        {d.code} · {d.title} · v{d.version}
                      </label>
                    ))}
                  </fieldset>
                  {field(
                    "Section numbers or reference notes",
                    "references",
                    plain(modal.references),
                  )}
                </>
              )}
              {modal.action === "document" && (
                <>
                  {field("Actual document code", "code", modal.code, true)}
                  {field("Document title", "title", modal.title, true)}
                  <label>
                    File (PDF, DOCX, TXT or MD, up to 20 MB)
                    <input
                      name="file"
                      type="file"
                      accept=".pdf,.docx,.txt,.md"
                      required
                    />
                  </label>
                  <p>
                    Replace the same record to keep question links intact, even
                    if the code changes.
                  </p>
                </>
              )}
              {modal.action === "search" && (
                <>
                  {field("What was searched?", "label", "", true)}
                  {field("Sources checked", "sources", "", false, "textarea")}
                  {field(
                    "When the search started (your local time, optional)",
                    "startedAt",
                    "",
                    false,
                    "datetime-local",
                  )}
                  {field(
                    "Search duration in seconds",
                    "duration",
                    "",
                    false,
                    "number",
                  )}
                  {field(
                    "Search cost shown",
                    "costAmount",
                    "",
                    false,
                    "number",
                  )}
                  {select(
                    "Currency",
                    "currency",
                    ["USD", "GBP", "EUR", "GHS", "NGN", "INR"],
                    "USD",
                  )}
                  {select("Cost type", "basis", [
                    "Not specified",
                    "Displayed estimate",
                    "Actual billed",
                  ])}
                  {field("Notes or exclusions", "notes", "", false, "textarea")}
                  <p>
                    Recorded as manual evidence. Leave unavailable figures
                    blank.
                  </p>
                </>
              )}
              {modal.action === "issue" && (
                <>
                  {select(
                    "Status",
                    "status",
                    [
                      "Reported",
                      "Sent to technical",
                      "In progress",
                      "Ready for retest",
                    ],
                    modal.status === "Resolved" ? "In progress" : modal.status,
                  )}
                  {select(
                    "Impact",
                    "priority",
                    ["Normal", "Critical", "High", "Low"],
                    modal.priority,
                  )}
                  {field("Technical owner", "owner", modal.owner)}
                  {field(
                    "Investigation and fix",
                    "fix",
                    modal.fix,
                    false,
                    "textarea",
                  )}
                  {field(
                    "Build containing the fix",
                    "fixBuild",
                    modal.fixBuild,
                  )}
                  <p>
                    A passing linked retest is required to resolve this issue.
                  </p>
                </>
              )}
              {modal.action === "comment" &&
                field("Note or technical reply", "body", "", true, "textarea")}
              {modal.action === "mergeIssue" && (
                <>
                  <p>
                    Move linked evidence into the shared issue below. Original
                    results remain unchanged; this issue will be marked Merged.
                  </p>
                  <label>
                    Keep this shared issue
                    <select name="targetId" required>
                      {issues
                        .filter(
                          (i: any) =>
                            i.questionId === modal.questionId &&
                            i.id !== modal.id &&
                            i.status !== "Merged",
                        )
                        .map((i: any) => (
                          <option key={i.id} value={i.id}>
                            {i.id} · {i.status}
                          </option>
                        ))}
                    </select>
                  </label>
                </>
              )}
              {modal.action === "linkIssue" && (
                <label>
                  Shared issue
                  <select name="issueId" required>
                    {issues
                      .filter(
                        (i: any) =>
                          i.questionId === modal.questionId &&
                          i.status !== "Merged",
                      )
                      .map((i: any) => (
                        <option key={i.id} value={i.id}>
                          {i.id} · {i.title}
                        </option>
                      ))}
                  </select>
                </label>
              )}
              {modal.action === "user" && (
                <>
                  {field("Name", "name", modal.name, true)}
                  {field("Email", "email", modal.email, true, "email")}
                  {select(
                    "Role",
                    "role",
                    ["tester", "technical", "admin"],
                    modal.role || "tester",
                  )}
                  {field(
                    modal.id
                      ? "New temporary password (leave blank to retain)"
                      : "Temporary password (at least 12 characters)",
                    "password",
                    "",
                    !modal.id,
                    "password",
                  )}
                  {modal.id && (
                    <label>
                      Access
                      <select name="active" defaultValue={String(modal.active)}>
                        <option value="true">Active</option>
                        <option value="false">Disabled</option>
                      </select>
                    </label>
                  )}
                  <p>
                    Testers see their own sessions and attempts. Technical and
                    administrators see the consolidated results. Only
                    administrators manage users, questions and documents.
                  </p>
                </>
              )}
              <div className="actions">
                <button className="primary" disabled={busy}>
                  {busy ? "Saving…" : "Save"}
                </button>
              </div>
            </form>
          </section>
        </div>
      )}
    </div>
  );
}
