// Report.jsx · the diagnostic report tab with three dashboard variations.
// A: Overview · B: Next steps · C: Print Summary

const { useState: useReportState, useMemo } = React;

const SCHOOL = {
  name: 'Greenfield Preparatory',
  class: 'Grade 7A',
  learners: 28,
  date: '14 August 2026',
  facilitator: 'T. Brown, Reflective',
  region: 'Cape Town',
};

// ---------- Shared bits ----------
function ConceptBar({ concept, height = 18 }) {
  return (
    <span className="pb-concept-track" style={{ height }}>
      {concept.segs.map((v, j) => (
        <span key={j} className={`pb-bar-seg ${BAND_KEYS[j]}`} style={{ width: `${v}%` }} title={`${BAND_LABELS[j]}: ${v}%`}/>
      ))}
    </span>
  );
}

function ConceptChart({ concepts, compact = false }) {
  return (
    <div className="pb-concept-chart">
      <div className="pb-concept-axis" style={{ marginBottom: 4, marginTop: 0 }}>
        <span></span>
        <span className="pb-concept-axis-ticks">
          {['0%','20%','40%','60%','80%','100%'].map(t => <span key={t}>{t}</span>)}
        </span>
        <span></span>
      </div>
      {concepts.map(c => (
        <div className="pb-concept-row" key={c.id}>
          <span className="pb-concept-label">{c.label}</span>
          <ConceptBar concept={c} height={compact ? 14 : 18}/>
          <span className="pb-concept-score">{c.segs[2] + c.segs[3]}%</span>
        </div>
      ))}
    </div>
  );
}

function Legend() {
  return (
    <div className="pb-legend">
      {BAND_LABELS.map((l, i) => (
        <span className="pb-legend-item" key={l}>
          <span className="pb-legend-swatch" style={{ background: BAND_COLORS[i] }}></span>
          {l}
        </span>
      ))}
      <span className="pb-legend-item" style={{ marginLeft: 'auto', fontStyle: 'italic', opacity: 0.7 }}>
        % of class at each level
      </span>
    </div>
  );
}

function LearnerTable({ roster, limit = 10 }) {
  const sorted = useMemo(() => roster.slice().sort((a,b) => a.avg - b.avg), [roster]);
  const shown = sorted.slice(0, limit);
  return (
    <div className="pb-table-wrap">
      <table className="pb-table">
        <thead>
          <tr>
            <th>Learner</th>
            <th>Functioning at</th>
            <th>Concepts secured</th>
            <th>Support level</th>
          </tr>
        </thead>
        <tbody>
          {shown.map((l, i) => {
            const pillClass = l.avg < 0.8 ? 'pb-pill-below' : l.avg < 1.5 ? 'pb-pill-low' : l.avg < 2.3 ? 'pb-pill-near' : 'pb-pill-at';
            const priorityClass = l.avg < 0.8 ? 'pb-pill-below' : l.avg < 1.5 ? 'pb-pill-low' : 'pb-pill-near';
            const priorityLabel = l.avg < 0.8 ? 'Focused support' : l.avg < 1.5 ? 'Targeted work' : 'On track';
            return (
              <tr key={i}>
                <td>{l.name}</td>
                <td><span className={`pb-pill ${pillClass}`}>{l.gradeLevel}</span></td>
                <td>
                  <span className="pb-mini-bar"><span style={{ width: `${(l.masteredCount / FRACTION_CONCEPTS.length) * 100}%` }}/></span>
                  <span style={{ fontVariantNumeric: 'tabular-nums', fontWeight: 500 }}>{l.masteredCount} / {FRACTION_CONCEPTS.length}</span>
                </td>
                <td><span className={`pb-pill ${priorityClass}`}>{priorityLabel}</span></td>
              </tr>
            );
          })}
        </tbody>
      </table>
    </div>
  );
}

