/* ENSSA Reporting — chrome + simple controls.
   Charts in Charts.jsx; tokens in tokens.jsx. */

/* global React, RISK, STATUS, TERMS, TERM_DEFAULT, YEAR_LEVELS */

const { useState } = React;

function Card({ children, style }) {
  return (
    <div style={{ background: 'var(--bg-surface)', border: '1px solid var(--border-subtle)', borderRadius: 10, padding: 24, boxShadow: 'var(--sh-1)', ...style }}>{children}</div>
  );
}

function Eyebrow({ children, style }) {
  return <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: '0.08em', textTransform: 'uppercase', color: 'var(--fg-3)', ...style }}>{children}</div>;
}

function RiskBadge({ level, size = 'md' }) {
  const r = RISK[level];
  const sm = size === 'sm';
  const isMore = level === 'more_info';
  return (
    <span style={{
      display: 'inline-flex', alignItems: 'center', gap: 6,
      background: r.bg, color: r.fg,
      border: `1px solid ${isMore ? 'var(--ink-300)' : r.color}`,
      fontSize: sm ? 11 : 13,
      padding: sm ? '2px 9px' : '4px 11px',
      fontWeight: 700, borderRadius: 999,
      whiteSpace: 'nowrap',
    }}>
      <span style={{
        width: sm ? 7 : 9, height: sm ? 7 : 9, borderRadius: '50%',
        background: isMore ? 'transparent' : r.color,
        border: isMore ? '1.5px dashed var(--ink-400)' : 'none',
        boxSizing: 'border-box',
      }} />
      {r.label}
    </span>
  );
}

function StatusBadge({ status }) {
  const s = STATUS[status];
  return (
    <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6, fontSize: 12, fontWeight: 600, color: 'var(--fg-2)' }}>
      <span style={{ width: 8, height: 8, borderRadius: '50%', background: s.color }} />
      {s.label}
    </span>
  );
}

function MoreInfoFlag() {
  return (
    <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6, fontSize: 12, fontWeight: 700, color: 'var(--fg-2)', background: 'var(--ink-100)', padding: '3px 10px', borderRadius: 999, border: '1px dashed var(--ink-300)' }}>
      ⓘ Unknown
    </span>
  );
}

/* Term selector. */
function TermSelector({ value, onChange }) {
  return (
    <select value={value} onChange={e => onChange(e.target.value)} style={{
      fontFamily: 'inherit', fontSize: 14, fontWeight: 600,
      padding: '8px 14px', borderRadius: 8,
      border: '1px solid var(--border-default)', background: '#fff', color: 'var(--fg-1)',
    }}>
      {TERMS.map(t => <option key={t.id} value={t.id}>{t.label}</option>)}
    </select>
  );
}

function YearLevelChips({ value, onChange, availableYears }) {
  // Only show year levels that exist in this context; order F before Y1.
  const all = YEAR_LEVELS.filter(y => !availableYears || availableYears.includes(y.id));
  if (all.length <= 1) return null; // only one year level — no toggle needed
  return (
    <div style={{ display: 'inline-flex', background: 'var(--ink-50)', borderRadius: 8, padding: 2, border: '1px solid var(--border-subtle)', flexShrink: 0 }}>
      {all.map(o => (
        <button key={o.id} onClick={() => onChange(o.id)}
          style={{
            border: 0, background: value === o.id ? '#fff' : 'transparent',
            boxShadow: value === o.id ? 'var(--sh-1)' : 'none',
            padding: '6px 14px', fontSize: 13, fontWeight: 600,
            color: value === o.id ? 'var(--fg-1)' : 'var(--fg-3)',
            borderRadius: 6, cursor: 'pointer', fontFamily: 'inherit',
            whiteSpace: 'nowrap',
          }}>{o.label}</button>
      ))}
    </div>
  );
}

