"use client";

import React, { useRef, useState, useEffect } from "react";
import { Printer, FileSpreadsheet, X, Check, Award, ShieldAlert, BookOpen, UserCheck, Calendar } from "lucide-react";
import { Button } from "@/components/ui/Button";
import { PrintOrientationToggle } from "@/components/ui/PrintOrientationToggle";
import { PrintOrientation } from "@/lib/printUtils";
import * as XLSX from "xlsx";

const DEFAULT_AVATAR_SVG =
  "data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='80' height='112' viewBox='0 0 80 112'><rect width='80' height='112' fill='%23f1f5f9'/><circle cx='40' cy='40' r='18' fill='%23cbd5e1'/><path d='M16 98 C16 72 64 72 64 98' fill='%23cbd5e1'/><text x='50%' y='105' font-size='8' font-family='sans-serif' text-anchor='middle' fill='%2364748b' font-weight='bold'>FOTO 3X4</text></svg>";

export interface StudentProfileData {
  student: {
    id: number;
    nis: string;
    nisn: string;
    nama_lengkap: string;
    jenis_kelamin: string;
    tingkat: string;
    rombel: string;
    status: string;
    tempat_lahir: string;
    tanggal_lahir: string;
    agama: string;
    nama_ortu_wali: string;
    no_wa_ortu: string;
    alamat: string;
    rencana_karir_universitas?: string;
    rencana_karir_jurusan?: string;
    photo_url?: string;
  };
  meta: {
    academic_year: string;
    semester: string;
    print_date: string;
  };
  homeroom_teacher: {
    name: string;
    nip?: string;
    phone?: string;
    email?: string;
  };
  school_principal: {
    name: string;
    nip: string;
    title: string;
  };
  attendance: {
    hadir: number;
    sakit: number;
    izin: number;
    alpa: number;
    total: number;
    percentage: number;
  };
  academic: {
    subjects: Array<{
      code: string;
      name: string;
      category?: string;
      kkm: number;
      knowledge_score?: number;
      skill_score?: number;
      score: number;
      predicate: string;
      description: string;
    }>;
    averageScore: number;
    rank: number;
    academicNotes: string;
    matrixRows?: Array<{
      no: number;
      subject_code: string;
      subject_name: string;
      subject_category: string;
      kkm: number;
      sem1: number | null;
      diff1: number | null;
      sem2: number | null;
      diff2: number | null;
      diffX?: number | null;
      sem3: number | null;
      diff3: number | null;
      sem4: number | null;
      diff4: number | null;
      diffXI?: number | null;
      sem5: number | null;
      diff5: number | null;
      sem6: number | null;
      diff6: number | null;
      diffXII?: number | null;
    }>;
    matrixRekapitulasi?: {
      rataRata?: {
        kkm: number | null;
        sem1: number | null;
        diff1: number | null;
        sem2: number | null;
        diff2: number | null;
        diffX?: number | null;
        sem3: number | null;
        diff3: number | null;
        sem4: number | null;
        diff4: number | null;
        diffXI?: number | null;
        sem5: number | null;
        diff5: number | null;
        sem6: number | null;
        diff6: number | null;
        diffXII?: number | null;
      };
      tertinggi?: any;
      terendah?: any;
    };
    top3Mapel?: Array<{
      code?: string;
      name: string;
      category?: string;
      score: number;
    }>;
    bottom3Mapel?: Array<{
      code?: string;
      name: string;
      category?: string;
      score: number;
    }>;
  };
  activities: {
    extracurriculars: Array<{
      name: string;
      role: string;
      predicate: string;
    }>;
    prolife: {
      name: string;
      predicate: string;
      description: string;
    };
    achievements: Array<{
      competition_name: string;
      field: string;
      rank: string;
      level: string;
      date: string;
      organizer?: string;
    }>;
  };
  discipline: {
    total_points: number;
    predicate: string;
    kesiswaan_records?: Array<{
      id?: number;
      date: string;
      violation_name: string;
      category: string;
      points: number;
      tindakan_pembinaan: string;
      status_pembinaan: string;
      reporter?: string;
      notes?: string;
    }>;
    violations: Array<{
      violation_name: string;
      category: string;
      points: number;
      date: string;
      notes?: string;
      reporter?: string;
    }>;
    homeroom_notes: Array<{
      date: string;
      category: string;
      target_type: string;
      notes: string;
      follow_up?: string;
      status: string;
    }>;
    counseling_notes: Array<{
      date: string;
      stage: string;
      counselor: string;
      action_plan?: string;
      result?: string;
      status: string;
    }>;
  };
}

interface CetakProfilSiswaPrintModalProps {
  isOpen: boolean;
  onClose: () => void;
  data: StudentProfileData | null;
}

