/* ENSSA Reporting — Student page (Level 4). */

/* global React, Card, Eyebrow, Section, Btn, PrintPDFButton,
   RiskBadge, MoreInfoFlag, StatusBadge, ScreeningDisclaimer, TermSelector,
   PopulationPositionBar, TaskPercentileBar,
   RISK, RISK_COPY, TASKS, TASK_DEFS, TEACHING_NOTE, TERMS, TERM_DEFAULT,
   getBattery */

/* ── Print-only masthead ── */
function PrintHeader({ school, klass, student }) {
  return (
    <div className="print-header" style={{
      display: 'none', // hidden on screen; shown via @media print
      justifyContent: 'space-between', alignItems: 'flex-start',
      borderBottom: '2px solid #322B44', paddingBottom: 12, marginBottom: 20,
    }}>
      <div>
        <div style={{ fontSize: 10, fontWeight: 700, letterSpacing: '0.08em', textTransform: 'uppercase', color: '#6F6783' }}>
          ENSSA Screening Report · {school.name} · {klass.year === 'F' ? 'Foundation' : 'Year 1'} {klass.name}
        </div>
        <div style={{ fontSize: 22, fontWeight: 900, marginTop: 4, color: '#1B1729' }}>{student.name}</div>
      </div>
      <div style={{ textAlign: 'right', fontSize: 10, color: '#6F6783' }}>
        <div style={{ fontWeight: 700 }}>ENSSA Reporting Portal</div>
        <div>Printed {new Date().toLocaleDateString('en-AU', { day: 'numeric', month: 'long', year: 'numeric' })}</div>
      </div>
    </div>
  );
}

const { useState: useSS, useMemo: useSM } = React;

/* Deterministic raw-score + duration from percentile + seed */
function rawDetails(studentId, taskId, percentile) {
  let h = 0;
  for (let i = 0; i < studentId.length + taskId.length; i++) {
    h = ((h << 5) - h) + (studentId + taskId).charCodeAt(i % (studentId.length + taskId.length));
    h |= 0;
  }
  const jitter = ((h >>> 0) % 9) - 4;           // -4 to +4
  const maxScore = 20;
  const rawScore = Math.max(0, Math.min(maxScore, Math.round(percentile / 100 * maxScore) + jitter));
  // Duration: lower percentile → longer; add noise
  const jitter2 = ((h >>> 4) % 60) - 30;        // ±30 s
  const duration = Math.max(30, Math.round(300 - percentile * 1.8 + jitter2));
  const mins = Math.floor(duration / 60);
  const secs = duration % 60;
  return { rawScore, maxScore, duration: `${mins}:${secs.toString().padStart(2,'0')}` };
}

/* Rank a student within a group, returning a percentile 0-100 */
function pctileInGroup(student, students) {
  const valid = students.filter(s => s.risk !== 'more_info');
  if (valid.length < 2) return student.overallPercentile;
  const sorted = [...valid].sort((a, b) => a.indexScore - b.indexScore);
  const rank = sorted.findIndex(s => s.id === student.id);
  if (rank === -1) return student.overallPercentile;
  return Math.round((rank / (sorted.length - 1)) * 100);
}

