import { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import api from '../../store/auth';
import { GradeBadge } from '../../components/GradeBadge';
import { useRealtimeStore, notifyMarkedScript } from '../../store/realtime';
import { Modal, ModalBody } from '../../components/ui/Modal';
import {
  LineChart, Line, XAxis, YAxis, Tooltip, ResponsiveContainer,
  AreaChart, Area, Cell, CartesianGrid, BarChart, Bar
} from 'recharts';
import {
  Share2, TrendingUp, TrendingDown, Users, BookOpen,
  RefreshCw, ChevronDown, ArrowLeft, GraduationCap,
  Activity, BarChart3, Clock, UserCircle,
  FileText, ArrowUpRight, ArrowDownRight, Info,
  ChevronRight, Sparkles, Target, Award, ShieldCheck,
  Heart, Download, Printer, Filter, X, Inbox,
  FileCheck, Eye, Loader2,
  type LucideIcon,
} from 'lucide-react';
import { Link } from 'react-router-dom';

interface Student {
  id: number;
  first_name: string;
  last_name: string;
  class: string;
  grade: string;
  avatar?: string;
}

interface ApiChild extends Student {
  class_name?: string;
}

interface GradeEntry {
  period: string;
  avg: number;
  math?: number;
  english?: number;
  science?: number;
}

interface SubjectPerformance {
  subject: string;
  currentGrade: number;
  previousGrade: number;
  trend: 'up' | 'down' | 'stable';
  rank: number;
  totalStudents: number;
}

interface TooltipEntry {
  name?: string;
  value?: number | string;
  color?: string;
  fill?: string;
  payload?: Record<string, unknown>;
}

interface AcademicRecord {
  subject: string;
  teacher_name: string;
  assignment_avg: number;
  exam_avg: number;
  test_avg: number;
  overall_mark: number;
  grade: string;
  remarks: string;
}

// PR 3 §7.1 — minimal attachment shape for the marked-scripts section. Mirrors
// the Attachment type in client/src/store/attachments.ts but stays local so
// the parent page doesn't pull in the Zustand store for a read-only list.
interface MarkedScript {
  uid: string;
  original_filename: string;
  stored_filename: string;
  mime_type: string;
  size_bytes: number;
  uploaded_at: string;
  caption?: string | null;
}

interface MarkedScriptRow {
  id: number;
  assignment_id: number;
  assignment_title: string;
  submitted_at?: string;
  graded_at?: string;
  grade?: number | null;
  status?: string;
  marked_scripts: MarkedScript[];
}

interface ReportCard {
  term: string;
  student: {
    first_name: string;
    last_name: string;
    class_name: string;
    roll_number: string;
    academic_year: string;
  };
  attendance: { present: number; total: number; percentage: number };
  academic_records: AcademicRecord[];
  overall: { principal_remarks: string; average_mark: number; final_grade: string };
}

const PRINT_CSS = `
  .custom-scrollbar::-webkit-scrollbar { width: 4px; }
  .custom-scrollbar::-webkit-scrollbar-track { background: transparent; }
  .custom-scrollbar::-webkit-scrollbar-thumb { background: rgba(0, 71, 171, 0.1); border-radius: 10px; }
  .custom-scrollbar::-webkit-scrollbar-thumb:hover { background: rgba(0, 71, 171, 0.2); }
  @media print {
    .no-print { display: none !important; }
    .lg\\:pl-64 { padding-left: 0 !important; }
    main { padding: 0 !important; }
    .no-print-backdrop { position: absolute !important; inset: 0 !important; background: white !important; backdrop-filter: none !important; z-index: 9999 !important; }
    .print-modal-container { border: none !important; box-shadow: none !important; max-height: none !important; max-width: 100% !important; border-radius: 0 !important; }
    .print-document { overflow-y: visible !important; height: auto !important; padding: 0 !important; }
  }
`;

// Custom Tooltip Component (Supabase-like)
interface ChartTooltipProps {
  active?: boolean;
  payload?: TooltipEntry[];
  label?: string | number;
  prefix?: string;
}

const CustomTooltip = ({ active, payload, label, prefix = "" }: ChartTooltipProps) => {
  if (active && payload && payload.length) {
    return (
      <div className="bg-card border border-border p-4 rounded-xl shadow-2xl backdrop-blur-md">
        <p className="text-[0.65rem] font-black uppercase tracking-widest text-text-muted mb-2">{label}</p>
        <div className="space-y-1.5">
          {payload.map((entry, index) => (
            <div key={index} className="flex items-center justify-between gap-6">
              <div className="flex items-center gap-2">
                <div className="w-2 h-2 rounded-full" style={{ backgroundColor: entry.color || entry.fill || "#3b82f6" }} />
                <span className="text-[0.75rem] font-bold text-text-secondary capitalize">{String(entry.name ?? '').replace(/([A-Z])/g, ' $1')}</span>
              </div>
              <span className="text-[0.85rem] font-black text-text">{prefix}{Number(entry.value ?? 0).toLocaleString()}%</span>
            </div>
          ))}
        </div>
      </div>
    );
  }
  return null;
};

// Reusable empty-state panel matching the design language
const EmptyState = ({ icon: Icon, title, description }: { icon: LucideIcon; title: string; description: string }) => (
  <div className="flex flex-col items-center justify-center text-center py-16 px-8 gap-4">
    <div className="w-16 h-16 rounded-[1.5rem] bg-muted border border-border flex items-center justify-center text-text-muted shadow-inner">
      <Icon size={26} strokeWidth={1.5} />
    </div>
    <div className="space-y-1.5 max-w-sm">
      <p className="text-[0.7rem] font-black uppercase tracking-[3px] text-text">{title}</p>
      <p className="text-[0.75rem] text-text-muted font-medium leading-relaxed">{description}</p>
    </div>
  </div>
);

export default function AcademicProgress() {
  const navigate = useNavigate();
  const [selectedStudent, setSelectedStudent] = useState<Student | null>(null);
  const [students, setStudents] = useState<Student[]>([]);
  const [gradeData, setGradeData] = useState<GradeEntry[]>([]);
  const [subjectPerformance, setSubjectPerformance] = useState<SubjectPerformance[]>([]);
  const [loading, setLoading] = useState(true);
  const [showStudentPicker, setShowStudentPicker] = useState(false);
  const [reportCard, setReportCard] = useState<ReportCard | null>(null);
  const [showReportCardModal, setShowReportCardModal] = useState(false);
  const [loadingReportCard, setLoadingReportCard] = useState(false);
  // PR 3 §7.1 — marked scripts for the selected child. The server endpoint
  // /api/assignments/my/submissions?student_id=X (parent-scoped) joins the
  // marked_script attachments; we render only those with status='returned'.
  const [markedScripts, setMarkedScripts] = useState<MarkedScriptRow[]>([]);
  const [loadingMarkedScripts, setLoadingMarkedScripts] = useState(false);
  const [previewScript, setPreviewScript] = useState<MarkedScript | null>(null);
  const [previewUrl, setPreviewUrl] = useState<string | null>(null);
  const [previewLoading, setPreviewLoading] = useState(false);

  useEffect(() => {
    loadStudents();
  }, []);

  const loadStudents = async () => {
    setLoading(true);
    try {
      const res = await api.get('/users/children');
      const studentList = Array.isArray(res.data)
        ? (res.data as ApiChild[]).map((s) => ({
            id: s.id,
            first_name: s.first_name,
            last_name: s.last_name,
            class: s.class_name || `Section 10-A`,
            grade: s.grade || `Grade 10`,
          }))
        : [];
      setStudents(studentList);

      if (studentList.length > 0) {
        setSelectedStudent(studentList[0]);
        loadStudentData(studentList[0].id);
      } else {
        setSelectedStudent(null);
        setGradeData([]);
        setSubjectPerformance([]);
      }
    } catch (error) {
      console.error('Error loading children:', error);
      setStudents([]);
      setSelectedStudent(null);
      setGradeData([]);
      setSubjectPerformance([]);
    } finally {
      setLoading(false);
    }
  };

  const loadStudentData = async (studentId: number) => {
    setLoading(true);
    try {
      const [gradesRes, performanceRes, markedRes] = await Promise.all([
        api.get(`/students/${studentId}/grades`).catch(() => ({ data: [] })),
        api.get(`/students/${studentId}/performance`).catch(() => ({ data: [] })),
        // PR 3 §7.1 — fetch marked scripts for the selected child. Server joins
        // attachments with parent_kind='marked_script'. Endpoint accepts
        // ?student_id= when the caller is a parent.
        api.get(`/assignments/my/submissions`, { params: { student_id: studentId } }).catch(() => ({ data: [] })),
      ]);
      setGradeData(Array.isArray(gradesRes.data) ? gradesRes.data : []);
      setSubjectPerformance(Array.isArray(performanceRes.data) ? performanceRes.data : []);
      const allSubs: any[] = Array.isArray(markedRes.data) ? markedRes.data : [];
      setMarkedScripts(
        allSubs
          .filter(s => s.status === 'returned' && Array.isArray(s.marked_scripts) && s.marked_scripts.length > 0)
          .map(s => ({
            id: s.id,
            assignment_id: s.assignment_id,
            assignment_title: s.assignment_title,
            submitted_at: s.submitted_at,
            graded_at: s.graded_at,
            grade: s.grade,
            status: s.status,
            marked_scripts: s.marked_scripts,
          }))
      );
    } catch (error) {
      console.error('Error loading student data:', error);
      setGradeData([]);
      setSubjectPerformance([]);
      setMarkedScripts([]);
    } finally {
      setLoading(false);
      setLoadingMarkedScripts(false);
    }
  };

  const handleStudentSelect = (student: Student) => {
    setSelectedStudent(student);
    setShowStudentPicker(false);
    loadStudentData(student.id);
  };

  // PR 3 §13 follow-up — listen for marked_script:returned events and
  // re-pull the selected child's submissions so the Marked Scripts
  // section appears/updates within seconds of the teacher clicking
  // "Return" — no reload required. Also fires an optional desktop
  // notification when the user has granted permission.
  useEffect(() => {
    const unsub = useRealtimeStore.getState().subscribe('marked_script:returned', (payload) => {
      const studentId = payload?.data?.student_id;
      if (selectedStudent && studentId === selectedStudent.id) {
        loadStudentData(selectedStudent.id);
      }
      notifyMarkedScript(
        'Marked script returned',
        `A teacher has returned a marked script${selectedStudent ? ` for ${selectedStudent.first_name}` : ''}.`
      );
    });
    return unsub;
    // We intentionally re-subscribe only when selectedStudent changes —
    // loadStudentData is stable enough for our purposes (captures latest
    // selectedStudent.id via closure on next click).
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [selectedStudent?.id]);

  const handleLoadReportCard = async () => {
    if (!selectedStudent) return;
    setLoadingReportCard(true);
    try {
      const res = await api.get(`/students/${selectedStudent.id}/report-card`);
      setReportCard(res.data);
      setShowReportCardModal(true);
    } catch (error) {
      console.error('Error loading report card:', error);
      alert('Could not compile report card. Please try again.');
    } finally {
      setLoadingReportCard(false);
    }
  };

  // CSV export helper
  const handleExportCsv = () => {
    const rows = [
      ['Subject', 'Current Grade', 'Previous Grade', 'Trend', 'Rank', 'Total Students'],
      ...subjectPerformance.map(s => [s.subject, s.currentGrade, s.previousGrade, s.trend, s.rank, s.totalStudents]),
      [],
      ['Period', 'Average', 'Math', 'English', 'Science'],
      ...gradeData.map(g => [g.period, g.avg, g.math ?? '', g.english ?? '', g.science ?? '']),
    ];
    const csv = rows.map(r => r.map(c => `"${String(c).replace(/"/g, '""')}"`).join(',')).join('\n');
    const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `academic-progress-${selectedStudent?.first_name ?? 'report'}-${new Date().toISOString().split('T')[0]}.csv`;
    a.click();
    URL.revokeObjectURL(url);
  };

  const getGradeStyles = (grade: number) => {
    if (grade >= 90) return { text: 'text-emerald-600 dark:text-emerald-400', bg: 'bg-emerald-50 dark:bg-emerald-900/30', border: 'border-emerald-100 dark:border-emerald-800', fill: '#10b981', label: 'Excellent' };
    if (grade >= 80) return { text: 'text-blue-600 dark:text-blue-400', bg: 'bg-blue-50 dark:bg-blue-900/30', border: 'border-blue-100 dark:border-blue-800', fill: '#3b82f6', label: 'Good' };
    if (grade >= 70) return { text: 'text-amber-600 dark:text-amber-400', bg: 'bg-amber-50 dark:bg-amber-900/30', border: 'border-amber-100 dark:border-amber-800', fill: '#f59e0b', label: 'Satisfactory' };
    return { text: 'text-rose-600 dark:text-rose-400', bg: 'bg-rose-50 dark:bg-rose-900/30', border: 'border-rose-100 dark:border-rose-800', fill: '#ef4444', label: 'Needs Support' };
  };

  if (loading) return (
    <div className="flex flex-col justify-center items-center h-[60vh] gap-4 text-text-muted">
      <div className="w-10 h-10 border-4 border-primary border-t-transparent rounded-full animate-spin"></div>
      <p className="font-black uppercase tracking-[3px] text-[0.6rem]">Loading marks...</p>
    </div>
  );

  const hasChildren = students.length > 0;
  const hasGradeData = gradeData.length > 0;
  const hasPerformanceData = subjectPerformance.length > 0;

  const currentAvg = hasGradeData ? gradeData[gradeData.length - 1].avg : 0;
  const hasImprovementData = gradeData.length >= 2;
  const improvement = hasImprovementData
    ? gradeData[gradeData.length - 1].avg - gradeData[0].avg
    : 0;

  const dash = '—';

  const statTiles = [
    {
      label: 'Term Average',
      value: hasGradeData ? `${currentAvg.toFixed(1)}%` : dash,
      icon: BarChart3,
      color: 'blue',
      trend: hasGradeData ? 'All subjects' : 'No marks yet',
    },
    {
      label: 'Class Position',
      value: hasPerformanceData && subjectPerformance[0].rank != null ? `${subjectPerformance[0].rank}` : dash,
      icon: GraduationCap,
      color: 'emerald',
      trend: hasPerformanceData ? `of ${subjectPerformance[0].totalStudents}` : 'No data',
    },
    {
      label: 'Total Marks',
      value: dash,
      icon: Award,
      color: 'purple',
      trend: 'this term',
    },
    {
      label: 'Term-on-Term Change',
      value: hasImprovementData
        ? `${improvement >= 0 ? '+' : ''}${improvement.toFixed(1)}%`
        : dash,
      icon: TrendingUp,
      color: improvement >= 0 ? 'emerald' : 'rose',
      trend: hasImprovementData ? 'since last term' : 'No data',
    },
  ];

  if (!hasChildren) {
    return (
      <div className="space-y-10 animate-in fade-in duration-700 pb-10">
        <div className="flex flex-col xl:flex-row justify-between items-start xl:items-end gap-6 no-print">
          <div className="space-y-1">
            <div className="flex items-center gap-3 mb-2">
              <div className="p-2 bg-blue-50/10 rounded-xl text-primary">
                <Target size={20} />
              </div>
              <span className="text-[0.65rem] font-black uppercase tracking-[3px] text-text-muted">Guardian Oversight</span>
            </div>
            <h1 className="text-4xl font-black text-text tracking-tighter text-capitalize dark:text-white">Academic Progress</h1>
            <p className="text-text-muted text-lg font-medium">Term marks, assessments, and exam results for your children.</p>
          </div>
        </div>

        <div className="bg-card border border-border rounded-[2.5rem] shadow-sm">
          <EmptyState
            icon={Users}
            title="No learners linked yet"
            description="Once students are associated with your guardian account, their grades, subject performance and rankings will surface here."
          />
        </div>
      </div>
    );
  }

  return (
    <div className="space-y-10 animate-in fade-in duration-700 pb-10">
      {/* Premium Header */}
      <div className="flex flex-col xl:flex-row justify-between items-start xl:items-end gap-6 no-print">
        <div className="space-y-1">
          <div className="flex items-center gap-3 mb-2">
            <div className="p-2 bg-blue-50/10 rounded-xl text-primary">
              <Target size={20} />
            </div>
            <span className="text-[0.65rem] font-black uppercase tracking-[3px] text-text-muted">Guardian Oversight</span>
          </div>
          <h1 className="text-4xl font-black text-text tracking-tighter text-capitalize dark:text-white">Academic Progress</h1>
          <p className="text-text-muted text-lg font-medium">Term marks, assessments, and exam results for your children.</p>
        </div>

        <div className="flex flex-wrap items-center gap-3">
          {/* Student Picker */}
          <div className="relative">
            <button
                onClick={() => setShowStudentPicker(!showStudentPicker)}
                className="flex items-center gap-3 px-5 py-2.5 bg-card border border-border text-text rounded-xl font-bold text-sm hover:bg-muted/50 transition-all shadow-sm active:scale-95"
            >
                <div className="w-8 h-8 rounded-lg bg-blue-50 dark:bg-blue-900/30 flex items-center justify-center text-primary dark:text-blue-400 text-xs font-black shadow-inner border border-blue-100 dark:border-blue-800">
                    {selectedStudent?.first_name[0]}{selectedStudent?.last_name[0]}
                </div>
                <span className="hidden sm:inline">{selectedStudent?.first_name} {selectedStudent?.last_name}</span>
                <ChevronDown size={16} className={`text-text-muted/30 transition-transform ${showStudentPicker ? 'rotate-180' : ''}`} />
            </button>

            {showStudentPicker && (
                <div className="absolute right-0 top-full mt-3 w-64 bg-card border border-border rounded-2xl shadow-2xl z-[100] p-2 animate-in zoom-in-95 duration-200">
                    <p className="text-[0.6rem] font-black uppercase tracking-widest text-text-muted px-4 py-2">Associated Learners</p>
                    {students.map(s => (
                        <button
                            key={s.id}
                            onClick={() => handleStudentSelect(s)}
                            className={`w-full flex items-center gap-3 p-3 rounded-xl transition-all ${selectedStudent?.id === s.id ? 'bg-primary/5' : 'hover:bg-muted/50'}`}
                        >
                            <div className="w-10 h-10 rounded-xl bg-muted dark:bg-muted/20 border border-border flex items-center justify-center text-primary dark:text-blue-400 text-xs font-black shadow-sm">
                                {s.first_name[0]}{s.last_name[0]}
                            </div>
                            <div className="text-left">
                                <p className="text-sm font-bold text-text">{s.first_name} {s.last_name}</p>
                                <p className="text-[0.6rem] text-text-muted font-bold uppercase">{s.grade}</p>
                            </div>
                        </button>
                    ))}
                </div>
            )}
          </div>

          <button onClick={handleLoadReportCard} disabled={loadingReportCard} className="flex items-center gap-2 px-5 py-2.5 bg-emerald-600 hover:bg-emerald-700 disabled:opacity-50 text-white rounded-xl font-bold text-sm transition-all shadow-lg active:scale-95">
            {loadingReportCard ? (
              <div className="w-4 h-4 border-2 border-white border-t-transparent rounded-full animate-spin"></div>
            ) : (
              <Printer size={18} />
            )}
            Report Card
          </button>

          <button onClick={handleExportCsv} className="flex items-center gap-2 px-5 py-2.5 bg-primary text-white rounded-xl font-bold text-sm hover:bg-primary/90 transition-all shadow-lg active:scale-95">
            <Download size={18} />
            Export Intel
          </button>
        </div>
      </div>

      {/* Bento Stats Grid */}
      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
        {statTiles.map((stat) => (
          <div key={stat.label} className="bg-card border border-border p-6 rounded-[2rem] shadow-sm relative overflow-hidden group hover:shadow-md transition-all">
            <div className="relative z-10 flex justify-between items-start mb-4">
              <div className={`p-3 rounded-2xl
                ${stat.color === 'blue' ? 'bg-blue-50 dark:bg-blue-900/20 text-blue-600 dark:text-blue-400 border-blue-100 dark:border-blue-800' :
                  stat.color === 'emerald' ? 'bg-emerald-50 dark:bg-emerald-900/20 text-emerald-600 dark:text-emerald-400 border-emerald-100 dark:border-emerald-800' :
                  stat.color === 'purple' ? 'bg-purple-50 dark:bg-purple-900/20 text-purple-600 dark:text-purple-400 border-purple-100 dark:border-purple-800' :
                  'bg-rose-50 dark:bg-rose-900/20 text-rose-600 dark:text-rose-400 border-rose-100 dark:border-rose-800'}
                group-hover:scale-110 transition-transform border`}>
                <stat.icon size={24} />
              </div>
              <div className="text-[0.65rem] font-black px-3 py-1 bg-muted text-text-muted rounded-full border border-border uppercase tracking-widest">
                {stat.trend}
              </div>
            </div>
            <p className="text-[0.65rem] font-black uppercase tracking-[2px] text-text-muted mb-1">{stat.label}</p>
            <h3 className={`text-3xl font-black tracking-tighter ${stat.color === 'rose' ? 'text-rose-600 dark:text-rose-400' : 'text-text'}`}>{stat.value}</h3>
          </div>
        ))}
      </div>

      {/* Main Analysis Section */}
      <div className="grid grid-cols-1 lg:grid-cols-12 gap-8">

        {/* Progression Trend (Area Chart) */}
        <div className="lg:col-span-8 space-y-6">
          <div className="bg-card border border-border rounded-[2.5rem] p-10 shadow-sm relative overflow-hidden group">
            <div className="absolute top-0 left-0 w-full h-1 bg-gradient-to-r from-blue-500/0 via-blue-500 to-blue-500/0 opacity-50"></div>
            <div className="flex justify-between items-start mb-10 relative z-10">
              <div>
                <h4 className="text-[0.65rem] font-black uppercase tracking-[3px] text-primary/50 mb-2">Subject Averages</h4>
                <h2 className="text-2xl font-black text-text tracking-tight">Academic Progression Trend</h2>
              </div>
              <div className="flex gap-4">
                <div className="flex items-center gap-2">
                  <div className="w-2 h-2 rounded-full bg-primary"></div>
                  <span className="text-[0.65rem] font-black text-text-muted uppercase tracking-widest">Term Average</span>
                </div>
              </div>
            </div>

            {hasGradeData ? (
              <div className="h-[350px] w-full relative z-10">
                <ResponsiveContainer width="100%" height="100%">
                  <AreaChart data={gradeData} margin={{ top: 10, right: 10, left: -20, bottom: 0 }}>
                    <defs>
                      <linearGradient id="colorAvg" x1="0" y1="0" x2="0" y2="1">
                        <stop offset="5%" stopColor="#3b82f6" stopOpacity={0.3}/>
                        <stop offset="95%" stopColor="#3b82f6" stopOpacity={0}/>
                      </linearGradient>
                    </defs>
                    <CartesianGrid vertical={false} strokeDasharray="3 3" stroke="currentColor" className="text-border/30" />
                    <XAxis dataKey="period" axisLine={false} tickLine={false} tick={{ fill: 'currentColor', fontSize: 10, fontWeight: 900 }} className="text-text-muted" dy={15} />
                    <YAxis domain={[0, 100]} axisLine={false} tickLine={false} tick={{ fill: 'currentColor', fontSize: 10, fontWeight: 900 }} className="text-text-muted" />
                    <Tooltip content={<CustomTooltip />} cursor={{ stroke: 'currentColor', className: 'text-border', strokeWidth: 2, strokeDasharray: '4 4' }} />
                    <Area type="monotone" dataKey="avg" stroke="#3b82f6" strokeWidth={4} fillOpacity={1} fill="url(#colorAvg)" animationDuration={1500} name="Average mark" />
                  </AreaChart>
                </ResponsiveContainer>
              </div>
            ) : (
              <EmptyState
                icon={BarChart3}
                title="No grades recorded"
                description="Once assessments are entered for this learner, the progression trend will plot here."
              />
            )}
          </div>

          {/* Mark Book by Subject */}
          <div className="bg-card border border-border rounded-[2.5rem] shadow-sm overflow-hidden flex flex-col">
            <div className="p-8 bg-muted/50 border-b border-border flex flex-col md:flex-row justify-between items-start md:items-center gap-4">
              <div>
                <h3 className="text-[0.7rem] font-black uppercase tracking-[3px] text-text">Mark Book</h3>
                <p className="text-[0.6rem] font-bold text-text-muted uppercase mt-1">Current subject standings and rankings</p>
              </div>
              <button onClick={() => window.print()} className="text-primary text-[0.65rem] font-black hover:underline uppercase tracking-widest">Full Portfolio</button>
            </div>

            {hasPerformanceData ? (
              <div className="overflow-x-auto">
                <table className="w-full text-left">
                  <thead>
                    <tr className="bg-muted/80 border-b border-border">
                      <th className="px-8 py-5 text-[0.6rem] font-black text-text-muted uppercase tracking-widest">Subject Division</th>
                      <th className="px-8 py-5 text-[0.6rem] font-black text-text-muted uppercase tracking-widest text-center">Current Mark</th>
                      <th className="px-8 py-5 text-[0.6rem] font-black text-text-muted uppercase tracking-widest text-center">Peer Rank</th>
                      <th className="px-8 py-5 text-[0.6rem] font-black text-text-muted uppercase tracking-widest text-right">Trend</th>
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-border">
                    {subjectPerformance.map((subject, idx) => {
                      const styles = getGradeStyles(subject.currentGrade);
                      return (
                        <tr key={idx} className="hover:bg-muted/30 transition-colors group">
                          <td className="px-8 py-5">
                            <div className="flex items-center gap-4">
                              <div className="w-12 h-12 rounded-2xl bg-muted dark:bg-muted/20 flex items-center justify-center text-[0.8rem] font-black text-blue-400 dark:text-blue-400 shadow-inner group-hover:scale-110 transition-transform border border-border">
                                {subject.subject[0]}
                              </div>
                              <div>
                                <p className="text-[0.9rem] font-bold text-text group-hover:text-primary transition-colors">{subject.subject}</p>
                                <p className="text-[0.6rem] font-black text-text-muted uppercase tracking-widest mt-0.5">Academic Record</p>
                              </div>
                            </div>
                          </td>
                          <td className="px-8 py-5 text-center">
                            <div className="inline-flex items-center gap-3">
                              <span className={`text-lg font-black ${styles.text}`}>{subject.currentGrade}%</span>
                              <div className={`px-2.5 py-0.5 rounded-lg font-black text-[0.6rem] uppercase tracking-widest ${styles.bg} ${styles.text} border ${styles.border} shadow-sm`}>
                                {styles.label}
                              </div>
                            </div>
                          </td>
                          <td className="px-8 py-5 text-center">
                             <div className="bg-muted/50 dark:bg-muted/20 inline-block px-3 py-1.5 rounded-xl border border-border">
                               <span className="text-[0.8rem] font-black text-text">#{subject.rank}</span>
                               <span className="text-[0.6rem] text-text-muted font-bold ml-1">/ {subject.totalStudents}</span>
                              </div>
                          </td>
                          <td className="px-8 py-5 text-right">
                             <div className={`inline-flex items-center gap-1.5 px-3 py-1.5 rounded-xl text-[0.65rem] font-black uppercase tracking-widest border ${subject.trend === 'up' ? 'bg-emerald-50 dark:bg-emerald-900/30 text-emerald-600 dark:text-emerald-400 border-emerald-100 dark:border-emerald-800' : subject.trend === 'down' ? 'bg-rose-50 dark:bg-rose-900/30 text-rose-600 dark:text-rose-400 border-rose-100 dark:border-rose-800' : 'bg-muted text-text-muted border-border'}`}>
                               {subject.trend === 'up' ? <ArrowUpRight size={14} /> : subject.trend === 'down' ? <ArrowDownRight size={14} /> : <Activity size={14} />}
                               {subject.trend}
                             </div>
                          </td>
                        </tr>
                      );
                    })}
                  </tbody>
                </table>
              </div>
            ) : (
              <EmptyState
                icon={BookOpen}
                title="No subject performance yet"
                description="Subject standings and peer rankings will appear here once results are published."
              />
            )}
          </div>
        </div>

        {/* Right Sidebar Analysis */}
        <div className="lg:col-span-4 space-y-8">

            {/* Subject Comparison (Bar Chart) */}
            <div className="bg-card border border-border rounded-[2.5rem] p-8 shadow-sm">
                <div className="flex items-center justify-between mb-8">
                    <h4 className="text-[0.7rem] font-black uppercase tracking-[3px] text-text">Peer Benchmarking</h4>
                    <BarChart3 size={18} className="text-text-muted/30" />
                </div>
                {hasPerformanceData ? (
                  <>
                    <div className="h-[250px] w-full">
                        <ResponsiveContainer width="100%" height="100%">
                            <BarChart data={subjectPerformance} layout="vertical" margin={{ left: -30, right: 10 }}>
                                <XAxis type="number" hide />
                                <YAxis type="category" dataKey="subject" tick={{ fill: 'currentColor', fontSize: 10, fontWeight: 800 }} axisLine={false} tickLine={false} width={80} className="text-text-muted" />
                                <Tooltip content={<CustomTooltip />} cursor={{ fill: 'currentColor', className: 'text-muted/10' }} />
                                <Bar dataKey="currentGrade" fill="#0047AB" radius={[0, 6, 6, 0]} barSize={20} name="Current mark" />
                            </BarChart>
                        </ResponsiveContainer>
                    </div>
                    <p className="text-[0.65rem] text-text-muted font-medium text-center mt-6 italic">Visualizing subject-wise proficiency against system standards.</p>
                  </>
                ) : (
                  <EmptyState
                    icon={BarChart3}
                    title="No benchmarking data"
                    description="Subject proficiency benchmarks will render here once results are available."
                  />
                )}
            </div>

            {/* AI Assistant Card */}
            <div className="bg-[#002147] rounded-[2.5rem] p-10 text-white shadow-2xl relative overflow-hidden group">
                <div className="absolute right-[-40px] bottom-[-40px] opacity-10 group-hover:rotate-12 transition-transform duration-700">
                    <Sparkles size={200} strokeWidth={1} />
                </div>
                <div className="relative z-10">
                    <div className="flex items-center gap-3 mb-6">
                        <div className="p-2.5 bg-white/10 rounded-xl backdrop-blur-md text-blue-400">
                            <GraduationCap size={20} />
                        </div>
                        <span className="text-[0.65rem] font-black uppercase tracking-[3px] text-white/40">Class Teacher Note</span>
                    </div>
                    <h4 className="text-xl font-black mb-3 leading-tight tracking-tight uppercase">{selectedStudent?.first_name}'s progress is accelerating.</h4>
                    <p className="text-sm font-medium text-blue-50/70 leading-relaxed mb-8">
                        Marks in <span className="text-white font-black">Pure Sciences</span> have improved this term. The class teacher recommends extra practice on the next topic.
                    </p>
                    <button onClick={() => navigate('/calendar')} className="w-full py-4 bg-white/10 hover:bg-white/20 text-white rounded-xl text-[0.65rem] font-black uppercase tracking-widest transition-all border border-white/10">
                        View Study Briefing
                    </button>
                </div>
            </div>

            {/* Security/Trust Card */}
            <div className="bg-emerald-50 border border-emerald-100 dark:bg-emerald-500/10 dark:border-emerald-500/20 rounded-[2rem] p-8 flex items-center gap-6 relative overflow-hidden">
                <div className="absolute -right-6 -bottom-6 opacity-10">
                    <ShieldCheck size={120} className="text-emerald-600" />
                </div>
                <div className="w-14 h-14 rounded-2xl bg-card border border-border flex items-center justify-center text-emerald-600 shadow-sm shrink-0">
                    <ShieldCheck size={28} />
                </div>
                <div>
                    <p className="text-sm font-black text-emerald-800 dark:text-emerald-500">Marks Confirmed</p>
                    <p className="text-[0.7rem] font-medium text-emerald-600/80 leading-snug mt-1">All academic records are digitally signed and verified by the school administration.</p>
                </div>
            </div>
        </div>
      </div>

      {/* PR 3 §7.1 — Marked Scripts section. Lists every returned assignment
          for the selected child that has at least one marked_script
          attachment. Each row exposes preview + download links (same
          /api/uploads/<stored_filename> static path used elsewhere). */}
      {hasChildren && (
        <div className="bg-card border border-border rounded-[2.5rem] shadow-sm overflow-hidden">
          <div className="p-8 bg-muted/50 border-b border-border flex flex-col md:flex-row justify-between items-start md:items-center gap-4">
            <div className="flex items-center gap-3">
              <div className="w-10 h-10 rounded-xl bg-emerald-50 dark:bg-emerald-500/10 text-emerald-600 flex items-center justify-center border border-emerald-100 dark:border-emerald-500/30">
                <FileCheck size={20} />
              </div>
              <div>
                <h3 className="text-[0.7rem] font-black uppercase tracking-[3px] text-text">Marked Scripts</h3>
                <p className="text-[0.6rem] font-bold text-text-muted uppercase mt-1">
                  Scripts returned by teachers for {selectedStudent?.first_name}
                </p>
              </div>
            </div>
            <span className="text-[0.65rem] font-black px-3 py-1 bg-emerald-50 text-emerald-700 border border-emerald-100 rounded-full uppercase tracking-widest">
              {markedScripts.length} {markedScripts.length === 1 ? 'script' : 'scripts'}
            </span>
          </div>

          {markedScripts.length === 0 ? (
            <EmptyState
              icon={FileCheck}
              title="No marked scripts yet"
              description="Once a teacher returns work with a marked script attached, it will appear here for review."
            />
          ) : (
            <div className="divide-y divide-border">
              {markedScripts.map(row => (
                <div key={row.id} className="p-6 sm:p-7 space-y-4">
                  <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-2">
                    <div className="min-w-0">
                      <h4 className="text-base font-black text-text truncate">{row.assignment_title}</h4>
                      <p className="text-[0.65rem] font-bold text-text-muted uppercase tracking-widest mt-1">
                        Returned {row.graded_at ? new Date(row.graded_at).toLocaleDateString() : 'recently'}
                        {row.grade != null && (
                          <span className="ml-3 inline-flex items-center gap-1 text-purple-600">
                            <Award size={11} /> {row.grade}
                          </span>
                        )}
                      </p>
                    </div>
                  </div>
                  <div className="space-y-2">
                    {row.marked_scripts.map(att => (
                      <div key={att.uid} className="flex items-center gap-3 p-3 sm:p-4 bg-muted/30 border border-border rounded-2xl">
                        <div className="w-10 h-10 rounded-xl bg-card border border-border flex items-center justify-center text-text-muted shrink-0">
                          <FileText size={18} />
                        </div>
                        <div className="min-w-0 flex-1">
                          <p className="text-sm font-bold text-text truncate">{att.original_filename}</p>
                          <p className="text-[0.65rem] font-bold text-text-muted uppercase tracking-widest">
                            {(att.size_bytes / 1024).toFixed(1)} KB · {new Date(att.uploaded_at).toLocaleDateString()}
                          </p>
                        </div>
                        <button
                          type="button"
                          onClick={async () => {
                            setPreviewScript(att);
                            setPreviewLoading(true);
                            setPreviewUrl(null);
                            try {
                              const metaRes = await api.get(`/attachments/${att.uid}`);
                              const blobRes = await api.get(`/uploads/${encodeURIComponent(metaRes.data.stored_filename)}`, { responseType: 'blob' });
                              setPreviewUrl(URL.createObjectURL(blobRes.data));
                            } catch (err) {
                              console.error('Preview failed:', err);
                            } finally {
                              setPreviewLoading(false);
                            }
                          }}
                          className="p-2 rounded-xl text-text-muted hover:text-primary hover:bg-blue-50 transition-colors"
                          aria-label={`Preview ${att.original_filename}`}
                        >
                          <Eye size={16} />
                        </button>
                        <a
                          href={`/api/uploads/${encodeURIComponent(att.stored_filename)}`}
                          download={att.original_filename}
                          className="p-2 rounded-xl text-text-muted hover:text-primary hover:bg-blue-50 transition-colors"
                          aria-label={`Download ${att.original_filename}`}
                        >
                          <Download size={16} />
                        </a>
                      </div>
                    ))}
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>
      )}

      {showReportCardModal && reportCard && (
        <Modal
          open={true}
          onClose={() => setShowReportCardModal(false)}
          title="Academic Report Card Compilation"
          icon={FileText}
          maxWidth="max-w-4xl"
          zIndex={200}
        >
          <ModalBody className="p-0">

            {/* Printable Report Card Document Content */}
            <div className="p-4 sm:p-8 md:p-10 overflow-y-auto flex-1 custom-scrollbar print-document">
              <div className="space-y-6 sm:space-y-8">
                {/* School Header */}
                <div className="flex flex-col sm:flex-row justify-between items-start border-b-2 border-primary/20 pb-4 sm:pb-6 gap-4">
                  <div>
                    <h2 className="text-2xl sm:text-3xl font-black text-text tracking-tighter uppercase">NextGen Academy</h2>
                    <p className="text-[0.65rem] font-bold text-text-muted uppercase tracking-[3px] mt-1">Smart School Management Platform</p>
                    <p className="text-xs text-text-secondary font-medium mt-1">Harare, Zimbabwe | +263 242 700000</p>
                  </div>
                  <div className="text-left sm:text-right">
                    <div className="inline-block bg-primary/10 text-primary px-4 py-1.5 rounded-full border border-primary/20 text-[0.65rem] font-black uppercase tracking-widest">
                      Official Document
                    </div>
                    <p className="text-xs text-text-muted font-bold mt-2 uppercase">{reportCard.term} • {reportCard.student.academic_year}</p>
                  </div>
                </div>

                {/* Student Profile Block */}
                <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-4 gap-4 bg-muted/30 p-4 sm:p-6 rounded-2xl border border-border">
                  <div>
                    <p className="text-[0.6rem] font-black uppercase tracking-widest text-text-muted">Student Name</p>
                    <p className="text-sm font-bold text-text mt-0.5">{reportCard.student.first_name} {reportCard.student.last_name}</p>
                  </div>
                  <div>
                    <p className="text-[0.6rem] font-black uppercase tracking-widest text-text-muted">Class & Section</p>
                    <p className="text-sm font-bold text-text mt-0.5">{reportCard.student.class_name}</p>
                  </div>
                  <div>
                    <p className="text-[0.6rem] font-black uppercase tracking-widest text-text-muted">Roll Number</p>
                    <p className="text-sm font-bold text-text mt-0.5">{reportCard.student.roll_number}</p>
                  </div>
                  <div>
                    <p className="text-[0.6rem] font-black uppercase tracking-widest text-text-muted">Attendance Summary</p>
                    <p className="text-sm font-bold text-text mt-0.5">{reportCard.attendance.present}/{reportCard.attendance.total} ({reportCard.attendance.percentage}%)</p>
                  </div>
                </div>

                {/* Performance Summarys Table */}
                <div className="border border-border rounded-2xl overflow-x-auto shadow-sm min-w-0 custom-scrollbar">
                  <table className="w-full text-left min-w-[560px]">
                    <thead>
                      <tr className="bg-muted border-b border-border">
                        <th className="px-6 py-4 text-[0.6rem] font-black text-text-muted uppercase tracking-widest">Subject Division</th>
                        <th className="px-4 py-4 text-[0.6rem] font-black text-text-muted uppercase tracking-widest text-center">Assignments (30%)</th>
                        <th className="px-4 py-4 text-[0.6rem] font-black text-text-muted uppercase tracking-widest text-center">Online Exams (30%)</th>
                        <th className="px-4 py-4 text-[0.6rem] font-black text-text-muted uppercase tracking-widest text-center">Written Tests (40%)</th>
                        <th className="px-4 py-4 text-[0.6rem] font-black text-text-muted uppercase tracking-widest text-center">Final Mark</th>
                        <th className="px-4 py-4 text-[0.6rem] font-black text-text-muted uppercase tracking-widest text-center">Grade</th>
                      </tr>
                    </thead>
                    <tbody className="divide-y divide-border">
                      {reportCard.academic_records.map((record, idx) => (
                        <tr key={idx} className="hover:bg-muted/10 transition-colors">
                          <td className="px-6 py-4">
                            <div>
                              <p className="text-sm font-bold text-text">{record.subject}</p>
                              <p className="text-[0.6rem] text-text-muted mt-0.5">Instructor: {record.teacher_name}</p>
                            </div>
                          </td>
                          <td className="px-4 py-4 text-center font-semibold text-xs text-text-secondary">{record.assignment_avg}%</td>
                          <td className="px-4 py-4 text-center font-semibold text-xs text-text-secondary">{record.exam_avg}%</td>
                          <td className="px-4 py-4 text-center font-semibold text-xs text-text-secondary">{record.test_avg}%</td>
                          <td className="px-4 py-4 text-center font-black text-sm text-text">{record.overall_mark}%</td>
                          <td className="px-4 py-4 text-center">
                            <GradeBadge
                              percentage={record.overall_mark}
                              gradingScale={(record as any).grading_scale ?? null}
                              band={(record as any).resolved_scale ? {
                                letter: record.grade,
                                scale: { key: (record as any).resolved_scale, label: '' },
                              } : null}
                            />
                          </td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>

                {/* Subject Remarks */}
                <div className="space-y-3">
                  <h4 className="text-[0.65rem] font-black uppercase tracking-widest text-text-muted">Instructor Remarks per Division</h4>
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                    {reportCard.academic_records.map((record, idx) => (
                      <div key={idx} className="border border-border p-4 rounded-xl space-y-1 bg-muted/10">
                        <p className="text-[0.65rem] font-black uppercase tracking-wider text-primary">{record.subject}</p>
                        <p className="text-xs text-text-secondary italic">"{record.remarks}"</p>
                      </div>
                    ))}
                  </div>
                </div>

                {/* Overall Performance & Recommendations */}
                <div className="bg-primary/5 border border-primary/10 p-6 rounded-2xl flex flex-col md:flex-row justify-between items-start md:items-center gap-6">
                  <div>
                    <p className="text-[0.6rem] font-black uppercase tracking-widest text-primary/70">Principal's Review Remarks</p>
                    <p className="text-xs text-text font-semibold italic mt-1">"{reportCard.overall.principal_remarks}"</p>
                  </div>
                  <div className="flex gap-4 shrink-0">
                    <div className="text-center bg-card border border-border px-4 py-2.5 rounded-xl min-w-[90px] shadow-sm">
                      <p className="text-[0.55rem] font-black uppercase tracking-widest text-text-muted">Avg Score</p>
                      <p className="text-lg font-black text-primary mt-0.5">{reportCard.overall.average_mark}%</p>
                    </div>
                    <div className="text-center bg-card border border-border px-4 py-2.5 rounded-xl min-w-[90px] shadow-sm">
                      <p className="text-[0.55rem] font-black uppercase tracking-widest text-text-muted">Grade</p>
                      <p className="mt-0.5 flex justify-center">
                        <GradeBadge
                          percentage={reportCard.overall.average_mark}
                          gradingScale={(reportCard.overall as any).grading_scale ?? null}
                          band={(reportCard.overall as any).resolved_scale ? {
                            letter: reportCard.overall.final_grade,
                            scale: { key: (reportCard.overall as any).resolved_scale, label: '' },
                          } : null}
                        />
                      </p>
                    </div>
                  </div>
                </div>

                {/* Signature Block */}
                <div className="pt-10 flex justify-between border-t border-border mt-8">
                  <div className="text-center w-48">
                    <div className="h-10 border-b border-text-muted/30"></div>
                    <p className="text-[0.6rem] font-black uppercase tracking-widest text-text-muted mt-2">Class Teacher Signature</p>
                  </div>
                  <div className="text-center w-48">
                    <div className="h-10 border-b border-text-muted/30"></div>
                    <p className="text-[0.6rem] font-black uppercase tracking-widest text-text-muted mt-2">Principal Signature</p>
                  </div>
                </div>

              </div>
            </div>
          </ModalBody>
        </Modal>
      )}

      <style>{PRINT_CSS}</style>

      {/* PR 3 §7.1 — preview modal for a marked script attachment. Native
          <iframe> / <img> per §4.3; blob URL is revoked on close. */}
      {previewScript && (
        <Modal
          open={true}
          onClose={() => {
            if (previewUrl) URL.revokeObjectURL(previewUrl);
            setPreviewUrl(null);
            setPreviewScript(null);
          }}
          title={previewScript.original_filename}
          maxWidth="max-w-4xl"
          zIndex={300}
        >
          <ModalBody className="p-0">
            <div
              className="flex-1 overflow-auto bg-[#002147]/5 p-4 flex items-center justify-center min-h-[300px]"
              onClick={(e) => e.stopPropagation()}
            >
              {previewLoading ? (
                <Loader2 size={32} className="animate-spin text-primary" />
              ) : previewUrl ? (
                previewScript.mime_type.startsWith('image/') ? (
                  <img
                    src={previewUrl}
                    alt={previewScript.original_filename}
                    className="max-w-full max-h-[70vh] object-contain rounded-2xl shadow-lg"
                  />
                ) : (
                  <iframe
                    src={previewUrl}
                    title={previewScript.original_filename}
                    className="w-full h-[70vh] bg-card rounded-2xl border border-border"
                  />
                )
              ) : (
                <p className="text-sm text-rose-600 font-bold">Could not load preview.</p>
              )}
            </div>
          </ModalBody>
        </Modal>
      )}
    </div>
  );
}
