// SAT Results Report - live data overlay
// Replaces the mock report-data.jsx from the design bundle. Fetches the real
// report from GET /api/local/exam/report/:attemptId and sets the globals
// report-app.jsx / report-charts.jsx read (REPORT, TESTS, EXAM, TARGET_SCORE),
// plus the presentational constants the mock used to define (SECTIONS,
// DIFF_LABEL, DIFF_ORDER). Grep-confirmed: of these three, only DIFF_LABEL is
// actually read by the ported components (report-charts.jsx ModuleGrid /
// TimeModule tooltips); SECTIONS and DIFF_ORDER are carried over per the port
// brief even though nothing currently references them, in case a future
// component pulls them in.

// Presentational constants (not data) -- copied from the mock report-data.jsx.
const SECTIONS = {
  rw: { name: "Reading & Writing", abbr: "R&W", color: "#5C7E3F" },
  math: { name: "Math", abbr: "Math", color: "#2E6B8A" },
};
const DIFF_LABEL = { E: "Easy", M: "Medium", H: "Hard" };
const DIFF_ORDER = ["E", "M", "H"];

// Loader the mount script awaits before rendering <ReportApp/>.
window.__loadReport = async function () {
  const params = new URLSearchParams(location.search);
  const attemptId = params.get('attempt') || 'guest';

  let payload;
  if (params.get('demo') === '1' || attemptId === 'sample') {
    // Public sample: render the REAL report against a bundled sample payload so the
    // marketing "sample report" is always the current report shape. No auth, no API.
    const res = await fetch('/data/sample-report.json');
    if (!res.ok) throw new Error('Failed to load sample report (' + res.status + ')');
    payload = await res.json();
  } else {
    // Same auth mechanism fetchAttemptResults uses in public/js/local-client.js:
    // Authorization: Bearer <lws_local_token> + credentials:'include' for the
    // httpOnly session cookie. This covers both the guest token and a real
    // logged-in student session; the server route (examAuthAllowGuest) tries
    // the cookie first, then falls back to the Bearer header.
    const res = await fetch('/api/local/exam/report/' + encodeURIComponent(attemptId), {
      credentials: 'include',
      headers: { 'Authorization': 'Bearer ' + (localStorage.getItem('lws_local_token') || '') }
    });
    if (!res.ok) throw new Error('Failed to load report (' + res.status + ')');
    payload = await res.json();
  }

  // payload.rw / payload.math already match the sec.* shape the components read.
  window.REPORT = payload;
  window.TARGET_SCORE = payload.targetScore || 1500;

  // Trajectory (report-charts.jsx Trajectory) needs low/high/q1/q3 per test point
  // for the box-and-whisker plot. The live payload only carries { label, date,
  // med, kind } today (no per-attempt score bands yet), so default all four to
  // med until that data is populated server-side -- this collapses each box to
  // a single median line rather than a true whisker range.
  window.TESTS = (payload.tests || []).map(t => Object.assign({}, t, {
    low: t.low != null ? t.low : t.med,
    high: t.high != null ? t.high : t.med,
    q1: t.q1 != null ? t.q1 : t.med,
    q3: t.q3 != null ? t.q3 : t.med
  }));

  // EXAM header fields, derived the same way the mock derived them.
  const e = payload.exam || {};
  const typeSeq = `${e.typeCode || 'PE'}${String(e.examNum || 1).padStart(2, '0')}`;
  window.EXAM = Object.assign({}, e, {
    typeSeq,
    sessionLabel: `${e.type === 'diagnostic' ? 'Diagnostic' : 'Practice'} Test ${e.examNum || 1}`,
    id: e.id || `${e.examCode || 'CSAT'}-${typeSeq}-${e.dateCode || '000000'}-${e.serial || '000000'}`
  });
};