function StudentPage({ school, klass, student, term: initialTerm }) {
  const idx = student.indexScore;
  const ivLow = student.indexInterval[0], ivHigh = student.indexInterval[1];
  const isMoreInfo = student.risk === 'more_info';
  const copy = RISK_COPY[student.risk];
  const [term, setTerm] = useSS(initialTerm || TERM_DEFAULT);
  const [compareScope, setCompareScope] = useSS('population');

  // Compute percentile for the selected comparison scope
  const comparePercentile = useSM(() => {
    if (compareScope === 'class') return pctileInGroup(student, klass.students);
    if (compareScope === 'school') {
      const allSchool = school.classes.flatMap(c => c.students);
      return pctileInGroup(student, allSchool);
    }
    return student.overallPercentile; // population (pre-computed)
  }, [compareScope, student, klass, school]);

  const compareScopeLabel = compareScope === 'class' ? `${klass.name}` : compareScope === 'school' ? school.name : 'national population';

  return (
    <>
      <PrintHeader school={school} klass={klass} student={student} />

      {/* ── Student header ── */}
      <Card style={{ marginBottom: 20 }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 24, flexWrap: 'wrap' }}>
          <div style={{ flex: 1, minWidth: 200 }}>
            <h2 style={{ fontSize: 30, fontWeight: 900, margin: '0 0 8px', letterSpacing: '-0.01em' }}>{student.name}</h2>
            <div style={{ display: 'flex', gap: 8, alignItems: 'center', flexWrap: 'wrap' }}>
              <StatusBadge status={student.status} />
              <span style={{ color: 'var(--fg-3)', fontSize: 12 }}>·</span>
              <span style={{ fontSize: 13, color: 'var(--fg-2)', fontFamily: 'var(--font-mono)' }}>{student.tasksDone}/{student.tasksTotal} tasks completed</span>
              {isMoreInfo && <MoreInfoFlag />}
            </div>
          </div>
          {/* Term selector */}
          <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-end', gap: 6 }}>
            <Eyebrow>Screening period</Eyebrow>
            <TermSelector value={term} onChange={setTerm} />
          </div>
        </div>
      </Card>

      {/* ── Score + Risk band card ── */}
      <Card style={{ marginBottom: 20 }}>
        <div style={{ display: 'flex', gap: 32, flexWrap: 'wrap', alignItems: 'flex-start' }}>
          {/* Score */}
          <div style={{ flexShrink: 0 }}>
            <Eyebrow>Score</Eyebrow>
            <div style={{ fontSize: 56, fontWeight: 900, lineHeight: 1, letterSpacing: '-0.02em', fontFamily: 'var(--font-mono)', color: isMoreInfo ? 'var(--fg-3)' : 'var(--fg-1)', margin: '8px 0 4px' }}>
              {isMoreInfo ? '—' : idx}
            </div>
            {!isMoreInfo && (
              <div style={{ fontSize: 13, color: 'var(--fg-3)', fontFamily: 'var(--font-mono)' }}>likely range {ivLow}–{ivHigh}</div>
            )}
          </div>
          {/* Divider */}
          <div style={{ width: 1, background: 'var(--border-subtle)', alignSelf: 'stretch', flexShrink: 0 }} />
          {/* Risk band */}
          <div style={{ flexShrink: 0 }}>
            <Eyebrow>Risk band</Eyebrow>
            <div style={{ margin: '10px 0 4px' }}>
              <RiskBadge level={student.risk} />
            </div>
            <div style={{ fontSize: 13, color: 'var(--fg-2)', lineHeight: 1.5, marginTop: 6, maxWidth: 220 }}>
              {copy.headline}
            </div>
          </div>
        </div>
      </Card>

      {/* ── Summary card (own card below score/risk) ── */}
      <Card style={{ marginBottom: 20 }}>
        <Eyebrow>Summary</Eyebrow>
        <p style={{ fontSize: 14, color: 'var(--fg-1)', lineHeight: 1.65, margin: '8px 0 0' }}>
          {interpretation(student.risk, student.name)} {copy.detail} Pair this signal with classroom evidence and teacher judgement.
        </p>
      </Card>

      {/* ── Percentile position with comparison toggle ── */}
      {!isMoreInfo && (
        <Card style={{ marginBottom: 20 }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 16, marginBottom: 16, flexWrap: 'wrap' }}>
            <div>
              <Eyebrow>Position</Eyebrow>
              <div style={{ fontSize: 28, fontWeight: 900, fontFamily: 'var(--font-mono)', marginTop: 4 }}>P{comparePercentile}</div>
              <div style={{ fontSize: 12, color: 'var(--fg-3)', marginTop: 2 }}>within {compareScopeLabel}</div>
            </div>
            <div style={{ display: 'inline-flex', background: 'var(--ink-50)', borderRadius: 8, padding: 2, border: '1px solid var(--border-subtle)', alignSelf: 'flex-start' }}>
              {[['class','Class'],['school','School'],['population','Population']].map(([id, lbl]) => (
                <button key={id} onClick={() => setCompareScope(id)}
                  style={{ border: 0, background: compareScope === id ? '#fff' : 'transparent', boxShadow: compareScope === id ? 'var(--sh-1)' : 'none', padding: '6px 14px', fontSize: 13, fontWeight: 600, color: compareScope === id ? 'var(--fg-1)' : 'var(--fg-3)', borderRadius: 6, cursor: 'pointer', fontFamily: 'inherit', whiteSpace: 'nowrap' }}
                >{lbl}</button>
              ))}
            </div>
          </div>
          <PopulationPositionBar
            percentile={comparePercentile}
            intervalLow={compareScope === 'population' ? ivLow : null}
            intervalHigh={compareScope === 'population' ? ivHigh : null}
          />
        </Card>
      )}

      {/* ── Task profile (eyebrow removed per design) ── */}
      <Section title="Results by task">
        <Card style={{ padding: 0 }}>
          <TaskPerfTable student={student} klass={klass} term={term} />
        </Card>
      </Section>

      {/* ── Raw assessment details ── */}
      <Section>
        <RawAssessmentDetails student={student} klass={klass} term={term} />
      </Section>

      {/* ── Disclaimer ── */}
      <Section>
        <ScreeningDisclaimer>
          The Score is a single-number summary derived from this student's task results. Use it as a screening signal, not a diagnostic. Pair it with the task profile above and your own classroom observation when planning support.
        </ScreeningDisclaimer>
      </Section>
    </>
  );
}