function Btn({ variant = 'primary', children, onClick, ...rest }) {
  const styles = {
    primary: { background: 'var(--accent)', color: '#fff', border: '1px solid var(--accent)' },
    ghost:   { background: 'transparent', color: 'var(--accent)', border: '1px solid var(--accent)' },
    neutral: { background: '#fff', color: 'var(--fg-1)', border: '1px solid var(--border-default)' },
  };
  return <button onClick={onClick} {...rest} style={{ fontFamily: 'inherit', fontSize: 14, fontWeight: 700, padding: '8px 16px', borderRadius: 8, cursor: 'pointer', whiteSpace: 'nowrap', ...styles[variant] }}>{children}</button>;
}

function CSVExportButton({ scope }) {
  return <span data-action="export-csv"><Btn variant="neutral">⤓ Export CSV{scope ? ` · ${scope}` : ''}</Btn></span>;
}
function PrintPDFButton() {
  return <span data-action="print"><Btn variant="neutral" onClick={() => window.print()}>⎙ Print / Save PDF</Btn></span>;
}

function Breadcrumbs({ items, onJump }) {
  return (
    <nav style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 13, color: 'var(--fg-3)', flexWrap: 'wrap' }}>
      {items.map((it, i) => {
        const last = i === items.length - 1;
        return (
          <React.Fragment key={it.key}>
            {last ? (
              <span style={{ color: 'var(--fg-1)', fontWeight: 600 }}>{it.label}</span>
            ) : (
              <button onClick={() => onJump(i)} style={{ background: 'none', border: 0, padding: 0, color: 'var(--accent)', fontSize: 13, fontWeight: 600, cursor: 'pointer', fontFamily: 'inherit' }}>{it.label}</button>
            )}
            {!last && <span style={{ color: 'var(--ink-300)' }}>›</span>}
          </React.Fragment>
        );
      })}
    </nav>
  );
}

function FooterStrip({ contextLabel, userName, userTitle }) {
  return (
    <footer style={{
      background: 'var(--enssa-aubergine)', color: '#fff',
      padding: '12px 32px',
      display: 'flex', alignItems: 'center', justifyContent: 'space-between',
      gap: 24, flexWrap: 'wrap',
    }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 16 }}>
        <div style={{ background: '#fff', borderRadius: 6, padding: '6px 10px', height: 40, display: 'flex', alignItems: 'center' }}>
          <img src="assets/logos/sol-lockup-with-cis.png" alt="Science of Learning · CIS" style={{ height: 26, width: 'auto', display: 'block' }} />
        </div>
        <div style={{ fontSize: 11, opacity: 0.7, letterSpacing: '0.08em', textTransform: 'uppercase', fontWeight: 700 }}>{contextLabel}</div>
      </div>
      <div style={{ fontSize: 12, opacity: 0.7, lineHeight: 1.4, textAlign: 'right' }}>
        <div style={{ fontWeight: 700, color: '#fff', fontSize: 13 }}>{userName}</div>
        <div style={{ marginTop: 1 }}>{userTitle}</div>
      </div>
    </footer>
  );
}

function PageHeader({ breadcrumbs, onJump, eyebrow, title, controls, role, onRoleChange }) {
  const ROLES = [
    { id: 'teacher',   label: 'Teacher' },
    { id: 'school',    label: 'School' },
    { id: 'district',  label: 'District' },
    { id: 'programme', label: 'Dev' },
  ];
  return (
    <header data-page-header style={{ padding: '16px 32px 18px', borderBottom: '1px solid var(--border-subtle)', background: '#fff' }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 16, marginBottom: 8 }}>
        {/* Breadcrumbs */}
        <div style={{ flex: 1, minWidth: 0 }}>
          {breadcrumbs && breadcrumbs.length > 0 && (
            <Breadcrumbs items={breadcrumbs} onJump={onJump} />
          )}
        </div>
        {/* Role switcher */}
        {role && onRoleChange && (
          <div style={{ display: 'inline-flex', background: 'var(--ink-50)', borderRadius: 8, padding: 2, border: '1px solid var(--border-subtle)', flexShrink: 0 }}>
            {ROLES.map(r => (
              <button key={r.id} onClick={() => onRoleChange(r.id)}
                style={{ border: 0, background: role === r.id ? 'var(--enssa-aubergine)' : 'transparent', color: role === r.id ? '#fff' : 'var(--fg-3)', padding: '5px 12px', fontSize: 12, fontWeight: 700, borderRadius: 6, cursor: 'pointer', fontFamily: 'inherit', whiteSpace: 'nowrap' }}>
                {r.label}
              </button>
            ))}
          </div>
        )}
      </div>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end', gap: 24, flexWrap: 'wrap' }}>
        <div style={{ flex: '1 1 280px', minWidth: 0 }}>
          {eyebrow && <Eyebrow>{eyebrow}</Eyebrow>}
          <h1 style={{ fontSize: 28, fontWeight: 900, margin: '4px 0 0', letterSpacing: '-0.01em', textWrap: 'balance' }}>{title}</h1>
        </div>
        <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', flexShrink: 0 }}>{controls}</div>
      </div>
    </header>
  );
}

