/* AMTS Streaming Tool — components */

const { useState, useEffect, useMemo, useRef } = React;
const D = window.AMTS_DATA;

// ============== utility components ==============

function Crumb({ active, children }) {
  return (
    <span className={"crumb" + (active ? " active" : "")}>
      <span className="dot" /> {children}
    </span>
  );
}

function Masthead({ trainee, phase }) {
  const today = new Date().toLocaleDateString("en-AU", { day: "2-digit", month: "short", year: "numeric" });
  return (
    <header>
      <div className="masthead">
        <div className="crest" aria-label="Optimised Human Performance" />
        <div className="masthead-meta">
          <div className="masthead-eyebrow">AMTS · Self-Assessment Module 1.0</div>
          <h1 className="masthead-title">Role Streaming Self-Assessment</h1>
          <div className="masthead-sub">Two-stage profile across six performance dimensions and nine specialist roles.</div>
        </div>
        <div className="masthead-right">
          <div>
            <span className="stamp">Advisory</span>
            <span className="stamp">Self-report</span>
          </div>
          <div className="masthead-issued">Issued {today} · Form AMTS-SA-01</div>
        </div>
      </div>
      <div className="section-bar">
        <Crumb active={phase === "intro"}>01 / Brief</Crumb>
        <span style={{ color: "var(--ink-4)" }}>—</span>
        <Crumb active={phase === "flow"}>02 / Assessment</Crumb>
        <span style={{ color: "var(--ink-4)" }}>—</span>
        <Crumb active={phase === "results"}>03 / Report</Crumb>
        <span style={{ marginLeft: "auto", color: "var(--ink-4)" }}>
          {trainee.name ? `${trainee.name} · ${trainee.serviceNumber || "—"}` : "Unidentified trainee"}
        </span>
      </div>
    </header>
  );
}

// ============== Intro ==============

function Intro({ trainee, setTrainee, onStart }) {
  return (
    <section className="intro-grid cornered">
      <span className="corner-tr" /><span className="corner-bl" />
      <div className="intro-left">
        <div className="intro-doc-id">§ 01  ·  Purpose &amp; framing</div>
        <h2 className="intro-h1">A structured signal — not a streaming decision.</h2>
        <p className="intro-lede">
          This module converts your responses into a profile across six performance dimensions, a broad Air or Ground orientation, and a ranked view of suitability across nine specialist roles. It runs for about ten minutes.
        </p>

        <div className="outline">
          <div className="outline-row"><span className="num">i.</span><span>Brief and identification</span><span className="duration">~1 min</span></div>
          <div className="outline-row"><span className="num">ii.</span><span>Stage 1 — Broad orientation (Q1–Q4)</span><span className="duration">~3 min</span></div>
          <div className="outline-row"><span className="num">iii.</span><span>Stage 2 — Role optimisation (Q5–Q10)</span><span className="duration">~5 min</span></div>
          <div className="outline-row"><span className="num">iv.</span><span>Profile, role rankings and instructor note</span><span className="duration">~1 min</span></div>
        </div>

        <div className="intro-pillars">
          <div className="intro-pillar">
            <div className="num">01</div>
            <h4>Transparent</h4>
            <p>You see exactly which dimensions drove each role result.</p>
          </div>
          <div className="intro-pillar">
            <div className="num">02</div>
            <h4>Advisory</h4>
            <p>One input among several. Streaming requires instructor input.</p>
          </div>
          <div className="intro-pillar">
            <div className="num">03</div>
            <h4>Private</h4>
            <p>Runs entirely in this browser. No external network calls.</p>
          </div>
        </div>
      </div>

      <div className="intro-right">
        <div className="intro-meta-row">
          <h3>Trainee identification</h3>
          <p className="muted" style={{ margin: 0, fontSize: 13 }}>
            Captured on the report cover sheet. Leave blank if completing anonymously and your instructor will fill in.
          </p>
        </div>

        <div className="field-grid" style={{ marginTop: 18 }}>
          <div className="field" style={{ gridColumn: "1 / -1" }}>
            <label>Full name</label>
            <input value={trainee.name} onChange={(e) => setTrainee({ ...trainee, name: e.target.value })} placeholder="Surname, Given names" />
          </div>
          <div className="field">
            <label>Service number</label>
            <input value={trainee.serviceNumber} onChange={(e) => setTrainee({ ...trainee, serviceNumber: e.target.value })} placeholder="A1234567" />
          </div>
          <div className="field">
            <label>Cohort</label>
            <input value={trainee.cohort} onChange={(e) => setTrainee({ ...trainee, cohort: e.target.value })} placeholder="AMTS / 2026-01" />
          </div>
          <div className="field" style={{ gridColumn: "1 / -1" }}>
            <label>Foundational module</label>
            <select value={trainee.module} onChange={(e) => setTrainee({ ...trainee, module: e.target.value })}>
              <option>Module 1 — Foundational Air Operations</option>
              <option>Module 1 — Re-take</option>
              <option>Module 2 — Familiarisation</option>
            </select>
          </div>
        </div>

        <div className="intro-warn">
          <span className="label">Notice</span>
          Results are <strong>self-report</strong> and may move with mood, fatigue or interpretation. They must be combined with foundational course performance, instructor observation and simulator-based assessment before any streaming decision is taken.
        </div>

        <div className="intro-actions">
          <button className="btn" onClick={onStart}>Begin assessment <span className="arrow">→</span></button>
          <span className="muted" style={{ fontSize: 12.5 }}>10 questions · approx. 10 minutes</span>
        </div>
      </div>
    </section>
  );
}