function InsightCards() {
  const k = computeKpis();
  const cards = [
    { tone: 'priority-high', tag: 'Concept to focus on',
      title: `${k.weakest.label}. ${k.weakest.segs[0] + k.weakest.segs[1]}% of class still building this.`,
      body: 'This is the foundation for proportional reasoning in Grade 8. A 3-week focused block before introducing ratio will set the class up well.' },
    { tone: 'priority-watch', tag: 'Watch closely',
      title: 'Equivalence across fractions, decimals and percentages.',
      body: 'Your class is confident on each representation individually. The next step is switching fluently between them, with cross-representation tasks.' },
    { tone: 'priority-strong', tag: 'Strength to build from',
      title: `${k.strongest.label}. ${k.strongest.segs[2] + k.strongest.segs[3]}% at grade level.`,
      body: 'Strong procedural fluency here. Use it as the scaffold for the developing concepts. Confidence carries across.' },
  ];
  return (
    <div className="pb-insights-grid">
      {cards.map((c, i) => (
        <div className={`pb-insight ${c.tone}`} key={i}>
          <span className="pb-insight-tag">{c.tag}</span>
          <h4>{c.title}</h4>
          <p>{c.body}</p>
        </div>
      ))}
    </div>
  );
}

function ReportHead({ variant }) {
  const tone = variant === 'C' ? 'white' : 'violet';
  return (
    <div className="pb-report-head">
      <div className="pb-report-school" style={{ display: 'flex', flexDirection: 'row', alignItems: 'center', gap: 18 }}>
        <ProjectBaselineMark size={56} tone={tone}/>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
          <span className="pb-fine">Diagnostic report · Phase 1, Term 2 2026</span>
          <h1>{SCHOOL.name}. {SCHOOL.class}.</h1>
          <span className="pb-fine">{SCHOOL.learners} learners assessed · 30-minute fractions diagnostic</span>
        </div>
      </div>
      <div className="pb-report-meta">
        <span>Assessment date <strong>{SCHOOL.date}</strong></span>
        <span>Facilitator <strong>{SCHOOL.facilitator}</strong></span>
        <span>Region <strong>{SCHOOL.region}</strong></span>
      </div>
    </div>
  );
}

function NumeratePlug({ variant }) {
  return (
    <div className="pb-numerate-plug">
      <div>
        <span style={{ fontSize: 11, fontWeight: 600, letterSpacing: '0.06em', textTransform: 'uppercase', color: 'rgba(255,255,255,0.7)' }}>The follow-through</span>
        <h3 style={{ marginTop: 8 }}>Keep tracking these learners. Every week. Automatically.</h3>
        <p>
          Numerate is the adaptive maths platform that picks up exactly where this diagnostic ends. Learners practise on the specific concepts identified in your report, teachers see live progress, and the system adjusts to each child as they go.
        </p>
        <div style={{ display: 'flex', gap: 16, flexWrap: 'wrap', fontSize: 13.5, color: 'rgba(255,255,255,0.86)', marginBottom: 18 }}>
          <span>✓ 30-day free trial included</span>
          <span>✓ Used in 240+ South African classrooms</span>
          <span>✓ CAPS-aligned, Grade 1 to 9</span>
        </div>
        <a className="pb-btn pb-btn-on-dark" href="https://reflective.global/sa/numerate-for-schools/" target="_blank" rel="noreferrer">
          Start your 30-day trial →
        </a>
      </div>
      <div style={{ textAlign: 'center' }}>
        <img src={(window.__resources && window.__resources.numerateWhite) || 'assets/numerate-white.png'} alt="Numerate" style={{ maxWidth: 220 }}/>
      </div>
    </div>
  );
}

