/* AMTS Streaming Tool — results screens */

const { useState: useStateR, useMemo: useMemoR } = React;
const DR = window.AMTS_DATA;

function classify(score) {
  return DR.classifyScore(score);
}

// Stream verdict block
function Verdict({ results }) {
  const air = results.streamScores.Air;
  const ground = results.streamScores.Ground;
  const recommended = air >= ground ? "Air" : "Ground";
  const tied = air === ground;
  return (
    <div className="verdict cornered">
      <span className="corner-tr" /><span className="corner-bl" />
      <div className="verdict-left">
        <div className="eyebrow">Stage 1 · Broad orientation</div>
        <h2>{recommended === "Air" ? "Air-oriented pathway" : "Ground-oriented pathway"}</h2>
        <p>
          Your current profile aligns most strongly with the {recommended.toLowerCase()} pathway. Both stream scores are shown — they are advisory and may shift with further evidence.{tied ? " Note: scores are tied; default has been applied." : ""}
        </p>
      </div>
      <div className="verdict-right">
        <div className="stream-dial">
          <div className={"stream-row" + (recommended === "Air" ? " recommended" : "")}>
            <span className={"label" + (recommended === "Air" ? " recommended" : "")}>Air</span>
            <div className="bar"><div className="fill" style={{ width: air + "%" }} /></div>
            <span className="v">{air}%</span>
          </div>
          <div className={"stream-row" + (recommended === "Ground" ? " recommended" : "")}>
            <span className={"label" + (recommended === "Ground" ? " recommended" : "")}>Ground</span>
            <div className="bar"><div className="fill" style={{ width: ground + "%" }} /></div>
            <span className="v">{ground}%</span>
          </div>
        </div>
      </div>
    </div>
  );
}

function RoleCard({ role, rank }) {
  const c = classify(role.score);
  return (
    <div className="role-card cornered">
      <span className="corner-tr" /><span className="corner-bl" />
      <div className="role-rank">Rank {String(rank).padStart(2, "0")}</div>
      <div className="role-card-head">
        <div className="role-id-row">
          <span className="id">{role.id}</span>
          <span>·</span>
          <span>{role.stream} stream</span>
        </div>
        <h3>{role.title}</h3>
        <div className="role-score-row">
          <span className="pct">{role.score}<span className="sym">%</span></span>
          {role.score !== role.baseScore && (
            <span className="delta">base {role.baseScore} · −{role.baseScore - role.score} cut-score</span>
          )}
        </div>
        <div className={"classify " + c.tone}>
          <span className="square" />
          {c.label}
        </div>
      </div>
      <div className="role-card-body">{role.advice}</div>
      <div className="role-card-foot">
        <span>Weights · P{role.weights.precision} S{role.weights.speed} A{role.weights.adaptability} I{role.weights.integration} Pl{role.weights.planning} T{role.weights.team}</span>
        <span>{role.minimumBreaches.length === 0 ? "Minimums met" : `${role.minimumBreaches.length} below cut`}</span>
      </div>
    </div>
  );
}

function SummaryTab({ results }) {
  const top = results.roleResults.slice(0, 3);
  const allLimited = top.every(r => r.score < 60);
  return (
    <div>
      <Verdict results={results} />
      {allLimited && (
        <div className="banner">
          <span className="label">Notice</span>
          <p>This profile does not currently align strongly with any of the assessed roles. Discuss with an instructor before drawing conclusions; results may reflect interpretation of the prompts rather than capability.</p>
        </div>
      )}
      <div className="roles-grid">
        {top.map((r, i) => <RoleCard key={r.id} role={r} rank={i + 1} />)}
      </div>
    </div>
  );
}

