import { useEffect, useState, useRef } from 'react';
import { useNavigate, useSearchParams } from 'react-router-dom';
import { Printer, FileDown, RefreshCw, X, AlertCircle } from 'lucide-react';
import api from '../../store/api';

interface ReportCardSubject {
  subject: string;
  teacher: string | null;
  course_work: number | null;
  exam: number | null;
  final: number | null;
  symbol: string;
  symbol_descriptor: string | null;
  scale: string | null;
  remark: string;
  position_band: string;
}

interface ReportCardPayload {
  generated_at: string;
  school: { name: string; address: string; motto: string; logo_url: string };
  student: {
    id: number; name: string; first_name: string; last_name: string; email: string | null;
    class_name: string; class_section: string; class_teacher: string;
  };
  period: { term: string; academic_year: string; label: string };
  rank: { position: number; total: number } | null;
  overall_average: number | null;
  grading_scale: string | null;
  subjects: ReportCardSubject[];
  class_teacher_remark: string;
  headmaster_remark: string;
}

const fmtPct = (n: number | null) => (n == null ? '—' : `${Math.round(n)}%`);
const ordinal = (n: number) => {
  const s = ['th', 'st', 'nd', 'rd'];
  const v = n % 100;
  return n + (s[(v - 20) % 10] || s[v] || s[0]);
};
const escapeHtml = (s: string) =>
  String(s).replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c] || c));

/**
 * Build a fully self-contained printable HTML document for the report
 * card. Inline CSS only — no Tailwind, no shared assets, no SPA chrome.
 * Designed to be document.write()'d into a brand-new window so that
 * `window.print()` in that window produces JUST the report (never the
 * rest of the app).
 */