// ============================================================================
// VARIANT A · Overview (light executive summary)
// ============================================================================
function ReportVariantA({ roster }) {
  const k = computeKpis();
  return (
    <div className="pb-report-page variant-a" data-screen-label="Report · Overview">
      <ReportHead variant="A"/>
      <div className="pb-kpi-grid">
        <div className="pb-kpi accent-violet">
          <span className="pb-kpi-label">Class fractions readiness</span>
          <span className="pb-kpi-value">{k.classAvg}<span className="unit">%</span></span>
          <span className="pb-kpi-trend">at or near Grade 7 mastery</span>
        </div>
        <div className="pb-kpi accent-amber">
          <span className="pb-kpi-label">Learners to support closely</span>
          <span className="pb-kpi-value">8<span className="unit"> / 28</span></span>
          <span className="pb-kpi-trend">would benefit from focused work before Gr 8</span>
        </div>
        <div className="pb-kpi accent-green">
          <span className="pb-kpi-label">Strength to build from</span>
          <span className="pb-kpi-value" style={{ fontSize: 20, lineHeight: 1.2 }}>{k.strongest.short}</span>
          <span className="pb-kpi-trend">{k.strongest.segs[2]+k.strongest.segs[3]}% at grade level</span>
        </div>
        <div className="pb-kpi accent-violet-soft">
          <span className="pb-kpi-label">Concept to focus on</span>
          <span className="pb-kpi-value" style={{ fontSize: 20, lineHeight: 1.2 }}>{k.weakest.short}</span>
          <span className="pb-kpi-trend">{k.weakest.segs[0]+k.weakest.segs[1]}% still building this</span>
        </div>
      </div>

      <div className="pb-report-section">
        <div className="pb-report-section-head">
          <div>
            <h2>Concept-level mastery across the Grade 7 fractions progression</h2>
            <p>Each row shows the proportion of the class at each level. The right column shows the share at or above Grade 6.</p>
          </div>
        </div>
        <Legend/>
        <ConceptChart concepts={FRACTION_CONCEPTS}/>
      </div>

      <div className="pb-report-section">
        <div className="pb-report-section-head">
          <div>
            <h2>What this report tells us</h2>
            <p>Three observations from this assessment, with what comes next.</p>
          </div>
        </div>
        <InsightCards/>
      </div>

      <div className="pb-report-section">
        <div className="pb-report-section-head">
          <div>
            <h2>Learners who would benefit from focused support</h2>
            <p>Sorted by overall functioning. The 10 learners we recommend prioritising in the next term.</p>
          </div>
          <span className="pb-fine">Full 28-learner table available in your downloadable PDF.</span>
        </div>
        <LearnerTable roster={roster}/>
      </div>

      <NumeratePlug/>
    </div>
  );
}