// ============== Question flow ==============

function QuestionMeter({ current, answers, onJump }) {
  return (
    <div className="q-meter" role="progressbar" aria-valuemin={0} aria-valuemax={D.questions.length} aria-valuenow={Object.keys(answers).length}>
      {D.questions.map((q, i) => {
        const answered = answers[q.id] !== undefined;
        const cls = (answered ? "answered " : "") + (i === current ? "current" : "");
        return (
          <button key={q.id} className={"tick " + cls} onClick={() => onJump(i)} aria-label={`Question ${i + 1}${answered ? " — answered" : ""}`}>
            {String(i + 1).padStart(2, "0")}
          </button>
        );
      })}
    </div>
  );
}

function QuestionCard({ index, answers, setAnswers, onPrev, onNext, onSubmit, complete, total, jumpTo }) {
  const q = D.questions[index];
  const selected = answers[q.id];
  const isLast = index === total - 1;
  function pick(i) { setAnswers({ ...answers, [q.id]: i }); }
  return (
    <article className="q-card cornered">
      <span className="corner-tr" /><span className="corner-bl" />
      <QuestionMeter current={index} answers={answers} onJump={jumpTo} />
      <header className="q-head">
        <div className="q-stage">
          <span><span className="id">Q{String(q.id).padStart(2, "0")}</span> &nbsp;·&nbsp; {q.section}</span>
          <span>4 mutually exclusive options</span>
        </div>
        <h2 className="q-prompt">{q.prompt}</h2>
      </header>
      <div className="q-options" role="radiogroup">
        {q.options.map((o, i) => (
          <button
            key={i}
            role="radio"
            aria-checked={selected === i}
            className={"q-option" + (selected === i ? " selected" : "")}
            onClick={() => pick(i)}
          >
            <span className="letter">{String.fromCharCode(65 + i)}</span>
            <span>{o.text}</span>
            <span className="check">{selected === i ? "✓ selected" : ""}</span>
          </button>
        ))}
      </div>
      <footer className="q-foot">
        <button className="btn-link" onClick={onPrev} disabled={index === 0}>← Back</button>
        <span className="pageno">{String(index + 1).padStart(2, "0")} / {String(total).padStart(2, "0")}</span>
        {isLast ? (
          <button className="btn" onClick={onSubmit} disabled={!complete}>Generate report <span className="arrow">→</span></button>
        ) : (
          <button className="btn" onClick={onNext} disabled={selected === undefined}>Next question <span className="arrow">→</span></button>
        )}
      </footer>
    </article>
  );
}

function LiveRanking({ results, answeredCount }) {
  const top = results.roleResults.slice(0, 6);
  return (
    <div className="live-panel cornered">
      <span className="corner-tr" /><span className="corner-bl" />
      <header className="live-head">
        <h3>Live role ranking</h3>
        <span className="answered">{answeredCount}/{D.questions.length} answered</span>
      </header>
      <div className="live-rows">
        {top.map((r, i) => {
          const breach = r.minimumBreaches.length > 0;
          return (
            <div key={r.id} className={"live-row" + (breach ? " flagged" : "")}>
              <span className="rank">{String(i + 1).padStart(2, "0")}</span>
              <span className="roleid">{r.id}</span>
              <span className="roletitle">
                <span className={"stream-dot " + (r.stream === "Air" ? "air" : "ground")} />
                {r.title}
              </span>
              <span className="pct">{r.score}%</span>
              <div className="live-bar"><div className="fill" style={{ width: r.score + "%" }} /></div>
              {breach && (
                <div className="cut-flag">
                  ⚑ Cut-score watch · {r.minimumBreaches.map(([k]) => D.dimensions.find(d => d.key === k).short).join(", ")}
                </div>
              )}
            </div>
          );
        })}
      </div>
    </div>
  );
}

function DimensionMini({ results }) {
  return (
    <div className="dim-mini cornered">
      <span className="corner-tr" /><span className="corner-bl" />
      <h3>Dimension running totals</h3>
      {D.dimensions.map(d => (
        <div className="row" key={d.key}>
          <span>{d.label}</span>
          <span className="v">{results.dimensionScores[d.key]}</span>
        </div>
      ))}
    </div>
  );
}

function Flow({ answers, setAnswers, onSubmit, onBack }) {
  const [index, setIndex] = useState(0);
  const complete = Object.keys(answers).length === D.questions.length;
  const results = useMemo(() => D.calculateResults(answers), [answers]);
  return (
    <section>
      <div className="topnav">
        <span className="label">§ 02 · Assessment</span>
        <div className="actions">
          <button className="btn-ghost btn" onClick={onBack}>← Return to brief</button>
        </div>
      </div>
      <div className="flow" style={{ marginTop: 18 }}>
        <QuestionCard
          index={index}
          answers={answers}
          setAnswers={setAnswers}
          onPrev={() => setIndex(i => Math.max(0, i - 1))}
          onNext={() => setIndex(i => Math.min(D.questions.length - 1, i + 1))}
          onSubmit={onSubmit}
          complete={complete}
          total={D.questions.length}
          jumpTo={(i) => setIndex(i)}
        />
        <aside className="aside">
          <div className="aside-note">
            <strong>Heads up.</strong> Rankings update live so you can see how your responses move the picture. Scores will keep moving until you complete all ten questions. Treat the running view as orientation only.
          </div>
          <LiveRanking results={results} answeredCount={Object.keys(answers).length} />
          <DimensionMini results={results} />
        </aside>
      </div>
    </section>
  );
}

window.AMTSComponents = { Masthead, Intro, Flow };