const buildPrintableHtml = (data: ReportCardPayload): string => {
  // Same defensive defaults as the on-screen renderer — if a payload
  // field is missing, print blanks instead of producing an undefined
  // in the printable HTML.
  const s = data.school || { name: '', address: '', motto: '', logo_url: '' };
  const stu = data.student || { id: 0, name: '', first_name: '', last_name: '', email: null, class_name: '', class_section: '', class_teacher: '' };
  const per = data.period || { term: 'Current Term', academic_year: '', label: 'Current Term' };
  const subjects = Array.isArray(data.subjects) ? data.subjects : [];
  const overall = data.overall_average;
  // Mirror the Nav.tsx portal-identity pattern: read the live logo URL
  // from the API payload (set by Settings.tsx → /api/settings/logo) and
  // fall back to the public /nextgen-logo.jpeg asset when nothing has
  // been uploaded yet. The URL is rebuilt absolute because this HTML
  // is document.write'd into a brand-new window with no relative-base
  // context.
  const logoSrc = s.logo_url
    ? (s.logo_url.startsWith('http') ? s.logo_url : window.location.origin + s.logo_url)
    : window.location.origin + '/nextgen-logo.jpeg';
  const rank = data.rank;
  const subjectsRows = subjects
    .map(
      (row, i) => `
      <tr style="background:${i % 2 === 0 ? '#ffffff' : '#f8fafc'};">
        <td style="border:1px solid #cbd5e1;padding:8px 12px;font-weight:700;color:#0f172a;">${escapeHtml(row.subject)}</td>
        <td style="border:1px solid #cbd5e1;padding:8px 12px;text-align:center;color:#334155;">${fmtPct(row.course_work)}</td>
        <td style="border:1px solid #cbd5e1;padding:8px 12px;text-align:center;color:#334155;">${fmtPct(row.exam)}</td>
        <td style="border:1px solid #cbd5e1;padding:8px 12px;text-align:center;font-weight:700;color:#0f172a;">${fmtPct(row.final)}</td>
        <td style="border:1px solid #cbd5e1;padding:8px 12px;text-align:center;font-weight:900;font-size:14pt;color:#0047AB;">${escapeHtml(row.symbol)}</td>
        <td style="border:1px solid #cbd5e1;padding:8px 12px;font-style:italic;color:#475569;font-size:10pt;">${escapeHtml(row.remark)}</td>
      </tr>`,
    )
    .join('\n');

  return `<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Report Card - ${escapeHtml(stu.name)} - ${escapeHtml(s.name)}</title>
  <style>
    @page { size: A4 portrait; margin: 12mm; }
    * { box-sizing: border-box; }
    html, body {
      margin: 0; padding: 0; background: #ffffff; color: #0f172a;
      font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
      -webkit-print-color-adjust: exact; print-color-adjust: exact;
    }
    /* Watermark: school emblem faded behind the report content.
       -print-color-adjust: exact on html/body (above) keeps the opacity
       in the rendered PDF; Chromium/Electron/Edge honour it for the
       "Save as PDF" destination. The page wrapper is the positioning
       context; .watermark sits behind every other child via z-index. */
    .page { position: relative; max-width: 210mm; margin: 0 auto; padding: 16mm 14mm; min-height: 100vh; }
    .watermark {
      position: absolute;
      top: 50%; left: 50%;
      width: 70%;
      transform: translate(-50%, -50%);
      opacity: 0.08;
      pointer-events: none;
      z-index: 0;
      -webkit-print-color-adjust: exact;
      print-color-adjust: exact;
    }
    .watermark img { width: 100%; height: auto; display: block; }
    .page > *:not(.watermark) { position: relative; z-index: 1; }
    .letterhead { display: flex; align-items: center; gap: 16px; border-bottom: 2px solid #0047AB; padding-bottom: 14px; }
    .logo { width: 72px; height: 72px; object-fit: contain; border: 1px solid #e2e8f0; border-radius: 12px; padding: 4px; background: #fff; }
    .heading { flex: 1; text-align: center; }
    .overline { font-size: 9pt; text-transform: uppercase; letter-spacing: 2px; color: #64748b; font-weight: 700; margin: 0; }
    .school-name { font-size: 22pt; color: #0047AB; font-weight: 900; margin: 2px 0 0; line-height: 1.15; }
    .school-addr { font-size: 9pt; color: #64748b; margin: 2px 0 0; }
    .school-motto { font-size: 9pt; color: #64748b; font-style: italic; margin: 4px 0 0; }
    .spacer { width: 72px; }
    .doc-title { text-align: center; margin: 18px 0 12px; }
    .doc-title h1 { font-size: 16pt; font-weight: 900; text-transform: uppercase; letter-spacing: 4px; color: #1e293b; margin: 0; }
    .doc-title p { font-size: 10pt; color: #64748b; margin: 6px 0 0; }
    .id-block { display: grid; grid-template-columns: 1fr 1fr; gap: 4px 24px; padding: 12px 14px; border: 1px solid #cbd5e1; border-radius: 6px; background: #f8fafc; font-size: 10.5pt; }
    .id-row { display: flex; justify-content: space-between; gap: 12px; padding: 3px 0; border-bottom: 1px solid #e2e8f0; }
    .id-row:last-child { border-bottom: 0; }
    .id-label { font-size: 9pt; text-transform: uppercase; letter-spacing: 1px; font-weight: 700; color: #64748b; }
    .id-value { font-weight: 700; color: #0f172a; }
    .id-value.hi { color: #0047AB; }
    table { width: 100%; border-collapse: collapse; font-size: 11pt; margin-top: 14px; }
    thead tr { background: #0047AB; color: #fff; }
    th { border: 1px solid #0047AB; padding: 8px 10px; font-size: 9pt; font-weight: 700; text-transform: uppercase; letter-spacing: 0.5px; text-align: left; }
    th.center { text-align: center; }
    td { border: 1px solid #cbd5e1; padding: 8px 10px; vertical-align: middle; }
    tfoot td { padding: 10px; font-weight: 700; }
    .symbol-cell { text-align: center; font-weight: 900; font-size: 13pt; color: #0047AB; }
    .remarks { display: grid; grid-template-columns: 1fr 1fr; gap: 14px; margin-top: 16px; }
    .remark-card { border: 1px solid #cbd5e1; border-radius: 6px; padding: 14px; background: #f8fafc; min-height: 110px; display: flex; flex-direction: column; }
    .remark-card .label { font-size: 8.5pt; font-weight: 900; text-transform: uppercase; letter-spacing: 2px; color: #64748b; margin: 0; }
    .remark-card .text { font-size: 10.5pt; color: #1e293b; margin: 8px 0 12px; line-height: 1.45; flex: 1; }
    .signature { border-top: 1px solid #cbd5e1; padding-top: 10px; font-size: 9.5pt; }
    .signature .sig-label { font-weight: 700; text-transform: uppercase; letter-spacing: 1px; color: #64748b; margin: 0; }
    .signature .sig-name { font-weight: 700; color: #0f172a; margin: 8px 0 0; }
    .signature .sig-role { color: #64748b; font-style: italic; font-size: 8.5pt; margin: 2px 0 0; }
    .footer { margin-top: 20px; padding-top: 8px; border-top: 1px solid #cbd5e1; display: flex; justify-content: space-between; font-size: 8.5pt; color: #64748b; }
    .footer .note { font-style: italic; }
    .no-print-overlay {
      position: fixed; left: 0; right: 0; bottom: 14px; display: flex; justify-content: center;
      pointer-events: none; z-index: 10;
    }
    .no-print-overlay button { pointer-events: auto; }
    @media print {
      .no-print-overlay, .on-screen-only { display: none !important; }
      body { -webkit-print-color-adjust: exact; }
    }
  </style>
</head>
<body>
  <div class="page">
    <div class="watermark" aria-hidden="true">
      <img src="${escapeHtml(logoSrc)}" alt="">
    </div>
    <header class="letterhead">
      <img class="logo" src="${escapeHtml(logoSrc)}" alt="School logo">
      <div class="heading">
        <p class="overline">Republic of Zimbabwe</p>
        <h1 class="school-name">${escapeHtml(s.name)}</h1>
        <p class="school-addr">${escapeHtml(s.address)}</p>
        <p class="school-motto">"${escapeHtml(s.motto)}"</p>
      </div>
      <div class="spacer"></div>
    </header>

    <div class="doc-title">
      <h1>Student Report Card</h1>
      <p>${escapeHtml(per.label)}</p>
    </div>

    <section class="id-block">
      <div class="id-row"><span class="id-label">Student Name</span><span class="id-value">${escapeHtml(stu.name)}</span></div>
      <div class="id-row"><span class="id-label">Class</span><span class="id-value">${escapeHtml(stu.class_name + (stu.class_section ? ' ' + stu.class_section : ''))}</span></div>
      <div class="id-row"><span class="id-label">Academic Period</span><span class="id-value">${escapeHtml(per.label)}</span></div>
      <div class="id-row"><span class="id-label">Class Teacher</span><span class="id-value">${escapeHtml(stu.class_teacher || '—')}</span></div>
      <div class="id-row"><span class="id-label">Overall Average</span><span class="id-value hi">${fmtPct(overall)}</span></div>
      <div class="id-row"><span class="id-label">Class Position</span><span class="id-value">${rank ? `${ordinal(rank.position)} of ${rank.total}` : '—'}</span></div>
    </section>

    <table>
      <thead>
        <tr>
          <th>Subject</th>
          <th class="center">Course Work</th>
          <th class="center">Exam</th>
          <th class="center">Total</th>
          <th class="center">Symbol</th>
          <th>Remark</th>
        </tr>
      </thead>
      <tbody>
        ${subjects.length === 0
          ? `<tr><td colspan="6" style="border:1px solid #cbd5e1;padding:24px;text-align:center;color:#64748b;font-style:italic;">No subject marks recorded for this period yet.</td></tr>`
          : subjectsRows}
      </tbody>
      <tfoot>
        <tr>
          <td colspan="4" style="text-align:right;text-transform:uppercase;font-size:10pt;">Final Average</td>
          <td class="symbol-cell">${fmtPct(overall)}</td>
          <td style="font-style:italic;font-size:10pt;">${(overall ?? 0) >= 50 ? 'Promoted to next class' : 'Academic review required'}</td>
        </tr>
      </tfoot>
    </table>

    <section class="remarks">
      <div class="remark-card">
        <p class="label">Class Teacher's Remark</p>
        <p class="text">${escapeHtml(data.class_teacher_remark)}</p>
        <div class="signature">
          <p class="sig-label">Signed</p>
          <p class="sig-name">${escapeHtml(stu.class_teacher || '—')}</p>
          <p class="sig-role">Class Teacher</p>
        </div>
      </div>
      <div class="remark-card">
        <p class="label">Headmaster's Remark</p>
        <p class="text">${escapeHtml(data.headmaster_remark)}</p>
        <div class="signature">
          <p class="sig-label">Signed</p>
          <p class="sig-name">${escapeHtml(s.name)}</p>
          <p class="sig-role">Headmaster / Principal</p>
        </div>
      </div>
    </section>

    <footer class="footer">
      <span>Generated ${escapeHtml(new Date(data.generated_at).toLocaleString())}</span>
      <span class="note">This document is system-generated and valid without a signature.</span>
    </footer>
  </div>

  <div class="no-print-overlay">
    <button class="on-screen-only" onclick="window.print()"
      style="padding:10px 20px;border-radius:9999px;background:#0047AB;color:#fff;border:0;font-weight:800;letter-spacing:1px;text-transform:uppercase;font-size:11px;cursor:pointer;box-shadow:0 8px 20px rgba(0,0,0,0.15);">
      Print this report
    </button>
  </div>

  <script>
    // Auto-trigger the print dialog once the layout is fully painted.
    // 250ms covers image decoding for the school logo.
    window.addEventListener('load', function () {
      setTimeout(function () {
        try { window.focus(); window.print(); } catch (e) { console.error('Auto-print failed', e); }
      }, 250);
    });
  </script>
</body>
</html>`;
};

