"use client";

import React, { useState, useEffect, useMemo, useCallback } from "react";
import {
  Search,
  Printer,
  FileSpreadsheet,
  Users,
  GraduationCap,
  Calendar,
  CheckCircle2,
  AlertTriangle,
  Award,
  BookOpen,
  Sparkles,
  ShieldAlert,
  UserCheck,
  RefreshCw,
  Phone,
  MapPin,
  HeartHandshake,
  TrendingUp,
} from "lucide-react";
import { Button } from "@/components/ui/Button";
import { Select } from "@/components/ui/Select";
import { StatCard } from "@/components/ui/StatCard";
import { getAcademicYearOptions } from "@/lib/academicYear";
import { CetakProfilSiswaPrintModal, StudentProfileData } from "./CetakProfilSiswaPrintModal";
import * as XLSX from "xlsx";

const AVAILABLE_CLASSES = [
  "X-1", "X-2", "X-3", "X-4", "X-5", "X-6", "X-7", "X-8", "X-9", "X-10",
  "XI-1", "XI-2", "XI-3", "XI-4", "XI-5", "XI-6", "XI-7", "XI-8", "XI-9", "XI-10",
  "XII-1", "XII-2", "XII-3", "XII-4", "XII-5", "XII-6", "XII-7", "XII-8", "XII-9", "XII-10",
];

const SEMESTER_OPTIONS = ["Ganjil", "Genap"];