// ============================================================================
// VARIANT B · Next steps (action-led, warm beige, grouped concept families)
// ============================================================================
function ReportVariantB({ roster }) {
  const k = computeKpis();
  const grouped = useMemo(() => ({
    'Fractions. Recognising and comparing.':    FRACTION_CONCEPTS.filter(c => ['cmp-frac', 'eq-prop', 'eq-mixed'].includes(c.id)),
    'Decimals and their relatives.':            FRACTION_CONCEPTS.filter(c => ['rnd-dec','cmp-dec','eq-fdp'].includes(c.id)),
    'Operations on fractions and decimals.':    FRACTION_CONCEPTS.filter(c => ['add-dec','sub-dec','add-frac','sub-frac'].includes(c.id)),
    'Applying it in context.':                  FRACTION_CONCEPTS.filter(c => ['int-frac','int-pct','int-ratio'].includes(c.id)),
  }), []);

  const nextSteps = [
    { tone: 'priority-high', tag: 'In the next 3 weeks', title: 'Run a focused ratio and proportion block.', body: 'Start with concrete representations (bar models, double number lines) before moving into ratio notation. Suggested 6 short lessons, 20 minutes each. Materials supplied.' },
    { tone: 'priority-watch', tag: 'Over the term', title: 'Cross-representation practice on fractions, decimals and percentages.', body: 'Build a 10-minute starter into each lesson where learners convert fluently between the three. Especially helpful for the 11 learners flagged at Grade 3 to 5.' },
    { tone: 'priority-strong', tag: 'In Term 3', title: 'Leverage decimal fluency to scaffold the harder concepts.', body: 'Your class has strong procedural confidence with adding and subtracting decimals. Use that as the scaffold when introducing fraction operations and equivalence.' },
  ];

  return (
    <div className="pb-report-page variant-b" data-screen-label="Report · Next steps">
      <ReportHead variant="B"/>

      <div style={{ display: 'grid', gridTemplateColumns: '1.4fr 1fr', gap: 20, marginBottom: 24 }}>
        <div className="pb-report-section-card" style={{ display: 'flex', flexDirection: 'column', justifyContent: 'space-between' }}>
          <div>
            <span className="pb-eyebrow">The headline</span>
            <h2 style={{ fontSize: 26, fontWeight: 600, lineHeight: 1.2, margin: '12px 0 14px', letterSpacing: '-0.018em', color: 'var(--graphite-950, #1c1b2f)' }}>
              <span style={{ color: 'var(--insight-violet, #7C3AED)' }}>{k.classAvg}% of {SCHOOL.class}</span> is on track for Grade 8 fractions. <span style={{ color: '#B07515' }}>{k.atRisk}%</span> would benefit from focused work before then.
            </h2>
            <p className="pb-body-tight">
              Your class is fluent on procedural decimal work (adding, rounding) but a third is still building the conceptual side. Equivalence, ratio and using percentages in context are the priority areas.
            </p>
          </div>
          <div style={{ display: 'flex', gap: 12, marginTop: 18 }}>
            <div style={{ flex: 1, padding: 14, background: 'var(--pb-beige)', borderRadius: 10 }}>
              <div style={{ fontSize: 11, fontWeight: 600, letterSpacing: '0.06em', textTransform: 'uppercase', color: 'var(--text-tertiary, #475467)' }}>Class average</div>
              <div style={{ fontSize: 22, fontWeight: 700, color: 'var(--graphite-950, #1c1b2f)', marginTop: 2 }}>Grade 5.8</div>
            </div>
            <div style={{ flex: 1, padding: 14, background: 'var(--pb-beige)', borderRadius: 10 }}>
              <div style={{ fontSize: 11, fontWeight: 600, letterSpacing: '0.06em', textTransform: 'uppercase', color: 'var(--text-tertiary, #475467)' }}>Range</div>
              <div style={{ fontSize: 22, fontWeight: 700, color: 'var(--graphite-950, #1c1b2f)', marginTop: 2 }}>Gr 2 to Gr 7+</div>
            </div>
          </div>
        </div>

        <div className="pb-report-section-card">
          <span className="pb-eyebrow">Distribution</span>
          <h3 style={{ fontSize: 16, fontWeight: 600, margin: '12px 0 18px', color: 'var(--graphite-950, #1c1b2f)' }}>Where are your 28 learners sitting overall?</h3>
          {[
            { l: 'Ready for Gr 8',    count: 4,  band: 'at' },
            { l: 'Securing Gr 6 to 7', count: 9,  band: 'near' },
            { l: 'Developing Gr 3 to 5', count: 11, band: 'low' },
            { l: 'Building below Gr 3', count: 4,  band: 'below' },
          ].map((r, i) => (
            <div key={i} style={{ display: 'grid', gridTemplateColumns: '140px 1fr 32px', gap: 10, alignItems: 'center', padding: '6px 0' }}>
              <span style={{ fontSize: 13, color: 'var(--text-secondary, #344054)' }}>{r.l}</span>
              <span className="pb-bar-track" style={{ height: 16 }}>
                <span className={`pb-bar-seg ${r.band}`} style={{ width: `${(r.count/28)*100}%` }}/>
              </span>
              <span style={{ fontSize: 13, fontWeight: 600, textAlign: 'right', fontVariantNumeric: 'tabular-nums' }}>{r.count}</span>
            </div>
          ))}
        </div>
      </div>

      <div className="pb-report-section">
        <div className="pb-report-section-head">
          <div>
            <h2>Three next steps for your maths team</h2>
            <p>Drawn directly from this class's pattern. Materials supplied with the report.</p>
          </div>
        </div>
        <div className="pb-insights-grid">
          {nextSteps.map((c, i) => (
            <div className={`pb-insight ${c.tone}`} key={i} style={{ background: '#fff' }}>
              <span className="pb-insight-tag">{c.tag}</span>
              <h4>{c.title}</h4>
              <p>{c.body}</p>
            </div>
          ))}
        </div>
      </div>

      <div className="pb-report-section">
        <Legend/>
        {Object.entries(grouped).map(([title, concepts], i) => (
          <div key={i} className="pb-report-section-card" style={{ marginBottom: 16 }}>
            <div className="pb-report-section-head" style={{ marginBottom: 14 }}>
              <h2 style={{ fontSize: 17 }}>{title}</h2>
              <span style={{ fontSize: 12, color: 'var(--text-tertiary, #475467)' }}>
                Class average: <strong>{Math.round(concepts.reduce((a,c) => a + c.segs[2]+c.segs[3], 0) / concepts.length)}%</strong> at grade level
              </span>
            </div>
            <ConceptChart concepts={concepts} compact/>
          </div>
        ))}
      </div>

      <NumeratePlug/>
    </div>
  );
}

