"use client";

import React, { useState, useEffect } from "react";
import { useAuth } from "@/context/AuthContext";
import {
  GraduationCap,
  UserCheck,
  Award,
  AlertCircle,
  ShieldCheck,
  Calendar,
  BookOpen,
  HeartHandshake,
  Printer,
  Sparkles,
  Phone,
  Mail,
  MapPin,
  CheckCircle2,
  Clock,
  Compass,
  FileText,
  User,
  Activity,
  Layers,
  ChevronRight,
  TrendingUp,
  TrendingDown,
  LineChart as LineChartIcon,
  Minus,
  ArrowUpRight,
  ArrowDownRight,
  Table as TableIcon,
  ShieldAlert,
} from "lucide-react";
import { Button } from "@/components/ui/Button";
import { Badge } from "@/components/ui/Badge";
import Link from "next/link";
import { useSearchParams, useRouter } from "next/navigation";

interface StudentPortalViewProps {
  mode?: "student" | "parent";
}

const StudentPortalViewContent: React.FC<StudentPortalViewProps> = ({
  mode = "student",
}) => {
  const { user, isLoading: authLoading } = useAuth();
  const searchParams = useSearchParams();
  const router = useRouter();
  const tabParam = searchParams?.get("tab");

  const [data, setData] = useState<any>(null);
  const [isLoading, setIsLoading] = useState(true);
  const [activeTab, setActiveTab] = useState<
    "profil" | "rapor" | "presensi" | "kedisiplinan" | "ekskul"
  >("profil");

  // Sinkronisasi tab aktif dengan parameter URL ?tab= secara real-time
  useEffect(() => {
    const sp = tabParam || (typeof window !== "undefined" ? new URLSearchParams(window.location.search).get("tab") : null);
    if (sp && ["profil", "rapor", "presensi", "kedisiplinan", "ekskul"].includes(sp)) {
      setActiveTab(sp as any);
    } else if (!sp) {
      setActiveTab("profil");
    }
  }, [tabParam]);
  const [selectedSemester, setSelectedSemester] = useState<string>("kumulatif");
  const [activeTableView, setActiveTableView] = useState<"matrix" | "breakdown">("matrix");
  const [showAllLine, setShowAllLine] = useState(true);
  const [showMipaLine, setShowMipaLine] = useState(true);
  const [showIpsLine, setShowIpsLine] = useState(true);
  const [showBahasaLine, setShowBahasaLine] = useState(true);
  const [showKhasBpiLine, setShowKhasBpiLine] = useState(true);

  // Helper fungsi untuk Line Chart SVG Tren Semester 1-6
  const svgW = 800;
  const svgH = 260;
  const padL = 55;
  const padR = 30;
  const padT = 25;
  const padB = 40;
  const chartW = svgW - padL - padR;
  const chartH = svgH - padT - padB;
  const minY = 60;
  const maxY = 100;

  const getX = (sem: number) => padL + ((sem - 1) / 5) * chartW;
  const getY = (val: number | null) => {
    if (val === null || val === undefined) return padT + chartH;
    const clamped = Math.max(minY, Math.min(maxY, Number(val)));
    return padT + chartH - ((clamped - minY) / (maxY - minY)) * chartH;
  };

  const makePath = (
    series: any[],
    key: "rataRataAll" | "rataRataMipa" | "rataRataIps" | "rataRataBahasa" | "rataRataKhasBpi"
  ) => {
    if (!series || series.length === 0) return "";
    let d = "";
    series.forEach((pt: any) => {
      const val = pt[key];
      if (val !== null && val !== undefined) {
        const x = getX(pt.semester);
        const y = getY(val);
        if (!d) d = `M ${x} ${y}`;
        else d += ` L ${x} ${y}`;
      }
    });
    return d;
  };

  const renderScoreValue = (val: number | null) => {
    if (val === null || val === undefined) {
      return <span className="text-gray-300 font-mono">-</span>;
    }
    const num = Number(val);
    const isBelowKkm = num < 75;
    const isExcellent = num >= 88;

    return (
      <span
        className={`inline-block font-mono px-2 py-0.5 rounded text-xs transition-colors ${
          isBelowKkm
            ? "bg-rose-100 text-rose-800 font-bold border border-rose-300"
            : isExcellent
            ? "font-bold text-emerald-800 bg-emerald-50 border border-emerald-200"
            : "font-medium text-gray-800"
        }`}
      >
        {num.toFixed(1)}
      </span>
    );
  };

  const renderDiffValue = (diff: number | null) => {
    if (diff === null || diff === undefined) {
      return <span className="text-gray-300 font-mono">-</span>;
    }
    const num = Number(diff);
    if (num > 0) {
      return (
        <span className="inline-flex items-center gap-0.5 text-[11px] font-semibold text-emerald-700 bg-emerald-50 px-1.5 py-0.5 rounded border border-emerald-200">
          <ArrowUpRight className="w-3 h-3 text-emerald-600" />
          <span>+{num.toFixed(1)}</span>
        </span>
      );
    }
    if (num < 0) {
      return (
        <span className="inline-flex items-center gap-0.5 text-[11px] font-bold text-rose-700 bg-rose-50 px-1.5 py-0.5 rounded border border-rose-200">
          <ArrowDownRight className="w-3 h-3 text-rose-600" />
          <span>{num.toFixed(1)}</span>
        </span>
      );
    }
    return (
      <span className="inline-flex items-center gap-0.5 text-[11px] font-normal text-slate-500 bg-slate-50 px-1.5 py-0.5 rounded border border-slate-200">
        <Minus className="w-2.5 h-2.5 text-slate-400" />
        <span>0.0</span>
      </span>
    );
  };

  useEffect(() => {
    // Tunggu sesi auth siap jika sedang memuat dan belum ada user di state
    if (authLoading && !user) {
      return;
    }

    async function fetchPortalData() {
      setIsLoading(true);
      try {
        const params = new URLSearchParams();
        if (user?.username) {
          params.set("username", user.username);
        }
        if (user?.reference_id) {
          params.set("student_id", String(user.reference_id));
        }
        if (user?.id_induk) {
          params.set("id_induk", user.id_induk);
        }
        const url = `/api/portal/student-data${params.toString() ? `?${params.toString()}` : ""}`;
        const res = await fetch(url, { cache: "no-store" });
        const json = await res.json();
        if (json.success) {
          setData(json);
        } else {
          setData(null);
        }
      } catch (err) {
        console.error("Gagal memuat data portal:", err);
        setData(null);
      } finally {
        setIsLoading(false);
      }
    }
    fetchPortalData();
  }, [user?.username, user?.reference_id, user?.id_induk, authLoading]);

  if (isLoading) {
    return (
      <div className="min-h-[60vh] flex flex-col items-center justify-center p-8 text-center space-y-4">
        <div className="w-12 h-12 border-4 border-blue-600 border-t-transparent rounded-full animate-spin" />
        <div className="text-slate-600 font-medium">
          Memuat data real-time peserta didik SMA BPI 1 Bandung...
        </div>
      </div>
    );
  }

  if (!data || !data.student) {
    return (
      <div className="p-8 max-w-2xl mx-auto text-center space-y-4 bg-white rounded-2xl shadow-sm border border-slate-200 mt-6">
        <AlertCircle className="w-12 h-12 text-amber-500 mx-auto" />
        <h3 className="text-lg font-bold text-slate-800">
          Data Siswa Belum Terhubung
        </h3>
        <p className="text-sm text-slate-600 leading-relaxed">
          Akun Anda belum terhubung dengan data induk siswa di sistem. Mohon
          hubungi Tim Administrator IT atau Bagian Kesiswaan SMA BPI 1 Bandung
          untuk sinkronisasi NIS/NISN.
        </p>
      </div>
    );
  }

  const {
    student,
    homeroomTeacher,
    attendance,
    dhuhaAttendance,
    academic,
    analisisRapor,
    violations,
    counselings,
    extracurricular,
    achievements,
  } = data;

  const analisisSummary = analisisRapor?.summary;
  const selectedStudent = analisisRapor?.selectedStudent;
  const matrixRows = analisisRapor?.matrixRows || [];
  const matrixRekap = analisisRapor?.matrixRekapitulasi;
  const trendSeries = analisisRapor?.trendSeries || [];
  const breakdownRows = analisisRapor?.breakdownRows || [];

  const effectiveAvgScore = analisisSummary?.rataRataRapor
    ? Number(analisisSummary.rataRataRapor).toFixed(1)
    : (academic?.averageScore ? String(academic.averageScore) : "0.0");
  const effectiveClassRank = selectedStudent?.rankClass || academic?.classRank || 1;
  const effectiveTotalClass = selectedStudent?.totalInClass || 36;
  const effectiveParallelRank = selectedStudent?.rankParallel || 1;
  const effectiveTotalParallel = selectedStudent?.totalInParallel || 719;

  const top3List = selectedStudent?.top3Mapel && selectedStudent.top3Mapel.length > 0
    ? selectedStudent.top3Mapel
    : (academic?.top3 || []);
  const bottom3List = selectedStudent?.bottom3Mapel && selectedStudent.bottom3Mapel.length > 0
    ? selectedStudent.bottom3Mapel
    : (academic?.bkAttention || []);

  const isParent = mode === "parent" || user?.role === "Orang Tua / Wali";

  return (
    <div className="space-y-6 pb-12">
      {/* 1. Header Banner & Identitas Siswa */}
      <div className="bg-gradient-to-r from-blue-900 via-blue-800 to-indigo-900 rounded-3xl p-6 sm:p-8 text-white shadow-lg relative overflow-hidden">
        {/* Pattern Background */}
        <div className="absolute inset-0 opacity-10 bg-[radial-gradient(#fff_1px,transparent_1px)] [background-size:16px_16px] pointer-events-none" />

        <div className="relative z-10 flex flex-col lg:flex-row lg:items-center justify-between gap-6">
          <div className="flex items-start sm:items-center gap-4 sm:gap-6">
            <div className="w-16 h-16 sm:w-20 sm:h-20 rounded-2xl bg-white/10 backdrop-blur-md border border-white/20 flex items-center justify-center shrink-0 shadow-inner">
              <GraduationCap className="w-9 h-9 sm:w-11 sm:h-11 text-blue-200" />
            </div>

            <div className="space-y-1.5">
              <div className="flex flex-wrap items-center gap-2">
                <span className="px-3 py-1 rounded-full text-xs font-bold uppercase tracking-wider bg-blue-500/30 text-blue-200 border border-blue-400/30">
                  {isParent ? "Portal Pemantauan Orang Tua" : "Portal Resmi Siswa"}
                </span>
                <span className="px-3 py-1 rounded-full text-xs font-bold bg-emerald-500/30 text-emerald-200 border border-emerald-400/30">
                  Status: {student.status}
                </span>
                <span className="px-3 py-1 rounded-full text-xs font-bold bg-white/20 text-white border border-white/20">
                  Kelas {student.rombel}
                </span>
              </div>

              <h1 className="text-2xl sm:text-3xl font-extrabold tracking-tight text-white drop-shadow-sm">
                {student.nama_lengkap}
              </h1>

              <div className="flex flex-wrap items-center gap-x-4 gap-y-1 text-xs sm:text-sm text-blue-100 font-medium">
                <span>NIS: <strong className="text-white font-mono">{student.nis}</strong></span>
                <span>•</span>
                <span>NISN: <strong className="text-white font-mono">{student.nisn || "-"}</strong></span>
                <span>•</span>
                <span>Wali Kelas: <strong className="text-white">{homeroomTeacher.name}</strong></span>
              </div>
            </div>
          </div>

          <div className="flex flex-wrap items-center gap-3 shrink-0 self-start lg:self-auto">
            {!isParent && (
              <Link href="/portal-siswa/biodata">
                <Button className="bg-amber-400 hover:bg-amber-500 text-slate-900 text-xs sm:text-sm font-bold h-10 px-4 rounded-xl shadow-md transition-all flex items-center gap-2 border border-amber-300">
                  <FileText className="w-4 h-4 text-slate-900" />
                  <span>Lengkapi Biodata</span>
                </Button>
              </Link>
            )}
          </div>
        </div>
      </div>

      {/* 2. 4 Kartu Metrik Ringkasan Utama */}
      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
        {/* Card 1: Kehadiran KBM */}
        <div className="bg-white p-5 rounded-2xl border border-slate-200 shadow-sm hover:shadow-md transition-all">
          <div className="flex items-center justify-between mb-3">
            <span className="text-xs font-bold uppercase tracking-wider text-slate-500">
              Presensi KBM Harian
            </span>
            <div className="w-9 h-9 rounded-xl bg-blue-50 text-blue-600 flex items-center justify-center">
              <UserCheck className="w-5 h-5" />
            </div>
          </div>
          <div className="flex items-baseline gap-2">
            <span className="text-3xl font-black text-slate-900">
              {attendance.percentage}%
            </span>
            <span className="text-xs font-semibold text-emerald-600">
              Tingkat Kehadiran
            </span>
          </div>
          <p className="mt-2 text-xs text-slate-500">
            Hadir: <strong>{attendance.hadir}</strong> | Sakit: {attendance.sakit} | Izin: {attendance.izin} | Alpa: {attendance.alpa}
          </p>
        </div>

        {/* Card 2: Rata-Rata Nilai Rapor */}
        <div className="bg-white p-5 rounded-2xl border border-slate-200 shadow-sm hover:shadow-md transition-all">
          <div className="flex items-center justify-between mb-3">
            <span className="text-xs font-bold uppercase tracking-wider text-slate-500">
              Rata-Rata Rapor
            </span>
            <div className="w-9 h-9 rounded-xl bg-emerald-50 text-emerald-600 flex items-center justify-center">
              <TrendingUp className="w-5 h-5" />
            </div>
          </div>
          <div className="flex items-baseline gap-2">
            <span className="text-3xl font-black text-slate-900">
              {effectiveAvgScore}
            </span>
            <span className="text-xs font-bold px-2 py-0.5 rounded-full bg-emerald-100 text-emerald-800">
              Rank #{effectiveClassRank} dari {effectiveTotalClass} Siswa
            </span>
          </div>
          <p className="mt-2 text-xs text-slate-500">
            {analisisSummary?.mapelTertinggi
              ? `Tertinggi: ${analisisSummary.mapelTertinggi.name} (${analisisSummary.mapelTertinggi.score})`
              : "Analisis rapor kumulatif Kurikulum Merdeka"}
          </p>
        </div>

        {/* Card 3: Presensi Shalat Dhuha */}
        <div className="bg-white p-5 rounded-2xl border border-slate-200 shadow-sm hover:shadow-md transition-all">
          <div className="flex items-center justify-between mb-3">
            <span className="text-xs font-bold uppercase tracking-wider text-slate-500">
              Shalat Dhuha (Jumat)
            </span>
            <div className="w-9 h-9 rounded-xl bg-indigo-50 text-indigo-600 flex items-center justify-center">
              <Sparkles className="w-5 h-5" />
            </div>
          </div>
          <div className="flex items-baseline gap-2">
            <span className="text-3xl font-black text-slate-900">
              {dhuhaAttendance.percentage}%
            </span>
            <span className="text-xs font-semibold text-indigo-600">
              Keaktifan Ibadah
            </span>
          </div>
          <p className="mt-2 text-xs text-slate-500">
            Hadir: <strong>{dhuhaAttendance.hadir}</strong>x
            {student.jenis_kelamin === "Perempuan" && ` | Halangan: ${dhuhaAttendance.halangan}x`}
          </p>
        </div>

        {/* Card 4: Catatan Kedisiplinan & Pelanggaran */}
        <div
          onClick={() => {
            setActiveTab("kedisiplinan");
            router.push(mode === "parent" ? "/portal-ortu?tab=kedisiplinan" : "/portal-siswa?tab=kedisiplinan");
          }}
          role="button"
          tabIndex={0}
          className="bg-white p-5 rounded-2xl border border-slate-200 shadow-sm hover:shadow-md transition-all cursor-pointer group"
        >
          <div className="flex items-center justify-between mb-3">
            <span className="text-xs font-bold uppercase tracking-wider text-slate-500 group-hover:text-blue-600 transition-colors">
              Catatan Pelanggaran
            </span>
            <div className={`w-9 h-9 rounded-xl flex items-center justify-center ${
              violations.totalPoints > 0 ? "bg-rose-50 text-rose-600" : "bg-emerald-50 text-emerald-600"
            }`}>
              {violations.totalPoints > 0 ? (
                <ShieldAlert className="w-5 h-5" />
              ) : (
                <ShieldCheck className="w-5 h-5" />
              )}
            </div>
          </div>
          <div className="flex items-baseline gap-2">
            <span className={`text-3xl font-black ${
              violations.totalPoints > 0 ? "text-rose-600" : "text-emerald-600"
            }`}>
              {violations.totalPoints}
            </span>
            <span className="text-xs font-semibold text-slate-500">
              Poin Akumulasi
            </span>
          </div>
          <p className="mt-2 text-xs text-slate-500 flex items-center justify-between">
            <span>
              {violations.totalPoints === 0
                ? "Catatan bersih tanpa pelanggaran"
                : `${violations.records.length} catatan kedisiplinan tercatat`}
            </span>
            <span className="text-[11px] font-bold text-blue-600 group-hover:underline">
              Buka &rarr;
            </span>
          </p>
        </div>
      </div>



      {/* 4. Tab Content */}
      <div className="bg-white rounded-3xl border border-slate-200 shadow-sm p-6 sm:p-8">
        {/* TAB 1: PROFIL & AKADEMIK */}
        {activeTab === "profil" && (
          <div className="space-y-8">
            {!isParent && (
              <div className="bg-gradient-to-r from-amber-50 via-orange-50 to-amber-50/70 border border-amber-200 rounded-2xl p-5 flex flex-col sm:flex-row sm:items-center justify-between gap-4 shadow-sm">
                <div className="flex items-start gap-3.5">
                  <div className="w-10 h-10 rounded-xl bg-amber-500/20 text-amber-700 flex items-center justify-center shrink-0 mt-0.5">
                    <FileText className="w-5 h-5 text-amber-700" />
                  </div>
                  <div>
                    <div className="flex items-center gap-2">
                      <h4 className="text-sm font-bold text-slate-900">
                        Pemutakhiran Biodata Mandiri Peserta Didik
                      </h4>
                      <span className="text-[10px] bg-amber-500 text-slate-950 font-black px-2 py-0.5 rounded-full uppercase">
                        Sinkronisasi Real-Time
                      </span>
                    </div>
                    <p className="text-xs text-slate-600 mt-1 max-w-2xl leading-relaxed">
                      Lengkapi seluruh 10 bagian biodata mandiri, scan dokumen resmi (KK, Akta, Ijazah SMP, Psikotes), riwayat keluarga, kesehatan, hingga nilai rapor SMP dan SPTJM keabsahan data.
                    </p>
                  </div>
                </div>
                <Link href="/portal-siswa/biodata" className="shrink-0 self-start sm:self-center">
                  <Button className="bg-amber-500 hover:bg-amber-600 text-slate-950 font-bold text-xs h-9 px-4 rounded-xl shadow-sm flex items-center gap-1.5">
                    <span>Lengkapi Formulir</span>
                    <span>&rarr;</span>
                  </Button>
                </Link>
              </div>
            )}

            <div>
              <h3 className="text-lg font-bold text-slate-900 flex items-center gap-2">
                <User className="w-5 h-5 text-blue-600" />
                <span>Biodata Induk Peserta Didik</span>
              </h3>
              <p className="text-xs sm:text-sm text-slate-500 mt-1">
                Data resmi yang terdaftar pada pangkalan data Dapodik dan SIMS SMA BPI 1 Bandung.
              </p>
            </div>

            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
              {/* Kolom Kiri: Biodata Siswa */}
              <div className="space-y-4 bg-slate-50/70 p-5 rounded-2xl border border-slate-200/80">
                <h4 className="text-xs font-bold uppercase tracking-wider text-slate-500">
                  Informasi Pribadi
                </h4>
                <div className="grid grid-cols-3 gap-2 text-xs sm:text-sm">
                  <span className="text-slate-500 font-medium">Nama Lengkap</span>
                  <span className="col-span-2 font-bold text-slate-800">{student.nama_lengkap}</span>

                  <span className="text-slate-500 font-medium">NIS / NISN</span>
                  <span className="col-span-2 font-mono text-slate-800">{student.nis} / {student.nisn || "-"}</span>

                  <span className="text-slate-500 font-medium">Jenis Kelamin</span>
                  <span className="col-span-2 text-slate-800">{student.jenis_kelamin}</span>

                  <span className="text-slate-500 font-medium">Tempat, Tgl Lahir</span>
                  <span className="col-span-2 text-slate-800">{student.tempat_lahir}, {student.tanggal_lahir}</span>

                  <span className="text-slate-500 font-medium">Alamat Domisili</span>
                  <span className="col-span-2 text-slate-800">{student.alamat}</span>
                </div>
              </div>

              {/* Kolom Kanan: Rombel & Orang Tua */}
              <div className="space-y-4 bg-slate-50/70 p-5 rounded-2xl border border-slate-200/80">
                <h4 className="text-xs font-bold uppercase tracking-wider text-slate-500">
                  Rombel, Wali Kelas & Orang Tua
                </h4>
                <div className="grid grid-cols-3 gap-2 text-xs sm:text-sm">
                  <span className="text-slate-500 font-medium">Tingkat / Kelas</span>
                  <span className="col-span-2 font-bold text-slate-800">Kelas {student.tingkat} ({student.rombel})</span>

                  <span className="text-slate-500 font-medium">Wali Kelas</span>
                  <span className="col-span-2 font-bold text-slate-800">{homeroomTeacher.name}</span>

                  <span className="text-slate-500 font-medium">Kontak Wali Kelas</span>
                  <span className="col-span-2 text-slate-800">{homeroomTeacher.phone}</span>

                  <span className="text-slate-500 font-medium">Orang Tua / Wali</span>
                  <span className="col-span-2 text-slate-800 font-semibold">{student.nama_ortu_wali}</span>

                  <span className="text-slate-500 font-medium">No. WA Orang Tua</span>
                  <span className="col-span-2 text-slate-800">{student.no_wa_ortu}</span>
                </div>
              </div>
            </div>

            {/* Target Karir & Universitas Impian */}
            <div className="p-5 rounded-2xl bg-gradient-to-r from-blue-50 to-indigo-50 border border-blue-200/70 flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4">
              <div className="flex items-center gap-4">
                <div className="w-12 h-12 rounded-xl bg-blue-600 text-white flex items-center justify-center shrink-0 shadow-md">
                  <Compass className="w-6 h-6" />
                </div>
                <div>
                  <h4 className="text-sm font-bold text-slate-900">
                    Rencana Studi Lanjut & Karir Masa Depan
                  </h4>
                  <p className="text-xs text-slate-600 mt-0.5">
                    Universitas Impian: <strong className="text-blue-900">{student.rencana_karir_universitas || "-"}</strong>
                    {" — "}
                    Program Studi: <strong className="text-blue-900">{student.rencana_karir_jurusan || "-"}</strong>
                  </p>
                </div>
              </div>
              <span className="px-3 py-1 rounded-full text-xs font-bold bg-blue-100 text-blue-800 border border-blue-200 shrink-0">
                Bimbingan Karir BK Aktif
              </span>
            </div>

            {/* Catatan Pelanggaran Tata Tertib & Kedisiplinan Siswa (Overview di Tab Profil) */}
            <div className="p-5 rounded-2xl bg-white border border-slate-200/90 shadow-xs space-y-4">
              <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-3 pb-3 border-b border-slate-100">
                <div className="flex items-center gap-3">
                  <div className={`w-10 h-10 rounded-xl flex items-center justify-center shrink-0 shadow-xs ${
                    violations.totalPoints > 0 ? "bg-rose-100 text-rose-700" : "bg-emerald-100 text-emerald-700"
                  }`}>
                    <ShieldAlert className="w-5 h-5" />
                  </div>
                  <div>
                    <h4 className="text-sm font-bold text-slate-900 flex items-center gap-2">
                      <span>Catatan Pelanggaran Tata Tertib & Kedisiplinan Siswa</span>
                      <span className={`text-[10px] font-bold px-2 py-0.5 rounded-full ${
                        violations.totalPoints > 0 ? "bg-rose-100 text-rose-800" : "bg-emerald-100 text-emerald-800"
                      }`}>
                        {violations.totalPoints > 0 ? "Perlu Pembinaan" : "Aman / Disiplin"}
                      </span>
                    </h4>
                    <p className="text-xs text-slate-500 mt-0.5">
                      Rekam jejak kepatuhan tata tertib, akumulasi poin pelanggaran, dan pembinaan kesiswaan.
                    </p>
                  </div>
                </div>
                <div className="flex items-center gap-2">
                  <span className={`text-xs font-bold px-3 py-1 rounded-full border ${
                    violations.totalPoints > 0
                      ? "bg-rose-50 text-rose-700 border-rose-200"
                      : "bg-emerald-50 text-emerald-700 border-emerald-200"
                  }`}>
                    Total: {violations.totalPoints} Poin
                  </span>
                  <button
                    onClick={() => setActiveTab("kedisiplinan")}
                    className="text-xs font-bold text-blue-600 hover:text-blue-800 bg-blue-50 hover:bg-blue-100 px-3 py-1 rounded-full transition-all flex items-center gap-1 cursor-pointer"
                  >
                    <span>Lihat Rincian</span>
                    <ArrowUpRight className="w-3.5 h-3.5" />
                  </button>
                </div>
              </div>

              {violations.records && violations.records.length > 0 ? (
                <div className="overflow-x-auto rounded-xl border border-slate-200">
                  <table className="w-full text-left text-xs">
                    <thead className="bg-slate-50 text-slate-600 font-bold border-b border-slate-200">
                      <tr>
                        <th className="py-2.5 px-3 w-10 text-center">No</th>
                        <th className="py-2.5 px-3">Tanggal</th>
                        <th className="py-2.5 px-4">Bentuk Pelanggaran</th>
                        <th className="py-2.5 px-3">Kategori</th>
                        <th className="py-2.5 px-3 text-center">Poin</th>
                        <th className="py-2.5 px-4">Guru Pelapor</th>
                        <th className="py-2.5 px-3 text-center">Status</th>
                      </tr>
                    </thead>
                    <tbody className="divide-y divide-slate-100">
                      {violations.records.slice(0, 3).map((v: any, idx: number) => (
                        <tr key={idx} className="hover:bg-slate-50/60 transition-colors">
                          <td className="py-2.5 px-3 text-center text-slate-400 font-mono">{idx + 1}</td>
                          <td className="py-2.5 px-3 font-medium text-slate-700">{v.date}</td>
                          <td className="py-2.5 px-4 font-bold text-slate-900">{v.violation_name}</td>
                          <td className="py-2.5 px-3">
                            <span className="px-2 py-0.5 rounded text-[11px] font-medium bg-slate-100 text-slate-700">
                              {v.category}
                            </span>
                          </td>
                          <td className="py-2.5 px-3 text-center font-black text-rose-600">+{v.points}</td>
                          <td className="py-2.5 px-4 text-slate-600">{v.reporter}</td>
                          <td className="py-2.5 px-3 text-center">
                            <span className="px-2 py-0.5 rounded text-[11px] font-bold bg-amber-50 text-amber-800 border border-amber-200">
                              {v.status}
                            </span>
                          </td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              ) : (
                <div className="p-4 rounded-xl bg-emerald-50/60 border border-emerald-200/80 flex items-center justify-between text-xs text-emerald-800">
                  <div className="flex items-center gap-2">
                    <CheckCircle2 className="w-4 h-4 text-emerald-600" />
                    <span><strong>Sangat Baik!</strong> Siswa tidak memiliki catatan pelanggaran tata tertib pada semester ini.</span>
                  </div>
                  <span className="font-semibold text-emerald-700">Tertib & Teladan</span>
                </div>
              )}
            </div>
          </div>
        )}

        {/* TAB 2: ANALISIS RAPOR SISWA (SEMESTER 1 S.D. 6) */}
        {activeTab === "rapor" && (
          <div className="space-y-6">
            {/* Header & Filter Semester */}
            <div className="bg-slate-50/80 rounded-2xl border border-slate-200 p-5 space-y-4">
              <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
                <div>
                  <h3 className="text-lg font-bold text-slate-900 flex items-center gap-2">
                    <LineChartIcon className="w-5 h-5 text-blue-600" />
                    <span>Analisis Rapor Siswa (Semester 1 s.d. 6)</span>
                  </h3>
                  <p className="text-xs sm:text-sm text-slate-500 mt-1">
                    Evaluasi komprehensif capaian akademik, tren progresi kumulatif, dan rekapitulasi KKM SMA BPI 1 Bandung.
                  </p>
                </div>

                <div className="flex items-center gap-2">
                  <span className="text-xs font-semibold text-slate-500">Filter Semester:</span>
                  <div className="flex flex-wrap items-center gap-1">
                    <button
                      type="button"
                      onClick={() => setSelectedSemester("kumulatif")}
                      className={`px-3 py-1.5 rounded-lg text-xs font-bold transition-all ${
                        selectedSemester === "kumulatif"
                          ? "bg-blue-600 text-white shadow-sm ring-2 ring-blue-200"
                          : "bg-white text-slate-600 hover:bg-slate-100 border border-slate-200"
                      }`}
                    >
                      🔄 Kumulatif (Sem 1 - 6)
                    </button>
                    {[1, 2, 3, 4, 5, 6].map((num) => (
                      <button
                        key={num}
                        type="button"
                        onClick={() => setSelectedSemester(String(num))}
                        className={`px-2.5 py-1.5 rounded-lg text-xs font-semibold transition-all ${
                          selectedSemester === String(num)
                            ? "bg-blue-600 text-white shadow-sm ring-2 ring-blue-200"
                            : "bg-white text-slate-600 hover:bg-slate-100 border border-slate-200"
                        }`}
                      >
                        Sem {num}
                      </button>
                    ))}
                  </div>
                </div>
              </div>
            </div>

            {/* 4 Metric Cards Ringkasan Akademis */}
            <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
              {/* Card 1: Rata-Rata Nilai Rapor */}
              <div className="bg-white rounded-2xl border border-slate-200 p-5 shadow-xs relative overflow-hidden">
                <div className="flex items-center justify-between">
                  <span className="text-xs font-bold text-slate-500 uppercase tracking-wider">
                    Rata-Rata Nilai Rapor
                  </span>
                  <div className="w-9 h-9 rounded-xl bg-blue-50 text-blue-600 flex items-center justify-center">
                    <TrendingUp className="w-5 h-5" />
                  </div>
                </div>
                <div className="mt-3 flex items-baseline gap-2">
                  <span className="text-3xl font-black text-slate-900 tracking-tight">
                    {effectiveAvgScore}
                  </span>
                  <span className="text-xs font-medium text-slate-400">/ 100</span>
                </div>
                <div className="mt-3 flex items-center gap-2">
                  {Number(effectiveAvgScore) >= 75 ? (
                    <span className="inline-flex items-center gap-1 text-xs font-semibold text-emerald-700 bg-emerald-50 px-2 py-0.5 rounded-md border border-emerald-200">
                      <CheckCircle2 className="w-3.5 h-3.5 text-emerald-600" />
                      +{(Number(effectiveAvgScore) - 75).toFixed(1)} pts di atas KKM (75.0)
                    </span>
                  ) : (
                    <span className="inline-flex items-center gap-1 text-xs font-semibold text-rose-700 bg-rose-50 px-2 py-0.5 rounded-md border border-rose-200">
                      <AlertCircle className="w-3.5 h-3.5 text-rose-600" />
                      Di Bawah Standar KKM
                    </span>
                  )}
                </div>
                <div className="w-full bg-slate-100 h-1.5 rounded-full mt-3 overflow-hidden">
                  <div
                    className="bg-blue-600 h-full rounded-full transition-all duration-500"
                    style={{ width: `${Math.min(100, Math.max(0, Number(effectiveAvgScore)))}%` }}
                  />
                </div>
              </div>

              {/* Card 2: Mapel Tertinggi & Terendah */}
              <div className="bg-white rounded-2xl border border-slate-200 p-5 shadow-xs relative overflow-hidden">
                <div className="flex items-center justify-between">
                  <span className="text-xs font-bold text-slate-500 uppercase tracking-wider">
                    Tertinggi & Terendah
                  </span>
                  <div className="w-9 h-9 rounded-xl bg-amber-50 text-amber-600 flex items-center justify-center">
                    <Sparkles className="w-5 h-5" />
                  </div>
                </div>
                <div className="mt-2.5 space-y-2">
                  <div className="flex items-center justify-between text-xs">
                    <span className="text-slate-600 flex items-center gap-1 truncate max-w-[140px]">
                      <span className="w-2 h-2 rounded-full bg-emerald-500 shrink-0" />
                      <span className="truncate">{top3List[0]?.name || top3List[0]?.subject_name || "-"}</span>
                    </span>
                    <span className="font-bold text-emerald-700 bg-emerald-50 px-2 py-0.5 rounded border border-emerald-200 shrink-0">
                      {top3List[0]?.score || top3List[0]?.final_score || 0}
                    </span>
                  </div>
                  <div className="flex items-center justify-between text-xs">
                    <span className="text-slate-600 flex items-center gap-1 truncate max-w-[140px]">
                      <span className="w-2 h-2 rounded-full bg-rose-500 shrink-0" />
                      <span className="truncate">{bottom3List[0]?.name || bottom3List[0]?.subject_name || "-"}</span>
                    </span>
                    <span className="font-bold text-rose-700 bg-rose-50 px-2 py-0.5 rounded border border-rose-200 shrink-0">
                      {bottom3List[0]?.score || bottom3List[0]?.final_score || 0}
                    </span>
                  </div>
                </div>
                <div className="mt-3 pt-2 border-t border-slate-100 text-[11px] text-slate-500 flex items-center justify-between">
                  <span>Rentang Selisih:</span>
                  <span className="font-semibold text-slate-700">
                    {(Number(top3List[0]?.score || 0) - Number(bottom3List[0]?.score || 0)).toFixed(1)} pts
                  </span>
                </div>
              </div>

              {/* Card 3: Peringkat Kelas & Paralel */}
              <div className="bg-white rounded-2xl border border-slate-200 p-5 shadow-xs relative overflow-hidden">
                <div className="flex items-center justify-between">
                  <span className="text-xs font-bold text-slate-500 uppercase tracking-wider">
                    Peringkat / Rank
                  </span>
                  <div className="w-9 h-9 rounded-xl bg-indigo-50 text-indigo-600 flex items-center justify-center">
                    <Award className="w-5 h-5" />
                  </div>
                </div>
                <div className="mt-3 flex items-baseline gap-2">
                  <span className="text-2xl font-black text-indigo-900 tracking-tight">
                    Rank #{effectiveClassRank}
                  </span>
                  <span className="text-xs font-medium text-slate-500">/ {effectiveTotalClass} Siswa</span>
                </div>
                <div className="mt-2 text-xs text-slate-600 truncate font-medium">
                  Paralel: <strong>#{effectiveParallelRank}</strong> dari {effectiveTotalParallel} Siswa
                </div>
                <div className="mt-3 pt-2 border-t border-slate-100 text-[11px] text-indigo-700 font-semibold flex items-center gap-1">
                  <GraduationCap className="w-3.5 h-3.5" />
                  <span>Target Eligible SNBP BPI</span>
                </div>
              </div>

              {/* Card 4: Ketuntasan KKM */}
              <div className="bg-white rounded-2xl border border-slate-200 p-5 shadow-xs relative overflow-hidden">
                <div className="flex items-center justify-between">
                  <span className="text-xs font-bold text-slate-500 uppercase tracking-wider">
                    Ketuntasan KKM (75)
                  </span>
                  <div className="w-9 h-9 rounded-xl bg-emerald-50 text-emerald-600 flex items-center justify-center">
                    <CheckCircle2 className="w-5 h-5" />
                  </div>
                </div>
                <div className="mt-3 flex items-baseline gap-2">
                  <span className="text-3xl font-black text-emerald-700 tracking-tight">
                    {analisisSummary?.tuntasKkmPercent || 100}%
                  </span>
                  <span className="text-xs font-bold text-emerald-600 uppercase">Tuntas</span>
                </div>
                <div className="mt-2 text-xs text-slate-600 flex items-center justify-between">
                  <span>Predikat Dominan:</span>
                  <span className="font-bold text-blue-700 px-2 py-0.5 bg-blue-50 rounded border border-blue-200">
                    Predikat {analisisSummary?.predikatDominan || "A"}
                  </span>
                </div>
                <div className="w-full bg-slate-100 h-1.5 rounded-full mt-3 overflow-hidden">
                  <div
                    className="bg-emerald-500 h-full rounded-full transition-all duration-500"
                    style={{ width: `${analisisSummary?.tuntasKkmPercent || 100}%` }}
                  />
                </div>
              </div>
            </div>

            {/* Top 3 & Bottom 3 Mapel */}
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              {/* Top 3 Highest Subjects */}
              <div className="bg-white rounded-2xl border border-emerald-200 p-5 shadow-xs relative overflow-hidden bg-gradient-to-br from-white via-white to-emerald-50/40">
                <div className="flex items-center justify-between pb-3 border-b border-emerald-100">
                  <div className="flex items-center gap-2.5">
                    <div className="w-9 h-9 rounded-xl bg-emerald-100 text-emerald-700 flex items-center justify-center font-bold shadow-xs">
                      <Award className="w-5 h-5 text-emerald-600" />
                    </div>
                    <div>
                      <h4 className="text-xs font-bold text-emerald-950 uppercase tracking-wider flex items-center gap-1.5">
                        Top 3 Highest Subjects
                        <span className="text-[10px] font-semibold text-emerald-700 bg-emerald-100/70 px-2 py-0.5 rounded-full">
                          Mapel Unggulan Siswa
                        </span>
                      </h4>
                      <p className="text-[11px] text-emerald-700/90 mt-0.5">
                        {student.nama_lengkap} • {selectedSemester !== "kumulatif" ? `Semester ${selectedSemester}` : "Kumulatif Sem 1 s.d. 6"}
                      </p>
                    </div>
                  </div>
                  <span className="text-xs font-bold text-emerald-800 bg-emerald-100/80 px-2.5 py-1 rounded-lg border border-emerald-200/80">
                    Unggulan
                  </span>
                </div>

                <div className="mt-3.5 space-y-2">
                  {top3List.length > 0 ? (
                    top3List.map((item: any, idx: number) => (
                      <div
                        key={idx}
                        className="flex items-center justify-between p-2.5 rounded-xl bg-emerald-50/60 hover:bg-emerald-50 border border-emerald-100/80 transition-all text-xs"
                      >
                        <div className="flex items-center gap-2.5 min-w-0 pr-2">
                          <span className="w-5 h-5 rounded-full bg-emerald-600 text-white font-bold text-[10px] flex items-center justify-center shrink-0 font-mono shadow-2xs">
                            {idx + 1}
                          </span>
                          <div className="truncate">
                            <span className="font-bold text-slate-900 truncate block">
                              {item.name || item.subject_name}
                            </span>
                            {(item.category || item.subject_category) && (
                              <span className="text-[10px] text-emerald-700 font-medium">
                                {item.category || item.subject_category}
                              </span>
                            )}
                          </div>
                        </div>
                        <div className="text-right shrink-0">
                          <span className="font-bold text-sm text-emerald-800 bg-white px-2.5 py-1 rounded-lg border border-emerald-200 shadow-2xs font-mono">
                            {item.score || item.final_score}
                          </span>
                        </div>
                      </div>
                    ))
                  ) : (
                    <div className="py-4 text-center text-xs text-slate-400 italic">
                      Belum ada data nilai mata pelajaran
                    </div>
                  )}
                </div>
                <div className="mt-3 pt-2.5 border-t border-emerald-100 text-[11px] text-emerald-800 flex items-center justify-between">
                  <span className="font-medium">Rekomendasi Karir/Peminatan:</span>
                  <span className="font-semibold text-emerald-950 truncate max-w-[280px]">
                    {top3List.map((s: any) => s.name || s.subject_name).join(", ") || "-"}
                  </span>
                </div>
              </div>

              {/* Bottom 3 Lowest Subjects */}
              <div className="bg-white rounded-2xl border border-rose-200 p-5 shadow-xs relative overflow-hidden bg-gradient-to-br from-white via-white to-rose-50/40">
                <div className="flex items-center justify-between pb-3 border-b border-rose-100">
                  <div className="flex items-center gap-2.5">
                    <div className="w-9 h-9 rounded-xl bg-rose-100 text-rose-700 flex items-center justify-center font-bold shadow-xs">
                      <AlertCircle className="w-5 h-5 text-rose-600" />
                    </div>
                    <div>
                      <h4 className="text-xs font-bold text-rose-950 uppercase tracking-wider flex items-center gap-1.5">
                        Bottom 3 Lowest Subjects
                        <span className="text-[10px] font-semibold text-rose-700 bg-rose-100/70 px-2 py-0.5 rounded-full">
                          Perlu Perhatian / Konseling BK
                        </span>
                      </h4>
                      <p className="text-[11px] text-rose-700/90 mt-0.5">
                        {student.nama_lengkap} • {selectedSemester !== "kumulatif" ? `Semester ${selectedSemester}` : "Kumulatif Sem 1 s.d. 6"}
                      </p>
                    </div>
                  </div>
                  <span className="text-xs font-bold text-rose-800 bg-rose-100/80 px-2.5 py-1 rounded-lg border border-rose-200/80">
                    Konseling BK
                  </span>
                </div>

                <div className="mt-3.5 space-y-2">
                  {bottom3List.length > 0 ? (
                    bottom3List.map((item: any, idx: number) => (
                      <div
                        key={idx}
                        className="flex items-center justify-between p-2.5 rounded-xl bg-rose-50/60 hover:bg-rose-50 border border-rose-100/80 transition-all text-xs"
                      >
                        <div className="flex items-center gap-2.5 min-w-0 pr-2">
                          <span className="w-5 h-5 rounded-full bg-rose-500 text-white font-bold text-[10px] flex items-center justify-center shrink-0 font-mono shadow-2xs">
                            {idx + 1}
                          </span>
                          <div className="truncate">
                            <span className="font-bold text-slate-900 truncate block">
                              {item.name || item.subject_name}
                            </span>
                            {(item.category || item.subject_category) && (
                              <span className="text-[10px] text-rose-600 font-medium">
                                {item.category || item.subject_category}
                              </span>
                            )}
                          </div>
                        </div>
                        <div className="text-right shrink-0">
                          <span className="font-bold text-sm text-rose-800 bg-white px-2.5 py-1 rounded-lg border border-rose-200 shadow-2xs font-mono">
                            {item.score || item.final_score}
                          </span>
                        </div>
                      </div>
                    ))
                  ) : (
                    <div className="py-4 text-center text-xs text-slate-400 italic">
                      Belum ada data nilai mata pelajaran
                    </div>
                  )}
                </div>
                <div className="mt-3 pt-2.5 border-t border-rose-100 text-[11px] text-rose-800 flex items-center justify-between">
                  <span className="font-medium">Fokus Remedial & Bimbingan:</span>
                  <span className="font-semibold text-rose-950 truncate max-w-[280px]">
                    {bottom3List.map((s: any) => s.name || s.subject_name).join(", ") || "-"}
                  </span>
                </div>
              </div>
            </div>

            {/* Visualisasi Tren Progresi Nilai (Grafik Garis Interaktif Semester 1-6) */}
            <div className="bg-white rounded-2xl border border-slate-200 p-6 shadow-xs space-y-4">
              <div className="flex flex-wrap items-center justify-between gap-4 pb-3 border-b border-slate-100">
                <div>
                  <h3 className="text-base font-bold text-slate-900 flex items-center gap-2">
                    <LineChartIcon className="w-5 h-5 text-blue-600" />
                    <span>Tren Progresi Nilai Rapor (Semester 1 s.d. 6)</span>
                  </h3>
                  <p className="text-xs text-slate-500 mt-0.5">
                    Grafik kumulatif fluktuasi rata-rata per semester berdasarkan rumpun mata pelajaran
                  </p>
                </div>

                {/* Toggle Rumpun Mapel */}
                <div className="flex flex-wrap items-center gap-2 text-xs font-medium">
                  <button
                    type="button"
                    onClick={() => setShowAllLine(!showAllLine)}
                    className={`px-2.5 py-1 rounded-full border transition-all flex items-center gap-1.5 cursor-pointer ${
                      showAllLine
                        ? "bg-blue-600 text-white border-blue-600 shadow-2xs"
                        : "bg-slate-100 text-slate-500 border-slate-200"
                    }`}
                  >
                    <span className="w-2.5 h-2.5 rounded-full bg-blue-300" />
                    <span>Semua Mapel</span>
                  </button>
                  <button
                    type="button"
                    onClick={() => setShowMipaLine(!showMipaLine)}
                    className={`px-2.5 py-1 rounded-full border transition-all flex items-center gap-1.5 cursor-pointer ${
                      showMipaLine
                        ? "bg-emerald-600 text-white border-emerald-600 shadow-2xs"
                        : "bg-slate-100 text-slate-500 border-slate-200"
                    }`}
                  >
                    <span className="w-2.5 h-2.5 rounded-full bg-emerald-300" />
                    <span>MIPA</span>
                  </button>
                  <button
                    type="button"
                    onClick={() => setShowIpsLine(!showIpsLine)}
                    className={`px-2.5 py-1 rounded-full border transition-all flex items-center gap-1.5 cursor-pointer ${
                      showIpsLine
                        ? "bg-amber-600 text-white border-amber-600 shadow-2xs"
                        : "bg-slate-100 text-slate-500 border-slate-200"
                    }`}
                  >
                    <span className="w-2.5 h-2.5 rounded-full bg-amber-300" />
                    <span>IPS</span>
                  </button>
                  <button
                    type="button"
                    onClick={() => setShowBahasaLine(!showBahasaLine)}
                    className={`px-2.5 py-1 rounded-full border transition-all flex items-center gap-1.5 cursor-pointer ${
                      showBahasaLine
                        ? "bg-purple-600 text-white border-purple-600 shadow-2xs"
                        : "bg-slate-100 text-slate-500 border-slate-200"
                    }`}
                  >
                    <span className="w-2.5 h-2.5 rounded-full bg-purple-300" />
                    <span>Bahasa</span>
                  </button>
                  <button
                    type="button"
                    onClick={() => setShowKhasBpiLine(!showKhasBpiLine)}
                    className={`px-2.5 py-1 rounded-full border transition-all flex items-center gap-1.5 cursor-pointer ${
                      showKhasBpiLine
                        ? "bg-rose-600 text-white border-rose-600 shadow-2xs"
                        : "bg-slate-100 text-slate-500 border-slate-200"
                    }`}
                  >
                    <span className="w-2.5 h-2.5 rounded-full bg-rose-300" />
                    <span>Khas BPI</span>
                  </button>
                </div>
              </div>

              {/* Area SVG Line Chart */}
              <div className="relative w-full overflow-x-auto">
                <div className="min-w-[680px]">
                  <svg
                    viewBox={`0 0 ${svgW} ${svgH}`}
                    className="w-full h-auto select-none"
                    style={{ maxHeight: "300px" }}
                  >
                    {/* Background Horizontal Grid Lines & Ticks */}
                    {[60, 70, 75, 80, 85, 90, 95, 100].map((val) => {
                      const y = getY(val);
                      const isKkm = val === 75;
                      return (
                        <g key={val}>
                          <line
                            x1={padL}
                            y1={y}
                            x2={svgW - padR}
                            y2={y}
                            stroke={isKkm ? "#ef4444" : "#e2e8f0"}
                            strokeWidth={isKkm ? 1.5 : 1}
                            strokeDasharray={isKkm ? "4 4" : undefined}
                          />
                          <text
                            x={padL - 8}
                            y={y + 3.5}
                            textAnchor="end"
                            fontSize="10"
                            fontWeight={isKkm ? "bold" : "normal"}
                            fill={isKkm ? "#ef4444" : "#94a3b8"}
                          >
                            {val} {isKkm ? "(KKM)" : ""}
                          </text>
                        </g>
                      );
                    })}

                    {/* X Axis Labels */}
                    {[1, 2, 3, 4, 5, 6].map((sem) => {
                      const x = getX(sem);
                      const isSelected = selectedSemester === String(sem);
                      return (
                        <g key={sem}>
                          <line
                            x1={x}
                            y1={padT}
                            x2={x}
                            y2={padT + chartH}
                            stroke="#f1f5f9"
                            strokeWidth="1"
                          />
                          <text
                            x={x}
                            y={svgH - 12}
                            textAnchor="middle"
                            fontSize="11"
                            fontWeight={isSelected ? "bold" : "600"}
                            fill={isSelected ? "#2563eb" : "#475569"}
                          >
                            Semester {sem}
                          </text>
                        </g>
                      );
                    })}

                    {/* Data Lines */}
                    {showMipaLine && (
                      <path
                        d={makePath(trendSeries, "rataRataMipa")}
                        fill="none"
                        stroke="#10b981"
                        strokeWidth="2"
                        strokeLinecap="round"
                        strokeLinejoin="round"
                      />
                    )}
                    {showIpsLine && (
                      <path
                        d={makePath(trendSeries, "rataRataIps")}
                        fill="none"
                        stroke="#f59e0b"
                        strokeWidth="2"
                        strokeLinecap="round"
                        strokeLinejoin="round"
                      />
                    )}
                    {showBahasaLine && (
                      <path
                        d={makePath(trendSeries, "rataRataBahasa")}
                        fill="none"
                        stroke="#8b5cf6"
                        strokeWidth="2"
                        strokeLinecap="round"
                        strokeLinejoin="round"
                      />
                    )}
                    {showKhasBpiLine && (
                      <path
                        d={makePath(trendSeries, "rataRataKhasBpi")}
                        fill="none"
                        stroke="#ec4899"
                        strokeWidth="2"
                        strokeLinecap="round"
                        strokeLinejoin="round"
                      />
                    )}
                    {showAllLine && (
                      <path
                        d={makePath(trendSeries, "rataRataAll")}
                        fill="none"
                        stroke="#2563eb"
                        strokeWidth="3.5"
                        strokeLinecap="round"
                        strokeLinejoin="round"
                      />
                    )}

                    {/* Data Nodes & Indicators */}
                    {trendSeries.map((pt: any) => {
                      const x = getX(pt.semester);
                      const hasData = pt.rataRataAll !== null;
                      const y = getY(pt.rataRataAll);

                      if (!hasData) {
                        return (
                          <g key={pt.semester}>
                            <circle
                              cx={x}
                              cy={padT + chartH}
                              r="4"
                              fill="#ffffff"
                              stroke="#cbd5e1"
                              strokeWidth="1.5"
                              strokeDasharray="2 2"
                            />
                            <text
                              x={x}
                              y={padT + chartH - 12}
                              textAnchor="middle"
                              fontSize="9"
                              fill="#94a3b8"
                              fontStyle="italic"
                            >
                              Belum Ditempuh
                            </text>
                          </g>
                        );
                      }

                      let nodeColor = "#2563eb";
                      if (pt.trendIndicator === "up") nodeColor = "#10b981";
                      if (pt.trendIndicator === "down") nodeColor = "#ef4444";

                      return (
                        <g key={pt.semester} className="cursor-pointer">
                          <circle
                            cx={x}
                            cy={y}
                            r="7"
                            fill={nodeColor}
                            fillOpacity="0.2"
                          />
                          <circle
                            cx={x}
                            cy={y}
                            r="4.5"
                            fill="#ffffff"
                            stroke={nodeColor}
                            strokeWidth="2.5"
                          />
                          <text
                            x={x}
                            y={y - 10}
                            textAnchor="middle"
                            fontSize="10"
                            fontWeight="bold"
                            fill={nodeColor}
                          >
                            {pt.rataRataAll}
                          </text>
                        </g>
                      );
                    })}
                  </svg>
                </div>
              </div>

              {/* Legend Indikator */}
              <div className="flex flex-wrap items-center justify-between text-xs text-slate-500 pt-2 border-t border-slate-100">
                <div className="flex flex-wrap items-center gap-4">
                  <span className="font-semibold text-slate-700">Indikator Tren:</span>
                  <span className="flex items-center gap-1.5 font-medium text-emerald-700">
                    <span className="w-2.5 h-2.5 rounded-full bg-emerald-500" />
                    🟢 Naik (&gt; +0.3 pts)
                  </span>
                  <span className="flex items-center gap-1.5 font-medium text-rose-700">
                    <span className="w-2.5 h-2.5 rounded-full bg-rose-500" />
                    🔴 Turun (&lt; -0.3 pts)
                  </span>
                  <span className="flex items-center gap-1.5 font-medium text-blue-700">
                    <span className="w-2.5 h-2.5 rounded-full bg-blue-500" />
                    🔵 Stabil
                  </span>
                  <span className="flex items-center gap-1.5 text-slate-400">
                    <span className="w-2 h-2 rounded-full border border-slate-400 border-dashed" />
                    Belum Ditempuh (Sesuai Fase)
                  </span>
                </div>
                <div className="text-[11px] text-slate-400 italic">
                  * Garis putus-putus merah = Standar KKM Sekolah (75)
                </div>
              </div>
            </div>

            {/* TABEL UTAMA: MATRIKS KOMPARASI & RINCIAN TRANSKRIP */}
            <div className="bg-white rounded-2xl border border-slate-200 shadow-xs overflow-hidden">
              {/* Switcher Tab Tampilan Tabel */}
              <div className="p-4 bg-slate-50 border-b border-slate-200 flex flex-wrap items-center justify-between gap-3">
                <div className="flex items-center gap-2">
                  <button
                    type="button"
                    onClick={() => setActiveTableView("matrix")}
                    className={`px-3.5 py-2 rounded-xl text-xs font-bold transition-all flex items-center gap-2 cursor-pointer ${
                      activeTableView === "matrix"
                        ? "bg-blue-600 text-white shadow-sm"
                        : "bg-white text-slate-700 hover:bg-slate-100 border border-slate-200"
                    }`}
                  >
                    <TableIcon className="w-4 h-4" />
                    <span>📋 Matriks Komparasi Semester 1 s.d. 6 (Format Standar)</span>
                  </button>
                  <button
                    type="button"
                    onClick={() => setActiveTableView("breakdown")}
                    className={`px-3.5 py-2 rounded-xl text-xs font-bold transition-all flex items-center gap-2 cursor-pointer ${
                      activeTableView === "breakdown"
                        ? "bg-blue-600 text-white shadow-sm"
                        : "bg-white text-slate-700 hover:bg-slate-100 border border-slate-200"
                    }`}
                  >
                    <BookOpen className="w-4 h-4" />
                    <span>📑 Rincian Transkrip Nilai (Pengetahuan & Keterampilan)</span>
                  </button>
                </div>

                <span className="text-xs text-slate-500 font-medium">
                  {matrixRows.length} Mata Pelajaran Kurikulum BPI
                </span>
              </div>

              {activeTableView === "matrix" ? (
                <div className="p-5 space-y-4">
                  {/* Header Informasi Siswa Terfokus */}
                  <div className="bg-slate-50 border border-slate-200 rounded-xl p-4 flex flex-wrap items-center justify-between gap-4">
                    <div className="grid grid-cols-1 sm:grid-cols-3 gap-y-2 gap-x-8 text-sm">
                      <div>
                        <span className="text-[11px] font-semibold text-slate-500 uppercase tracking-wider block">
                          Nama Siswa
                        </span>
                        <span className="font-bold text-slate-900 text-base flex items-center gap-2">
                          {student.nama_lengkap}
                          <Badge variant="secondary">Kelas {student.tingkat} ({student.rombel})</Badge>
                        </span>
                      </div>
                      <div>
                        <span className="text-[11px] font-semibold text-slate-500 uppercase tracking-wider block">
                          NIS / NISN
                        </span>
                        <span className="font-bold text-slate-800 font-mono">
                          {student.nis} / {student.nisn || "-"}
                        </span>
                      </div>
                      <div>
                        <span className="text-[11px] font-semibold text-slate-500 uppercase tracking-wider block">
                          Periode Rapor
                        </span>
                        <span className="font-semibold text-blue-700">
                          Rekapitulasi Kumulatif Semester 1 s.d. 6
                        </span>
                      </div>
                    </div>
                  </div>

                  {/* Tabel Matriks Komparasi Dengan Selisih (S) */}
                  <div className="overflow-x-auto border border-slate-200 rounded-xl shadow-2xs">
                    <table className="w-full text-left border-collapse text-xs">
                      <thead>
                        {/* Baris Header Grup 1 */}
                        <tr className="bg-slate-100 text-slate-700 border-b border-slate-300 font-bold">
                          <th rowSpan={2} className="py-3 px-2 text-center w-8 border-r border-slate-300">
                            No
                          </th>
                          <th rowSpan={2} className="py-3 px-3 border-r border-slate-300 min-w-[190px]">
                            Mata Pelajaran
                          </th>
                          <th rowSpan={2} className="py-3 px-2 text-center border-r border-slate-300 w-24">
                            Kategori
                          </th>
                          <th rowSpan={2} className="py-3 px-2 text-center border-r border-slate-300 w-16 bg-amber-50 text-amber-950">
                            KKM
                          </th>
                          <th
                            colSpan={4}
                            className="py-2 px-2 text-center bg-blue-100 text-blue-950 border-r border-slate-300 tracking-wide font-extrabold uppercase text-[11px]"
                          >
                            Grup Kelas X
                          </th>
                          <th
                            colSpan={4}
                            className="py-2 px-2 text-center bg-indigo-100 text-indigo-950 border-r border-slate-300 tracking-wide font-extrabold uppercase text-[11px]"
                          >
                            Grup Kelas XI
                          </th>
                          <th
                            colSpan={4}
                            className="py-2 px-2 text-center bg-purple-100 text-purple-950 tracking-wide font-extrabold uppercase text-[11px]"
                          >
                            Grup Kelas XII
                          </th>
                        </tr>
                        {/* Baris Header Kolom 2 */}
                        <tr className="bg-slate-50 text-slate-700 border-b border-slate-300 font-semibold text-[11px]">
                          {/* Kelas X: Sem 1, S, Sem 2, S */}
                          <th className="py-2.5 px-2 text-center border-r border-slate-200 w-16">
                            Sem 1
                          </th>
                          <th className="py-2.5 px-2 text-center border-r border-slate-200 w-14 bg-blue-50 text-blue-900 font-bold" title="S = Sem 1 - KKM">
                            S
                          </th>
                          <th className="py-2.5 px-2 text-center border-r border-slate-200 w-16">
                            Sem 2
                          </th>
                          <th className="py-2.5 px-2 text-center border-r border-slate-300 w-14 bg-blue-50 text-blue-900 font-bold" title="S = Sem 2 - Sem 1">
                            S
                          </th>
                          {/* Kelas XI: Sem 3, S, Sem 4, S */}
                          <th className="py-2.5 px-2 text-center border-r border-slate-200 w-16">
                            Sem 3
                          </th>
                          <th className="py-2.5 px-2 text-center border-r border-slate-200 w-14 bg-indigo-50 text-indigo-900 font-bold" title="S = Sem 3 - Sem 2">
                            S
                          </th>
                          <th className="py-2.5 px-2 text-center border-r border-slate-200 w-16">
                            Sem 4
                          </th>
                          <th className="py-2.5 px-2 text-center border-r border-slate-300 w-14 bg-indigo-50 text-indigo-900 font-bold" title="S = Sem 4 - Sem 3">
                            S
                          </th>
                          {/* Kelas XII: Sem 5, S, Sem 6, S */}
                          <th className="py-2.5 px-2 text-center border-r border-slate-200 w-16">
                            Sem 5
                          </th>
                          <th className="py-2.5 px-2 text-center border-r border-slate-200 w-14 bg-purple-50 text-purple-900 font-bold" title="S = Sem 5 - Sem 4">
                            S
                          </th>
                          <th className="py-2.5 px-2 text-center border-r border-slate-200 w-16">
                            Sem 6
                          </th>
                          <th className="py-2.5 px-2 text-center w-14 bg-purple-50 text-purple-900 font-bold" title="S = Sem 6 - Sem 5">
                            S
                          </th>
                        </tr>
                      </thead>
                      <tbody className="divide-y divide-slate-200">
                        {matrixRows.length === 0 ? (
                          <tr>
                            <td colSpan={16} className="py-10 text-center text-slate-400">
                              <AlertCircle className="w-8 h-8 mx-auto text-slate-300 mb-2" />
                              <p className="font-medium text-slate-600">Belum ada data nilai matriks rapor siswa</p>
                            </td>
                          </tr>
                        ) : (
                          matrixRows.map((row: any) => (
                            <tr key={row.subject_code} className="hover:bg-blue-50/40 transition-colors">
                              <td className="py-2.5 px-2 text-center text-slate-400 font-mono border-r border-slate-200">
                                {row.no}
                              </td>
                              <td className="py-2.5 px-3 font-semibold text-slate-900 border-r border-slate-200">
                                <div>{row.subject_name}</div>
                                <span className="text-[10px] text-slate-400 font-normal">
                                  {row.subject_code}
                                </span>
                              </td>
                              <td className="py-2.5 px-2 text-center border-r border-slate-200">
                                <span
                                  className={`inline-block px-2 py-0.5 rounded text-[10px] font-semibold ${
                                    row.subject_category === "MIPA"
                                      ? "bg-emerald-50 text-emerald-700 border border-emerald-200"
                                      : row.subject_category === "IPS"
                                      ? "bg-amber-50 text-amber-700 border border-amber-200"
                                      : row.subject_category === "Bahasa"
                                      ? "bg-purple-50 text-purple-700 border border-purple-200"
                                      : "bg-pink-50 text-pink-700 border border-pink-200"
                                  }`}
                                >
                                  {row.subject_category}
                                </span>
                              </td>
                              <td className="py-2 px-2 text-center border-r border-slate-300 bg-amber-50/30 font-mono font-bold text-amber-900">
                                {row.kkm}
                              </td>

                              {/* Kelas X: Sem 1, S, Sem 2, S */}
                              <td className="py-2.5 px-2 text-center border-r border-slate-200">
                                {renderScoreValue(row.sem1)}
                              </td>
                              <td className="py-2.5 px-1.5 text-center border-r border-slate-200 bg-blue-50/20">
                                {renderDiffValue(row.diff1)}
                              </td>
                              <td className="py-2.5 px-2 text-center border-r border-slate-200">
                                {renderScoreValue(row.sem2)}
                              </td>
                              <td className="py-2.5 px-1.5 text-center border-r border-slate-300 bg-blue-50/30">
                                {renderDiffValue(row.diff2)}
                              </td>

                              {/* Kelas XI: Sem 3, S, Sem 4, S */}
                              <td className="py-2.5 px-2 text-center border-r border-slate-200">
                                {renderScoreValue(row.sem3)}
                              </td>
                              <td className="py-2.5 px-1.5 text-center border-r border-slate-200 bg-indigo-50/20">
                                {renderDiffValue(row.diff3)}
                              </td>
                              <td className="py-2.5 px-2 text-center border-r border-slate-200">
                                {renderScoreValue(row.sem4)}
                              </td>
                              <td className="py-2.5 px-1.5 text-center border-r border-slate-300 bg-indigo-50/30">
                                {renderDiffValue(row.diff4)}
                              </td>

                              {/* Kelas XII: Sem 5, S, Sem 6, S */}
                              <td className="py-2.5 px-2 text-center border-r border-slate-200">
                                {renderScoreValue(row.sem5)}
                              </td>
                              <td className="py-2.5 px-1.5 text-center border-r border-slate-200 bg-purple-50/20">
                                {renderDiffValue(row.diff5)}
                              </td>
                              <td className="py-2.5 px-2 text-center border-r border-slate-200">
                                {renderScoreValue(row.sem6)}
                              </td>
                              <td className="py-2.5 px-1.5 text-center bg-purple-50/30">
                                {renderDiffValue(row.diff6)}
                              </td>
                            </tr>
                          ))
                        )}
                      </tbody>

                      {/* Baris Rekapitulasi Rata-Rata, Tertinggi, Terendah */}
                      {matrixRekap && (
                        <tfoot className="border-t-2 border-slate-400 font-bold divide-y divide-slate-200">
                          {/* Rata-Rata */}
                          <tr className="bg-slate-100 text-slate-900">
                            <td colSpan={3} className="py-3 px-3 text-left uppercase tracking-wider text-xs border-r border-slate-300">
                              <span className="flex items-center gap-1.5 font-extrabold text-blue-900">
                                <TrendingUp className="w-4 h-4 text-blue-700" />
                                Nilai Rata-Rata
                              </span>
                            </td>
                            <td className="py-3 px-2 text-center border-r border-slate-300 font-mono text-xs text-amber-900 bg-amber-50/50">
                              {matrixRekap.rataRata?.kkm ?? "-"}
                            </td>
                            <td className="py-3 px-2 text-center border-r border-slate-200 font-mono text-xs">
                              {renderScoreValue(matrixRekap.rataRata?.sem1)}
                            </td>
                            <td className="py-3 px-1.5 text-center border-r border-slate-200 bg-blue-50/40">
                              {renderDiffValue(matrixRekap.rataRata?.diff1)}
                            </td>
                            <td className="py-3 px-2 text-center border-r border-slate-200 font-mono text-xs">
                              {renderScoreValue(matrixRekap.rataRata?.sem2)}
                            </td>
                            <td className="py-3 px-1.5 text-center border-r border-slate-300 bg-blue-100/50">
                              {renderDiffValue(matrixRekap.rataRata?.diff2)}
                            </td>
                            <td className="py-3 px-2 text-center border-r border-slate-200 font-mono text-xs">
                              {renderScoreValue(matrixRekap.rataRata?.sem3)}
                            </td>
                            <td className="py-3 px-1.5 text-center border-r border-slate-200 bg-indigo-50/40">
                              {renderDiffValue(matrixRekap.rataRata?.diff3)}
                            </td>
                            <td className="py-3 px-2 text-center border-r border-slate-200 font-mono text-xs">
                              {renderScoreValue(matrixRekap.rataRata?.sem4)}
                            </td>
                            <td className="py-3 px-1.5 text-center border-r border-slate-300 bg-indigo-100/50">
                              {renderDiffValue(matrixRekap.rataRata?.diff4)}
                            </td>
                            <td className="py-3 px-2 text-center border-r border-slate-200 font-mono text-xs">
                              {renderScoreValue(matrixRekap.rataRata?.sem5)}
                            </td>
                            <td className="py-3 px-1.5 text-center border-r border-slate-200 bg-purple-50/40">
                              {renderDiffValue(matrixRekap.rataRata?.diff5)}
                            </td>
                            <td className="py-3 px-2 text-center border-r border-slate-200 font-mono text-xs">
                              {renderScoreValue(matrixRekap.rataRata?.sem6)}
                            </td>
                            <td className="py-3 px-1.5 text-center bg-purple-100/50">
                              {renderDiffValue(matrixRekap.rataRata?.diff6)}
                            </td>
                          </tr>

                          {/* Nilai Tertinggi */}
                          <tr className="bg-emerald-50/50 text-emerald-900">
                            <td colSpan={3} className="py-2.5 px-3 text-left uppercase tracking-wider text-xs border-r border-slate-300 font-extrabold">
                              <span className="flex items-center gap-1.5 text-emerald-800">
                                <Sparkles className="w-4 h-4 text-emerald-600" />
                                Nilai Tertinggi
                              </span>
                            </td>
                            <td className="py-2.5 px-2 text-center border-r border-slate-300 font-mono text-xs text-amber-900">
                              {matrixRekap.tertinggi?.kkm ?? "-"}
                            </td>
                            <td className="py-2.5 px-2 text-center border-r border-slate-200 font-mono text-xs font-bold text-emerald-800">
                              {matrixRekap.tertinggi?.sem1 ?? "-"}
                            </td>
                            <td className="py-2.5 px-1.5 text-center border-r border-slate-200">
                              {renderDiffValue(matrixRekap.tertinggi?.diff1)}
                            </td>
                            <td className="py-2.5 px-2 text-center border-r border-slate-200 font-mono text-xs font-bold text-emerald-800">
                              {matrixRekap.tertinggi?.sem2 ?? "-"}
                            </td>
                            <td className="py-2.5 px-1.5 text-center border-r border-slate-300">
                              {renderDiffValue(matrixRekap.tertinggi?.diff2)}
                            </td>
                            <td className="py-2.5 px-2 text-center border-r border-slate-200 font-mono text-xs font-bold text-emerald-800">
                              {matrixRekap.tertinggi?.sem3 ?? "-"}
                            </td>
                            <td className="py-2.5 px-1.5 text-center border-r border-slate-200">
                              {renderDiffValue(matrixRekap.tertinggi?.diff3)}
                            </td>
                            <td className="py-2.5 px-2 text-center border-r border-slate-200 font-mono text-xs font-bold text-emerald-800">
                              {matrixRekap.tertinggi?.sem4 ?? "-"}
                            </td>
                            <td className="py-2.5 px-1.5 text-center border-r border-slate-300">
                              {renderDiffValue(matrixRekap.tertinggi?.diff4)}
                            </td>
                            <td className="py-2.5 px-2 text-center border-r border-slate-200 font-mono text-xs font-bold text-emerald-800">
                              {matrixRekap.tertinggi?.sem5 ?? "-"}
                            </td>
                            <td className="py-2.5 px-1.5 text-center border-r border-slate-200">
                              {renderDiffValue(matrixRekap.tertinggi?.diff5)}
                            </td>
                            <td className="py-2.5 px-2 text-center border-r border-slate-200 font-mono text-xs font-bold text-emerald-800">
                              {matrixRekap.tertinggi?.sem6 ?? "-"}
                            </td>
                            <td className="py-2.5 px-1.5 text-center">
                              {renderDiffValue(matrixRekap.tertinggi?.diff6)}
                            </td>
                          </tr>

                          {/* Nilai Terendah */}
                          <tr className="bg-rose-50/50 text-rose-900">
                            <td colSpan={3} className="py-2.5 px-3 text-left uppercase tracking-wider text-xs border-r border-slate-300 font-extrabold">
                              <span className="flex items-center gap-1.5 text-rose-800">
                                <AlertCircle className="w-4 h-4 text-rose-600" />
                                Nilai Terendah
                              </span>
                            </td>
                            <td className="py-2.5 px-2 text-center border-r border-slate-300 font-mono text-xs text-amber-900">
                              {matrixRekap.terendah?.kkm ?? "-"}
                            </td>
                            <td className="py-2.5 px-2 text-center border-r border-slate-200 font-mono text-xs font-bold text-rose-800">
                              {matrixRekap.terendah?.sem1 ?? "-"}
                            </td>
                            <td className="py-2.5 px-1.5 text-center border-r border-slate-200">
                              {renderDiffValue(matrixRekap.terendah?.diff1)}
                            </td>
                            <td className="py-2.5 px-2 text-center border-r border-slate-200 font-mono text-xs font-bold text-rose-800">
                              {matrixRekap.terendah?.sem2 ?? "-"}
                            </td>
                            <td className="py-2.5 px-1.5 text-center border-r border-slate-300">
                              {renderDiffValue(matrixRekap.terendah?.diff2)}
                            </td>
                            <td className="py-2.5 px-2 text-center border-r border-slate-200 font-mono text-xs font-bold text-rose-800">
                              {matrixRekap.terendah?.sem3 ?? "-"}
                            </td>
                            <td className="py-2.5 px-1.5 text-center border-r border-slate-200">
                              {renderDiffValue(matrixRekap.terendah?.diff3)}
                            </td>
                            <td className="py-2.5 px-2 text-center border-r border-slate-200 font-mono text-xs font-bold text-rose-800">
                              {matrixRekap.terendah?.sem4 ?? "-"}
                            </td>
                            <td className="py-2.5 px-1.5 text-center border-r border-slate-300">
                              {renderDiffValue(matrixRekap.terendah?.diff4)}
                            </td>
                            <td className="py-2.5 px-2 text-center border-r border-slate-200 font-mono text-xs font-bold text-rose-800">
                              {matrixRekap.terendah?.sem5 ?? "-"}
                            </td>
                            <td className="py-2.5 px-1.5 text-center border-r border-slate-200">
                              {renderDiffValue(matrixRekap.terendah?.diff5)}
                            </td>
                            <td className="py-2.5 px-2 text-center border-r border-slate-200 font-mono text-xs font-bold text-rose-800">
                              {matrixRekap.terendah?.sem6 ?? "-"}
                            </td>
                            <td className="py-2.5 px-1.5 text-center">
                              {renderDiffValue(matrixRekap.terendah?.diff6)}
                            </td>
                          </tr>
                        </tfoot>
                      )}
                    </table>
                  </div>

                  {/* Catatan / Keterangan Formula Matriks */}
                  <div className="p-3 bg-slate-50 border border-slate-200 rounded-xl text-xs text-slate-600 flex flex-wrap items-center justify-between gap-3">
                    <div className="flex flex-wrap items-center gap-3">
                      <span className="font-semibold text-slate-700">Keterangan Kolom:</span>
                      <span className="text-slate-600">
                        <strong>S (Sem 1)</strong> = Sem 1 - KKM
                      </span>
                      <span className="text-slate-600">
                        <strong>S (Sem n)</strong> = Sem n - Sem (n-1)
                      </span>
                      <span className="text-emerald-700 font-bold">
                        ▲ = Selisih Positif / Naik
                      </span>
                      <span className="text-rose-700 font-bold">
                        ▼ = Selisih Negatif / Menurun
                      </span>
                      <span className="text-slate-400 font-mono">
                        - = Belum Ditempuh
                      </span>
                    </div>
                  </div>
                </div>
              ) : (
                /* TABEL RINCIAN TRANSKRIP (VIEW 2) */
                <div className="overflow-x-auto">
                  <table className="w-full text-left border-collapse text-xs">
                    <thead>
                      <tr className="bg-slate-50 border-b border-slate-200 text-slate-600 uppercase tracking-wider font-semibold">
                        <th className="py-3 px-3 w-12 text-center">No</th>
                        <th className="py-3 px-3">Semester</th>
                        <th className="py-3 px-4">Mata Pelajaran</th>
                        <th className="py-3 px-3 text-center">KKM</th>
                        <th className="py-3 px-3 text-center">Pengetahuan</th>
                        <th className="py-3 px-3 text-center">Keterampilan</th>
                        <th className="py-3 px-3 text-center font-bold text-slate-800">Nilai Akhir</th>
                        <th className="py-3 px-3 text-center">Predikat</th>
                        <th className="py-3 px-3 text-center">Status KKM</th>
                      </tr>
                    </thead>
                    <tbody className="divide-y divide-slate-100">
                      {breakdownRows && breakdownRows.length > 0 ? (
                        (selectedSemester === "kumulatif"
                          ? breakdownRows
                          : breakdownRows.filter((r: any) => String(r.semester_number) === selectedSemester)
                        ).map((row: any, idx: number) => (
                          <tr key={idx} className="hover:bg-blue-50/40 transition-colors">
                            <td className="py-2.5 px-3 text-center text-slate-400 font-mono">
                              {idx + 1}
                            </td>
                            <td className="py-2.5 px-3">
                              <span className="font-semibold text-slate-700 bg-slate-100 px-2 py-0.5 rounded text-[11px]">
                                Sem {row.semester_number}
                              </span>
                            </td>
                            <td className="py-2.5 px-4">
                              <div className="font-bold text-slate-900">{row.subject_name}</div>
                              <span className="text-[10px] text-slate-400 font-medium">
                                {row.subject_category} • {row.subject_code}
                              </span>
                            </td>
                            <td className="py-2.5 px-3 text-center font-mono text-slate-600">
                              {row.kkm || 75}
                            </td>
                            <td className="py-2.5 px-3 text-center font-mono text-slate-600">
                              {Number(row.knowledge_score || row.final_score).toFixed(1)}
                            </td>
                            <td className="py-2.5 px-3 text-center font-mono text-slate-600">
                              {Number(row.skill_score || row.final_score).toFixed(1)}
                            </td>
                            <td className="py-2.5 px-3 text-center font-black font-mono text-sm text-slate-900">
                              {Number(row.final_score).toFixed(1)}
                            </td>
                            <td className="py-2.5 px-3 text-center">
                              <span
                                className={`inline-block px-2 py-0.5 text-center font-bold rounded text-xs ${
                                  row.predicate === "A"
                                    ? "bg-emerald-100 text-emerald-800"
                                    : row.predicate === "B"
                                    ? "bg-blue-100 text-blue-800"
                                    : "bg-amber-100 text-amber-800"
                                }`}
                              >
                                {row.predicate}
                              </span>
                            </td>
                            <td className="py-2.5 px-3 text-center">
                              {row.status_kkm === "Tuntas" || Number(row.final_score) >= (row.kkm || 75) ? (
                                <span className="inline-flex items-center gap-1 px-2.5 py-0.5 rounded-full text-[11px] font-semibold bg-emerald-50 text-emerald-700 border border-emerald-200">
                                  <CheckCircle2 className="w-3.5 h-3.5 text-emerald-600" />
                                  Tuntas
                                </span>
                              ) : (
                                <span className="inline-flex items-center gap-1 px-2.5 py-0.5 rounded-full text-[11px] font-semibold bg-rose-50 text-rose-700 border border-rose-200">
                                  <AlertCircle className="w-3.5 h-3.5 text-rose-600" />
                                  Belum Tuntas
                                </span>
                              )}
                            </td>
                          </tr>
                        ))
                      ) : academic?.subjects && academic.subjects.length > 0 ? (
                        academic.subjects.map((sub: any, idx: number) => (
                          <tr key={idx} className="hover:bg-slate-50/60 transition-colors">
                            <td className="py-2.5 px-3 text-center font-medium text-slate-400">{idx + 1}</td>
                            <td className="py-2.5 px-3">
                              <span className="font-semibold text-slate-700 bg-slate-100 px-2 py-0.5 rounded text-[11px]">
                                Sem 1
                              </span>
                            </td>
                            <td className="py-2.5 px-4 font-bold text-slate-800">{sub.name}</td>
                            <td className="py-2.5 px-3 text-center text-slate-600 font-mono">{sub.kkm}</td>
                            <td className="py-2.5 px-3 text-center font-mono text-slate-600">{sub.score}</td>
                            <td className="py-2.5 px-3 text-center font-mono text-slate-600">{sub.score}</td>
                            <td className="py-2.5 px-3 text-center font-black font-mono text-sm text-slate-900">{sub.score}</td>
                            <td className="py-2.5 px-3 text-center font-bold text-slate-700">{sub.predicate}</td>
                            <td className="py-2.5 px-3 text-center">
                              <span className={`inline-flex px-2 py-0.5 rounded text-xs font-bold ${
                                sub.score >= sub.kkm ? "text-emerald-700 bg-emerald-50" : "text-rose-700 bg-rose-50"
                              }`}>
                                {sub.score >= sub.kkm ? "Tuntas" : "Belum Tuntas"}
                              </span>
                            </td>
                          </tr>
                        ))
                      ) : (
                        <tr>
                          <td colSpan={9} className="py-8 text-center text-slate-400 italic">
                            Belum ada rincian transkrip nilai yang tersedia.
                          </td>
                        </tr>
                      )}
                    </tbody>
                  </table>
                </div>
              )}
            </div>
          </div>
        )}

        {/* TAB 3: PRESENSI & SHALAT DHUHA */}
        {activeTab === "presensi" && (
          <div className="space-y-8">
            <div>
              <h3 className="text-lg font-bold text-slate-900 flex items-center gap-2">
                <Calendar className="w-5 h-5 text-blue-600" />
                <span>Rekapitulasi Presensi KBM & Shalat Dhuha Berjamaah</span>
              </h3>
              <p className="text-xs sm:text-sm text-slate-500 mt-1">
                Data kehadiran terhubung langsung dengan sistem Presensi Digital KBM dan kegiatan Shalat Dhuha Jumat.
              </p>
            </div>

            {/* Presensi KBM Detail */}
            <div className="p-5 rounded-2xl bg-slate-50 border border-slate-200/80 space-y-4">
              <h4 className="text-sm font-bold text-slate-800">
                Statistik Kehadiran Tatap Muka (KBM Harian)
              </h4>
              <div className="grid grid-cols-2 sm:grid-cols-4 gap-4">
                <div className="p-3 bg-white rounded-xl border border-slate-200 text-center">
                  <span className="text-xs font-bold text-slate-400 uppercase">Hadir</span>
                  <div className="text-2xl font-black text-emerald-600 mt-1">{attendance.hadir}</div>
                </div>
                <div className="p-3 bg-white rounded-xl border border-slate-200 text-center">
                  <span className="text-xs font-bold text-slate-400 uppercase">Sakit</span>
                  <div className="text-2xl font-black text-blue-600 mt-1">{attendance.sakit}</div>
                </div>
                <div className="p-3 bg-white rounded-xl border border-slate-200 text-center">
                  <span className="text-xs font-bold text-slate-400 uppercase">Izin</span>
                  <div className="text-2xl font-black text-amber-600 mt-1">{attendance.izin}</div>
                </div>
                <div className="p-3 bg-white rounded-xl border border-slate-200 text-center">
                  <span className="text-xs font-bold text-slate-400 uppercase">Alpa</span>
                  <div className="text-2xl font-black text-rose-600 mt-1">{attendance.alpa}</div>
                </div>
              </div>
            </div>

            {/* Riwayat Shalat Dhuha Jumat */}
            <div className="space-y-4">
              <div className="flex items-center justify-between">
                <h4 className="text-sm font-bold text-slate-800 flex items-center gap-2">
                  <Sparkles className="w-4 h-4 text-indigo-600" />
                  <span>Riwayat Presensi Shalat Dhuha (Hari Jumat)</span>
                </h4>
                <span className="text-xs text-slate-500">
                  Total Tercatat: <strong>{dhuhaAttendance.total}</strong> pertemuan
                </span>
              </div>

              {dhuhaAttendance.history && dhuhaAttendance.history.length > 0 ? (
                <div className="overflow-x-auto rounded-2xl border border-slate-200">
                  <table className="w-full text-left text-xs sm:text-sm">
                    <thead className="bg-slate-50 border-b border-slate-200 text-slate-600 font-bold text-xs">
                      <tr>
                        <th className="py-3 px-4 w-12 text-center">No</th>
                        <th className="py-3 px-4">Hari & Tanggal</th>
                        <th className="py-3 px-4">Waktu Presensi</th>
                        <th className="py-3 px-4 text-center">Status Kehadiran</th>
                        <th className="py-3 px-4">Petugas / Pencatat</th>
                        <th className="py-3 px-4">Catatan</th>
                      </tr>
                    </thead>
                    <tbody className="divide-y divide-slate-100">
                      {dhuhaAttendance.history.map((dh: any, i: number) => (
                        <tr key={i} className="hover:bg-slate-50/60 transition-colors">
                          <td className="py-3 px-4 text-center font-medium text-slate-400">{i + 1}</td>
                          <td className="py-3 px-4 font-bold text-slate-800">{dh.date}</td>
                          <td className="py-3 px-4 text-slate-500 font-mono text-xs">{dh.time || "06:45"} WIB</td>
                          <td className="py-3 px-4 text-center">
                            <span className={`inline-flex px-3 py-0.5 rounded-full text-xs font-bold ${
                              dh.status === "Hadir"
                                ? "bg-emerald-100 text-emerald-800"
                                : dh.status.includes("Halangan")
                                ? "bg-purple-100 text-purple-800"
                                : dh.status === "Sakit"
                                ? "bg-blue-100 text-blue-800"
                                : dh.status === "Izin"
                                ? "bg-amber-100 text-amber-800"
                                : "bg-rose-100 text-rose-800"
                            }`}>
                              {dh.status}
                            </span>
                          </td>
                          <td className="py-3 px-4 text-xs text-slate-600">{dh.recorder || "Guru PAI / Kesiswaan"}</td>
                          <td className="py-3 px-4 text-xs text-slate-500">{dh.notes || "-"}</td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              ) : (
                <div className="p-8 text-center text-slate-500 border border-dashed border-slate-200 rounded-2xl">
                  Belum ada catatan riwayat Shalat Dhuha yang tersimpan untuk siswa ini.
                </div>
              )}
            </div>
          </div>
        )}

        {/* TAB 4: CATATAN PELANGGARAN SISWA & KONSELING BK */}
        {activeTab === "kedisiplinan" && (
          <div className="space-y-8">
            <div>
              <h3 className="text-lg font-bold text-slate-900 flex items-center gap-2">
                <ShieldAlert className="w-5 h-5 text-blue-600" />
                <span>Catatan Pelanggaran Tata Tertib & Kedisiplinan Siswa</span>
              </h3>
              <p className="text-xs sm:text-sm text-slate-500 mt-1">
                Transparansi pencatatan kepatuhan tata tertib, pembinaan kesiswaan, serta pendampingan Bimbingan Konseling (BK) SMA BPI 1 Bandung.
              </p>
            </div>

            {/* Panduan Akumulasi Poin Tata Tertib & Sanksi Edukatif */}
            <div className="p-4 rounded-2xl bg-amber-50/70 border border-amber-200/90 space-y-2.5">
              <div className="flex items-center gap-2 text-amber-900 font-bold text-xs uppercase tracking-wider">
                <AlertCircle className="w-4 h-4 text-amber-600" />
                <span>Pedoman Akumulasi Poin Tata Tertib & Pembinaan SMA BPI 1 Bandung</span>
              </div>
              <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-2.5 text-xs">
                <div className="p-3 rounded-xl bg-white border border-amber-200/60 shadow-2xs">
                  <span className="font-black text-amber-900 block text-sm">1 - 15 Poin</span>
                  <span className="text-slate-600 text-[11px] mt-0.5 block">Peringatan lisan & pembinaan langsung oleh wali kelas.</span>
                </div>
                <div className="p-3 rounded-xl bg-white border border-amber-200/60 shadow-2xs">
                  <span className="font-black text-amber-900 block text-sm">16 - 30 Poin</span>
                  <span className="text-slate-600 text-[11px] mt-0.5 block">Surat Peringatan I (SP 1) & pemanggilan resmi orang tua.</span>
                </div>
                <div className="p-3 rounded-xl bg-white border border-amber-200/60 shadow-2xs">
                  <span className="font-black text-amber-900 block text-sm">31 - 50 Poin</span>
                  <span className="text-slate-600 text-[11px] mt-0.5 block">Surat Peringatan II (SP 2) & konseling intensif Guru BK.</span>
                </div>
                <div className="p-3 rounded-xl bg-white border border-rose-200 shadow-2xs">
                  <span className="font-black text-rose-700 block text-sm">&gt; 50 Poin</span>
                  <span className="text-slate-600 text-[11px] mt-0.5 block">Konferensi kasus dengan Kepala Sekolah & Komite Sekolah.</span>
                </div>
              </div>
            </div>

            {/* Riwayat Pelanggaran */}
            <div className="space-y-4">
              <div className="flex items-center justify-between">
                <h4 className="text-sm font-bold text-slate-800 flex items-center gap-2">
                  <ShieldAlert className="w-4 h-4 text-rose-600" />
                  <span>Daftar Catatan Pelanggaran Tata Tertib Siswa</span>
                </h4>
                <span className={`text-xs font-bold px-3 py-1 rounded-full border ${
                  violations.totalPoints > 0
                    ? "bg-rose-100 text-rose-800 border-rose-300"
                    : "bg-emerald-100 text-emerald-800 border-emerald-300"
                }`}>
                  Total Akumulasi: {violations.totalPoints} Poin
                </span>
              </div>

              {violations.records && violations.records.length > 0 ? (
                <div className="overflow-x-auto rounded-2xl border border-slate-200">
                  <table className="w-full text-left text-xs sm:text-sm">
                    <thead className="bg-slate-50 border-b border-slate-200 text-slate-600 font-bold text-xs">
                      <tr>
                        <th className="py-3 px-3 w-10 text-center">No</th>
                        <th className="py-3 px-3">Tanggal</th>
                        <th className="py-3 px-4">Bentuk Pelanggaran</th>
                        <th className="py-3 px-3">Kategori</th>
                        <th className="py-3 px-3 text-center">Bobot Poin</th>
                        <th className="py-3 px-4">Guru Pelapor</th>
                        <th className="py-3 px-4">Catatan Khusus</th>
                        <th className="py-3 px-4">Sanksi / Tindak Lanjut</th>
                        <th className="py-3 px-3 text-center">Status</th>
                      </tr>
                    </thead>
                    <tbody className="divide-y divide-slate-100">
                      {violations.records.map((v: any, i: number) => (
                        <tr key={i} className="hover:bg-slate-50/60 transition-colors">
                          <td className="py-3 px-3 text-center font-medium text-slate-400 font-mono">{i + 1}</td>
                          <td className="py-3 px-3 font-medium text-slate-800 whitespace-nowrap">{v.date}</td>
                          <td className="py-3 px-4 font-bold text-slate-900">{v.violation_name}</td>
                          <td className="py-3 px-3">
                            <span className="px-2 py-0.5 rounded text-[11px] font-semibold bg-slate-100 text-slate-700">
                              {v.category}
                            </span>
                          </td>
                          <td className="py-3 px-3 text-center font-black text-rose-600">+{v.points}</td>
                          <td className="py-3 px-4 text-xs text-slate-600">{v.reporter}</td>
                          <td className="py-3 px-4 text-xs text-slate-500 max-w-[180px]">{v.notes || "-"}</td>
                          <td className="py-3 px-4 text-xs text-slate-700 font-medium">{v.sanction || "-"}</td>
                          <td className="py-3 px-3 text-center">
                            <span className="px-2.5 py-1 rounded-full text-[11px] font-bold bg-amber-50 text-amber-800 border border-amber-200 whitespace-nowrap">
                              {v.status || "Tercatat di SIMS"}
                            </span>
                          </td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              ) : (
                <div className="p-6 text-center text-emerald-700 bg-emerald-50/60 border border-emerald-200 rounded-2xl flex items-center justify-center gap-3">
                  <ShieldCheck className="w-6 h-6 text-emerald-600" />
                  <span className="font-semibold text-sm">
                    Sangat Baik! Tidak ada catatan pelanggaran tata tertib pada semester ini.
                  </span>
                </div>
              )}
            </div>

            {/* Riwayat Konseling BK */}
            <div className="space-y-4 pt-4 border-t border-slate-200">
              <h4 className="text-sm font-bold text-slate-800">
                Riwayat Sesi Bimbingan & Konseling BK
              </h4>

              {counselings && counselings.length > 0 ? (
                <div className="space-y-3">
                  {counselings.map((c: any, i: number) => (
                    <div key={i} className="p-4 rounded-2xl bg-slate-50 border border-slate-200 space-y-2">
                      <div className="flex flex-wrap items-center justify-between gap-2">
                        <span className="font-bold text-sm text-slate-800">
                          {c.stage} — Konselor: {c.counselor}
                        </span>
                        <span className="text-xs text-slate-500 font-mono">{c.date}</span>
                      </div>
                      <p className="text-xs text-slate-600">
                        <strong>Rencana Tindak Lanjut:</strong> {c.action_plan || "-"}
                      </p>
                      <p className="text-xs text-slate-600">
                        <strong>Hasil / Progres:</strong> {c.result || "-"}
                      </p>
                    </div>
                  ))}
                </div>
              ) : (
                <div className="p-6 text-center text-slate-500 border border-dashed border-slate-200 rounded-2xl">
                  Belum ada catatan sesi konseling khusus untuk siswa ini.
                </div>
              )}
            </div>
          </div>
        )}

        {/* TAB 5: EKSKUL, PROLIFE & PRESTASI */}
        {activeTab === "ekskul" && (
          <div className="space-y-8">
            <div>
              <h3 className="text-lg font-bold text-slate-900 flex items-center gap-2">
                <Award className="w-5 h-5 text-blue-600" />
                <span>Kegiatan Ekstrakurikuler, Prolife & Penghargaan Siswa</span>
              </h3>
              <p className="text-xs sm:text-sm text-slate-500 mt-1">
                Pengembangan bakat, kepemimpinan, dan portofolio prestasi peserta didik di luar jam pelajaran.
              </p>
            </div>

            {/* Ekstrakurikuler & Prolife */}
            <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
              <div className="p-5 rounded-2xl bg-blue-50/70 border border-blue-200">
                <span className="text-xs font-bold uppercase tracking-wider text-blue-700">
                  Ekskul Wajib
                </span>
                <div className="text-lg font-extrabold text-blue-950 mt-1">
                  {extracurricular.wajib}
                </div>
                <p className="text-xs text-blue-700/80 mt-1">Kepramukaan Terpimpin</p>
              </div>

              <div className="p-5 rounded-2xl bg-indigo-50/70 border border-indigo-200">
                <span className="text-xs font-bold uppercase tracking-wider text-indigo-700">
                  Ekskul Pilihan Minat & Bakat
                </span>
                <div className="text-lg font-extrabold text-indigo-950 mt-1">
                  {extracurricular.pilihan1 !== "-" ? extracurricular.pilihan1 : "Belum Memilih"}
                </div>
                <p className="text-xs text-indigo-700/80 mt-1">
                  Pilihan 2: {extracurricular.pilihan2}
                </p>
              </div>

              <div className="p-5 rounded-2xl bg-purple-50/70 border border-purple-200">
                <span className="text-xs font-bold uppercase tracking-wider text-purple-700">
                  Program Prolife (Life Skill)
                </span>
                <div className="text-lg font-extrabold text-purple-950 mt-1">
                  {extracurricular.prolife !== "-" ? extracurricular.prolife : "Kewirausahaan / Desain"}
                </div>
                <p className="text-xs text-purple-700/80 mt-1">Life Skill Unggulan SMA BPI 1</p>
              </div>
            </div>

            {/* Piagam Prestasi */}
            <div className="space-y-4 pt-4 border-t border-slate-200">
              <h4 className="text-sm font-bold text-slate-800 flex items-center gap-2">
                <Sparkles className="w-4 h-4 text-amber-500" />
                <span>Piagam & Rekam Jejak Prestasi Siswa</span>
              </h4>

              {achievements && achievements.length > 0 ? (
                <div className="overflow-x-auto rounded-2xl border border-slate-200">
                  <table className="w-full text-left text-xs sm:text-sm">
                    <thead className="bg-slate-50 border-b border-slate-200 text-slate-600 font-bold text-xs">
                      <tr>
                        <th className="py-3 px-4 w-12 text-center">No</th>
                        <th className="py-3 px-4">Nama Kejuaraan / Prestasi</th>
                        <th className="py-3 px-4">Kategori</th>
                        <th className="py-3 px-4">Tingkat</th>
                        <th className="py-3 px-4 text-center">Peringkat / Capaian</th>
                        <th className="py-3 px-4">Penyelenggara & No Sertifikat</th>
                      </tr>
                    </thead>
                    <tbody className="divide-y divide-slate-100">
                      {achievements.map((ach: any, i: number) => (
                        <tr key={i} className="hover:bg-slate-50/60 transition-colors">
                          <td className="py-3 px-4 text-center font-medium text-slate-400">{i + 1}</td>
                          <td className="py-3 px-4 font-bold text-slate-800">{ach.achievement_name}</td>
                          <td className="py-3 px-4 text-slate-500 text-xs">{ach.category}</td>
                          <td className="py-3 px-4 text-slate-600 font-medium">{ach.level}</td>
                          <td className="py-3 px-4 text-center">
                            <span className="px-2.5 py-0.5 rounded-full font-bold text-xs bg-amber-100 text-amber-800">
                              {ach.rank}
                            </span>
                          </td>
                          <td className="py-3 px-4 text-xs text-slate-500">
                            {ach.organizer || "-"} ({ach.certificate_number || "-"})
                          </td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              ) : (
                <div className="p-8 text-center text-slate-500 border border-dashed border-slate-200 rounded-2xl">
                  Belum ada rekam piagam prestasi yang diunggah untuk siswa ini.
                </div>
              )}
            </div>
          </div>
        )}
      </div>
    </div>
  );
};

export const StudentPortalView: React.FC<StudentPortalViewProps> = (props) => (
  <React.Suspense
    fallback={
      <div className="min-h-[400px] flex items-center justify-center">
        <div className="w-8 h-8 border-3 border-blue-600 border-t-transparent rounded-full animate-spin" />
      </div>
    }
  >
    <StudentPortalViewContent {...props} />
  </React.Suspense>
);