function interpretation(risk, name) {
  const first = name.split(' ')[0];
  if (risk === 'high')     return `${first}'s screening result places them in the high-risk band — they may benefit from targeted support.`;
  if (risk === 'moderate') return `${first}'s screening result places them in the moderate-risk band — worth monitoring closely.`;
  if (risk === 'low')      return `${first}'s screening result is in the low-risk band for this point in the year.`;
  return `${first} has incomplete tasks — confirm completion before drawing conclusions.`;
}

function teachingNoteFor(percentile, isComplete) {
  if (!isComplete) return TEACHING_NOTE.insufficient;
  if (percentile < 15) return TEACHING_NOTE.priority;
  if (percentile < 30) return TEACHING_NOTE.needs;
  if (percentile < 45) return TEACHING_NOTE.monitor;
  return TEACHING_NOTE.none;
}

function TaskPerfTable({ student, klass, term }) {
  const battery = getBattery(student.year, student.cohort || klass?.cohort || 'A', term || TERM_DEFAULT);
  const isComplete = student.tasksDone === student.tasksTotal;
  return (
    <div style={{ overflowX: 'auto' }}>
      <table style={{ width: '100%', borderCollapse: 'collapse', minWidth: 560 }}>
        <thead style={{ background: 'var(--ink-50)' }}>
          <tr>
            {['Task', 'Completed', 'Percentile', 'Teaching note'].map((h, i) => (
              <th key={h} style={{ textAlign: i === 1 ? 'center' : 'left', padding: '14px 18px', fontSize: 11, textTransform: 'uppercase', letterSpacing: '0.08em', color: 'var(--fg-3)', fontWeight: 700, borderBottom: '1px solid var(--border-subtle)' }}>{h}</th>
            ))}
          </tr>
        </thead>
        <tbody>
          {battery.map(t => {
            const p = student.tp[t.id];
            const note = teachingNoteFor(p, isComplete);
            return (
              <tr key={t.id} style={{ borderBottom: '1px solid var(--border-subtle)' }}>
                <td style={{ padding: '16px 18px', fontWeight: 600, width: 180 }}>{t.label}</td>
                <td style={{ padding: '16px 18px', textAlign: 'center', color: isComplete ? 'var(--risk-on-track)' : 'var(--fg-3)', fontSize: 16 }}>{isComplete ? '✓' : '—'}</td>
                <td style={{ padding: '16px 18px' }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
                    <span style={{ fontFamily: 'var(--font-mono)', fontWeight: 700, fontSize: 14, width: 36, color: p < 20 ? 'var(--risk-concern-fg)' : 'var(--fg-1)' }}>P{p}</span>
                    <div style={{ flex: 1, maxWidth: 260 }}><TaskPercentileBar value={p} /></div>
                  </div>
                </td>
                <td style={{ padding: '16px 18px' }}>
                  {note.id !== 'none' && (
                    <span style={{
                      display: 'inline-block', fontSize: 12, fontWeight: 700, padding: '3px 10px', borderRadius: 999,
                      background: note.tone === 'concern' ? 'var(--risk-concern-bg)' : note.tone === 'emerging' ? 'var(--risk-emerging-bg)' : 'var(--ink-100)',
                      color: note.tone === 'concern' ? 'var(--risk-concern-fg)' : note.tone === 'emerging' ? 'var(--risk-emerging-fg)' : 'var(--fg-3)',
                      border: `1px solid ${note.tone === 'concern' ? 'var(--risk-concern)' : note.tone === 'emerging' ? 'var(--risk-emerging)' : 'var(--ink-300)'}`,
                    }}>{note.label}</span>
                  )}
                </td>
              </tr>
            );
          })}
        </tbody>
      </table>
    </div>
  );
}

function RawAssessmentDetails({ student, klass, term }) {
  const [open, setOpen] = useSS(false);
  const battery = getBattery(student.year, student.cohort || klass?.cohort || 'A', term || TERM_DEFAULT);
  return (
    <Card>
      <button onClick={() => setOpen(!open)} style={{ width: '100%', display: 'flex', justifyContent: 'space-between', alignItems: 'center', background: 'none', border: 0, padding: 0, cursor: 'pointer', fontFamily: 'inherit', textAlign: 'left' }}>
        <div>
          <Eyebrow>Raw assessment details</Eyebrow>
          <h3 style={{ fontSize: 16, fontWeight: 700, margin: '4px 0 0' }}>For audit and reference</h3>
        </div>
        <span style={{ fontSize: 22, color: 'var(--fg-3)' }}>{open ? '−' : '+'}</span>
      </button>
      {open && (
        <div style={{ marginTop: 18, overflowX: 'auto' }}>
          <table style={{ width: '100%', borderCollapse: 'collapse', minWidth: 420 }}>
            <thead>
              <tr>
                {['Task', 'Raw score', 'Duration'].map(h => (
                  <th key={h} style={{ textAlign: 'left', padding: '10px 14px', fontSize: 11, textTransform: 'uppercase', letterSpacing: '0.08em', color: 'var(--fg-3)', fontWeight: 700, borderBottom: '1px solid var(--border-subtle)', background: 'var(--ink-50)' }}>{h}</th>
                ))}
              </tr>
            </thead>
            <tbody>
              {battery.map(t => {
                const { rawScore, maxScore, duration } = rawDetails(student.id, t.id, student.tp[t.id]);
                return (
                  <tr key={t.id} style={{ borderBottom: '1px solid var(--border-subtle)' }}>
                    <td style={{ padding: '12px 14px', fontWeight: 600, fontSize: 14 }}>{t.label}</td>
                    <td style={{ padding: '12px 14px', fontFamily: 'var(--font-mono)', fontSize: 13 }}>{rawScore} / {maxScore}</td>
                    <td style={{ padding: '12px 14px', fontFamily: 'var(--font-mono)', fontSize: 13, color: 'var(--fg-2)' }}>{duration}</td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
      )}
    </Card>
  );
}

window.StudentPage = StudentPage;