function ScoresTab({ results }) {
  const sorted = [...DR.dimensions].sort((a, b) => results.dimensionScores[b.key] - results.dimensionScores[a.key]);
  const top = sorted[0];
  return (
    <div>
      <div style={{ marginBottom: 18, display: "grid", gridTemplateColumns: "1fr auto", gap: 18, alignItems: "end" }}>
        <div>
          <div className="eyebrow" style={{ marginBottom: 6 }}>Dimension profile</div>
          <p className="muted" style={{ margin: 0, fontSize: 14, maxWidth: "62ch" }}>
            Scores are normalised against the maximum any single response could award to each dimension across the question bank. Dimensions are directly comparable to one another.
          </p>
        </div>
        <div className="panel-tag">Dominant · {top.short}</div>
      </div>
      <div className="scores-grid">
        {DR.dimensions.map(d => {
          const v = results.dimensionScores[d.key];
          return (
            <div className="score-row" key={d.key}>
              <div className="name">{d.label}<small>{d.key}</small></div>
              <div className="rule">
                <div className="scale">{Array.from({ length: 10 }).map((_, i) => <span key={i} />)}</div>
                <div className="fill" style={{ width: v + "%" }} />
              </div>
              <div className="v">{v}</div>
              <div className="meta">{v >= 70 ? "High" : v >= 50 ? "Mid" : "Low"} · /100</div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

function ReportTab({ results, trainee, allRoles }) {
  const top = results.roleResults.slice(0, 3);
  const sorted = [...DR.dimensions].sort((a, b) => results.dimensionScores[b.key] - results.dimensionScores[a.key]);
  const today = new Date().toLocaleDateString("en-AU", { day: "2-digit", month: "long", year: "numeric" });
  return (
    <div className="report cornered">
      <span className="corner-tr" /><span className="corner-bl" />
      <div className="report-head">
        <div>
          <div className="eyebrow" style={{ marginBottom: 6 }}>Form AMTS-SA-01 · Participant report</div>
          <h1>Streaming self-assessment — {trainee.name || "—"}</h1>
        </div>
        <div className="meta">
          <div>{trainee.serviceNumber || "Service no. —"}</div>
          <div>{trainee.cohort || "Cohort —"}</div>
          <div>{today}</div>
        </div>
      </div>

      <div className="report-section">
        <h2>Participant advice</h2>
        <p>
          Your strongest current alignment is <strong>{top[0].title}</strong> ({top[0].id}, {top[0].stream}), with secondary alignment to <strong>{top[1].title}</strong> and <strong>{top[2].title}</strong>. Your profile suggests the strongest evidence sits in <em>{sorted[0].label.toLowerCase()}</em>, supported by {sorted[1].label.toLowerCase()}.
        </p>
      </div>

      <div className="report-section">
        <h2>Recommended study and development</h2>
        <p>{top[0].study}</p>
      </div>

      <div className="report-section">
        <h2>Top three roles</h2>
        <table className="report-roles-table">
          <thead><tr><th>Rank</th><th>ID</th><th>Role</th><th>Stream</th><th>Classification</th><th style={{ textAlign: "right" }}>Score</th></tr></thead>
          <tbody>
            {top.map((r, i) => {
              const c = classify(r.score);
              return (
                <tr key={r.id}>
                  <td>{i + 1}</td>
                  <td className="id">{r.id}</td>
                  <td>{r.title}</td>
                  <td>{r.stream}</td>
                  <td>{c.label}</td>
                  <td className="score">{r.score}%</td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>

      <div className="report-section callout">
        <h2>Instructor review notes</h2>
        <p>
          This module uses self-report and situational-judgement signals only. Operational use must combine these results with foundational course performance, instructor observation, cognitive assessment and simulator-based evaluation before any streaming decision is confirmed. Re-assessment is permitted; results from a single sitting are not determinative.
        </p>
      </div>

      <div className="report-footer">
        Advisory self-assessment. Not a streaming decision. To be read alongside instructor observation, course performance and other assessment inputs. · AMTS-SA-01 · Optimised Human Performance.
      </div>
    </div>
  );
}

function InstructorPacket({ results, trainee, answers }) {
  // Detect "same letter every time"
  const letterCounts = {};
  Object.values(answers).forEach(v => { letterCounts[v] = (letterCounts[v] || 0) + 1; });
  const samePattern = Object.values(letterCounts).some(c => c === DR.questions.length);
  const top = results.roleResults.slice(0, 3);
  const allLimited = top.every(r => r.score < 60);
  return (
    <div className="report cornered" style={{ background: "var(--bg-sunken)" }}>
      <span className="corner-tr" /><span className="corner-bl" />
      <div className="report-head">
        <div>
          <div className="instructor-tag"><span className="square" /> Instructor packet · not for trainee</div>
          <h1 style={{ marginTop: 10 }}>Review note — {trainee.name || "—"}</h1>
        </div>
        <div className="meta">
          <div>{trainee.serviceNumber || "—"}</div>
          <div>{trainee.cohort || "—"}</div>
          <div>Form AMTS-SA-01-I</div>
        </div>
      </div>

      <div className="report-section">
        <h2>Profile summary</h2>
        <p>
          Air {results.streamScores.Air}% · Ground {results.streamScores.Ground}%. Top role: <strong>{top[0].title}</strong> ({top[0].id}) at {top[0].score}%. Second: {top[1].id} at {top[1].score}%. Third: {top[2].id} at {top[2].score}%.
        </p>
      </div>

      <div className="report-section">
        <h2>Flags for instructor attention</h2>
        <ul className="flag-list">
          {samePattern && <li><span className="marker">⚑</span><span>Response pattern suggests possible disengagement — every answer used the same option letter. Review with the trainee before relying on this result.</span></li>}
          {allLimited && <li><span className="marker">⚑</span><span>No top-three role exceeds 60%. Treat the profile as inconclusive; consider re-assessment after additional foundational exposure.</span></li>}
          {top[0].minimumBreaches.length > 0 && <li><span className="marker">⚑</span><span>Top role <strong>{top[0].id}</strong> falls below cut on: {top[0].minimumBreaches.map(([k]) => DR.dimensions.find(d => d.key === k).label).join(", ")}. Probe in interview.</span></li>}
          {!samePattern && !allLimited && top[0].minimumBreaches.length === 0 && <li><span className="marker">·</span><span>No automated flags raised. Continue with standard streaming conversation.</span></li>}
        </ul>
      </div>

      <div className="report-section">
        <h2>Conversation prompts</h2>
        <p style={{ fontSize: 14.5 }}>
          1. Where in the foundational module did the trainee show evidence consistent with the dominant dimension ({DR.dimensions.find(d => d.key === Object.entries(results.dimensionScores).sort((a, b) => b[1] - a[1])[0][0]).label.toLowerCase()})?<br />
          2. Has simulator or live observation contradicted the top role recommendation?<br />
          3. Is there a stream preference the trainee has not surfaced in the form?
        </p>
      </div>

      <div className="report-footer">
        Instructor-facing companion to the participant report. Combine with course-performance evidence, simulator data, interview notes and prior cohort observations before recording a streaming preference.
      </div>
    </div>
  );
}

function Results({ answers, results, trainee, onReset, onBack }) {
  const [tab, setTab] = useStateR("summary");
  const [showInstructor, setShowInstructor] = useStateR(false);

  function exportTxt() {
    const top = results.roleResults.slice(0, 3);
    const lines = [
      "AMTS Streaming Self-Assessment — Participant Report",
      `Trainee: ${trainee.name || "—"}    Service no.: ${trainee.serviceNumber || "—"}    Cohort: ${trainee.cohort || "—"}`,
      `Date: ${new Date().toLocaleDateString("en-AU")}`,
      "",
      `Stage 1 orientation: Air ${results.streamScores.Air}% / Ground ${results.streamScores.Ground}%`,
      "",
      "Top role matches:",
      ...top.map((r, i) => `  ${i + 1}. ${r.title} (${r.id}, ${r.stream}) — ${r.score}% [${classify(r.score).label}]`),
      "",
      "Dimension scores:",
      ...DR.dimensions.map(d => `  ${d.label}: ${results.dimensionScores[d.key]}%`),
      "",
      "Participant advice:",
      `  ${top[0].advice}`,
      "",
      "Recommended development:",
      `  ${top[0].study}`,
      "",
      "Instructor review note:",
      "  This module uses self-report/SJT signals only. Operational use must combine these results with foundational course performance, instructor observation, cognitive assessment and simulator-based evaluation before any streaming decision is confirmed.",
      "",
      "Advisory self-assessment. Not a streaming decision."
    ].join("\n");
    const blob = new Blob([lines], { type: "text/plain" });
    const url = URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.href = url;
    a.download = `AMTS_${(trainee.serviceNumber || "report").replace(/\s/g, "_")}.txt`;
    a.click();
    URL.revokeObjectURL(url);
  }

  return (
    <section>
      <div className="topnav">
        <span className="label">§ 03 · Report</span>
        <div className="actions">
          <button className="btn-ghost btn" onClick={onBack}>← Review answers</button>
          <button className="btn-ghost btn" onClick={onReset}>↺ Reset</button>
          <button className="btn" onClick={exportTxt}>↓ Export .txt</button>
          <button className="btn" onClick={() => window.print()}>↓ Save as PDF</button>
        </div>
      </div>

      <div style={{ marginTop: 18, border: "1px solid var(--rule)", background: "var(--bg-card)" }}>
        <div className="results-tabs">
          <button className={"results-tab" + (tab === "summary" ? " active" : "")} onClick={() => setTab("summary")}>Summary</button>
          <button className={"results-tab" + (tab === "scores" ? " active" : "")} onClick={() => setTab("scores")}>Dimension scores</button>
          <button className={"results-tab" + (tab === "report" ? " active" : "")} onClick={() => setTab("report")}>Participant report</button>
        </div>
        <div className="results-body">
          {tab === "summary" && <SummaryTab results={results} />}
          {tab === "scores" && <ScoresTab results={results} />}
          {tab === "report" && <ReportTab results={results} trainee={trainee} allRoles={DR.roles} />}
        </div>
      </div>

      <div className="instructor-toggle">
        <div className="desc">
          <strong>Instructor packet.</strong> A companion review note for the streaming officer — flags, prompts and the same scores in a different framing. Hidden from the trainee in operational deployment.
        </div>
        <button className="btn-ghost btn" onClick={() => setShowInstructor(s => !s)}>
          {showInstructor ? "Hide instructor view" : "Show instructor view"}
        </button>
      </div>

      {showInstructor && (
        <div style={{ marginTop: 18 }}>
          <InstructorPacket results={results} trainee={trainee} answers={answers} />
        </div>
      )}
    </section>
  );
}

window.AMTSResults = { Results };