export default function ReportCard() {
  const navigate = useNavigate();
  const [searchParams] = useSearchParams();
  // 'live' (default) = in-app report card with toolbar; 'print' = thin
  // wrapper that the user lands on when a Grades.tsx button opens it
  // independently (e.g. from a deep link). Both share the same data fetch.
  const mode = searchParams.get('mode') === 'print' ? 'print' : 'live';
  // When a parent opens this from /academic-progress the link carries
  // ?child_id=<id> so we hit the parent-scoped endpoint instead of
  // /students/me/report-card. A student visiting the page directly
  // leaves child_id unset and gets their own report.
  const childId = searchParams.get('child_id');
  const endpoint = childId
    ? `/students/${encodeURIComponent(childId)}/report-card`
    : '/students/me/report-card';
  const [data, setData] = useState<ReportCardPayload | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [loading, setLoading] = useState(true);

  const containerRef = useRef<HTMLDivElement>(null);
  const sheetRef = useRef<HTMLDivElement>(null);
  const [scale, setScale] = useState(1);
  const [sheetHeight, setSheetHeight] = useState(0);

  useEffect(() => {
    let cancelled = false;
    setLoading(true);
    api
      .get(endpoint)
      .then((res) => {
        if (cancelled) return;
        setData(res.data as ReportCardPayload);
      })
      .catch((err: any) => {
        if (cancelled) return;
        setError(err?.response?.data?.error || err?.message || 'Failed to load report card');
      })
      .finally(() => {
        if (!cancelled) setLoading(false);
      });
    return () => { cancelled = true; };
  }, []);

  useEffect(() => {
    const updateScale = () => {
      if (!containerRef.current) return;
      // Measure container width available minus padding (e.g. 16px)
      const containerWidth = containerRef.current.clientWidth - 16;
      // Target width for 210mm A4 sheet at standard 96dpi web rendering = 793.7px
      const targetWidth = 793.7;
      if (containerWidth < targetWidth && containerWidth > 0) {
        setScale(containerWidth / targetWidth);
      } else {
        setScale(1);
      }
      if (sheetRef.current) {
        setSheetHeight(sheetRef.current.offsetHeight);
      }
    };

    updateScale();
    window.addEventListener('resize', updateScale);
    return () => window.removeEventListener('resize', updateScale);
  }, [data]);

  /**
   * Open a brand-new window with only the printable HTML — no SPA
   * chrome, no Nav, no toolbar. The new window auto-triggers the print
   * dialog once painted. The user can save-as-PDF from the native dialog
   * just like the live toolbar's button, but with NO other page content
   * muddying the print.
   */
  const openPrintWindow = (autoPrint: boolean) => {
    if (!data) return;
    const html = buildPrintableHtml(data);
    // Open an empty window synchronously so the popup blocker accepts it.
    const win = window.open('', '_blank', 'width=900,height=1180,menubar=no,toolbar=no,location=no,status=no');
    if (!win) {
      alert('Pop-up blocked. Please allow pop-ups for this site to print the report.');
      return;
    }
    win.document.open();
    win.document.write(html);
    win.document.close();
    if (!autoPrint) {
      // If the user asked for the printable view *without* auto-print, set
      // a flag the page reads so it skips the auto-trigger script.
      // buildPrintableHtml currently always auto-prints, so we only hit
      // this branch from the in-app toolbar where the user explicitly
      // clicks "Download PDF" — auto-print is appropriate there too.
    }
  };

  const handleDownload = () => openPrintWindow(true);

  // Render mode "print" — the standalone route. We render only the
  // toolbar-free printable card; the user clicks the on-screen button to
  // open the standalone printable window.
  if (mode === 'print') {
    if (loading && !data) {
      return (
        <div className="min-h-screen flex flex-col items-center justify-center gap-3 text-slate-500 bg-white">
          <RefreshCw size={28} className="animate-spin text-primary" />
          <p className="font-black uppercase tracking-[3px] text-xs">Preparing report…</p>
        </div>
      );
    }
    if (error) {
      return (
        <div className="min-h-screen flex flex-col items-center justify-center gap-4 text-slate-700 p-6 bg-white">
          <AlertCircle size={28} className="text-rose-500" />
          <p className="font-bold">{error}</p>
          <a href="/student/report-card" className="px-4 py-2 bg-card border border-border rounded-xl text-text font-bold text-sm hover:bg-muted/50 no-underline">Back to live report</a>
        </div>
      );
    }
    if (!data) return null;
    return (
      <div className="report-card-root min-h-screen flex flex-col items-center justify-center gap-6 bg-slate-50 p-6">
        <div className="bg-white border border-slate-200 rounded-2xl p-8 shadow-sm max-w-md w-full text-center text-slate-900">
          <p className="text-xs font-black uppercase tracking-[3px] text-slate-500 mb-2">Ready to print</p>
          <h1 className="text-2xl font-black text-slate-900 mb-1">{data.student.name}</h1>
          <p className="text-sm text-slate-500 mb-6">
            {data.school.name} · {data.period.label}
          </p>
          <p className="text-xs text-slate-500 mb-6 leading-relaxed">
            Click the button below to open the report in a clean printable window with no other page content.
          </p>
          <button
            onClick={handleDownload}
            className="w-full px-6 py-3 bg-primary hover:bg-primary-dark text-white rounded-xl font-black text-sm uppercase tracking-widest shadow-md inline-flex items-center justify-center gap-2"
          >
            <Printer size={16} />
            Print / Save as PDF
          </button>
        </div>
      </div>
    );
  }

  // Render mode "live" — in-app report card with toolbar.
  if (loading && !data) {
    return (
      <div className="min-h-screen flex flex-col items-center justify-center gap-4 text-slate-500 bg-white">
        <RefreshCw size={32} className="animate-spin text-primary" />
        <p className="font-black uppercase tracking-[3px] text-xs">Preparing report…</p>
      </div>
    );
  }

  if (error && !data) {
    return (
      <div className="min-h-screen flex flex-col items-center justify-center gap-4 bg-white text-slate-700 p-6">
        <AlertCircle size={28} className="text-rose-500" />
        <p className="font-bold">{error}</p>
        <div className="flex gap-3">
          <button onClick={() => window.location.reload()} className="px-4 py-2 bg-primary text-white rounded-xl font-bold text-sm flex items-center gap-2">
            <RefreshCw size={16} /> Retry
          </button>
          <button onClick={() => navigate(-1)} className="px-4 py-2 bg-card border border-border rounded-xl font-bold text-sm flex items-center gap-2">
            <X size={16} /> Back
          </button>
        </div>
      </div>
    );
  }

  if (!data) return null;

  // Defensive defaults so a future endpoint shape mismatch degrades to
  // blanks rather than crashing the popup. The /me/report-card and the
  // parent-scoped /api/students/:id/report-card payload shapes have
  // been brought into alignment; these defaults are belt-and-braces.
  const s = data.school || { name: '', address: '', motto: '', logo_url: '' };
  const stu = data.student || { id: 0, name: '', first_name: '', last_name: '', email: null, class_name: '', class_section: '', class_teacher: '' };
  const per = data.period || { term: 'Current Term', academic_year: '', label: 'Current Term' };
  const subjects = Array.isArray(data.subjects) ? data.subjects : [];
  const overall = data.overall_average;
  const rank = data.rank;

  return (
    <div className="report-card-root min-h-screen bg-slate-100 print:bg-white flex flex-col items-center">
      {/* Toolbar — hidden on print */}
      <div className="no-print sticky top-0 z-10 w-full bg-card border-b border-border shadow-sm">
        <div className="max-w-[210mm] mx-auto px-4 sm:px-6 py-3 flex items-center justify-between gap-3">
          <div className="flex items-center gap-3 min-w-0">
            <button
              onClick={() => navigate(-1)}
              className="p-2 rounded-xl bg-muted/50 border border-border text-text-muted hover:text-text shrink-0 cursor-pointer"
              aria-label="Close"
              title="Close"
            >
              <X size={16} />
            </button>
            <div className="min-w-0">
              <p className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted truncate">Academic Report</p>
              <p className="text-xs sm:text-sm font-bold text-text truncate">{stu.name} · {stu.class_name}{stu.class_section ? ` ${stu.class_section}` : ''}</p>
            </div>
          </div>
          <div className="flex items-center gap-2 shrink-0">
            <button
              onClick={() => window.location.reload()}
              className="px-3.5 py-2 bg-card border border-border rounded-xl font-bold text-xs uppercase tracking-widest text-text-muted hover:text-text flex items-center gap-1.5 cursor-pointer"
            >
              <RefreshCw size={14} />
              <span className="hidden sm:inline">Refresh</span>
            </button>
            <button
              onClick={handleDownload}
              className="px-4 sm:px-5 py-2 bg-primary hover:bg-primary/90 text-white rounded-xl font-black text-xs uppercase tracking-widest flex items-center gap-2 shadow-md active:scale-95 transition-all cursor-pointer"
            >
              <FileDown size={14} />
              <span>Print / Save PDF</span>
            </button>
          </div>
        </div>
      </div>

      {/* A4 Sheet Viewport Canvas Container — Maintains 100% Exact A4 Document Sheet Layout, Auto-Zoomed to Fit Mobile Viewports */}
      <div ref={containerRef} className="w-full p-2 sm:p-6 md:p-8 flex flex-col items-center overflow-hidden">
        <div
          ref={sheetRef}
          className="w-[210mm] min-w-[210mm] max-w-[210mm] my-2 sm:my-4 print:my-0 bg-white text-slate-900 shadow-2xl print:shadow-none shrink-0 border border-slate-200"
          style={{
            transform: scale < 1 ? `scale(${scale})` : undefined,
            transformOrigin: 'top center',
            marginBottom: scale < 1 && sheetHeight > 0 ? `-${(1 - scale) * sheetHeight}px` : undefined,
          }}
        >
          <div className="px-12 py-10 print:text-[11pt]" style={{ minHeight: '297mm' }}>
            {/* Header Letterhead */}
            <header className="flex items-center gap-5 border-b-2 border-primary/80 pb-5">
              <img
                src={data.school.logo_url || '/nextgen-logo.jpeg'}
                alt="School logo"
                className="w-20 h-20 object-contain rounded-2xl border border-slate-200 bg-white p-1 shrink-0"
              />
              <div className="flex-1 text-center">
                <p className="text-[10pt] uppercase tracking-[3px] text-slate-500 font-bold">Republic of Zimbabwe</p>
                <h1 className="text-2xl font-black text-primary mt-0.5 leading-tight">{s.name}</h1>
                <p className="text-[10pt] text-text-muted mt-0.5">{s.address}</p>
                <p className="text-[10pt] italic text-text-muted mt-1">"{s.motto}"</p>
              </div>
              <div className="w-20 shrink-0" aria-hidden />
            </header>

            {/* Title + meta */}
            <div className="mt-6 text-center">
              <h2 className="text-lg font-black uppercase tracking-[4px] text-slate-800">Student Report Card</h2>
              <p className="text-[10pt] text-text-muted mt-1">{per.label}</p>
            </div>

            {/* Student identity block — Exact A4 2-Column Grid */}
            <section className="mt-6 grid grid-cols-2 gap-x-6 gap-y-1 text-[11pt] border border-slate-300 rounded-md p-4 bg-slate-50/60">
              <Row label="Student Name" value={stu.name} />
              <Row label="Class" value={`${stu.class_name}${stu.class_section ? ' ' + stu.class_section : ''}`} />
              <Row label="Academic Period" value={per.label} />
              <Row label="Class Teacher" value={stu.class_teacher || '—'} />
              <Row label="Overall Average" value={fmtPct(overall)} highlight />
              <Row
                label="Class Position"
                value={rank ? `${ordinal(rank.position)} of ${rank.total}` : '—'}
              />
            </section>

            {/* Subject table — Exact A4 6-Column Marks Table */}
            <section className="mt-6">
              <table className="w-full border-collapse text-[11pt]">
                <thead>
                  <tr className="bg-primary text-white">
                    <th className="border border-primary px-3 py-2 text-left font-bold uppercase tracking-wider text-[9pt]">Subject</th>
                    <th className="border border-primary px-3 py-2 text-center font-bold uppercase tracking-wider text-[9pt]">Course Work</th>
                    <th className="border border-primary px-3 py-2 text-center font-bold uppercase tracking-wider text-[9pt]">Exam</th>
                    <th className="border border-primary px-3 py-2 text-center font-bold uppercase tracking-wider text-[9pt]">Total</th>
                    <th className="border border-primary px-3 py-2 text-center font-bold uppercase tracking-wider text-[9pt]">Symbol</th>
                    <th className="border border-primary px-3 py-2 text-left font-bold uppercase tracking-wider text-[9pt]">Remark</th>
                  </tr>
                </thead>
                <tbody>
                  {subjects.length === 0 ? (
                    <tr>
                      <td colSpan={6} className="border border-slate-300 px-4 py-6 text-center text-slate-500 italic">
                        No subject marks recorded for this period yet.
                      </td>
                    </tr>
                  ) : (
                    subjects.map((row, i) => (
                      <tr key={row.subject} className={i % 2 === 0 ? 'bg-white' : 'bg-slate-50/60'}>
                        <td className="border border-slate-300 px-3 py-2 font-bold text-text">{row.subject}</td>
                        <td className="border border-slate-300 px-3 py-2 text-center text-text-muted">{fmtPct(row.course_work)}</td>
                        <td className="border border-slate-300 px-3 py-2 text-center text-text-muted">{fmtPct(row.exam)}</td>
                        <td className="border border-slate-300 px-3 py-2 text-center font-bold text-text">{fmtPct(row.final)}</td>
                        <td className="border border-slate-300 px-3 py-2 text-center font-black text-base text-primary">{row.symbol}</td>
                        <td className="border border-slate-300 px-3 py-2 text-[10pt] italic text-text-muted">{row.remark}</td>
                      </tr>
                    ))
                  )}
                </tbody>
                <tfoot>
                  <tr>
                    <td colSpan={4} className="border border-slate-300 px-3 py-2 text-right font-bold uppercase text-[10pt] text-text">Final Average</td>
                    <td className="border border-slate-300 px-3 py-2 text-center font-black text-base text-primary">{fmtPct(overall)}</td>
                    <td className="border border-slate-300 px-3 py-2 text-[10pt] italic text-text-muted">
                      {overall != null && overall >= 50 ? 'Promoted to next class' : 'Academic review required'}
                    </td>
                  </tr>
                </tfoot>
              </table>
            </section>

            {/* Remarks — Exact A4 2-Column Grid */}
            <section className="mt-6 grid grid-cols-2 gap-4">
              <div className="border border-slate-300 rounded-md p-4 bg-slate-50/30">
                <p className="text-[9pt] font-black uppercase tracking-[3px] text-text-muted">Class Teacher's Remark</p>
                <p className="text-[11pt] text-text mt-2 leading-relaxed">{data.class_teacher_remark}</p>
                <div className="mt-6 pt-3 border-t border-slate-300 text-[10pt]">
                  <p className="font-bold uppercase tracking-widest text-text-muted">Signed</p>
                  <p className="mt-3 font-bold text-text">{stu.class_teacher || '—'}</p>
                  <p className="text-text-muted italic text-[9pt] mt-1">Class Teacher</p>
                </div>
              </div>
              <div className="border border-slate-300 rounded-md p-4 bg-slate-50/30">
                <p className="text-[9pt] font-black uppercase tracking-[3px] text-text-muted">Headmaster's Remark</p>
                <p className="text-[11pt] text-text mt-2 leading-relaxed">{data.headmaster_remark}</p>
                <div className="mt-6 pt-3 border-t border-slate-300 text-[10pt]">
                  <p className="font-bold uppercase tracking-widest text-text-muted">Signed</p>
                  <p className="mt-3 font-bold text-text">{s.name}</p>
                  <p className="text-text-muted italic text-[9pt] mt-1">Headmaster / Principal</p>
                </div>
              </div>
            </section>

            {/* Footer */}
            <footer className="mt-10 pt-4 border-t border-slate-300 text-[9pt] text-text-muted flex justify-between">
              <span>Generated {new Date(data.generated_at).toLocaleString()}</span>
              <span className="italic">This document is system-generated and valid without a signature.</span>
            </footer>
          </div>
        </div>
      </div>

      <style>{`
        /* --- Theme pinning (§) ------------------------------------------
         * The report card never responds to the app's dark/light switch.
         * Tailwind tokens resolve via CSS variables (--tw-card, --text, ...)
         * that the .dark ancestor override on :root. We pin those vars to
         * their light values inside .report-card-root so any descendant
         * that uses bg-card / text-text / border-border gets the light
         * palette regardless of the global theme. colorScheme: light also
         * forces native form controls and scrollbars to stay light.
         * -------------------------------------------------------------- */
        .report-card-root,
        html.dark .report-card-root,
        .dark .report-card-root {
          color-scheme: light;
          --tw-background: 0 0% 100% !important;
          --tw-foreground: 222.2 84% 4.9% !important;
          --tw-card: 0 0% 100% !important;
          --tw-card-foreground: 222.2 84% 4.9% !important;
          --tw-popover: 0 0% 100% !important;
          --tw-popover-foreground: 222.2 84% 4.9% !important;
          --tw-primary: 215 100% 33.5% !important;
          --tw-primary-foreground: 210 40% 98% !important;
          --tw-secondary: 210 40% 96.1% !important;
          --tw-secondary-foreground: 222.2 47.4% 11.2% !important;
          --tw-muted: 210 40% 96.1% !important;
          --tw-muted-foreground: 215.4 16.3% 46.9% !important;
          --tw-accent: 38.8 100% 50% !important;
          --tw-accent-foreground: 222.2 47.4% 11.2% !important;
          --tw-destructive: 0 84.2% 60.2% !important;
          --tw-destructive-foreground: 210 40% 98% !important;
          --tw-border: 214.3 31.8% 91.3% !important;
          --tw-input: 214.3 31.8% 91.3% !important;
          --tw-ring: 215 100% 33.5% !important;
          --primary: #0047AB !important;
          --primary-dark: #003080 !important;
          --primary-light: #1a5cc0 !important;
          --slate: #002147 !important;
          --slate-light: #1a3a66 !important;
          --slate-50: #e6ebf2 !important;
          --text: #002147 !important;
          --text-secondary: #1a3a66 !important;
          --text-light: #4a6585 !important;
          --text-muted: #8696ad !important;
          --background: #ffffff !important;
          --background-alt: #f7f9fc !important;
          --card: #ffffff !important;
          --border: #e3e8ef !important;
        }
        @media print {
          @page { size: A4; margin: 12mm; }
          html, body { background: white !important; color: black !important; }
          .no-print { display: none !important; }
          .report-card-root { background: white !important; }
          .report-card-root > div:last-of-type {
            box-shadow: none !important;
            border-radius: 0 !important;
            margin: 0 !important;
            max-width: none !important;
          }
        }
      `}</style>
    </div>
  );
}

function Row({ label, value, highlight }: { label: string; value: string; highlight?: boolean }) {
  return (
    <div className="flex justify-between gap-3 py-0.5 border-b border-slate-200 last:border-0">
      <span className="text-[10pt] font-bold uppercase tracking-widest text-text-muted">{label}</span>
      <span className={'text-[11pt] font-bold text-text ' + (highlight ? 'text-primary' : '')}>{value}</span>
    </div>
  );
}