// ============================================================================
// VARIANT C · Print Summary (dense, dark-ink, print-first)
// ============================================================================
function ReportVariantC({ roster }) {
  const k = computeKpis();
  return (
    <div className="pb-report-page variant-c" data-screen-label="Report · Print summary">
      <ReportHead variant="C"/>

      <div className="pb-kpi-grid">
        <div className="pb-kpi">
          <span className="pb-kpi-label">Class readiness</span>
          <span className="pb-kpi-value">{k.classAvg}<span className="unit">%</span></span>
          <span className="pb-kpi-trend">on track for Grade 8</span>
        </div>
        <div className="pb-kpi">
          <span className="pb-kpi-label">Targeted support</span>
          <span className="pb-kpi-value" style={{ color: '#E8A53E' }}>8<span className="unit"> / 28</span></span>
          <span className="pb-kpi-trend">would benefit from focused work</span>
        </div>
        <div className="pb-kpi">
          <span className="pb-kpi-label">Range</span>
          <span className="pb-kpi-value" style={{ fontSize: 22 }}>Gr 2 to Gr 7+</span>
          <span className="pb-kpi-trend">5 grade-level spread</span>
        </div>
        <div className="pb-kpi">
          <span className="pb-kpi-label">Class average</span>
          <span className="pb-kpi-value" style={{ fontSize: 22 }}>Grade 5.8</span>
          <span className="pb-kpi-trend">1.2 grades below CAPS</span>
        </div>
      </div>

      <div className="pb-report-section">
        <div className="pb-report-section-head">
          <div>
            <h2>Mastery on numbers conceptual landmarks</h2>
            <p>The fractions progression. Where your class sits today.</p>
          </div>
        </div>
        <Legend/>
        <ConceptChart concepts={FRACTION_CONCEPTS}/>
      </div>

      <div className="pb-report-section">
        <div className="pb-report-section-head">
          <div>
            <h2>Learner × concept heatmap</h2>
            <p>Each cell shows that learner's level on that concept. Sorted by overall functioning, lowest first.</p>
          </div>
        </div>
        <div style={{ background: 'rgba(255,255,255,0.03)', borderRadius: 12, padding: '14px 14px 18px', overflowX: 'auto' }}>
          <div className="pb-heatmap" style={{ gridTemplateColumns: `170px repeat(${FRACTION_CONCEPTS.length}, minmax(28px, 1fr))` }}>
            <div className="h-corner"></div>
            {FRACTION_CONCEPTS.map(c => (
              <div className="h-col" key={c.id} style={{ color: 'rgba(255,255,255,0.6)' }}>{c.short}</div>
            ))}
            {roster.slice().sort((a,b) => a.avg - b.avg).slice(0, 14).map((l, i) => (
              <React.Fragment key={i}>
                <div className="h-row-label" style={{ color: 'rgba(255,255,255,0.88)' }}>{l.name}</div>
                {l.lvls.map((lv, j) => (
                  <div key={j} className={`h-cell lvl-${lv}`} title={`${FRACTION_CONCEPTS[j].short}: ${BAND_LABELS[lv]}`}/>
                ))}
              </React.Fragment>
            ))}
          </div>
        </div>
        <p className="pb-fine" style={{ color: 'rgba(255,255,255,0.5)', marginTop: 12 }}>
          Showing 14 of 28 learners. Full roster available in your downloadable PDF.
        </p>
      </div>

      <div className="pb-report-section">
        <div className="pb-report-section-head">
          <div>
            <h2>Recommended next steps</h2>
          </div>
        </div>
        <InsightCards/>
      </div>

      <NumeratePlug/>
    </div>
  );
}