export const CetakProfilSiswaPrintModal: React.FC<CetakProfilSiswaPrintModalProps> = ({
  isOpen,
  onClose,
  data,
}) => {
  const printRef = useRef<HTMLDivElement>(null);
  const [printOrientation, setPrintOrientation] = useState<PrintOrientation>("portrait");
  const [isPrinting, setIsPrinting] = useState(false);
  const [isReady, setIsReady] = useState(false);

  // Preload kop surat images and ensure full DOM mount
  useEffect(() => {
    if (isOpen) {
      setPrintOrientation("portrait");
      setIsReady(false);
      const img1 = new Image();
      img1.src = "/images/logo-yayasan-bpi.png";
      const img2 = new Image();
      img2.src = "/images/tulisan-bpi.png";
      if (data?.student?.photo_url) {
        const img3 = new Image();
        img3.src = data.student.photo_url;
      }
      const timer = setTimeout(() => {
        setIsReady(true);
      }, 150);
      return () => clearTimeout(timer);
    }
  }, [isOpen, data]);

  // Handle Escape key to close modal
  useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
      if (e.key === "Escape" && isOpen) {
        onClose();
      }
    };
    if (isOpen) {
      window.addEventListener("keydown", handleKeyDown);
    }
    return () => {
      window.removeEventListener("keydown", handleKeyDown);
    };
  }, [isOpen, onClose]);

  if (!isOpen || !data) return null;

  const { student, meta, homeroom_teacher, school_principal, attendance, academic, activities, discipline } = data;

  const handlePrint = () => {
    setIsPrinting(true);
    // Double requestAnimationFrame + delay ensures DOM reflow, fonts, and images are fully painted
    requestAnimationFrame(() => {
      requestAnimationFrame(() => {
        setTimeout(() => {
          if (document.body) {
            document.body.style.overflow = "visible";
          }
          window.print();
          setTimeout(() => {
            setIsPrinting(false);
          }, 800);
        }, 300);
      });
    });
  };

  const handleExportExcel = () => {
    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
      role="dialog"
      aria-modal="true"
      className="fixed inset-0 z-50 flex items-center justify-center p-2 sm:p-4 overflow-y-auto bg-slate-900/70 backdrop-blur-xs print:p-0 print:static print:block print:inset-auto print:z-auto print:bg-transparent"
    >
      <div className="relative w-full max-w-5xl bg-white rounded-2xl shadow-2xl border border-slate-200 overflow-hidden my-auto max-h-[96vh] flex flex-col print:border-none print:shadow-none print:max-w-none print:max-h-none print:w-full print:rounded-none print:static print:overflow-visible print:p-0 print:m-0 print:block">
        {/* Print Stylesheet Standar F4 / Folio (215 x 330 mm) */}
        <style
          dangerouslySetInnerHTML={{
            __html: `
            @page {
              size: ${printOrientation === "landscape" ? "330mm 215mm" : "215mm 330mm"};
              margin: 0 !important;
            }
            @media print {
              @page {
                size: ${printOrientation === "landscape" ? "330mm 215mm" : "215mm 330mm"};
                margin: 0 !important;
              }
              body * {
                visibility: hidden !important;
              }
              aside,
              header,
              nav,
              footer,
              nextjs-portal,
              [data-nextjs-toast],
              [data-nextjs-dialog-overlay],
              #next-route-announcer,
              .no-print,
              .print-hidden,
              .print\\:hidden,
              button {
                display: none !important;
                visibility: hidden !important;
              }
              #printable-profil-siswa,
              #printable-profil-siswa * {
                visibility: visible !important;
              }
              #printable-profil-siswa {
                position: absolute !important;
                left: 0 !important;
                top: 0 !important;
                width: 100% !important;
                max-width: 100% !important;
                margin: 0 !important;
                padding: 10mm 14mm 10mm 14mm !important;
                box-sizing: border-box !important;
                background: #ffffff !important;
                border: none !important;
                box-shadow: none !important;
                z-index: 9999999 !important;
                display: block !important;
              }
              #printable-profil-siswa .profil-section-block {
                display: block !important;
                visibility: visible !important;
                page-break-inside: avoid !important;
                break-inside: avoid !important;
              }
              table {
                page-break-inside: auto;
              }
              tr {
                page-break-inside: avoid !important;
                break-inside: avoid !important;
              }
              .signature-section {
                page-break-inside: avoid !important;
                break-inside: avoid !important;
              }
              html, body {
                width: 100% !important;
                height: auto !important;
                min-height: 100% !important;
                overflow: visible !important;
                margin: 0 !important;
                padding: 0 !important;
                background: #ffffff !important;
                -webkit-print-color-adjust: exact !important;
                print-color-adjust: exact !important;
              }
            }
          `,
          }}
        />

        {/* Toolbar Header (Print Hidden) */}
        <div className="flex flex-wrap items-center justify-between gap-3 p-3.5 bg-slate-50 border-b border-slate-200 rounded-t-2xl print:hidden">
          <div className="flex items-center gap-2 shrink-0">
            <span className="inline-flex items-center px-2.5 py-1 rounded text-[11px] font-bold bg-blue-50 text-blue-700 border border-blue-200 shrink-0">
              Standar Folio / F4 (215×330 mm)
            </span>
            <span className="text-xs text-slate-700 font-medium hidden md:inline">
              Profil Kumulatif Siswa: <b>{student.nama_lengkap}</b> ({student.nis}) &bull; Kelas {student.rombel}
            </span>
          </div>

          <div className="flex flex-wrap items-center gap-2 shrink-0">
            <PrintOrientationToggle
              value={printOrientation}
              onChange={setPrintOrientation}
            />

            <Button
              variant="outline"
              size="sm"
              onClick={handleExportExcel}
              className="h-9 px-3.5 text-xs font-semibold text-emerald-700 border-emerald-300 hover:bg-emerald-50 inline-flex items-center gap-1.5 whitespace-nowrap shadow-2xs"
              title="Unduh Profil Lengkap Excel (.xlsx)"
            >
              <FileSpreadsheet className="w-4 h-4 text-emerald-600" />
              <span>Unduh Excel</span>
            </Button>

            <Button
              variant="outline"
              size="sm"
              onClick={onClose}
              className="h-9 px-3.5 text-xs font-medium text-slate-700 hover:bg-slate-100 whitespace-nowrap shadow-2xs"
            >
              Tutup
            </Button>

            <Button
              variant="primary"
              size="sm"
              onClick={handlePrint}
              disabled={isPrinting || !isReady}
              className="h-9 px-4 text-xs font-semibold bg-blue-600 hover:bg-blue-700 text-white inline-flex items-center gap-2 whitespace-nowrap shadow-xs"
            >
              <Printer className="w-4 h-4" />
              <span>{isPrinting ? "Menyiapkan Cetak..." : !isReady ? "Memuat Dokumen..." : "Cetak Sekarang (PDF)"}</span>
            </Button>
          </div>
        </div>

        {/* Document Scroll Preview Container */}
        <div className="flex-1 overflow-y-auto p-4 sm:p-6 bg-slate-100 print:bg-white print:p-0 print:m-0 print:overflow-visible print:block print:h-auto print:max-h-none">
          <div
            id="printable-profil-siswa"
            ref={printRef}
            className={`printable-document printable-area print-${printOrientation} bg-white p-6 sm:p-9 border border-slate-200 rounded-xl shadow-xs text-black mx-auto print:border-none print:shadow-none print:p-0 print:m-0 print:w-full`}
            style={{
              fontFamily: "'Times New Roman', Times, serif",
              lineHeight: 1.35,
              maxWidth: printOrientation === "landscape" ? "1080px" : "840px",
            }}
          >
            {/* KOP SURAT RESMI SMA BPI 1 BANDUNG */}
            <div className="w-full pb-1 mb-2">
              <div className="flex items-center justify-between gap-4 pb-2">
                {/* Logo Yayasan BPI Kiri */}
                <div className="w-20 shrink-0 flex items-center justify-center">
                  {/* eslint-disable-next-line @next/next/no-img-element */}
                  <img
                    src="/images/logo-yayasan-bpi.png"
                    alt="Logo Yayasan BPI"
                    className="w-16 h-auto object-contain block"
                    onError={(e) => {
                      (e.target as HTMLImageElement).src = "/images/logo-ypbpi.png";
                    }}
                  />
                </div>

                {/* Teks Kop Surat Tengah */}
                <div className="text-center flex-1 px-2 font-serif text-black leading-tight space-y-0.5">
                  <h4 className="text-[13px] sm:text-[14px] font-bold tracking-wider text-slate-900 uppercase">
                    YAYASAN BADAN PERGURUAN INDONESIA
                  </h4>
                  <h3 className="text-[12px] sm:text-[13px] font-bold tracking-wider text-slate-800 uppercase">
                    SEKOLAH MENENGAH ATAS
                  </h3>
                  <h1 className="text-[17px] sm:text-[18px] font-extrabold text-slate-950 uppercase tracking-wide">
                    SMA BPI 1 BANDUNG
                  </h1>
                  <p className="text-[10px] sm:text-[10.5px] text-slate-800 font-semibold">
                    TERAKREDITASI &ldquo;A&rdquo; (UNGGUL) &bull; NSS: 30.0.02.60.13.088 &bull; NPSN: 20219738
                  </p>
                  <p className="text-[9px] sm:text-[9.5px] text-slate-700 font-normal">
                    Jl. Burangrang No. 8 Telp. (022) 7301739 - Fax. (022) 7305805 Bandung 40262
                  </p>
                </div>

                {/* Logo BPI Kanan */}
                <div className="w-20 shrink-0 flex items-center justify-center">
                  {/* eslint-disable-next-line @next/next/no-img-element */}
                  <img
                    src="/images/tulisan-bpi.png"
                    alt="Logo BPI"
                    className="w-16 h-auto object-contain block"
                    onError={(e) => {
                      (e.target as HTMLImageElement).src = "/images/logo-bpi.png";
                    }}
                  />
                </div>
              </div>

              {/* Garis Pembatas Tebal Ganda Kop Surat */}
              <div className="w-full border-b-[3px] border-double border-slate-950" />
            </div>

            {/* JUDUL DOKUMEN */}
            <div className="text-center my-2 space-y-0.5">
              <h2 className="text-sm sm:text-base font-bold uppercase underline tracking-wider text-slate-950">
                LEMBAR PROFIL KUMULATIF & REKAM JEJAK SISWA
              </h2>
              <p className="text-xs font-serif text-slate-800">
                Tahun Ajaran {meta.academic_year} &bull; Semester {meta.semester} &bull; Kelas {student.rombel}
              </p>
            </div>

            {/* ======================================================== */}
            {/* BAGIAN 1: BIODATA & DATA INDUK SISWA                    */}
            {/* ======================================================== */}
            <div className="my-2.5 profil-section-block">
              <div className="bg-slate-100 border border-slate-800 px-2 py-1 text-xs font-bold uppercase text-slate-900 tracking-wider">
                I. BIODATA & DATA INDUK SISWA
              </div>
              <div className="border-x border-b border-slate-800 p-2.5 flex items-start gap-3.5 text-xs">
                {/* Kotak Pas Foto Siswa */}
                <div className="w-24 shrink-0 flex flex-col items-center justify-center border border-slate-400 bg-slate-50 p-1 rounded-sm text-center">
                  <div className="w-20 h-28 bg-slate-200 border border-slate-300 flex items-center justify-center overflow-hidden">
                    {/* eslint-disable-next-line @next/next/no-img-element */}
                    <img
                      src={student.photo_url || DEFAULT_AVATAR_SVG}
                      alt={student.nama_lengkap}
                      className="w-full h-full object-cover block"
                      onError={(e) => {
                        (e.target as HTMLImageElement).src = DEFAULT_AVATAR_SVG;
                      }}
                    />
                  </div>
                  <span className="text-[9px] text-slate-600 mt-1 uppercase font-semibold">Foto 3x4</span>
                </div>

                {/* Kolom Biodata */}
                <div className="flex-1 grid grid-cols-1 sm:grid-cols-2 gap-x-4 gap-y-1 text-xs">
                  <div className="flex items-baseline">
                    <span className="w-32 font-semibold text-slate-800 shrink-0">Nama Lengkap</span>
                    <span className="w-3 font-semibold">:</span>
                    <span className="font-bold text-slate-950 uppercase">{student.nama_lengkap}</span>
                  </div>
                  <div className="flex items-baseline">
                    <span className="w-32 font-semibold text-slate-800 shrink-0">Kelas / Fase</span>
                    <span className="w-3 font-semibold">:</span>
                    <span className="font-bold text-slate-950">{student.rombel} (Fase {student.tingkat === "X" ? "E" : "F"})</span>
                  </div>
                  <div className="flex items-baseline">
                    <span className="w-32 font-semibold text-slate-800 shrink-0">NIS / NISN</span>
                    <span className="w-3 font-semibold">:</span>
                    <span className="font-mono text-slate-900">{student.nis} / {student.nisn}</span>
                  </div>
                  <div className="flex items-baseline">
                    <span className="w-32 font-semibold text-slate-800 shrink-0">Status Siswa</span>
                    <span className="w-3 font-semibold">:</span>
                    <span className="font-semibold text-emerald-900">{student.status}</span>
                  </div>
                  <div className="flex items-baseline">
                    <span className="w-32 font-semibold text-slate-800 shrink-0">Tempat, Tgl Lahir</span>
                    <span className="w-3 font-semibold">:</span>
                    <span className="text-slate-900">{student.tempat_lahir}, {student.tanggal_lahir}</span>
                  </div>
                  <div className="flex items-baseline">
                    <span className="w-32 font-semibold text-slate-800 shrink-0">Jenis Kelamin</span>
                    <span className="w-3 font-semibold">:</span>
                    <span className="text-slate-900">{student.jenis_kelamin}</span>
                  </div>
                  <div className="flex items-baseline">
                    <span className="w-32 font-semibold text-slate-800 shrink-0">Agama</span>
                    <span className="w-3 font-semibold">:</span>
                    <span className="text-slate-900">{student.agama}</span>
                  </div>
                  <div className="flex items-baseline">
                    <span className="w-32 font-semibold text-slate-800 shrink-0">Nama Ortu / Wali</span>
                    <span className="w-3 font-semibold">:</span>
                    <span className="text-slate-900">{student.nama_ortu_wali}</span>
                  </div>
                  <div className="flex items-baseline">
                    <span className="w-32 font-semibold text-slate-800 shrink-0">No. Kontak / WA</span>
                    <span className="w-3 font-semibold">:</span>
                    <span className="font-mono text-slate-900">{student.no_wa_ortu}</span>
                  </div>
                  <div className="flex items-baseline">
                    <span className="w-32 font-semibold text-slate-800 shrink-0">Rencana Karir</span>
                    <span className="w-3 font-semibold">:</span>
                    <span className="text-slate-900 italic">
                      {student.rencana_karir_universitas && student.rencana_karir_universitas !== "-"
                        ? `${student.rencana_karir_universitas} (${student.rencana_karir_jurusan || "-"})`
                        : (student.rencana_karir_jurusan && student.rencana_karir_jurusan !== "-" ? student.rencana_karir_jurusan : "-")}
                    </span>
                  </div>
                  <div className="flex items-baseline sm:col-span-2">
                    <span className="w-32 font-semibold text-slate-800 shrink-0">Alamat Tempat Tinggal</span>
                    <span className="w-3 font-semibold">:</span>
                    <span className="text-slate-900 flex-1">{student.alamat}</span>
                  </div>
                </div>
              </div>
            </div>

            {/* ======================================================== */}
            {/* BAGIAN 2: REKAPITULASI PRESENSI KEHADIRAN               */}
            {/* ======================================================== */}
            <div className="my-2.5 profil-section-block">
              <div className="bg-slate-100 border border-slate-800 px-2 py-1 text-xs font-bold uppercase text-slate-900 tracking-wider">
                II. REKAPITULASI PRESENSI KEHADIRAN SISWA
              </div>
              <div className="border-x border-b border-slate-800 p-2.5 text-xs">
                <div className="grid grid-cols-2 sm:grid-cols-6 gap-2 text-center">
                  <div className="border border-slate-300 p-1.5 rounded bg-emerald-50/50">
                    <span className="text-[10px] uppercase font-bold text-slate-600 block">Hadir</span>
                    <span className="text-sm font-bold text-emerald-800">{attendance.hadir} Hari</span>
                  </div>
                  <div className="border border-slate-300 p-1.5 rounded bg-blue-50/50">
                    <span className="text-[10px] uppercase font-bold text-slate-600 block">Sakit</span>
                    <span className="text-sm font-bold text-blue-800">{attendance.sakit} Hari</span>
                  </div>
                  <div className="border border-slate-300 p-1.5 rounded bg-amber-50/50">
                    <span className="text-[10px] uppercase font-bold text-slate-600 block">Izin</span>
                    <span className="text-sm font-bold text-amber-800">{attendance.izin} Hari</span>
                  </div>
                  <div className="border border-slate-300 p-1.5 rounded bg-rose-50/50">
                    <span className="text-[10px] uppercase font-bold text-slate-600 block">Alpha (Tanpa Ket.)</span>
                    <span className="text-sm font-bold text-rose-800">{attendance.alpa} Hari</span>
                  </div>
                  <div className="border border-slate-300 p-1.5 rounded bg-slate-50">
                    <span className="text-[10px] uppercase font-bold text-slate-600 block">Total Hari Efektif</span>
                    <span className="text-sm font-bold text-slate-800">{attendance.total} Hari</span>
                  </div>
                  <div className="border border-slate-800 p-1.5 rounded bg-blue-100">
                    <span className="text-[10px] uppercase font-bold text-slate-700 block">% Kehadiran</span>
                    <span className="text-sm font-extrabold text-blue-950">
                      {attendance.total > 0 ? `${attendance.percentage}%` : "-"}
                    </span>
                  </div>
                </div>
              </div>
            </div>

            {/* ======================================================== */}
            {/* BAGIAN 3: MATRIKS ANALISIS EVALUASI NILAI RAPOR PESERTA DIDIK */}
            {/* ======================================================== */}
            <div className="my-2.5 profil-section-block">
              <div className="bg-slate-100 border border-slate-800 px-2 py-1 text-xs font-bold uppercase text-slate-900 tracking-wider flex justify-between items-center">
                <span>III. MATRIKS ANALISIS EVALUASI NILAI RAPOR PESERTA DIDIK</span>
                <span className="text-[11px] font-normal lowercase tracking-normal">
                  Rata-rata: <b>{academic.averageScore > 0 ? academic.averageScore : "-"}</b> &bull; Peringkat: <b>{academic.rank > 0 ? `Ke-${academic.rank}` : "-"}</b>
                </span>
              </div>
              <div className="border-x border-b border-slate-800 p-2 text-xs">
                {/* Header Ringkasan Atas: Top 3 Mapel (Hijau) & Perhatian BK (Merah) */}
                <div className="grid grid-cols-1 sm:grid-cols-2 gap-2 mb-2 p-1.5 bg-slate-50 border border-slate-300 rounded text-[11px] print:p-1 print:mb-1">
                  <div className="flex items-center gap-1.5 flex-wrap">
                    <span className="font-bold text-emerald-800 bg-emerald-100 border border-emerald-300 px-1.5 py-0.5 rounded text-[10px] shrink-0 uppercase tracking-wide">
                      ★ Top 3 Mapel:
                    </span>
                    <div className="flex items-center gap-1.5 flex-wrap">
                      {academic.top3Mapel && academic.top3Mapel.length > 0 ? (
                        academic.top3Mapel.map((item, idx) => (
                          <span
                            key={item.code || idx}
                            className="bg-white border border-emerald-300 px-1.5 py-0.5 rounded text-[10.5px] text-slate-800 font-medium"
                          >
                            <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-[10px]">-</span>
                      )}
                    </div>
                  </div>
                  <div className="flex items-center gap-1.5 flex-wrap">
                    <span className="font-bold text-rose-800 bg-rose-100 border border-rose-300 px-1.5 py-0.5 rounded text-[10px] shrink-0 uppercase tracking-wide">
                      ▲ Perhatian BK:
                    </span>
                    <div className="flex items-center gap-1.5 flex-wrap">
                      {academic.bottom3Mapel && academic.bottom3Mapel.length > 0 ? (
                        academic.bottom3Mapel.map((item, idx) => (
                          <span
                            key={item.code || idx}
                            className="bg-white border border-rose-300 px-1.5 py-0.5 rounded text-[10.5px] text-slate-800 font-medium"
                          >
                            <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-[10px]">-</span>
                      )}
                    </div>
                  </div>
                </div>

                {/* TABEL MATRIKS MULTI-SEMESTER DENGAN SELISIH */}
                <div className="overflow-x-auto">
                  <table className="w-full border border-slate-700 border-collapse text-[10px]" style={{ 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-200 text-slate-900 border-b border-slate-700 font-bold">
                        <th rowSpan={2} className="border border-slate-500 py-1 px-1 text-center">No</th>
                        <th rowSpan={2} className="border border-slate-500 py-1 px-1.5 text-left">Mata Pelajaran</th>
                        <th rowSpan={2} className="border border-slate-500 py-1 px-1 text-center">Kategori</th>
                        <th rowSpan={2} className="border border-slate-500 py-1 px-1 text-center bg-amber-100">KKM</th>
                        <th colSpan={4} className="border border-slate-500 py-0.5 px-1 text-center bg-blue-100 font-extrabold text-blue-950">Grup Kelas X</th>
                        <th colSpan={4} className="border border-slate-500 py-0.5 px-1 text-center bg-indigo-100 font-extrabold text-indigo-950">Grup Kelas XI</th>
                        <th colSpan={4} className="border border-slate-500 py-0.5 px-1 text-center bg-purple-100 font-extrabold text-purple-950">Grup Kelas XII</th>
                      </tr>
                      <tr className="bg-slate-100 text-slate-800 border-b border-slate-600 font-bold">
                        {/* Kelas X */}
                        <th className="border border-slate-400 py-0.5 text-center">Sem 1</th>
                        <th className="border border-slate-400 py-0.5 text-center bg-blue-50 font-extrabold">S</th>
                        <th className="border border-slate-400 py-0.5 text-center">Sem 2</th>
                        <th className="border border-slate-400 py-0.5 text-center bg-blue-50 font-extrabold">S</th>
                        {/* Kelas XI */}
                        <th className="border border-slate-400 py-0.5 text-center">Sem 3</th>
                        <th className="border border-slate-400 py-0.5 text-center bg-indigo-50 font-extrabold">S</th>
                        <th className="border border-slate-400 py-0.5 text-center">Sem 4</th>
                        <th className="border border-slate-400 py-0.5 text-center bg-indigo-50 font-extrabold">S</th>
                        {/* Kelas XII */}
                        <th className="border border-slate-400 py-0.5 text-center">Sem 5</th>
                        <th className="border border-slate-400 py-0.5 text-center bg-purple-50 font-extrabold">S</th>
                        <th className="border border-slate-400 py-0.5 text-center">Sem 6</th>
                        <th className="border border-slate-400 py-0.5 text-center bg-purple-50 font-extrabold">S</th>
                      </tr>
                    </thead>
                    <tbody>
                      {(academic.matrixRows && academic.matrixRows.length > 0) ? (
                        academic.matrixRows.map((r) => (
                          <tr key={r.subject_code} className="border-b border-slate-300 hover:bg-slate-50/50">
                            <td className="border border-slate-400 py-0.5 text-center font-mono">{r.no}</td>
                            <td className="border border-slate-400 py-0.5 px-1.5 font-medium truncate" title={r.subject_name}>{r.subject_name}</td>
                            <td className="border border-slate-400 py-0.5 text-center text-slate-600">{r.subject_category}</td>
                            <td className="border border-slate-400 py-0.5 text-center font-bold bg-amber-50/50">{r.kkm}</td>

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

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

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

                {/* Catatan / Keterangan Selisih */}
                <div className="mt-1.5 pt-1 border-t border-slate-200 flex flex-wrap items-center justify-between text-[9.5px] text-slate-600">
                  <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">
                      <span className="inline-block w-2.5 h-2.5 bg-rose-100 border border-rose-300"></span>
                      <span>Merah: Penurunan nilai</span>
                    </span>
                    <span className="flex items-center gap-1">
                      <span className="inline-block w-2.5 h-2.5 bg-amber-100 border border-amber-300"></span>
                      <span>KKM Mapel</span>
                    </span>
                  </div>
                  {academic.academicNotes && (
                    <span className="italic truncate max-w-md">{academic.academicNotes}</span>
                  )}
                </div>
              </div>
            </div>

            {/* ======================================================== */}
            {/* BAGIAN 4: EKSTRAKURIKULER, PROLIFE & PRESTASI           */}
            {/* ======================================================== */}
            <div className="my-2.5 profil-section-block">
              <div className="bg-slate-100 border border-slate-800 px-2 py-1 text-xs font-bold uppercase text-slate-900 tracking-wider">
                IV. KEGIATAN EKSTRAKURIKULER, PROGRAM PROLIFE & PRESTASI
              </div>
              <div className="border-x border-b border-slate-800 p-2.5 space-y-2 text-xs">
                {/* Tabel Ekskul & Prolife */}
                <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
                  <div>
                    <span className="font-bold block text-slate-900 border-b border-slate-200 pb-0.5 mb-1">
                      A. Ekstrakurikuler yang Diikuti:
                    </span>
                    {(activities.extracurriculars && activities.extracurriculars.length > 0) ? (
                      <ul className="space-y-1">
                        {activities.extracurriculars.map((e, idx) => (
                          <li key={idx} className="flex justify-between items-center text-[11px] border-b border-dashed border-slate-200 pb-0.5">
                            <span>&bull; {e.name} ({e.role})</span>
                            <span className="font-semibold text-slate-800">Predikat: {e.predicate}</span>
                          </li>
                        ))}
                      </ul>
                    ) : (
                      <p className="text-[11px] text-slate-500 italic">Belum ada kegiatan ekstrakurikuler yang diikuti.</p>
                    )}
                  </div>

                  <div>
                    <span className="font-bold block text-slate-900 border-b border-slate-200 pb-0.5 mb-1">
                      B. Program Prolife (Pengembangan Diri):
                    </span>
                    <div className="text-[11px] space-y-0.5">
                      {activities.prolife && activities.prolife.name !== "-" ? (
                        <>
                          <p className="font-semibold text-slate-900">&bull; {activities.prolife.name}</p>
                          <p className="text-slate-700 italic">Predikat: <b>{activities.prolife.predicate}</b> &mdash; {activities.prolife.description}</p>
                        </>
                      ) : (
                        <p className="text-slate-500 italic">Belum ada program Prolife yang terdaftar.</p>
                      )}
                    </div>
                  </div>
                </div>

                {/* Tabel Prestasi / Penghargaan */}
                <div className="pt-1.5 border-t border-slate-200">
                  <span className="font-bold block text-slate-900 mb-1">
                    C. Rekapitulasi Prestasi / Penghargaan:
                  </span>
                  {activities.achievements.length === 0 ? (
                    <p className="text-[11px] text-slate-500 italic">
                      Belum ada catatan kejuaraan / Dalam proses pembinaan prestasi dan kompetisi.
                    </p>
                  ) : (
                    <table className="w-full border border-slate-400 text-[10.5px]">
                      <thead>
                        <tr className="bg-slate-100 font-bold">
                          <th className="py-1 px-1.5 border-r border-slate-400 text-center w-6">No</th>
                          <th className="py-1 px-2 border-r border-slate-400 text-left">Nama Kejuaraan / Lomba</th>
                          <th className="py-1 px-2 border-r border-slate-400 text-left">Bidang</th>
                          <th className="py-1 px-1.5 border-r border-slate-400 text-center">Peringkat</th>
                          <th className="py-1 px-1.5 border-r border-slate-400 text-center">Tingkat</th>
                          <th className="py-1 px-2 text-left">Penyelenggara / Waktu</th>
                        </tr>
                      </thead>
                      <tbody>
                        {activities.achievements.map((ach, idx) => (
                          <tr key={idx} className="border-t border-slate-300">
                            <td className="py-1 px-1.5 border-r border-slate-300 text-center font-mono">{idx + 1}</td>
                            <td className="py-1 px-2 border-r border-slate-300 font-semibold">{ach.competition_name}</td>
                            <td className="py-1 px-2 border-r border-slate-300">{ach.field}</td>
                            <td className="py-1 px-1.5 border-r border-slate-300 text-center font-bold text-emerald-800">{ach.rank}</td>
                            <td className="py-1 px-1.5 border-r border-slate-300 text-center">{ach.level}</td>
                            <td className="py-1 px-2">{ach.organizer ? `${ach.organizer} (${ach.date})` : ach.date}</td>
                          </tr>
                        ))}
                      </tbody>
                    </table>
                  )}
                </div>
              </div>
            </div>

            {/* ======================================================== */}
            {/* BAGIAN 5: KEDISIPLINAN, CATATAN WALI KELAS & BK         */}
            {/* ======================================================== */}
            <div className="my-2.5 profil-section-block">
              <div className="bg-slate-100 border border-slate-800 px-2 py-1 text-xs font-bold uppercase text-slate-900 tracking-wider flex justify-between items-center">
                <span>V. KEDISIPLINAN, CATATAN WALI KELAS & BIMBINGAN KONSELING</span>
                <span className="text-[11px] font-normal lowercase tracking-normal">
                  Total Poin Pelanggaran: <b>{discipline.total_points} Poin</b> ({discipline.predicate})
                </span>
              </div>
              <div className="border-x border-b border-slate-800 p-2.5 space-y-2 text-xs">
                {/* Tabel Pelanggaran & Pembinaan Terhubung Real-Time Modul Kesiswaan */}
                <div>
                  <div className="flex items-center justify-between border-b border-slate-200 pb-0.5 mb-1">
                    <span className="font-bold text-slate-900">
                      A. Rekapitulasi Pelanggaran & Pembinaan (Terhubung Real-Time Modul Kesiswaan):
                    </span>
                    <span className="text-[10px] text-slate-600 italic">
                      Sinkronisasi Database Kesiswaan
                    </span>
                  </div>
                  {(!discipline.kesiswaan_records || discipline.kesiswaan_records.length === 0) ? (
                    <div className="p-1.5 bg-slate-50 border border-dashed border-slate-300 rounded text-[10.5px] text-slate-700 italic">
                      Nihil Catatan Pelanggaran — Siswa tidak memiliki catatan pelanggaran tata tertib kesiswaan (Predikat Kedisiplinan: <b>{discipline.predicate}</b>).
                    </div>
                  ) : (
                    <table className="w-full border border-slate-400 text-[10.5px]">
                      <thead>
                        <tr className="bg-slate-100 font-bold">
                          <th className="py-1 px-1.5 border-r border-slate-400 text-center w-6">No</th>
                          <th className="py-1 px-2 border-r border-slate-400 text-center w-20">Tanggal</th>
                          <th className="py-1 px-2 border-r border-slate-400 text-left">Jenis Pelanggaran</th>
                          <th className="py-1 px-2 border-r border-slate-400 text-left w-24">Kategori</th>
                          <th className="py-1 px-1.5 border-r border-slate-400 text-center w-12">Poin</th>
                          <th className="py-1 px-2 border-r border-slate-400 text-left">Tindakan / Status Pembinaan</th>
                          <th className="py-1 px-2 text-left w-24">Petugas / Pelapor</th>
                        </tr>
                      </thead>
                      <tbody>
                        {discipline.kesiswaan_records.map((k, idx) => (
                          <tr key={idx} className="border-t border-slate-300">
                            <td className="py-1 px-1.5 border-r border-slate-300 text-center font-mono">{idx + 1}</td>
                            <td className="py-1 px-2 border-r border-slate-300 text-center font-mono">{k.date}</td>
                            <td className="py-1 px-2 border-r border-slate-300 font-semibold">{k.violation_name}</td>
                            <td className="py-1 px-2 border-r border-slate-300">{k.category}</td>
                            <td className="py-1 px-1.5 border-r border-slate-300 text-center font-mono font-bold text-rose-800">
                              +{k.points}
                            </td>
                            <td className="py-1 px-2 border-r border-slate-300 leading-tight">
                              <span className="font-medium text-slate-900">{k.tindakan_pembinaan}</span>
                              <span className="text-[10px] text-slate-600 block italic">Status: {k.status_pembinaan}</span>
                            </td>
                            <td className="py-1 px-2 text-[10px]">{k.reporter || "-"}</td>
                          </tr>
                        ))}
                      </tbody>
                    </table>
                  )}
                </div>

                {/* Catatan Pembinaan Wali Kelas */}
                <div className="pt-1.5 border-t border-slate-200">
                  <span className="font-bold block text-slate-900 mb-1">
                    B. Riwayat Pembinaan Wali Kelas:
                  </span>
                  {(!discipline.homeroom_notes || discipline.homeroom_notes.length === 0) ? (
                    <div className="p-1.5 bg-slate-50 border border-dashed border-slate-300 rounded text-[10.5px] text-slate-700 italic">
                      Nihil Catatan Pembinaan — Belum ada catatan pembinaan khusus dari wali kelas.
                    </div>
                  ) : (
                    <table className="w-full border border-slate-400 text-[10.5px]">
                      <thead>
                        <tr className="bg-slate-100 font-bold">
                          <th className="py-1 px-1.5 border-r border-slate-400 text-center w-6">No</th>
                          <th className="py-1 px-2 border-r border-slate-400 text-center w-20">Tanggal</th>
                          <th className="py-1 px-2 border-r border-slate-400 text-left w-36">Kategori</th>
                          <th className="py-1 px-2 border-r border-slate-400 text-left">Uraian Catatan & Perkembangan</th>
                          <th className="py-1 px-2 border-r border-slate-400 text-left w-36">Tindak Lanjut</th>
                          <th className="py-1 px-1.5 text-center w-16">Status</th>
                        </tr>
                      </thead>
                      <tbody>
                        {discipline.homeroom_notes.map((hn, idx) => (
                          <tr key={idx} className="border-t border-slate-300">
                            <td className="py-1 px-1.5 border-r border-slate-300 text-center font-mono">{idx + 1}</td>
                            <td className="py-1 px-2 border-r border-slate-300 text-center font-mono">{hn.date}</td>
                            <td className="py-1 px-2 border-r border-slate-300 font-medium">{hn.category}</td>
                            <td className="py-1 px-2 border-r border-slate-300 leading-tight">{hn.notes}</td>
                            <td className="py-1 px-2 border-r border-slate-300 italic">{hn.follow_up || "-"}</td>
                            <td className="py-1 px-1.5 text-center font-semibold">{hn.status}</td>
                          </tr>
                        ))}
                      </tbody>
                    </table>
                  )}
                </div>

                {/* Catatan Layanan BK */}
                <div className="pt-1.5 border-t border-slate-200">
                  <span className="font-bold block text-slate-900 mb-1">
                    C. Layanan Bimbingan & Konseling (BK):
                  </span>
                  {(!discipline.counseling_notes || discipline.counseling_notes.length === 0) ? (
                    <div className="p-1.5 bg-slate-50 border border-dashed border-slate-300 rounded text-[10.5px] text-slate-700 italic">
                      Nihil Layanan Konseling — Belum ada catatan riwayat bimbingan & konseling.
                    </div>
                  ) : (
                    <table className="w-full border border-slate-400 text-[10.5px]">
                      <thead>
                        <tr className="bg-slate-100 font-bold">
                          <th className="py-1 px-1.5 border-r border-slate-400 text-center w-6">No</th>
                          <th className="py-1 px-2 border-r border-slate-400 text-center w-20">Tanggal</th>
                          <th className="py-1 px-2 border-r border-slate-400 text-left w-44">Jenis Layanan / Bimbingan</th>
                          <th className="py-1 px-2 border-r border-slate-400 text-left">Hasil / Rekomendasi Konseling</th>
                          <th className="py-1 px-2 text-left w-36">Konselor</th>
                        </tr>
                      </thead>
                      <tbody>
                        {discipline.counseling_notes.map((cn, idx) => (
                          <tr key={idx} className="border-t border-slate-300">
                            <td className="py-1 px-1.5 border-r border-slate-300 text-center font-mono">{idx + 1}</td>
                            <td className="py-1 px-2 border-r border-slate-300 text-center font-mono">{cn.date}</td>
                            <td className="py-1 px-2 border-r border-slate-300 font-medium">{cn.stage}</td>
                            <td className="py-1 px-2 border-r border-slate-300 leading-tight">{cn.action_plan || cn.result || "-"}</td>
                            <td className="py-1 px-2">{cn.counselor}</td>
                          </tr>
                        ))}
                      </tbody>
                    </table>
                  )}
                </div>
              </div>
            </div>

            {/* BLOK TANDA TANGAN DINAMIS */}
            <div
              className="flex items-start justify-between text-xs text-slate-950 pt-3 signature-section"
              style={{ pageBreakInside: "avoid" }}
            >
              {/* Sisi Kiri: Kepala SMA BPI 1 Bandung */}
              <div className="text-center min-w-[220px]">
                <p className="mb-0.5">Mengetahui,</p>
                <p className="font-bold">Kepala SMA BPI 1 Bandung</p>
                <div className="h-16 flex items-center justify-center">
                  <span className="text-[10px] text-slate-400 italic">
                    (Tanda Tangan & Cap Sekolah)
                  </span>
                </div>
                <p className="font-bold underline uppercase tracking-wide">
                  {school_principal.name}
                </p>
                <p className="text-[11px] font-mono text-slate-800">
                  {school_principal.nip}
                </p>
              </div>

              {/* Sisi Kanan: Wali Kelas Dinamis */}
              <div className="text-center min-w-[220px]">
                <p className="mb-0.5">Bandung, {meta.print_date}</p>
                <p className="font-bold">Wali Kelas {student.rombel}</p>
                <div className="h-16 flex items-center justify-center">
                  <span className="text-[10px] text-slate-400 italic">
                    (Tanda Tangan)
                  </span>
                </div>
                <p className="font-bold underline uppercase tracking-wide">
                  {homeroom_teacher.name}
                </p>
                <p className="text-[11px] font-mono text-slate-800">
                  {homeroom_teacher.nip || "NIPY. 10105"}
                </p>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};