function StatPill({ label, value, sub }) {
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
      <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: '0.08em', textTransform: 'uppercase', color: 'var(--fg-3)' }}>{label}</div>
      <div style={{ fontSize: 24, fontWeight: 900, letterSpacing: '-0.02em', fontFamily: 'var(--font-mono)', color: 'var(--fg-1)', lineHeight: 1 }}>{value}</div>
      {sub && <div style={{ fontSize: 12, color: 'var(--fg-3)', marginTop: 2 }}>{sub}</div>}
    </div>
  );
}

function KPI({ label, value, sub, accent }) {
  return (
    <Card style={{ padding: 20 }}>
      <Eyebrow>{label}</Eyebrow>
      <div style={{ fontSize: 32, fontWeight: 900, margin: '6px 0 2px', letterSpacing: '-0.01em', color: accent || 'var(--fg-1)', fontFamily: 'var(--font-mono)' }}>{value}</div>
      {sub && <div style={{ fontSize: 12, color: 'var(--fg-3)' }}>{sub}</div>}
    </Card>
  );
}

function Section({ eyebrow, title, hint, controls, children, style }) {
  return (
    <section style={{ marginBottom: 32, ...style }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end', marginBottom: 14, gap: 16, flexWrap: 'wrap' }}>
        <div style={{ flex: '1 1 320px', minWidth: 0 }}>
          {eyebrow && <Eyebrow>{eyebrow}</Eyebrow>}
          {title && <h2 style={{ fontSize: 20, fontWeight: 700, margin: '4px 0 0', letterSpacing: '-0.005em' }}>{title}</h2>}
          {hint && <p style={{ margin: '6px 0 0', fontSize: 13, color: 'var(--fg-2)', maxWidth: 720, lineHeight: 1.55 }}>{hint}</p>}
        </div>
        {controls && <div style={{ display: 'flex', gap: 8, flexShrink: 0, flexWrap: 'wrap' }}>{controls}</div>}
      </div>
      {children}
    </section>
  );
}

/* Inline screening disclaimer — appears once per page near the top result block. */
function ScreeningDisclaimer({ children }) {
  return (
    <div style={{
      display: 'flex', gap: 12, alignItems: 'flex-start',
      background: 'color-mix(in oklab, var(--enssa-mauve) 8%, white)',
      border: '1px solid color-mix(in oklab, var(--enssa-mauve) 25%, white)',
      borderRadius: 8, padding: '12px 16px',
      fontSize: 13, color: 'var(--fg-2)', lineHeight: 1.55,
      maxWidth: 880,
    }}>
      <span style={{ flexShrink: 0, width: 22, height: 22, borderRadius: '50%', background: 'var(--enssa-mauve)', color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 13, fontWeight: 800 }}>i</span>
      <div>
        {children || <>Screening results are a signal, not a diagnosis. Use them alongside classroom evidence and teacher judgement.</>}
      </div>
    </div>
  );
}

Object.assign(window, { Card, Eyebrow, RiskBadge, StatusBadge, MoreInfoFlag, TermSelector, YearLevelChips, Btn, CSVExportButton, PrintPDFButton, Breadcrumbs, FooterStrip, PageHeader, KPI, StatPill, Section, ScreeningDisclaimer });