// ============================================================================
// Top-level Report tab with variant switcher
// ============================================================================
function ReportTab() {
  const [variant, setVariant] = useReportState('A');
  const roster = useMemo(() => generateRoster(), []);
  const variants = [
    { id: 'A', name: 'Overview',      sub: 'A clean one-page summary for leadership' },
    { id: 'B', name: 'Next steps',    sub: 'Action-led layout for your maths team' },
    { id: 'C', name: 'Print Summary', sub: 'Dense single-PDF view, optimised for printing' },
  ];

  return (
    <div data-screen-label="Inside the report">
      <section className="pb-section-tight" style={{ background: 'var(--pb-beige)', borderBottom: '1px solid rgba(28,27,47,0.06)' }}>
        <div className="pb-container">
          <div className="pb-section-head" style={{ marginBottom: 24, maxWidth: 760 }}>
            <span className="pb-eyebrow">Inside the report</span>
            <h2 className="pb-display-lg" style={{ marginTop: 12 }}>What your school receives, one week after the assessment.</h2>
            <p className="pb-lead" style={{ marginTop: 14 }}>
              A complete diagnostic. Class overview, concept-level mastery, individual learner profiles, and concrete next steps. Three layouts are available below. Pick whichever suits how your team reads.
            </p>
          </div>
          <div className="pb-report-toolbar">
            <div className="pb-variant-tabs" role="tablist">
              {variants.map(v => (
                <button key={v.id} className={`pb-variant-tab ${variant === v.id ? 'is-active' : ''}`}
                  onClick={() => setVariant(v.id)} role="tab">
                  <span style={{ display: 'inline-block', marginRight: 6, opacity: 0.6, fontWeight: 600 }}>{v.id}.</span>
                  {v.name}
                </button>
              ))}
            </div>
            <span className="pb-fine">{variants.find(v => v.id === variant).sub}</span>
          </div>
        </div>
      </section>

      <section className="pb-section-tight" style={{ background: 'var(--pb-beige)' }}>
        <div className="pb-container">
          <div className="pb-report-canvas">
            {variant === 'A' && <ReportVariantA roster={roster}/>}
            {variant === 'B' && <ReportVariantB roster={roster}/>}
            {variant === 'C' && <ReportVariantC roster={roster}/>}
          </div>
          <p className="pb-fine" style={{ marginTop: 16, textAlign: 'center' }}>
            All data shown is illustrative. Your school's report will contain only your learners' data.
          </p>
        </div>
      </section>
    </div>
  );
}

Object.assign(window, { ReportTab });
