'use client';

import { useEffect, useRef } from 'react';
import styles from './SatsChart.module.css';

interface SubjectData {
  name: string;
  expectedPct: number | null;
  exceedingPct: number | null;
  nationalExpectedPct: number | null;
  /** National higher-standard / greater-depth benchmark for the exceeding
   * bar — a different figure from the expected national. */
  nationalExceedingPct: number | null;
}

interface SatsChartProps {
  subjects: SubjectData[];
}

const RULER_TICKS = [0, 25, 50, 75, 100];
const GRIDLINE_POSITIONS = [25, 50, 75];

/** One results bar with a national marker positioned on its own track, so the
 * expected and exceeding bars each compare against their own benchmark. */
function BarRow({
  label,
  value,
  national,
  barRef,
  barClass,
}: {
  label: string;
  value: number;
  national: number | null;
  barRef: React.RefObject<HTMLDivElement | null>;
  barClass: string;
}) {
  return (
    <div className={styles.barRow}>
      <div className={styles.barHeader}>
        <span className={styles.barLabelSuffix}>{label}</span>
        <span className={styles.barHeaderRight}>
          {national != null && <span className={styles.natLabel}>nat {national.toFixed(0)}%</span>}
          <span className={styles.barLabel}>{value.toFixed(0)}%</span>
        </span>
      </div>
      <div className={styles.barTrack}>
        <div ref={barRef} className={`${styles.bar} ${barClass}`} data-width={value} />
        {national != null && (
          <div className={styles.natTick} style={{ left: `${national}%` }} aria-hidden="true" />
        )}
      </div>
    </div>
  );
}

function SubjectColumn({ subject }: { subject: SubjectData }) {
  const expectedRef = useRef<HTMLDivElement>(null);
  const exceedingRef = useRef<HTMLDivElement>(null);

  const { name, expectedPct, exceedingPct, nationalExpectedPct, nationalExceedingPct } = subject;

  // Animate bars on mount
  useEffect(() => {
    const bars = [expectedRef.current, exceedingRef.current];
    bars.forEach((bar) => {
      if (!bar) return;
      const target = bar.dataset.width;
      bar.style.width = '0%';
      requestAnimationFrame(() => {
        requestAnimationFrame(() => {
          bar.style.width = `${target}%`;
        });
      });
    });
  }, [expectedPct, exceedingPct]);

  if (expectedPct == null && exceedingPct == null) return null;

  return (
    <div className={styles.subjectChart}>
      <div className={styles.subjectName}>{name}</div>
      <div className={styles.chartArea}>
        {/* Gridlines */}
        <div className={styles.gridlines}>
          {GRIDLINE_POSITIONS.map((pct) => (
            <div key={pct} className={styles.gridline} style={{ left: `${pct}%` }} />
          ))}
        </div>

        {/* Bars — each carries its own national marker */}
        <div className={styles.barGroup}>
          {expectedPct != null && (
            <BarRow
              label="Expected"
              value={expectedPct}
              national={nationalExpectedPct}
              barRef={expectedRef}
              barClass={styles.barExpected}
            />
          )}
          {exceedingPct != null && (
            <BarRow
              label="Exceeding"
              value={exceedingPct}
              national={nationalExceedingPct}
              barRef={exceedingRef}
              barClass={styles.barExceeding}
            />
          )}
        </div>

        {/* Ruler */}
        <div className={styles.ruler}>
          {RULER_TICKS.map((pct, i) => (
            <span key={pct}>
              <div className={styles.rulerTick} style={{ left: `${pct}%` }} />
              <div
                className={`${styles.rulerLabel} ${i === 0 ? styles.rulerLabelFirst : ''} ${i === RULER_TICKS.length - 1 ? styles.rulerLabelLast : ''}`}
                style={{ left: `${pct}%` }}
              >
                {pct}%
              </div>
            </span>
          ))}
        </div>
      </div>
    </div>
  );
}

export default function SatsChart({ subjects }: SatsChartProps) {
  const visibleSubjects = subjects.filter(
    (s) => s.expectedPct != null || s.exceedingPct != null
  );

  if (visibleSubjects.length === 0) return null;

  return (
    <div>
      <div className={styles.container}>
        {visibleSubjects.map((subject) => (
          <SubjectColumn key={subject.name} subject={subject} />
        ))}
      </div>
      <div className={styles.legend}>
        <div className={styles.legendItem}>
          <div className={styles.legendSwatch} style={{ background: 'var(--status-above)' }} />
          Expected standard
        </div>
        <div className={styles.legendItem}>
          <div className={styles.legendSwatch} style={{ background: 'var(--status-above)' }} />
          Exceeding / high score
        </div>
        <div className={styles.legendItem}>
          <div className={styles.legendSwatch} style={{ background: 'var(--brand)', width: '3px', height: '12px', borderRadius: '2px' }} />
          National average
        </div>
      </div>
    </div>
  );
}
