/* ENSSA Reporting — Portal Home (Level 0). System-level cross-district view. */

/* global React, Card, Eyebrow, KPI, Section, Btn, CSVExportButton, RiskBreakdownStackedBar,
   RiskTransitionSankey, TaskBoxPlotPanel, ScreeningDisclaimer,
   RISK, RISK_ORDER, DISTRICTS, allStudents, riskCountsOf, taskBoxStats, sankeyTransitions */

function PortalHome({ onOpenDistrict }) {
  const allDistrictsNode = { schools: DISTRICTS.flatMap(d => d.schools) };
  const totalSchools = DISTRICTS.reduce((a,d) => a + d.schools.length, 0);
  const totalStudents = allStudents(allDistrictsNode).length;
  const breakF = riskCountsOf(allDistrictsNode, 'F');
  const breakY1 = riskCountsOf(allDistrictsNode, 'Y1');
  const all = riskCountsOf(allDistrictsNode);
  const transitions = getMultiStageTransitions(allDistrictsNode);
  const stats = taskBoxStats(allDistrictsNode);

  return (
    <>
      <div style={{ marginBottom: 24 }}><ScreeningDisclaimer /></div>

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(200px, 1fr))', gap: 18, marginBottom: 32 }}>
        <KPI label="Districts reporting" value={DISTRICTS.length} />
        <KPI label="Schools" value={totalSchools} sub="reporting this term" />
        <KPI label="Students screened" value={totalStudents} sub="Foundation + Year 1" />
        <KPI label="High-risk band" value={all.high} accent="var(--risk-concern-fg)" sub={`${Math.round(all.high/totalStudents*100)}% of cohort`} />
      </div>

      <Section eyebrow="Population breakdown" title="Risk bands by year level"
        hint="Stacked bars show the proportion of students in each band, by year level, for the selected term.">
        <Card>
          <div style={{ display: 'grid', gridTemplateColumns: '120px 1fr', gap: 18, alignItems: 'center', marginBottom: 18 }}>
            <div style={{ fontWeight: 700, fontSize: 14 }}>Foundation</div>
            <RiskBreakdownStackedBar counts={breakF} showLabels />
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: '120px 1fr', gap: 18, alignItems: 'center' }}>
            <div style={{ fontWeight: 700, fontSize: 14 }}>Year 1</div>
            <RiskBreakdownStackedBar counts={breakY1} showLabels />
          </div>
        </Card>
      </Section>

      <Section eyebrow="Movement" title="Risk-band movement across terms"
        hint="Ribbons show how students moved between bands across screening windows. Hover a ribbon to focus it."
        controls={<Btn variant="ghost">Compare windows</Btn>}>
        <Card><RiskTransitionSankey transitions={transitions} /></Card>
      </Section>

      <Section eyebrow="Task profile" title="Where the cohort is strong and weak"
        hint="Each row is the percentile distribution across all students for one task. Lower medians indicate a system-wide gap.">
        <Card><TaskBoxPlotPanel stats={stats} /></Card>
      </Section>

      <Section eyebrow="Districts" title="Drill into a region"
        controls={<CSVExportButton scope="districts" />}>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(380px, 1fr))', gap: 18 }}>
          {DISTRICTS.map(d => {
            const dn = { schools: d.schools };
            const counts = riskCountsOf(dn);
            return (
              <Card key={d.id} style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 12 }}>
                  <div>
                    <Eyebrow>District</Eyebrow>
                    <h3 style={{ fontSize: 18, fontWeight: 700, margin: '4px 0 0' }}>{d.name}</h3>
                    <div style={{ fontSize: 13, color: 'var(--fg-3)', marginTop: 4 }}>
                      {d.schools.length} schools · {counts.total} students
                    </div>
                  </div>
                  <Btn variant="ghost" onClick={() => onOpenDistrict(d.id)}>Open →</Btn>
                </div>
                <RiskBreakdownStackedBar counts={counts} showLegend={false} />
                <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 12, color: 'var(--fg-3)', flexWrap: 'wrap', gap: 8 }}>
                  <span><strong style={{ color: 'var(--risk-on-track-fg)', fontFamily: 'var(--font-mono)' }}>{counts.low}</strong> low</span>
                  <span><strong style={{ color: 'var(--risk-emerging-fg)', fontFamily: 'var(--font-mono)' }}>{counts.moderate}</strong> moderate</span>
                  <span><strong style={{ color: 'var(--risk-concern-fg)', fontFamily: 'var(--font-mono)' }}>{counts.high}</strong> high</span>
                  <span><strong style={{ fontFamily: 'var(--font-mono)' }}>{counts.more_info}</strong> more info</span>
                </div>
              </Card>
            );
          })}
        </div>
      </Section>
    </>
  );
}

window.PortalHome = PortalHome;