export const CetakProfilSiswaView: React.FC = () => {
  // Academic Years
  const academicYearOptions = useMemo(() => {
    const list = getAcademicYearOptions();
    if (!list.includes("2025/2026")) list.unshift("2025/2026");
    if (!list.includes("2027/2028")) list.push("2027/2028");
    return list;
  }, []);

  // Filter States
  const [selectedAcademicYear, setSelectedAcademicYear] = useState<string>("2026/2027");
  const [selectedSemester, setSelectedSemester] = useState<"Ganjil" | "Genap">("Ganjil");
  const [selectedClass, setSelectedClass] = useState<string>("XII-6");
  const [selectedStudentNis, setSelectedStudentNis] = useState<string>("");
  const [searchStudentText, setSearchStudentText] = useState<string>("");

  // Data States
  const [classStudents, setClassStudents] = useState<any[]>([]);
  const [isLoadingClassStudents, setIsLoadingClassStudents] = useState<boolean>(false);
  const [profileData, setProfileData] = useState<StudentProfileData | null>(null);
  const [isLoadingProfile, setIsLoadingProfile] = useState<boolean>(false);

  // Modal State
  const [isPrintModalOpen, setIsPrintModalOpen] = useState<boolean>(false);

  // 1. Fetch Student List when selectedClass changes
  const fetchStudentsForClass = useCallback(async (className: string) => {
    if (!className) return;
    setIsLoadingClassStudents(true);
    try {
      const res = await fetch(`/api/cetak-profil-siswa?class_name=${encodeURIComponent(className)}`);
      const json = await res.json();
      if (json.success && Array.isArray(json.students)) {
        setClassStudents(json.students);
        // Automatically select the first student in the class if none selected or if selected student is not in this class
        if (json.students.length > 0) {
          const currentExists = json.students.some((s: any) => s.nis === selectedStudentNis);
          if (!currentExists) {
            setSelectedStudentNis(json.students[0].nis);
          }
        } else {
          setSelectedStudentNis("");
          setProfileData(null);
        }
      }
    } catch (err) {
      console.error("Gagal memuat daftar siswa rombel:", err);
    } finally {
      setIsLoadingClassStudents(false);
    }
  }, [selectedStudentNis]);

  useEffect(() => {
    fetchStudentsForClass(selectedClass);
  }, [selectedClass, fetchStudentsForClass]);

  // 2. Fetch Full Profile when selectedStudentNis, academicYear, or semester changes
  const fetchStudentProfile = useCallback(async (nis: string) => {
    if (!nis) {
      setProfileData(null);
      return;
    }
    setIsLoadingProfile(true);
    try {
      const url = `/api/cetak-profil-siswa?nis=${encodeURIComponent(nis)}&academic_year=${encodeURIComponent(selectedAcademicYear)}&semester=${encodeURIComponent(selectedSemester)}&class_name=${encodeURIComponent(selectedClass)}`;
      const res = await fetch(url);
      const json = await res.json();
      if (json.success && json.data) {
        setProfileData(json.data);
      } else {
        setProfileData(null);
      }
    } catch (err) {
      console.error("Gagal memuat profil kumulatif siswa:", err);
      setProfileData(null);
    } finally {
      setIsLoadingProfile(false);
    }
  }, [selectedAcademicYear, selectedSemester, selectedClass]);

  useEffect(() => {
    if (selectedStudentNis) {
      fetchStudentProfile(selectedStudentNis);
    }
  }, [selectedStudentNis, fetchStudentProfile]);

  // Handle Ctrl+P / Cmd+P to open print modal when profile is loaded
  useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
      if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === "p") {
        if (profileData && !isPrintModalOpen) {
          e.preventDefault();
          setIsPrintModalOpen(true);
        }
      }
    };
    window.addEventListener("keydown", handleKeyDown);
    return () => window.removeEventListener("keydown", handleKeyDown);
  }, [profileData, isPrintModalOpen]);

  // Filtered Students for Dropdown Autocomplete
  const filteredStudents = useMemo(() => {
    if (!searchStudentText.trim()) return classStudents;
    const term = searchStudentText.toLowerCase();
    return classStudents.filter(
      (s) =>
        s.nama_lengkap.toLowerCase().includes(term) ||
        (s.nis && s.nis.toLowerCase().includes(term)) ||
        (s.nisn && s.nisn.toLowerCase().includes(term))
    );
  }, [classStudents, searchStudentText]);

  // Handle Export Excel
  const handleExportExcel = () => {
    if (!profileData) return;
    const { student, meta, homeroom_teacher, school_principal, attendance, academic, activities, discipline } = profileData;
    const wb = XLSX.utils.book_new();

    // 1. Data Induk Sheet
    const biodataRows = [
      ["LEMBAR PROFIL KUMULATIF SISWA — SMA BPI 1 BANDUNG"],
      ["Tahun Ajaran", meta.academic_year, "Semester", meta.semester],
      [""],
      ["A. BIODATA & DATA INDUK SISWA"],
      ["Nama Lengkap", student.nama_lengkap],
      ["Nomor Induk Siswa (NIS)", student.nis],
      ["NISN", student.nisn],
      ["Kelas / Rombel", student.rombel],
      ["Tempat, Tanggal Lahir", `${student.tempat_lahir}, ${student.tanggal_lahir}`],
      ["Jenis Kelamin", student.jenis_kelamin],
      ["Agama", student.agama],
      ["Nama Orang Tua / Wali", student.nama_ortu_wali],
      ["No. HP / WhatsApp", student.no_wa_ortu],
      ["Alamat", student.alamat],
      ["Rencana Studi / Karir", `${student.rencana_karir_universitas || "-"} (${student.rencana_karir_jurusan || "-"})`],
      [""],
      ["B. REKAPITULASI KEHADIRAN KBM"],
      ["Hadir (Hari)", attendance.hadir],
      ["Sakit (Hari)", attendance.sakit],
      ["Izin (Hari)", attendance.izin],
      ["Alpa / Tanpa Keterangan", attendance.alpa],
      ["Total Hari Efektif", attendance.total],
      ["Persentase Kehadiran", `${attendance.percentage}%`],
      [""],
      ["C. RINGKASAN AKADEMIK & KEDISIPLINAN"],
      ["Rata-Rata Nilai Rapor", academic.averageScore],
      ["Peringkat Rombel", `Ke-${academic.rank}`],
      ["Catatan Akademik", academic.academicNotes],
      ["Total Poin Pelanggaran", discipline.total_points],
      ["Predikat Disiplin", discipline.predicate],
      ["Wali Kelas Pengampu", homeroom_teacher.name],
      ["Kepala SMA BPI 1 Bandung", school_principal.name],
    ];
    const wsBio = XLSX.utils.aoa_to_sheet(biodataRows);
    XLSX.utils.book_append_sheet(wb, wsBio, "Biodata & Ringkasan");

    // 2. Nilai Rapor Sheet (Matriks Analisis Evaluasi Rapor Multi-Semester)
    const hasMatrix = academic.matrixRows && academic.matrixRows.length > 0;
    let wsGrades;
    if (hasMatrix) {
      const matrixHeaders = [
        ["MATRIKS ANALISIS EVALUASI NILAI RAPOR PESERTA DIDIK — SMA BPI 1 BANDUNG"],
        [`Nama Siswa: ${student.nama_lengkap} (NIS: ${student.nis})`, `Kelas: ${student.rombel}`],
        [""],
        [
          "No",
          "Mata Pelajaran",
          "Kategori",
          "KKM",
          "Sem 1 (X)",
          "S 1",
          "Sem 2 (X)",
          "S 2",
          "Sem 3 (XI)",
          "S 3",
          "Sem 4 (XI)",
          "S 4",
          "Sem 5 (XII)",
          "S 5",
          "Sem 6 (XII)",
          "S 6",
        ],
      ];
      const matrixDataRows = academic.matrixRows!.map((r) => [
        r.no,
        r.subject_name,
        r.subject_category,
        r.kkm,
        r.sem1 ?? "-",
        r.diff1 !== null ? (r.diff1 > 0 ? `+${r.diff1}` : r.diff1) : "-",
        r.sem2 ?? "-",
        r.diff2 !== null ? (r.diff2 > 0 ? `+${r.diff2}` : r.diff2) : "-",
        r.sem3 ?? "-",
        r.diff3 !== null ? (r.diff3 > 0 ? `+${r.diff3}` : r.diff3) : "-",
        r.sem4 ?? "-",
        r.diff4 !== null ? (r.diff4 > 0 ? `+${r.diff4}` : r.diff4) : "-",
        r.sem5 ?? "-",
        r.diff5 !== null ? (r.diff5 > 0 ? `+${r.diff5}` : r.diff5) : "-",
        r.sem6 ?? "-",
        r.diff6 !== null ? (r.diff6 > 0 ? `+${r.diff6}` : r.diff6) : "-",
      ]);
      if (academic.matrixRekapitulasi?.rataRata) {
        const rr = academic.matrixRekapitulasi.rataRata;
        matrixDataRows.push([
          "",
          "NILAI RATA-RATA",
          "",
          rr.kkm ?? "-",
          rr.sem1 ?? "-",
          rr.diff1 !== null ? (rr.diff1 > 0 ? `+${rr.diff1}` : rr.diff1) : "-",
          rr.sem2 ?? "-",
          rr.diff2 !== null ? (rr.diff2 > 0 ? `+${rr.diff2}` : rr.diff2) : "-",
          rr.sem3 ?? "-",
          rr.diff3 !== null ? (rr.diff3 > 0 ? `+${rr.diff3}` : rr.diff3) : "-",
          rr.sem4 ?? "-",
          rr.diff4 !== null ? (rr.diff4 > 0 ? `+${rr.diff4}` : rr.diff4) : "-",
          rr.sem5 ?? "-",
          rr.diff5 !== null ? (rr.diff5 > 0 ? `+${rr.diff5}` : rr.diff5) : "-",
          rr.sem6 ?? "-",
          rr.diff6 !== null ? (rr.diff6 > 0 ? `+${rr.diff6}` : rr.diff6) : "-",
        ]);
      }
      wsGrades = XLSX.utils.aoa_to_sheet([...matrixHeaders, ...matrixDataRows]);
    } else {
      const gradeHeaders = ["No", "Kode Mapel", "Mata Pelajaran", "Kategori", "KKM", "Nilai Akhir", "Predikat", "Capaian Kompetensi Belajar"];
      const gradeRows = academic.subjects.map((sub, i) => [
        i + 1,
        sub.code,
        sub.name,
        sub.category || "Umum",
        sub.kkm,
        sub.score,
        sub.predicate,
        sub.description,
      ]);
      wsGrades = XLSX.utils.aoa_to_sheet([["REKAPITULASI ANALISIS RAPOR SISWA"], [""], gradeHeaders, ...gradeRows]);
    }
    XLSX.utils.book_append_sheet(wb, wsGrades, "Matriks Analisis Rapor");

    // 3. Ekskul & Prestasi Sheet
    const actRows = [
      ["KEGIATAN EKSTRAKURIKULER & PROLIFE"],
      ["No", "Nama Kegiatan / Program", "Peran / Kategori", "Predikat"],
      ...((activities.extracurriculars && activities.extracurriculars.length > 0)
        ? activities.extracurriculars.map((e, idx) => [idx + 1, e.name, e.role, e.predicate])
        : [[1, "Belum ada kegiatan ekstrakurikuler", "-", "-"]]),
      [
        (activities.extracurriculars?.length || 0) + 1,
        activities.prolife.name !== "-" ? activities.prolife.name : "Belum ada program Prolife",
        "Program Prolife BPI",
        activities.prolife.predicate,
      ],
      [""],
      ["REKAP PRESTASI & PENGHARGAAN"],
      ["No", "Nama Lomba / Kejuaraan", "Bidang", "Peringkat", "Tingkat", "Tanggal", "Penyelenggara"],
      ...((activities.achievements && activities.achievements.length > 0)
        ? activities.achievements.map((ach, idx) => [
            idx + 1,
            ach.competition_name,
            ach.field,
            ach.rank,
            ach.level,
            ach.date,
            ach.organizer || "-",
          ])
        : [[1, "Belum ada catatan kejuaraan / prestasi", "-", "-", "-", "-", "-"]]),
    ];
    const wsAct = XLSX.utils.aoa_to_sheet(actRows);
    XLSX.utils.book_append_sheet(wb, wsAct, "Ekskul & Prestasi");

    // 4. Pelanggaran & Pembinaan Kesiswaan Sheet
    const kesiswaanRows = [
      ["REKAPITULASI PELANGGARAN & PEMBINAAN KESISWAAN"],
      ["Total Poin Pelanggaran", discipline.total_points, "Predikat Kedisiplinan", discipline.predicate],
      [""],
      ["No", "Tanggal Pelanggaran", "Jenis Pelanggaran", "Kategori", "Poin", "Tindakan / Status Pembinaan", "Petugas / Pelapor"],
      ...((discipline.kesiswaan_records && discipline.kesiswaan_records.length > 0)
        ? discipline.kesiswaan_records.map((k, idx) => [
            idx + 1,
            k.date,
            k.violation_name,
            k.category,
            k.points,
            `${k.tindakan_pembinaan} [${k.status_pembinaan}]`,
            k.reporter || "-",
          ])
        : [[1, "-", "Nihil Catatan Pelanggaran", "-", 0, "Siswa Berkelakuan Sangat Baik", "-"]]),
    ];
    const wsKesiswaan = XLSX.utils.aoa_to_sheet(kesiswaanRows);
    XLSX.utils.book_append_sheet(wb, wsKesiswaan, "Pelanggaran & Pembinaan");

    // 5. Catatan Pembinaan & BK Sheet
    const noteRows = [
      ["RIWAYAT CATATAN PEMBINAAN WALI KELAS"],
      ["No", "Tanggal", "Kategori", "Sasaran", "Uraian Catatan", "Tindak Lanjut", "Status"],
      ...((discipline.homeroom_notes && discipline.homeroom_notes.length > 0)
        ? discipline.homeroom_notes.map((hn, idx) => [
            idx + 1,
            hn.date,
            hn.category,
            hn.target_type,
            hn.notes,
            hn.follow_up || "-",
            hn.status,
          ])
        : [[1, "-", "Nihil Catatan Pembinaan", "-", "Belum ada catatan pembinaan wali kelas", "-", "-"]]),
      [""],
      ["RIWAYAT BIMBINGAN KONSELING (BK)"],
      ["No", "Tanggal", "Layanan / Tahapan", "Konselor", "Rencana Tindak / Hasil", "Status"],
      ...((discipline.counseling_notes && discipline.counseling_notes.length > 0)
        ? discipline.counseling_notes.map((cn, idx) => [
            idx + 1,
            cn.date,
            cn.stage,
            cn.counselor,
            cn.action_plan || cn.result || "-",
            cn.status,
          ])
        : [[1, "-", "Nihil Layanan Konseling", "-", "Belum ada catatan bimbingan konseling", "-"]]),
    ];
    const wsNotes = XLSX.utils.aoa_to_sheet(noteRows);
    XLSX.utils.book_append_sheet(wb, wsNotes, "Pembinaan & BK");

    const cleanName = student.nama_lengkap.replace(/[^A-Za-z0-9]/g, "_");
    XLSX.writeFile(wb, `Profil_Kumulatif_${student.nis}_${cleanName}_TA${meta.academic_year.replace(/\//g, "-")}.xlsx`);
  };

  return (
    <div className="space-y-6">
      {/* Page Header */}
      <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4 border-b border-slate-200 pb-5">
        <div>
          <div className="flex items-center gap-2 mb-1">
            <span className="p-2 bg-blue-50 text-blue-600 rounded-xl">
              <GraduationCap className="w-5 h-5" />
            </span>
            <h1 className="text-xl sm:text-2xl font-bold text-slate-900 tracking-tight">
              Cetak Profil & Rekam Jejak Siswa
            </h1>
          </div>
          <p className="text-xs sm:text-sm text-slate-500">
            Pencarian dan cetak resmi lembar profil kumulatif siswa (Cumulative Record) standar Folio/F4 SMA BPI 1 Bandung
          </p>
        </div>

        {/* Action Header Buttons */}
        <div className="flex flex-wrap items-center gap-2.5">
          <Button
            variant="outline"
            size="sm"
            onClick={handleExportExcel}
            disabled={!profileData || isLoadingProfile}
            className="text-xs font-semibold gap-1.5 text-emerald-700 border-emerald-300 hover:bg-emerald-50 shadow-2xs"
            title="Unduh Rekapitulasi Profil ke Excel (.xlsx)"
          >
            <FileSpreadsheet className="w-4 h-4 text-emerald-600" />
            <span>Export Excel</span>
          </Button>

          <Button
            variant="primary"
            size="sm"
            onClick={() => setIsPrintModalOpen(true)}
            disabled={!profileData || isLoadingProfile}
            className="text-xs font-semibold gap-1.5 bg-blue-600 hover:bg-blue-700 text-white shadow-xs"
            title="Pratinjau Cetak Lembar F4 Resmi"
          >
            <Printer className="w-4 h-4" />
            <span>Cetak Profil (F4)</span>
          </Button>
        </div>
      </div>

      {/* FILTER & PENCARIAN PANEL */}
      <div className="bg-white p-4 sm:p-5 rounded-2xl border border-slate-200 shadow-2xs space-y-4">
        <div className="flex items-center justify-between border-b border-slate-100 pb-3">
          <div className="flex items-center gap-2">
            <Calendar className="w-4 h-4 text-blue-600" />
            <h3 className="text-sm font-bold text-slate-800">
              Panel Filter & Pencarian Siswa (Real-Time)
            </h3>
          </div>
          {profileData && (
            <span className="text-xs font-semibold text-slate-500">
              Wali Kelas: <b className="text-slate-800">{profileData.homeroom_teacher.name}</b>
            </span>
          )}
        </div>

        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-3 sm:gap-4">
          {/* Dropdown Tahun Ajaran */}
          <div>
            <label className="text-xs font-semibold text-slate-700 block mb-1">
              Tahun Ajaran
            </label>
            <Select
              value={selectedAcademicYear}
              onChange={(e) => setSelectedAcademicYear(e.target.value)}
              className="w-full text-xs font-medium"
            >
              {academicYearOptions.map((year) => (
                <option key={year} value={year}>
                  {year}
                </option>
              ))}
            </Select>
          </div>

          {/* Dropdown Semester */}
          <div>
            <label className="text-xs font-semibold text-slate-700 block mb-1">
              Semester
            </label>
            <Select
              value={selectedSemester}
              onChange={(e) => setSelectedSemester(e.target.value as "Ganjil" | "Genap")}
              className="w-full text-xs font-medium"
            >
              {SEMESTER_OPTIONS.map((sem) => (
                <option key={sem} value={sem}>
                  Semester {sem}
                </option>
              ))}
            </Select>
          </div>

          {/* Dropdown Rombel / Kelas */}
          <div>
            <label className="text-xs font-semibold text-slate-700 block mb-1">
              Rombel / Kelas
            </label>
            <Select
              value={selectedClass}
              onChange={(e) => setSelectedClass(e.target.value)}
              className="w-full text-xs font-semibold text-blue-900 bg-blue-50/30"
            >
              {AVAILABLE_CLASSES.map((cls) => (
                <option key={cls} value={cls}>
                  Kelas {cls}
                </option>
              ))}
            </Select>
          </div>

          {/* Dropdown / Autocomplete Siswa */}
          <div>
            <label className="text-xs font-semibold text-slate-700 block mb-1">
              Nama Siswa ({classStudents.length} siswa)
            </label>
            {isLoadingClassStudents ? (
              <div className="h-9 flex items-center px-3 border border-slate-200 rounded-lg bg-slate-50 text-xs text-slate-400">
                Memuat siswa...
              </div>
            ) : (
              <Select
                value={selectedStudentNis}
                onChange={(e) => setSelectedStudentNis(e.target.value)}
                className="w-full text-xs font-semibold text-slate-900"
              >
                {classStudents.map((s) => (
                  <option key={s.nis} value={s.nis}>
                    {s.nama_lengkap} (NIS: {s.nis})
                  </option>
                ))}
              </Select>
            )}
          </div>
        </div>

        {/* Quick Search Autocomplete Filter */}
        <div className="flex items-center gap-2 pt-2 border-t border-slate-100">
          <div className="relative flex-1 max-w-sm">
            <Search className="w-3.5 h-3.5 absolute left-3 top-2.5 text-slate-400" />
            <input
              type="text"
              placeholder="Cari nama atau NIS siswa di kelas ini..."
              value={searchStudentText}
              onChange={(e) => setSearchStudentText(e.target.value)}
              className="w-full pl-8 pr-3 py-1.5 text-xs border border-slate-300 rounded-lg focus:ring-2 focus:ring-blue-500/20"
            />
          </div>
          <Button
            variant="outline"
            size="sm"
            onClick={() => fetchStudentProfile(selectedStudentNis)}
            disabled={isLoadingProfile || !selectedStudentNis}
            className="text-xs gap-1.5 text-blue-700 border-blue-200 hover:bg-blue-50"
          >
            <RefreshCw className={`w-3.5 h-3.5 ${isLoadingProfile ? "animate-spin" : ""}`} />
            <span>Tampilkan Profil</span>
          </Button>
        </div>
      </div>

      {/* METRIC OVERVIEW STATS (When profile is loaded) */}
      {profileData && (
        <div className="grid grid-cols-2 sm:grid-cols-4 gap-3 sm:gap-4">
          <StatCard
            title="Tingkat Kehadiran"
            value={profileData.attendance.total > 0 ? `${profileData.attendance.percentage}%` : "-"}
            subtitle={
              profileData.attendance.total > 0
                ? `${profileData.attendance.hadir} Hadir dari ${profileData.attendance.total} Pertemuan (S:${profileData.attendance.sakit}, I:${profileData.attendance.izin}, A:${profileData.attendance.alpa})`
                : "0 Hadir dari 0 Hari"
            }
            icon={UserCheck}
            trend={profileData.attendance.percentage >= 90 ? "positive" : profileData.attendance.percentage > 0 ? "warning" : "neutral"}
          />
          <StatCard
            title="Rata-Rata Nilai Rapor"
            value={profileData.academic.averageScore.toFixed(1)}
            subtitle={`Peringkat ke-${profileData.academic.rank} di Kelas ${profileData.student.rombel}`}
            icon={TrendingUp}
            trend="positive"
          />
          <StatCard
            title="Poin Pelanggaran"
            value={`${profileData.discipline.total_points} Poin`}
            subtitle={profileData.discipline.predicate}
            icon={ShieldAlert}
            trend={profileData.discipline.total_points === 0 ? "positive" : "negative"}
          />
          <StatCard
            title="Total Prestasi / Ekskul"
            value={`${profileData.activities.achievements.length} Prestasi`}
            subtitle={`${profileData.activities.extracurriculars.length} Ekskul & 1 Prolife`}
            icon={Award}
            trend="neutral"
          />
        </div>
      )}

      {/* PROFILE DETAIL CARDS PREVIEW */}
      {isLoadingProfile ? (
        <div className="p-12 text-center bg-white rounded-2xl border border-slate-200">
          <RefreshCw className="w-8 h-8 animate-spin mx-auto text-blue-600 mb-2" />
          <p className="text-sm font-semibold text-slate-700">Memuat lembar profil kumulatif siswa...</p>
        </div>
      ) : profileData ? (
        <div className="space-y-5">
          {/* Card 1: Biodata & Data Induk Siswa */}
          <div className="bg-white rounded-2xl border border-slate-200 shadow-2xs overflow-hidden">
            <div className="px-5 py-3.5 bg-slate-50 border-b border-slate-200 flex items-center justify-between">
              <div className="flex items-center gap-2">
                <Users className="w-4 h-4 text-blue-600" />
                <h3 className="text-sm font-bold text-slate-900 uppercase tracking-wide">
                  1. Biodata & Data Induk Siswa
                </h3>
              </div>
              <span className="text-xs font-semibold px-2.5 py-0.5 rounded-full bg-blue-100 text-blue-800">
                Fase {profileData.student.tingkat === "X" ? "E" : "F"} &bull; Kelas {profileData.student.rombel}
              </span>
            </div>

            <div className="p-5 flex flex-col md:flex-row items-start gap-6">
              {/* Foto Siswa */}
              <div className="w-32 shrink-0 flex flex-col items-center p-2 border border-slate-200 rounded-xl bg-slate-50 text-center">
                <div className="w-24 h-32 bg-slate-200 border border-slate-300 rounded-lg overflow-hidden flex items-center justify-center">
                  {/* eslint-disable-next-line @next/next/no-img-element */}
                  <img
                    src={profileData.student.photo_url || "/images/students/avatar-male.png"}
                    alt={profileData.student.nama_lengkap}
                    className="w-full h-full object-cover"
                    onError={(e) => {
                      (e.target as HTMLImageElement).src =
                        "data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='96' height='128' viewBox='0 0 96 128'><rect width='96' height='128' fill='%23e2e8f0'/><text x='50%' y='50%' font-size='11' font-family='sans-serif' text-anchor='middle' fill='%2364748b'>FOTO 3X4</text></svg>";
                    }}
                  />
                </div>
                <span className="text-[10px] text-slate-500 font-bold uppercase mt-1.5">Foto Resmi 3x4</span>
              </div>

              {/* Data Detail Siswa */}
              <div className="flex-1 grid grid-cols-1 sm:grid-cols-2 gap-y-2.5 gap-x-6 text-xs">
                <div>
                  <span className="text-slate-500 font-medium block">Nama Lengkap Siswa</span>
                  <span className="text-sm font-bold text-slate-900 uppercase">{profileData.student.nama_lengkap}</span>
                </div>
                <div>
                  <span className="text-slate-500 font-medium block">Nomor Induk Siswa / NISN</span>
                  <span className="font-mono text-slate-800 font-semibold">{profileData.student.nis} / {profileData.student.nisn}</span>
                </div>
                <div>
                  <span className="text-slate-500 font-medium block">Tempat, Tanggal Lahir</span>
                  <span className="text-slate-800 font-medium">{profileData.student.tempat_lahir}, {profileData.student.tanggal_lahir}</span>
                </div>
                <div>
                  <span className="text-slate-500 font-medium block">Jenis Kelamin / Agama</span>
                  <span className="text-slate-800 font-medium">{profileData.student.jenis_kelamin} / {profileData.student.agama}</span>
                </div>
                <div>
                  <span className="text-slate-500 font-medium block">Nama Orang Tua / Wali</span>
                  <span className="text-slate-800 font-medium">{profileData.student.nama_ortu_wali}</span>
                </div>
                <div>
                  <span className="text-slate-500 font-medium block">Kontak / No. WhatsApp Ortu</span>
                  <span className="font-mono text-slate-800 font-semibold flex items-center gap-1.5">
                    <Phone className="w-3 h-3 text-emerald-600" />
                    {profileData.student.no_wa_ortu}
                  </span>
                </div>
                <div className="sm:col-span-2">
                  <span className="text-slate-500 font-medium block">Alamat Tinggal</span>
                  <span className="text-slate-800 font-medium flex items-center gap-1.5">
                    <MapPin className="w-3.5 h-3.5 text-slate-400 shrink-0" />
                    {profileData.student.alamat}
                  </span>
                </div>
                <div className="sm:col-span-2 p-2.5 bg-blue-50/50 rounded-xl border border-blue-100 flex items-center justify-between">
                  <div>
                    <span className="text-[11px] text-blue-700 font-semibold uppercase block">Rencana Peminatan Karir / Studi Lanjut</span>
                    <span className="text-xs font-bold text-blue-950">
                      {profileData.student.rencana_karir_universitas && profileData.student.rencana_karir_universitas !== "-"
                        ? `${profileData.student.rencana_karir_universitas} — ${profileData.student.rencana_karir_jurusan || "-"}`
                        : (profileData.student.rencana_karir_jurusan && profileData.student.rencana_karir_jurusan !== "-" ? profileData.student.rencana_karir_jurusan : "-")}
                    </span>
                  </div>
                  <Sparkles className="w-4 h-4 text-blue-500 shrink-0" />
                </div>
              </div>
            </div>
          </div>

          {/* Card 2: Rekapitulasi Presensi Kehadiran */}
          <div className="bg-white rounded-2xl border border-slate-200 shadow-2xs overflow-hidden">
            <div className="px-5 py-3.5 bg-slate-50 border-b border-slate-200 flex items-center justify-between">
              <div className="flex items-center gap-2">
                <CheckCircle2 className="w-4 h-4 text-emerald-600" />
                <h3 className="text-sm font-bold text-slate-900 uppercase tracking-wide">
                  2. Rekapitulasi Presensi Kehadiran Siswa
                </h3>
              </div>
              <span className="text-xs font-bold text-slate-700">
                Tahun Ajaran {profileData.meta.academic_year} &bull; Semester {profileData.meta.semester}
              </span>
            </div>

            <div className="p-5">
              <div className="grid grid-cols-2 sm:grid-cols-6 gap-3 text-center">
                <div className="p-3 rounded-xl border border-emerald-200 bg-emerald-50/40">
                  <span className="text-[11px] font-semibold text-emerald-800 uppercase block">Hadir</span>
                  <span className="text-xl font-extrabold text-emerald-900">{profileData.attendance.hadir}</span>
                  <span className="text-[10px] text-emerald-600 block">Hari</span>
                </div>
                <div className="p-3 rounded-xl border border-blue-200 bg-blue-50/40">
                  <span className="text-[11px] font-semibold text-blue-800 uppercase block">Sakit</span>
                  <span className="text-xl font-extrabold text-blue-900">{profileData.attendance.sakit}</span>
                  <span className="text-[10px] text-blue-600 block">Hari</span>
                </div>
                <div className="p-3 rounded-xl border border-amber-200 bg-amber-50/40">
                  <span className="text-[11px] font-semibold text-amber-800 uppercase block">Izin</span>
                  <span className="text-xl font-extrabold text-amber-900">{profileData.attendance.izin}</span>
                  <span className="text-[10px] text-amber-600 block">Hari</span>
                </div>
                <div className="p-3 rounded-xl border border-rose-200 bg-rose-50/40">
                  <span className="text-[11px] font-semibold text-rose-800 uppercase block">Alpha / Alpa</span>
                  <span className="text-xl font-extrabold text-rose-900">{profileData.attendance.alpa}</span>
                  <span className="text-[10px] text-rose-600 block">Hari</span>
                </div>
                <div className="p-3 rounded-xl border border-slate-200 bg-slate-50">
                  <span className="text-[11px] font-semibold text-slate-700 uppercase block">Total Hari KBM</span>
                  <span className="text-xl font-extrabold text-slate-800">{profileData.attendance.total}</span>
                  <span className="text-[10px] text-slate-500 block">Hari</span>
                </div>
                <div className="p-3 rounded-xl border border-blue-300 bg-blue-100/60">
                  <span className="text-[11px] font-bold text-blue-900 uppercase block">% Kehadiran</span>
                  <span className="text-xl font-black text-blue-950">
                    {profileData.attendance.total > 0 ? `${profileData.attendance.percentage}%` : "-"}
                  </span>
                  <span className="text-[10px] text-blue-700 font-semibold block">
                    {profileData.attendance.total > 0
                      ? (profileData.attendance.percentage >= 90 ? "Sangat Baik" : profileData.attendance.percentage >= 75 ? "Baik" : "Perlu Pembinaan")
                      : "0 Hadir dari 0 Hari"}
                  </span>
                </div>
              </div>
            </div>
          </div>

          {/* Card 3: MATRIKS ANALISIS EVALUASI NILAI RAPOR PESERTA DIDIK */}
          <div className="bg-white rounded-2xl border border-slate-200 shadow-2xs overflow-hidden">
            <div className="px-5 py-3.5 bg-slate-50 border-b border-slate-200 flex flex-wrap items-center justify-between gap-2">
              <div className="flex items-center gap-2">
                <BookOpen className="w-4 h-4 text-blue-600" />
                <h3 className="text-sm font-bold text-slate-900 uppercase tracking-wide">
                  3. Matriks Analisis Evaluasi Nilai Rapor Peserta Didik
                </h3>
              </div>
              <div className="flex items-center gap-3 text-xs font-semibold">
                <span className="text-blue-900 bg-blue-100/70 px-2.5 py-1 rounded-md">
                  Rata-Rata Kumulatif: <b>{profileData.academic.averageScore.toFixed(1)}</b>
                </span>
                <span className="text-slate-700 bg-slate-200/70 px-2.5 py-1 rounded-md">
                  Peringkat: <b>Ke-{profileData.academic.rank}</b>
                </span>
              </div>
            </div>

            <div className="p-4 space-y-3">
              {/* Header Ringkasan Atas: Top 3 Mapel (Hijau) & Perhatian BK (Merah) */}
              <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
                <div className="p-3 bg-emerald-50/60 rounded-xl border border-emerald-200 flex items-start gap-2.5">
                  <Award className="w-4 h-4 text-emerald-700 mt-0.5 shrink-0" />
                  <div className="space-y-1 overflow-hidden flex-1">
                    <span className="text-xs font-bold text-emerald-900 uppercase tracking-wide block">
                      ★ Top 3 Mata Pelajaran Tertinggi:
                    </span>
                    <div className="flex items-center gap-1.5 flex-wrap">
                      {profileData.academic.top3Mapel && profileData.academic.top3Mapel.length > 0 ? (
                        profileData.academic.top3Mapel.map((item, idx) => (
                          <span
                            key={item.code || idx}
                            className="bg-white border border-emerald-300 px-2 py-0.5 rounded text-xs text-slate-800 font-medium shadow-2xs"
                          >
                            <strong>{idx + 1}.</strong> {item.name}{" "}
                            <span className="font-bold text-emerald-700 font-mono">
                              ({typeof item.score === "number" ? item.score.toFixed(1) : item.score})
                            </span>
                          </span>
                        ))
                      ) : (
                        <span className="text-slate-400 italic text-xs">-</span>
                      )}
                    </div>
                  </div>
                </div>

                <div className="p-3 bg-rose-50/60 rounded-xl border border-rose-200 flex items-start gap-2.5">
                  <AlertTriangle className="w-4 h-4 text-rose-700 mt-0.5 shrink-0" />
                  <div className="space-y-1 overflow-hidden flex-1">
                    <span className="text-xs font-bold text-rose-900 uppercase tracking-wide block">
                      ▲ Perhatian BK (Nilai Perlu Pembinaan):
                    </span>
                    <div className="flex items-center gap-1.5 flex-wrap">
                      {profileData.academic.bottom3Mapel && profileData.academic.bottom3Mapel.length > 0 ? (
                        profileData.academic.bottom3Mapel.map((item, idx) => (
                          <span
                            key={item.code || idx}
                            className="bg-white border border-rose-300 px-2 py-0.5 rounded text-xs text-slate-800 font-medium shadow-2xs"
                          >
                            <strong>{idx + 1}.</strong> {item.name}{" "}
                            <span className="font-bold text-rose-700 font-mono">
                              ({typeof item.score === "number" ? item.score.toFixed(1) : item.score})
                            </span>
                          </span>
                        ))
                      ) : (
                        <span className="text-slate-400 italic text-xs">-</span>
                      )}
                    </div>
                  </div>
                </div>
              </div>

              {/* TABEL MATRIKS MULTI-SEMESTER DENGAN SELISIH */}
              <div className="overflow-x-auto border border-slate-200 rounded-xl">
                <table className="w-full text-xs" style={{ minWidth: "950px", tableLayout: "fixed" }}>
                  <colgroup>
                    <col style={{ width: "3.5%" }} />
                    <col style={{ width: "20.5%" }} />
                    <col style={{ width: "8%" }} />
                    <col style={{ width: "4%" }} />
                    <col style={{ width: "5.333%" }} />
                    <col style={{ width: "5.333%" }} />
                    <col style={{ width: "5.333%" }} />
                    <col style={{ width: "5.333%" }} />
                    <col style={{ width: "5.333%" }} />
                    <col style={{ width: "5.333%" }} />
                    <col style={{ width: "5.333%" }} />
                    <col style={{ width: "5.333%" }} />
                    <col style={{ width: "5.333%" }} />
                    <col style={{ width: "5.333%" }} />
                    <col style={{ width: "5.333%" }} />
                    <col style={{ width: "5.333%" }} />
                  </colgroup>
                  <thead>
                    <tr className="bg-slate-100 text-slate-800 border-b border-slate-300 font-bold">
                      <th rowSpan={2} className="border-r border-slate-300 py-2 px-1 text-center">No</th>
                      <th rowSpan={2} className="border-r border-slate-300 py-2 px-2 text-left">Mata Pelajaran</th>
                      <th rowSpan={2} className="border-r border-slate-300 py-2 px-1 text-center">Kategori</th>
                      <th rowSpan={2} className="border-r border-slate-300 py-2 px-1 text-center bg-amber-100/70">KKM</th>
                      <th colSpan={4} className="border-r border-slate-300 py-1 px-1 text-center bg-blue-100/80 font-extrabold text-blue-950">Grup Kelas X</th>
                      <th colSpan={4} className="border-r border-slate-300 py-1 px-1 text-center bg-indigo-100/80 font-extrabold text-indigo-950">Grup Kelas XI</th>
                      <th colSpan={4} className="py-1 px-1 text-center bg-purple-100/80 font-extrabold text-purple-950">Grup Kelas XII</th>
                    </tr>
                    <tr className="bg-slate-50 text-slate-700 border-b border-slate-200 font-semibold text-[11px]">
                      {/* Kelas X */}
                      <th className="border-r border-slate-200 py-1 text-center">Sem 1</th>
                      <th className="border-r border-slate-200 py-1 text-center bg-blue-50/80 font-bold">S</th>
                      <th className="border-r border-slate-200 py-1 text-center">Sem 2</th>
                      <th className="border-r border-slate-200 py-1 text-center bg-blue-50/80 font-bold">S</th>
                      {/* Kelas XI */}
                      <th className="border-r border-slate-200 py-1 text-center">Sem 3</th>
                      <th className="border-r border-slate-200 py-1 text-center bg-indigo-50/80 font-bold">S</th>
                      <th className="border-r border-slate-200 py-1 text-center">Sem 4</th>
                      <th className="border-r border-slate-200 py-1 text-center bg-indigo-50/80 font-bold">S</th>
                      {/* Kelas XII */}
                      <th className="border-r border-slate-200 py-1 text-center">Sem 5</th>
                      <th className="border-r border-slate-200 py-1 text-center bg-purple-50/80 font-bold">S</th>
                      <th className="border-r border-slate-200 py-1 text-center">Sem 6</th>
                      <th className="py-1 text-center bg-purple-50/80 font-bold">S</th>
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-slate-100">
                    {(profileData.academic.matrixRows && profileData.academic.matrixRows.length > 0) ? (
                      profileData.academic.matrixRows.map((r) => (
                        <tr key={r.subject_code} className="hover:bg-slate-50/80 transition-colors">
                          <td className="border-r border-slate-200 py-2 text-center font-mono text-slate-500">{r.no}</td>
                          <td className="border-r border-slate-200 py-2 px-2 font-medium text-slate-900 truncate" title={r.subject_name}>
                            {r.subject_name}
                          </td>
                          <td className="border-r border-slate-200 py-2 text-center text-slate-600 text-[11px]">{r.subject_category}</td>
                          <td className="border-r border-slate-200 py-2 text-center font-mono font-bold bg-amber-50/40 text-slate-800">{r.kkm}</td>

                          {/* Kelas X */}
                          <td className="border-r border-slate-200 py-2 text-center font-mono">{r.sem1 !== null ? r.sem1.toFixed(1) : "-"}</td>
                          <td 
                            className={`border-r border-slate-200 py-2 text-center font-mono text-[11px] ${
                              r.diff1 !== null && r.diff1 < 0 ? "bg-rose-100 text-rose-800 font-bold" : r.diff1 !== null && r.diff1 > 0 ? "text-emerald-700 font-semibold" : ""
                            }`}
                          >
                            {r.diff1 !== null ? (r.diff1 > 0 ? `+${r.diff1.toFixed(1)}` : r.diff1.toFixed(1)) : "-"}
                          </td>
                          <td className="border-r border-slate-200 py-2 text-center font-mono">{r.sem2 !== null ? r.sem2.toFixed(1) : "-"}</td>
                          <td 
                            className={`border-r border-slate-200 py-2 text-center font-mono text-[11px] ${
                              r.diff2 !== null && r.diff2 < 0 ? "bg-rose-100 text-rose-800 font-bold" : r.diff2 !== null && r.diff2 > 0 ? "text-emerald-700 font-semibold" : ""
                            }`}
                          >
                            {r.diff2 !== null ? (r.diff2 > 0 ? `+${r.diff2.toFixed(1)}` : r.diff2.toFixed(1)) : "-"}
                          </td>

                          {/* Kelas XI */}
                          <td className="border-r border-slate-200 py-2 text-center font-mono">{r.sem3 !== null ? r.sem3.toFixed(1) : "-"}</td>
                          <td 
                            className={`border-r border-slate-200 py-2 text-center font-mono text-[11px] ${
                              r.diff3 !== null && r.diff3 < 0 ? "bg-rose-100 text-rose-800 font-bold" : r.diff3 !== null && r.diff3 > 0 ? "text-emerald-700 font-semibold" : ""
                            }`}
                          >
                            {r.diff3 !== null ? (r.diff3 > 0 ? `+${r.diff3.toFixed(1)}` : r.diff3.toFixed(1)) : "-"}
                          </td>
                          <td className="border-r border-slate-200 py-2 text-center font-mono">{r.sem4 !== null ? r.sem4.toFixed(1) : "-"}</td>
                          <td 
                            className={`border-r border-slate-200 py-2 text-center font-mono text-[11px] ${
                              r.diff4 !== null && r.diff4 < 0 ? "bg-rose-100 text-rose-800 font-bold" : r.diff4 !== null && r.diff4 > 0 ? "text-emerald-700 font-semibold" : ""
                            }`}
                          >
                            {r.diff4 !== null ? (r.diff4 > 0 ? `+${r.diff4.toFixed(1)}` : r.diff4.toFixed(1)) : "-"}
                          </td>

                          {/* Kelas XII */}
                          <td className="border-r border-slate-200 py-2 text-center font-mono">{r.sem5 !== null ? r.sem5.toFixed(1) : "-"}</td>
                          <td 
                            className={`border-r border-slate-200 py-2 text-center font-mono text-[11px] ${
                              r.diff5 !== null && r.diff5 < 0 ? "bg-rose-100 text-rose-800 font-bold" : r.diff5 !== null && r.diff5 > 0 ? "text-emerald-700 font-semibold" : ""
                            }`}
                          >
                            {r.diff5 !== null ? (r.diff5 > 0 ? `+${r.diff5.toFixed(1)}` : r.diff5.toFixed(1)) : "-"}
                          </td>
                          <td className="border-r border-slate-200 py-2 text-center font-mono">{r.sem6 !== null ? r.sem6.toFixed(1) : "-"}</td>
                          <td 
                            className={`py-2 text-center font-mono text-[11px] ${
                              r.diff6 !== null && r.diff6 < 0 ? "bg-rose-100 text-rose-800 font-bold" : r.diff6 !== null && r.diff6 > 0 ? "text-emerald-700 font-semibold" : ""
                            }`}
                          >
                            {r.diff6 !== null ? (r.diff6 > 0 ? `+${r.diff6.toFixed(1)}` : r.diff6.toFixed(1)) : "-"}
                          </td>
                        </tr>
                      ))
                    ) : (profileData.academic.subjects && profileData.academic.subjects.length > 0) ? (
                      profileData.academic.subjects.map((sub, idx) => (
                        <tr key={sub.code} className="hover:bg-slate-50">
                          <td className="border-r border-slate-200 py-2 text-center font-mono text-slate-500">{idx + 1}</td>
                          <td className="border-r border-slate-200 py-2 px-2 font-medium text-slate-900">{sub.name}</td>
                          <td className="border-r border-slate-200 py-2 text-center text-slate-600">{sub.category || "Umum"}</td>
                          <td className="border-r border-slate-200 py-2 text-center font-bold bg-amber-50/50">{sub.kkm}</td>
                          <td className="border-r border-slate-200 py-2 text-center font-mono font-bold text-blue-900">{sub.score}</td>
                          <td className="border-r border-slate-200 py-2 text-center font-mono text-emerald-700">+{(sub.score - sub.kkm).toFixed(1)}</td>
                          <td colSpan={10} className="py-2 text-center text-slate-400 italic">Dalam proses sinkronisasi multi-semester</td>
                        </tr>
                      ))
                    ) : (
                      <tr>
                        <td colSpan={16} className="py-4 text-center text-slate-500 italic">
                          Belum ada rekapitulasi data nilai rapor untuk peserta didik ini.
                        </td>
                      </tr>
                    )}
                  </tbody>
                  {/* REKAPITULASI BAWAH VIEW */}
                  {profileData.academic.matrixRekapitulasi?.rataRata && (
                    <tfoot className="border-t-2 border-slate-300 font-bold bg-slate-50">
                      <tr>
                        <td colSpan={3} className="border-r border-slate-200 py-2.5 px-3 text-left uppercase text-blue-950 font-extrabold text-[11px]">
                          Nilai Rata-Rata Siswa
                        </td>
                        <td className="border-r border-slate-200 py-2 text-center bg-amber-100/70 font-extrabold text-slate-900 font-mono">
                          {profileData.academic.matrixRekapitulasi.rataRata.kkm ?? "-"}
                        </td>
                        <td className="border-r border-slate-200 py-2 text-center font-bold text-blue-900 font-mono">
                          {profileData.academic.matrixRekapitulasi.rataRata.sem1?.toFixed(1) ?? "-"}
                        </td>
                        <td 
                          className={`border-r border-slate-200 py-2 text-center font-mono text-[11px] ${
                            profileData.academic.matrixRekapitulasi.rataRata.diff1 !== null && profileData.academic.matrixRekapitulasi.rataRata.diff1 < 0 ? "bg-rose-100 text-rose-800" : "text-emerald-800"
                          }`}
                        >
                          {profileData.academic.matrixRekapitulasi.rataRata.diff1 !== null ? (profileData.academic.matrixRekapitulasi.rataRata.diff1 > 0 ? `+${profileData.academic.matrixRekapitulasi.rataRata.diff1.toFixed(1)}` : profileData.academic.matrixRekapitulasi.rataRata.diff1.toFixed(1)) : "-"}
                        </td>
                        <td className="border-r border-slate-200 py-2 text-center font-bold text-blue-900 font-mono">
                          {profileData.academic.matrixRekapitulasi.rataRata.sem2?.toFixed(1) ?? "-"}
                        </td>
                        <td 
                          className={`border-r border-slate-200 py-2 text-center font-mono text-[11px] ${
                            profileData.academic.matrixRekapitulasi.rataRata.diff2 !== null && profileData.academic.matrixRekapitulasi.rataRata.diff2 < 0 ? "bg-rose-100 text-rose-800" : "text-emerald-800"
                          }`}
                        >
                          {profileData.academic.matrixRekapitulasi.rataRata.diff2 !== null ? (profileData.academic.matrixRekapitulasi.rataRata.diff2 > 0 ? `+${profileData.academic.matrixRekapitulasi.rataRata.diff2.toFixed(1)}` : profileData.academic.matrixRekapitulasi.rataRata.diff2.toFixed(1)) : "-"}
                        </td>
                        <td className="border-r border-slate-200 py-2 text-center font-bold text-blue-900 font-mono">
                          {profileData.academic.matrixRekapitulasi.rataRata.sem3?.toFixed(1) ?? "-"}
                        </td>
                        <td 
                          className={`border-r border-slate-200 py-2 text-center font-mono text-[11px] ${
                            profileData.academic.matrixRekapitulasi.rataRata.diff3 !== null && profileData.academic.matrixRekapitulasi.rataRata.diff3 < 0 ? "bg-rose-100 text-rose-800" : "text-emerald-800"
                          }`}
                        >
                          {profileData.academic.matrixRekapitulasi.rataRata.diff3 !== null ? (profileData.academic.matrixRekapitulasi.rataRata.diff3 > 0 ? `+${profileData.academic.matrixRekapitulasi.rataRata.diff3.toFixed(1)}` : profileData.academic.matrixRekapitulasi.rataRata.diff3.toFixed(1)) : "-"}
                        </td>
                        <td className="border-r border-slate-200 py-2 text-center font-bold text-blue-900 font-mono">
                          {profileData.academic.matrixRekapitulasi.rataRata.sem4?.toFixed(1) ?? "-"}
                        </td>
                        <td 
                          className={`border-r border-slate-200 py-2 text-center font-mono text-[11px] ${
                            profileData.academic.matrixRekapitulasi.rataRata.diff4 !== null && profileData.academic.matrixRekapitulasi.rataRata.diff4 < 0 ? "bg-rose-100 text-rose-800" : "text-emerald-800"
                          }`}
                        >
                          {profileData.academic.matrixRekapitulasi.rataRata.diff4 !== null ? (profileData.academic.matrixRekapitulasi.rataRata.diff4 > 0 ? `+${profileData.academic.matrixRekapitulasi.rataRata.diff4.toFixed(1)}` : profileData.academic.matrixRekapitulasi.rataRata.diff4.toFixed(1)) : "-"}
                        </td>
                        <td className="border-r border-slate-200 py-2 text-center font-bold text-blue-900 font-mono">
                          {profileData.academic.matrixRekapitulasi.rataRata.sem5?.toFixed(1) ?? "-"}
                        </td>
                        <td 
                          className={`border-r border-slate-200 py-2 text-center font-mono text-[11px] ${
                            profileData.academic.matrixRekapitulasi.rataRata.diff5 !== null && profileData.academic.matrixRekapitulasi.rataRata.diff5 < 0 ? "bg-rose-100 text-rose-800" : "text-emerald-800"
                          }`}
                        >
                          {profileData.academic.matrixRekapitulasi.rataRata.diff5 !== null ? (profileData.academic.matrixRekapitulasi.rataRata.diff5 > 0 ? `+${profileData.academic.matrixRekapitulasi.rataRata.diff5.toFixed(1)}` : profileData.academic.matrixRekapitulasi.rataRata.diff5.toFixed(1)) : "-"}
                        </td>
                        <td className="border-r border-slate-200 py-2 text-center font-bold text-blue-900 font-mono">
                          {profileData.academic.matrixRekapitulasi.rataRata.sem6?.toFixed(1) ?? "-"}
                        </td>
                        <td 
                          className={`py-2 text-center font-mono text-[11px] ${
                            profileData.academic.matrixRekapitulasi.rataRata.diff6 !== null && profileData.academic.matrixRekapitulasi.rataRata.diff6 < 0 ? "bg-rose-100 text-rose-800" : "text-emerald-800"
                          }`}
                        >
                          {profileData.academic.matrixRekapitulasi.rataRata.diff6 !== null ? (profileData.academic.matrixRekapitulasi.rataRata.diff6 > 0 ? `+${profileData.academic.matrixRekapitulasi.rataRata.diff6.toFixed(1)}` : profileData.academic.matrixRekapitulasi.rataRata.diff6.toFixed(1)) : "-"}
                        </td>
                      </tr>
                    </tfoot>
                  )}
                </table>
              </div>

              {/* Catatan / Keterangan Selisih */}
              <div className="pt-2 flex flex-wrap items-center justify-between text-xs text-slate-600 gap-2">
                <div className="flex items-center gap-3">
                  <span><b>Keterangan:</b> Kolom <b>S</b> = Selisih nilai terhadap semester sebelumnya / KKM.</span>
                  <span className="flex items-center gap-1.5">
                    <span className="inline-block w-3 h-3 bg-rose-100 border border-rose-300 rounded-xs"></span>
                    <span>Merah: Penurunan nilai</span>
                  </span>
                  <span className="flex items-center gap-1.5">
                    <span className="inline-block w-3 h-3 bg-amber-100 border border-amber-300 rounded-xs"></span>
                    <span>KKM Mapel</span>
                  </span>
                </div>
                {profileData.academic.academicNotes && (
                  <span className="italic text-slate-500">{profileData.academic.academicNotes}</span>
                )}
              </div>
            </div>
          </div>

          {/* Card 4: Ekstrakurikuler, Prolife & Prestasi */}
          <div className="bg-white rounded-2xl border border-slate-200 shadow-2xs overflow-hidden">
            <div className="px-5 py-3.5 bg-slate-50 border-b border-slate-200 flex items-center justify-between">
              <div className="flex items-center gap-2">
                <Award className="w-4 h-4 text-amber-600" />
                <h3 className="text-sm font-bold text-slate-900 uppercase tracking-wide">
                  4. Ekstrakurikuler, Program Prolife & Prestasi
                </h3>
              </div>
            </div>

            <div className="p-5 space-y-4">
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                {/* Ekstrakurikuler */}
                <div className="p-3.5 bg-slate-50 rounded-xl border border-slate-200 space-y-2">
                  <span className="text-xs font-bold text-slate-800 block uppercase">
                    A. Ekstrakurikuler yang Diikuti:
                  </span>
                  {(profileData.activities.extracurriculars && profileData.activities.extracurriculars.length > 0) ? (
                    <div className="space-y-1.5">
                      {profileData.activities.extracurriculars.map((e, idx) => (
                        <div key={idx} className="flex items-center justify-between p-2 bg-white rounded-lg border border-slate-200 text-xs">
                          <div>
                            <span className="font-semibold text-slate-900">{e.name}</span>
                            <span className="text-slate-500 block text-[11px]">{e.role}</span>
                          </div>
                          <span className="px-2 py-0.5 rounded text-[10px] font-bold bg-blue-100 text-blue-800">
                            {e.predicate}
                          </span>
                        </div>
                      ))}
                    </div>
                  ) : (
                    <p className="text-xs text-slate-500 italic p-3 bg-white rounded-lg border border-slate-200">
                      Belum ada kegiatan ekstrakurikuler yang diikuti.
                    </p>
                  )}
                </div>

                {/* Prolife */}
                <div className="p-3.5 bg-slate-50 rounded-xl border border-slate-200 space-y-2">
                  <span className="text-xs font-bold text-slate-800 block uppercase">
                    B. Program Prolife (Pengembangan Karakter):
                  </span>
                  {profileData.activities.prolife && profileData.activities.prolife.name !== "-" ? (
                    <div className="p-2.5 bg-white rounded-lg border border-slate-200 text-xs space-y-1">
                      <div className="flex items-center justify-between">
                        <span className="font-bold text-slate-900">{profileData.activities.prolife.name}</span>
                        <span className="px-2 py-0.5 rounded text-[10px] font-bold bg-emerald-100 text-emerald-800">
                          {profileData.activities.prolife.predicate}
                        </span>
                      </div>
                      <p className="text-slate-600 text-[11px] leading-relaxed italic">
                        {profileData.activities.prolife.description}
                      </p>
                    </div>
                  ) : (
                    <p className="text-xs text-slate-500 italic p-3 bg-white rounded-lg border border-slate-200">
                      Belum ada program Prolife yang terdaftar.
                    </p>
                  )}
                </div>
              </div>

              {/* Prestasi */}
              <div className="pt-2">
                <span className="text-xs font-bold text-slate-800 block mb-2 uppercase">
                  C. Rekap Prestasi & Penghargaan Siswa:
                </span>
                {profileData.activities.achievements.length === 0 ? (
                  <p className="text-xs text-slate-500 italic p-3 bg-slate-50 rounded-lg border border-slate-200">
                    Belum ada catatan kejuaraan khusus / Dalam proses pembinaan prestasi dan kompetisi sekolah.
                  </p>
                ) : (
                  <div className="overflow-x-auto border border-slate-200 rounded-xl">
                    <table className="w-full text-xs">
                      <thead>
                        <tr className="bg-slate-100 font-semibold text-slate-700 border-b border-slate-200 text-left">
                          <th className="py-2 px-3 text-center w-10">No</th>
                          <th className="py-2 px-3">Nama Kejuaraan / Kompetisi</th>
                          <th className="py-2 px-3">Bidang</th>
                          <th className="py-2 px-3 text-center">Peringkat</th>
                          <th className="py-2 px-3 text-center">Tingkat</th>
                          <th className="py-2 px-3">Waktu & Penyelenggara</th>
                        </tr>
                      </thead>
                      <tbody className="divide-y divide-slate-100">
                        {profileData.activities.achievements.map((ach, idx) => (
                          <tr key={idx} className="hover:bg-slate-50">
                            <td className="py-2 px-3 text-center font-mono text-slate-500">{idx + 1}</td>
                            <td className="py-2 px-3 font-semibold text-slate-900">{ach.competition_name}</td>
                            <td className="py-2 px-3 text-slate-700">{ach.field}</td>
                            <td className="py-2 px-3 text-center font-bold text-emerald-700">{ach.rank}</td>
                            <td className="py-2 px-3 text-center text-slate-700">{ach.level}</td>
                            <td className="py-2 px-3 text-slate-600">{ach.organizer ? `${ach.organizer} (${ach.date})` : ach.date}</td>
                          </tr>
                        ))}
                      </tbody>
                    </table>
                  </div>
                )}
              </div>
            </div>
          </div>

          {/* Card 5: Kedisiplinan, Catatan Wali Kelas & BK */}
          <div className="bg-white rounded-2xl border border-slate-200 shadow-2xs overflow-hidden">
            <div className="px-5 py-3.5 bg-slate-50 border-b border-slate-200 flex items-center justify-between">
              <div className="flex items-center gap-2">
                <ShieldAlert className="w-4 h-4 text-rose-600" />
                <h3 className="text-sm font-bold text-slate-900 uppercase tracking-wide">
                  5. Kedisiplinan, Catatan Pembinaan Wali Kelas & BK
                </h3>
              </div>
              <span className="text-xs font-bold text-slate-700">
                Total Poin: <b className="text-rose-700">{profileData.discipline.total_points} Poin</b> ({profileData.discipline.predicate})
              </span>
            </div>

            <div className="p-5 space-y-4">
              {/* Riwayat Pelanggaran & Pembinaan Terhubung Real-Time Modul Kesiswaan */}
              <div>
                <div className="flex items-center justify-between mb-2">
                  <span className="text-xs font-bold text-slate-800 uppercase">
                    A. Rekapitulasi Pelanggaran & Pembinaan (Terhubung Real-Time Modul Kesiswaan):
                  </span>
                  <span className="text-[11px] font-semibold text-emerald-700 bg-emerald-50 px-2 py-0.5 rounded border border-emerald-200">
                    Live Sync Modul Kesiswaan
                  </span>
                </div>
                {(!profileData.discipline.kesiswaan_records || profileData.discipline.kesiswaan_records.length === 0) ? (
                  <div className="p-3 bg-emerald-50/50 rounded-xl border border-emerald-200 text-xs text-emerald-800 flex items-center gap-2">
                    <UserCheck className="w-4 h-4 text-emerald-600 shrink-0" />
                    <span>
                      <b>Nihil Catatan Pelanggaran:</b> Siswa tidak memiliki catatan pelanggaran tata tertib kesiswaan (Predikat Kedisiplinan: <b>{profileData.discipline.predicate}</b>).
                    </span>
                  </div>
                ) : (
                  <div className="overflow-x-auto border border-slate-200 rounded-xl">
                    <table className="w-full text-xs">
                      <thead>
                        <tr className="bg-slate-100 font-semibold text-slate-700 border-b border-slate-200 text-left">
                          <th className="py-2 px-3 text-center w-10">No</th>
                          <th className="py-2 px-3 text-center w-24">Tanggal</th>
                          <th className="py-2 px-3">Jenis Pelanggaran</th>
                          <th className="py-2 px-3">Kategori</th>
                          <th className="py-2 px-3 text-center w-16">Poin</th>
                          <th className="py-2 px-3">Tindakan / Status Pembinaan</th>
                          <th className="py-2 px-3">Petugas / Pelapor</th>
                        </tr>
                      </thead>
                      <tbody className="divide-y divide-slate-100">
                        {profileData.discipline.kesiswaan_records.map((k, idx) => (
                          <tr key={idx} className="hover:bg-slate-50">
                            <td className="py-2 px-3 text-center font-mono text-slate-500">{idx + 1}</td>
                            <td className="py-2 px-3 text-center font-mono text-slate-700">{k.date}</td>
                            <td className="py-2 px-3 font-semibold text-slate-900">{k.violation_name}</td>
                            <td className="py-2 px-3 text-slate-700">{k.category}</td>
                            <td className="py-2 px-3 text-center font-mono font-bold text-rose-700">+{k.points}</td>
                            <td className="py-2 px-3">
                              <span className="font-medium text-slate-900 block">{k.tindakan_pembinaan}</span>
                              <span className="inline-block mt-0.5 px-1.5 py-0.5 rounded text-[10px] font-semibold bg-slate-100 text-slate-700 border border-slate-200">
                                {k.status_pembinaan}
                              </span>
                            </td>
                            <td className="py-2 px-3 text-slate-600">{k.reporter || "-"}</td>
                          </tr>
                        ))}
                      </tbody>
                    </table>
                  </div>
                )}
              </div>

              {/* Riwayat Pembinaan Wali Kelas */}
              <div className="pt-2">
                <span className="text-xs font-bold text-slate-800 block mb-2 uppercase">
                  B. Riwayat Pembinaan & Catatan Wali Kelas:
                </span>
                {(!profileData.discipline.homeroom_notes || profileData.discipline.homeroom_notes.length === 0) ? (
                  <div className="p-3 bg-slate-50 rounded-xl border border-slate-200 text-xs text-slate-500 italic">
                    Nihil Catatan Pembinaan — Belum ada catatan pembinaan khusus dari wali kelas.
                  </div>
                ) : (
                  <div className="overflow-x-auto border border-slate-200 rounded-xl">
                    <table className="w-full text-xs">
                      <thead>
                        <tr className="bg-slate-100 font-semibold text-slate-700 border-b border-slate-200 text-left">
                          <th className="py-2 px-3 text-center w-10">No</th>
                          <th className="py-2 px-3 text-center w-24">Tanggal</th>
                          <th className="py-2 px-3">Kategori</th>
                          <th className="py-2 px-3">Uraian Kejadian / Bimbingan</th>
                          <th className="py-2 px-3">Tindak Lanjut</th>
                          <th className="py-2 px-3 text-center w-24">Status</th>
                        </tr>
                      </thead>
                      <tbody className="divide-y divide-slate-100">
                        {profileData.discipline.homeroom_notes.map((hn, idx) => (
                          <tr key={idx} className="hover:bg-slate-50">
                            <td className="py-2 px-3 text-center font-mono text-slate-500">{idx + 1}</td>
                            <td className="py-2 px-3 text-center font-mono text-slate-700">{hn.date}</td>
                            <td className="py-2 px-3 font-semibold text-slate-900">{hn.category}</td>
                            <td className="py-2 px-3 text-slate-700 leading-relaxed">{hn.notes}</td>
                            <td className="py-2 px-3 text-slate-600 italic">{hn.follow_up || "-"}</td>
                            <td className="py-2 px-3 text-center">
                              <span
                                className={`inline-block px-2 py-0.5 rounded text-[11px] font-bold ${
                                  hn.status === "Selesai"
                                    ? "bg-emerald-100 text-emerald-800"
                                    : "bg-amber-100 text-amber-800"
                                }`}
                              >
                                {hn.status}
                              </span>
                            </td>
                          </tr>
                        ))}
                      </tbody>
                    </table>
                  </div>
                )}
              </div>

              {/* Catatan Konseling BK */}
              <div className="pt-2">
                <span className="text-xs font-bold text-slate-800 block mb-2 uppercase">
                  C. Layanan Bimbingan & Konseling (BK):
                </span>
                {(!profileData.discipline.counseling_notes || profileData.discipline.counseling_notes.length === 0) ? (
                  <div className="p-3 bg-slate-50 rounded-xl border border-slate-200 text-xs text-slate-500 italic">
                    Nihil Layanan Konseling — Belum ada catatan riwayat bimbingan & konseling.
                  </div>
                ) : (
                  <div className="overflow-x-auto border border-slate-200 rounded-xl">
                    <table className="w-full text-xs">
                      <thead>
                        <tr className="bg-slate-100 font-semibold text-slate-700 border-b border-slate-200 text-left">
                          <th className="py-2 px-3 text-center w-10">No</th>
                          <th className="py-2 px-3 text-center w-24">Tanggal</th>
                          <th className="py-2 px-3">Jenis Layanan / Tahapan</th>
                          <th className="py-2 px-3">Konselor BK</th>
                          <th className="py-2 px-3">Rekomendasi / Hasil Konseling</th>
                          <th className="py-2 px-3 text-center w-24">Status</th>
                        </tr>
                      </thead>
                      <tbody className="divide-y divide-slate-100">
                        {profileData.discipline.counseling_notes.map((cn, idx) => (
                          <tr key={idx} className="hover:bg-slate-50">
                            <td className="py-2 px-3 text-center font-mono text-slate-500">{idx + 1}</td>
                            <td className="py-2 px-3 text-center font-mono text-slate-700">{cn.date}</td>
                            <td className="py-2 px-3 font-semibold text-slate-900">{cn.stage}</td>
                            <td className="py-2 px-3 text-slate-700">{cn.counselor}</td>
                            <td className="py-2 px-3 text-slate-600 leading-relaxed">{cn.action_plan || cn.result || "-"}</td>
                            <td className="py-2 px-3 text-center">
                              <span className="inline-block px-2 py-0.5 rounded text-[11px] font-bold bg-blue-100 text-blue-800">
                                {cn.status}
                              </span>
                            </td>
                          </tr>
                        ))}
                      </tbody>
                    </table>
                  </div>
                )}
              </div>
            </div>
          </div>
        </div>
      ) : (
        <div className="p-12 text-center bg-white rounded-2xl border border-slate-200 text-slate-500">
          <GraduationCap className="w-12 h-12 text-slate-300 mx-auto mb-3" />
          <h4 className="text-base font-bold text-slate-800 mb-1">Pilih Siswa untuk Menampilkan Profil</h4>
          <p className="text-xs text-slate-500 max-w-md mx-auto">
            Silakan pilih Tahun Ajaran, Semester, Rombel/Kelas, dan Nama Siswa pada panel filter di atas untuk memuat lembar rekam jejak kumulatif siswa secara real-time.
          </p>
        </div>
      )}

      {/* PRINT MODAL (STANDAR F4 FOLIO 215X330 MM) */}
      <CetakProfilSiswaPrintModal
        isOpen={isPrintModalOpen}
        onClose={() => setIsPrintModalOpen(false)}
        data={profileData}
      />
    </div>
  );
};
