/**
 * @license
 * SPDX-License-Identifier: Apache-2.0
 */

import React, { useMemo } from "react";
import { Employee, WorkflowRequest, AttendanceRecord } from "../types";
import { calculateExpiringDocuments, ExpiringDocumentAlert } from "../utils/documentExpiry";
import { 
  Users, 
  UserCheck, 
  FileText, 
  Cake, 
  Clock, 
  FileWarning, 
  GraduationCap, 
  Award, 
  TrendingUp, 
  Briefcase, 
  CalendarClock, 
  TrendingDown, 
  AlertTriangle,
  QrCode,
  UserX,
  CheckCircle2,
  ShieldAlert,
  Search,
  ArrowRight,
  Plane,
  Wallet,
  Receipt
} from "lucide-react";
import {
  ResponsiveContainer,
  LineChart,
  Line,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  Legend
} from "recharts";

const DIVISION_COLORS: Record<string, string> = {
  "Executive Office": "#38bdf8",
  "Bendahara": "#0284c7",
  "Developer dan Maintenance": "#10b981",
  "Payroll dan kesejahteraan": "#f43f5e",
  "Core bisnis (Developer dan sewa Aplikasi web)": "#818cf8",
  "Marketing dan Legal Corporate": "#f59e0b",
  "General Affair (GA) dan Sarpras": "#cbd5e1",
  "Akuntansi dan Perpajakan": "#06b6d4",
  "Rekrutmen dan Jenjang Karir": "#ec4899",
};

const DEFAULT_LINE_COLORS = ["#38bdf8", "#0284c7", "#10b981", "#f43f5e", "#818cf8", "#f59e0b", "#06b6d4"];

const CustomKpiTooltip = ({ active, payload, label }: any) => {
  if (active && payload && payload.length) {
    return (
      <div className="bg-[#0f172a] border border-[#1e3a8a]/80 p-2.5 sm:p-3 shadow-xl text-xs font-mono rounded-lg">
        <p className="font-bold text-sky-400 border-b border-[#1e3a8a] pb-1 mb-2 uppercase tracking-wider text-[11px]">
          Periode: {label}
        </p>
        <div className="space-y-1 max-h-48 overflow-y-auto pr-1">
          {payload.map((entry: any, index: number) => (
            <div key={`item-${index}`} className="flex items-center justify-between gap-3 text-[11px]">
              <span className="flex items-center gap-1.5 text-slate-300">
                <span className="w-2 h-2 rounded-full inline-block" style={{ backgroundColor: entry.color }} />
                {entry.name}:
              </span>
              <span className="font-mono font-bold text-white">{entry.value} Pts</span>
            </div>
          ))}
        </div>
      </div>
    );
  }
  return null;
};

import { getDirectorateName } from "./LoginModal";

interface DashboardProps {
  employees: Employee[];
  workflows: WorkflowRequest[];
  onSelectEmployee: (empId: string) => void;
  currentUser?: Employee;
  onOpenLoginModal?: () => void;
  onNavigateTab?: (tab: string) => void;
}

export default function Dashboard({ employees, workflows, onSelectEmployee, currentUser, onOpenLoginModal, onNavigateTab }: DashboardProps) {
  // Document Expiry Alert State
  const [docAlertFilter, setDocAlertFilter] = React.useState<"all" | "SK" | "Sertifikasi" | "urgent">("all");
  const [docAlertSearch, setDocAlertSearch] = React.useState<string>("");

  // Calculate Expiring Documents (< 30 Days)
  const expiringDocAlerts = useMemo(() => {
    return calculateExpiringDocuments(employees, 30);
  }, [employees]);

  // Filtered Expiring Documents
  const filteredDocAlerts = useMemo(() => {
    return expiringDocAlerts.filter(item => {
      // Filter type/urgency
      if (docAlertFilter === "SK" && item.docType !== "SK") return false;
      if (docAlertFilter === "Sertifikasi" && item.docType !== "Sertifikasi") return false;
      if (docAlertFilter === "urgent" && item.daysRemaining > 10) return false;

      // Search filter
      if (docAlertSearch.trim()) {
        const q = docAlertSearch.toLowerCase();
        const matchName = item.employeeName.toLowerCase().includes(q);
        const matchNip = item.employeeNip.toLowerCase().includes(q);
        const matchTitle = item.docTitle.toLowerCase().includes(q);
        const matchPos = item.employeePosition.toLowerCase().includes(q);
        return matchName || matchNip || matchTitle || matchPos;
      }

      return true;
    });
  }, [expiringDocAlerts, docAlertFilter, docAlertSearch]);

  const skCount = useMemo(() => expiringDocAlerts.filter(a => a.docType === "SK").length, [expiringDocAlerts]);
  const certCount = useMemo(() => expiringDocAlerts.filter(a => a.docType === "Sertifikasi").length, [expiringDocAlerts]);
  const urgentCount = useMemo(() => expiringDocAlerts.filter(a => a.daysRemaining <= 10).length, [expiringDocAlerts]);

  // Compute Attendance Real-time Stats
  const attendanceStats = useMemo(() => {
    const todayStr = new Date().toISOString().split("T")[0];
    let logs: AttendanceRecord[] = [];
    try {
      const cached = localStorage.getItem("simulated_attendance_logs");
      if (cached) {
        logs = JSON.parse(cached);
      }
    } catch (e) {
      console.warn("Error loading attendance logs:", e);
    }

    if (logs.length === 0) {
      logs = [
        { id: "att-101", employeeId: "emp-ceo-01", employeeNip: "NIP-202401001", employeeName: "Bambang Hartono, M.B.A.", employeePosition: "Chief Executive Officer (CEO)", employeeDivision: "Direksi Utama", date: todayStr, checkInTime: "07:45 WIB", checkOutTime: "17:30 WIB", status: "Tepat Waktu", lateMinutes: 0, locationName: "Kantor Pusat HQ Jakarta", qrCodeScanData: "", verifiedByScanner: "Scanner Pos Utama 01" },
        { id: "att-102", employeeId: "emp-dev-001", employeeNip: "NIP-202402014", employeeName: "Ahmad Wijaya", employeePosition: "Senior Lead Software Architect", employeeDivision: "Teknologi Informasi (IT)", date: todayStr, checkInTime: "08:12 WIB", checkOutTime: "17:15 WIB", status: "Tepat Waktu", lateMinutes: 0, locationName: "Kantor Pusat HQ Jakarta", qrCodeScanData: "", verifiedByScanner: "Scanner Pos Utama 02" },
        { id: "att-103", employeeId: "emp-hr-002", employeeNip: "NIP-202403022", employeeName: "Siti Rahmawati, M.Psi", employeePosition: "Payroll & Compensation Manager", employeeDivision: "Sumber Daya Manusia (HRD)", date: todayStr, checkInTime: "08:48 WIB", checkOutTime: "17:00 WIB", status: "Terlambat", lateMinutes: 18, locationName: "Kantor Pusat HQ Jakarta", qrCodeScanData: "", verifiedByScanner: "Scanner Pos Utama 01" },
        { id: "att-104", employeeId: "emp-fin-003", employeeNip: "NIP-202404005", employeeName: "Dewi Lestari, S.E., Ak.", employeePosition: "Senior Financial Controller", employeeDivision: "Keuangan & Akuntansi", date: todayStr, checkInTime: "07:58 WIB", checkOutTime: "17:02 WIB", status: "Tepat Waktu", lateMinutes: 0, locationName: "Kantor Pusat HQ Jakarta", qrCodeScanData: "", verifiedByScanner: "Scanner Pos Utama 02" }
      ];
    }

    const todayLogs = logs.filter(l => l.date === todayStr || !l.date);
    const totalEmployees = employees.length || 1;
    const hadir = todayLogs.length;
    const tepatWaktu = todayLogs.filter(l => l.status === "Tepat Waktu").length;
    const terlambat = todayLogs.filter(l => l.status === "Terlambat").length;
    const izinDinas = todayLogs.filter(l => l.status === "Izin / Sakit" || l.status === "Dinas Luar").length;
    const tidakHadir = Math.max(0, totalEmployees - hadir);
    const percentHadir = Math.round((hadir / totalEmployees) * 100);

    return { totalEmployees, hadir, tepatWaktu, terlambat, izinDinas, tidakHadir, percentHadir, todayStr };
  }, [employees]);
  // Compute Stats
  const stats = useMemo(() => {
    const total = employees.length;
    const active = employees.filter(e => e.status === 'Aktif').length;
    const contract = employees.filter(e => e.status === 'Kontrak').length;
    const resigned = employees.filter(e => e.status === 'Resigned').length;
    const pensiun = employees.filter(e => e.status === 'Pensiun').length;

    const male = employees.filter(e => e.gender === 'L').length;
    const female = employees.filter(e => e.gender === 'P').length;

    const today = new Date();
    const currentMonth = today.getMonth(); // 0-11
    const currentDate = today.getDate();

    // Birthday Today & Month
    const birthdayToday = employees.filter(e => {
      const bDate = new Date(e.birthDate);
      return bDate.getMonth() === currentMonth && bDate.getDate() === currentDate;
    });

    const birthdayMonth = employees.filter(e => {
      const bDate = new Date(e.birthDate);
      return bDate.getMonth() === currentMonth;
    });

    // Masa Kerja > 10 Tahun
    const tenureOver10 = employees.filter(e => {
      const tDate = new Date(e.tmtKerja);
      const diffYears = (today.getFullYear() - tDate.getFullYear());
      return diffYears >= 10;
    });

    // Contract Expiring in 3 months
    const contractExpiring = employees.filter(e => {
      if (e.status !== 'Kontrak') return false;
      // In this realistic scenario, let's assume contracts last 1-2 years from TMT
      const tmt = new Date(e.tmtKerja);
      const contractEnd = new Date(tmt);
      contractEnd.setFullYear(contractEnd.getFullYear() + 1); // 1 year contract
      
      const diffMs = contractEnd.getTime() - today.getTime();
      const diffDays = Math.ceil(diffMs / (1000 * 60 * 60 * 24));
      return diffDays > 0 && diffDays <= 90;
    });

    // Retiring this year (Age >= 55)
    const retiringThisYear = employees.filter(e => {
      const bDate = new Date(e.birthDate);
      const ageThisYear = today.getFullYear() - bDate.getFullYear();
      return e.status === 'Aktif' && ageThisYear >= 55;
    });

    // Training this month
    const trainingThisMonth = employees.filter(e => {
      return e.riwayatPelatihan.some(p => {
        const pDate = new Date(p.date);
        return pDate.getFullYear() === today.getFullYear() && pDate.getMonth() === currentMonth;
      });
    }).length;

    // Average HR KPI Score
    const activeKPIs = employees.filter(e => e.status === 'Aktif' || e.status === 'Kontrak');
    const avgKPI = activeKPIs.length > 0 
      ? Math.round(activeKPIs.reduce((sum, e) => sum + e.kpiScore, 0) / activeKPIs.length)
      : 0;

    return {
      total,
      active,
      contract,
      resigned,
      pensiun,
      male,
      female,
      birthdayToday,
      birthdayMonth,
      tenureOver10,
      contractExpiring,
      retiringThisYear,
      trainingThisMonth,
      avgKPI
    };
  }, [employees]);

  // Compute KPI trend over time grouped by division
  const { kpiTrendData, trackedDivisions } = useMemo(() => {
    // Collect all periods from riwayatKPI across employees
    const periodSet = new Set<string>(["2025 Q1", "2025 Q2", "2025 Q3", "2025 Q4", "2026 Q1"]);
    employees.forEach(emp => {
      emp.riwayatKPI?.forEach(kpi => {
        if (kpi.period) periodSet.add(kpi.period);
      });
    });

    const sortedPeriods = Array.from(periodSet).sort((a, b) => a.localeCompare(b));

    // Get list of divisions with active employees
    const divisionList = Array.from(new Set(employees.map(e => e.division).filter(Boolean)));

    // Create time-series points
    const data = sortedPeriods.map((period, periodIndex) => {
      const point: Record<string, any> = { period };

      divisionList.forEach((div) => {
        const divEmps = employees.filter(e => e.division === div);
        if (divEmps.length === 0) return;

        // Find scores for this period in this division
        let scores: number[] = [];
        divEmps.forEach(emp => {
          const match = emp.riwayatKPI?.find(k => k.period === period);
          if (match && typeof match.score === 'number') {
            scores.push(match.score);
          }
        });

        if (scores.length > 0) {
          const avg = Math.round(scores.reduce((a, b) => a + b, 0) / scores.length);
          point[div] = avg;
        } else {
          // Synthetic realistic trend baseline based on division current KPI average
          const baseAvg = Math.round(divEmps.reduce((s, e) => s + (e.kpiScore || 88), 0) / divEmps.length);
          // Add small variation over periods for visual trend analysis
          const delta = (periodIndex - (sortedPeriods.length - 1)) * 1.8 + ((div.length % 3) - 1);
          point[div] = Math.min(100, Math.max(65, Math.round(baseAvg + delta)));
        }
      });

      return point;
    });

    return { kpiTrendData: data, trackedDivisions: divisionList };
  }, [employees]);

  // Simulated Turnover Data for GAN
  const turnoverTrend = [
    { month: "Jan", hires: 4, exits: 1 },
    { month: "Feb", hires: 2, exits: 0 },
    { month: "Mar", hires: 5, exits: 2 },
    { month: "Apr", hires: 3, exits: 1 },
    { month: "Mei", hires: 6, exits: 0 },
    { month: "Jun", hires: 4, exits: 2 },
  ];

  const pendingApprovalsCount = useMemo(() => {
    return workflows.filter(w => w.status === 'Pending').length;
  }, [workflows]);

  return (
    <div className="space-y-6 animate-fadeIn" id="executive-dashboard-container">
      {/* Overview Top bar */}
      <div className="flex flex-col md:flex-row md:items-end md:justify-between border-b border-[#1e3a8a]/40 pb-4 sm:pb-6 gap-3">
        <div>
          <p className="text-[9px] sm:text-[10px] uppercase tracking-[0.25em] text-sky-400 font-extrabold mb-1">
            Real-Time Analytics Portal
          </p>
          <h2 className="text-2xl sm:text-3xl md:text-4xl font-extrabold text-white uppercase tracking-tight leading-none bg-gradient-to-r from-sky-400 via-blue-200 to-white bg-clip-text text-transparent" id="dashboard-title">
            Human Capital Dashboard
          </h2>
          <p className="text-[10px] sm:text-xs text-sky-200/70 font-mono mt-1">
            MEDIAN PT MEDIA EKOSISTEM DIGITAL APLIKASI NASIONAL
          </p>
        </div>
        <div className="flex items-center gap-3 font-mono">
          <span className="inline-flex items-center gap-1.5 text-[10px] sm:text-xs font-bold px-2.5 py-1 bg-emerald-500/10 text-emerald-300 border border-emerald-500/30 rounded-lg">
            <span className="w-2 h-2 rounded-full bg-emerald-400 animate-pulse"></span>
            SYSTEM ONLINE
          </span>
          <span className="text-[10px] sm:text-xs text-slate-400">SYNC: 2026-07-05</span>
        </div>
      </div>

      {/* Role-Based Active User Welcome & Authority Card */}
      {currentUser && (
        <div className="bg-[#0f172a] border border-[#1e3a8a] p-4 sm:p-5 rounded-xl shadow-lg flex flex-col md:flex-row items-start md:items-center justify-between gap-4 font-sans relative overflow-hidden">
          <div className="absolute top-0 right-0 w-32 h-32 bg-sky-500/10 pointer-events-none rounded-full blur-2xl"></div>

          <div className="flex items-center gap-3 sm:gap-4">
            <div className="w-12 h-12 sm:w-14 sm:h-14 bg-gradient-to-br from-blue-600 to-sky-500 text-white font-extrabold text-xl sm:text-2xl flex items-center justify-center shrink-0 rounded-xl shadow-md shadow-blue-500/20">
              {currentUser.name.charAt(0)}
            </div>

            <div>
              <div className="flex items-center gap-2 flex-wrap mb-1">
                <span className="text-[9px] font-bold font-mono uppercase bg-sky-500/20 text-sky-300 border border-sky-500/40 px-2 py-0.5 rounded">
                  USER TERHUBUNG
                </span>
                <span className="text-[9px] font-bold font-mono uppercase bg-slate-800 text-slate-300 px-2 py-0.5 border border-slate-700 rounded">
                  {getDirectorateName(currentUser.position, currentUser.division)}
                </span>
                <span className="text-[9px] font-mono text-slate-400">
                  NIP: {currentUser.nip}
                </span>
              </div>

              <h3 className="text-base sm:text-lg font-bold text-white">
                Selamat Datang, {currentUser.name}
              </h3>
              <p className="text-[11px] sm:text-xs text-slate-300 font-mono mt-0.5">
                Jabatan: <span className="text-sky-300 font-bold">{currentUser.position}</span> • Divisi: {currentUser.division}
              </p>
            </div>
          </div>

          <div className="flex items-center gap-3 w-full md:w-auto justify-end border-t md:border-t-0 border-[#1e3a8a]/50 pt-3 md:pt-0">
            {onOpenLoginModal && (
              <button
                onClick={onOpenLoginModal}
                className="px-3.5 py-1.5 sm:px-4 sm:py-2 bg-gradient-to-r from-blue-600 to-sky-500 hover:from-blue-500 hover:to-sky-400 text-white font-bold uppercase text-[10px] sm:text-xs tracking-wider transition-all flex items-center gap-2 shadow-md rounded-lg"
              >
                Ganti Role Login
              </button>
            )}
          </div>
        </div>
      )}

      {/* Ringkasan Real-Time Kehadiran Karyawan (Scanner QR Name Tag HRD) */}
      <div className="bg-[#0f172a] border-2 border-amber-500/40 p-4 sm:p-5 rounded-xl shadow-xl font-sans relative overflow-hidden space-y-4">
        <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-3 border-b border-[#1e3a8a]/60 pb-3">
          <div className="flex items-center gap-2.5">
            <div className="p-2 bg-amber-500/10 border border-amber-500/30 text-amber-400 rounded-lg shrink-0">
              <QrCode className="w-5 h-5 text-amber-400" />
            </div>
            <div>
              <div className="flex items-center gap-2">
                <span className="text-[10px] font-black uppercase tracking-wider bg-amber-400 text-black px-2 py-0.5 rounded font-mono">
                  MODUL ABSENSI REAL-TIME HRD
                </span>
                <span className="text-[10px] text-slate-400 font-mono">
                  Tanggal Hari Ini: {attendanceStats.todayStr}
                </span>
              </div>
              <h3 className="text-base sm:text-lg font-black text-white uppercase tracking-tight mt-0.5">
                Ringkasan Kehadiran Karyawan Hari Ini
              </h3>
            </div>
          </div>

          {onNavigateTab && (
            <button
              type="button"
              onClick={() => onNavigateTab("attendance")}
              className="px-3.5 py-1.5 bg-gradient-to-r from-amber-500 to-yellow-500 hover:from-amber-400 hover:to-yellow-400 text-slate-950 font-black uppercase text-xs tracking-wider transition-all flex items-center gap-1.5 shadow-md rounded-lg shrink-0 cursor-pointer"
            >
              <QrCode className="w-4 h-4 text-slate-950" />
              Kelola Scanner QR Presensi
            </button>
          )}
        </div>

        {/* Attendance Metrics Grid */}
        <div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-5 gap-3 font-mono">
          <div className="bg-[#080d1a] border border-[#1e3a8a]/80 p-3.5 rounded-lg space-y-1">
            <span className="text-[10px] font-bold text-slate-400 uppercase block flex items-center gap-1">
              <UserCheck className="w-3.5 h-3.5 text-emerald-400" />
              Hadir Hari Ini
            </span>
            <div className="text-2xl sm:text-3xl font-black text-emerald-400">
              {attendanceStats.hadir} <span className="text-xs text-emerald-500 font-normal">/ {attendanceStats.totalEmployees}</span>
            </div>
            <div className="w-full bg-slate-800 h-1.5 rounded-full overflow-hidden mt-1">
              <div className="bg-emerald-400 h-full rounded-full" style={{ width: `${attendanceStats.percentHadir}%` }} />
            </div>
            <span className="text-[9px] text-slate-400 block pt-0.5">{attendanceStats.percentHadir}% Presensi Terverifikasi</span>
          </div>

          <div className="bg-[#080d1a] border border-[#1e3a8a]/80 p-3.5 rounded-lg space-y-1">
            <span className="text-[10px] font-bold text-slate-400 uppercase block flex items-center gap-1">
              <CheckCircle2 className="w-3.5 h-3.5 text-sky-400" />
              Tepat Waktu
            </span>
            <div className="text-2xl sm:text-3xl font-black text-sky-300">
              {attendanceStats.tepatWaktu}
            </div>
            <span className="text-[9px] text-sky-400 block">Scan &lt; 08:30 WIB</span>
          </div>

          <div className="bg-[#080d1a] border border-[#1e3a8a]/80 p-3.5 rounded-lg space-y-1">
            <span className="text-[10px] font-bold text-slate-400 uppercase block flex items-center gap-1">
              <Clock className="w-3.5 h-3.5 text-amber-400" />
              Terlambat
            </span>
            <div className="text-2xl sm:text-3xl font-black text-amber-400">
              {attendanceStats.terlambat}
            </div>
            <span className="text-[9px] text-amber-400/80 block">Kena Potongan Absensi</span>
          </div>

          <div className="bg-[#080d1a] border border-[#1e3a8a]/80 p-3.5 rounded-lg space-y-1">
            <span className="text-[10px] font-bold text-slate-400 uppercase block flex items-center gap-1">
              <UserX className="w-3.5 h-3.5 text-rose-400" />
              Tidak Hadir / Alpa
            </span>
            <div className="text-2xl sm:text-3xl font-black text-rose-400">
              {attendanceStats.tidakHadir}
            </div>
            <span className="text-[9px] text-rose-400/80 block">Potongan Gaji Pokok</span>
          </div>

          <div className="bg-[#080d1a] border border-[#1e3a8a]/80 p-3.5 rounded-lg space-y-1 col-span-2 sm:col-span-1">
            <span className="text-[10px] font-bold text-slate-400 uppercase block flex items-center gap-1">
              <AlertTriangle className="w-3.5 h-3.5 text-blue-400" />
              Izin / Dinas Luar
            </span>
            <div className="text-2xl sm:text-3xl font-black text-blue-300">
              {attendanceStats.izinDinas}
            </div>
            <span className="text-[9px] text-blue-400/80 block">Tercatat Resmi HRD</span>
          </div>
        </div>
      </div>

      {/* Perjalanan Dinas (SPPD & Financial Voucher) Quick Action Widget */}
      <div className="bg-gradient-to-r from-slate-900 via-sky-950/60 to-slate-900 border border-sky-500/30 p-4 sm:p-5 rounded-xl shadow-xl flex flex-col sm:flex-row sm:items-center justify-between gap-4">
        <div className="flex items-center gap-3.5">
          <div className="p-3 bg-gradient-to-br from-sky-500 to-blue-600 rounded-xl text-slate-950 shadow-md shadow-sky-500/20 shrink-0">
            <Plane className="w-5 h-5 font-black" />
          </div>
          <div>
            <div className="flex items-center gap-2">
              <span className="text-[10px] font-black uppercase tracking-wider bg-sky-400 text-slate-950 px-2 py-0.5 rounded font-mono">
                MODUL SPPD & VOUCHER KEUANGAN
              </span>
              <span className="text-[10px] text-emerald-400 font-mono font-bold">
                ✓ Standar Fasilitas Sesuai Grade
              </span>
            </div>
            <h4 className="text-sm sm:text-base font-bold text-white mt-1">
              Pengelolaan Surat Perintah Perjalanan Dinas & Pertanggungjawaban LPJ
            </h4>
            <p className="text-[11px] text-slate-300">
              Mencakup Hubungan Eksternal/Internal, Tugas Belajar, Plafon Hotel, Tiket Pesawat/Kereta/Bis, Uang Saku & Uang Makan Harian, serta Taksi Kota.
            </p>
          </div>
        </div>

        {onNavigateTab && (
          <button
            onClick={() => onNavigateTab("travel")}
            className="px-4 py-2 bg-gradient-to-r from-sky-500 to-blue-600 hover:from-sky-400 hover:to-blue-500 text-slate-950 font-black text-xs uppercase tracking-wider rounded-lg shadow-md shadow-sky-500/20 flex items-center gap-2 shrink-0 self-start sm:self-auto transition-all cursor-pointer"
          >
            <span>Buka Modul SPPD</span>
            <ArrowRight className="w-4 h-4" />
          </button>
        )}
      </div>

      {/* UMK Kas Kecil Seksi Umum (GA) Quick Action Widget */}
      <div className="bg-gradient-to-r from-slate-900 via-emerald-950/50 to-slate-900 border border-emerald-500/30 p-4 sm:p-5 rounded-xl shadow-xl flex flex-col sm:flex-row sm:items-center justify-between gap-4">
        <div className="flex items-center gap-3.5">
          <div className="p-3 bg-gradient-to-br from-emerald-500 to-teal-600 rounded-xl text-slate-950 shadow-md shadow-emerald-500/20 shrink-0">
            <Wallet className="w-5 h-5 font-black" />
          </div>
          <div>
            <div className="flex items-center gap-2">
              <span className="text-[10px] font-black uppercase tracking-wider bg-emerald-400 text-slate-950 px-2 py-0.5 rounded font-mono">
                UMK KAS KECIL SEKSI UMUM (GA)
              </span>
              <span className="text-[10px] text-amber-400 font-mono font-bold">
                ✓ Batas 2 Minggu (14 Hari) & 2 Voucher LPJ
              </span>
            </div>
            <h4 className="text-sm sm:text-base font-bold text-white mt-1">
              Uang Muka Kerja Kas Kecil Operasional & Pertanggungjawaban Keuangan
            </h4>
            <p className="text-[11px] text-slate-300">
              1 Akun Anggaran UMK Induk (1101.02) dengan sistem pelaporan 2 Voucher: Voucher 1 Pengembalian Sisa Kas & Voucher 2 Realisasi Belanja Expendables + Kuitansi Sah.
            </p>
          </div>
        </div>

        {onNavigateTab && (
          <button
            onClick={() => onNavigateTab("umk")}
            className="px-4 py-2 bg-gradient-to-r from-emerald-500 to-teal-600 hover:from-emerald-400 hover:to-teal-500 text-slate-950 font-black text-xs uppercase tracking-wider rounded-lg shadow-md shadow-emerald-500/20 flex items-center gap-2 shrink-0 self-start sm:self-auto transition-all cursor-pointer"
          >
            <span>Buka UMK Kas Kecil</span>
            <ArrowRight className="w-4 h-4" />
          </button>
        )}
      </div>

      {/* Primary KPI Grid */}
      <div className="grid grid-cols-2 lg:grid-cols-4 gap-3 sm:gap-4" id="primary-kpi-grid">
        <div className="bg-[#0f172a]/90 border border-[#1e3a8a]/60 rounded-xl p-3.5 sm:p-5 flex items-center gap-3 sm:gap-4 shadow-sm">
          <div className="w-10 h-10 sm:w-12 sm:h-12 bg-blue-950/80 border border-sky-500/30 text-sky-400 flex items-center justify-center rounded-lg shrink-0">
            <Users className="w-5 h-5 sm:w-6 sm:h-6" />
          </div>
          <div>
            <p className="text-[9px] sm:text-[10px] uppercase tracking-wider font-semibold text-slate-400">Total Pegawai</p>
            <h3 className="text-2xl sm:text-3xl font-extrabold text-white leading-none mt-1 font-mono">{stats.total}</h3>
            <p className="text-[8px] sm:text-[9px] text-sky-400 uppercase tracking-wider font-semibold mt-1">Database Terdaftar</p>
          </div>
        </div>

        <div className="bg-[#0f172a]/90 border border-[#1e3a8a]/60 rounded-xl p-3.5 sm:p-5 flex items-center gap-3 sm:gap-4 shadow-sm">
          <div className="w-10 h-10 sm:w-12 sm:h-12 bg-blue-950/80 border border-sky-500/30 text-sky-400 flex items-center justify-center rounded-lg shrink-0">
            <UserCheck className="w-5 h-5 sm:w-6 sm:h-6" />
          </div>
          <div>
            <p className="text-[9px] sm:text-[10px] uppercase tracking-wider font-semibold text-slate-400">Pegawai Aktif</p>
            <h3 className="text-2xl sm:text-3xl font-extrabold text-white leading-none mt-1 font-mono">{stats.active}</h3>
            <p className="text-[8px] sm:text-[9px] text-emerald-400 uppercase tracking-wider font-semibold mt-1">{(stats.active/stats.total*100).toFixed(0)}% Karyawan Tetap</p>
          </div>
        </div>

        <div className="bg-[#0f172a]/90 border border-[#1e3a8a]/60 rounded-xl p-3.5 sm:p-5 flex items-center gap-3 sm:gap-4 shadow-sm">
          <div className="w-10 h-10 sm:w-12 sm:h-12 bg-blue-950/80 border border-sky-500/30 text-sky-400 flex items-center justify-center rounded-lg shrink-0">
            <FileText className="w-5 h-5 sm:w-6 sm:h-6" />
          </div>
          <div>
            <p className="text-[9px] sm:text-[10px] uppercase tracking-wider font-semibold text-slate-400">Pegawai Kontrak</p>
            <h3 className="text-2xl sm:text-3xl font-extrabold text-white leading-none mt-1 font-mono">{stats.contract}</h3>
            <p className="text-[8px] sm:text-[9px] text-amber-400 uppercase tracking-wider font-semibold mt-1">{stats.contract} PKWT Aktif</p>
          </div>
        </div>

        <div className="bg-[#0f172a]/90 border border-[#1e3a8a]/60 rounded-xl p-3.5 sm:p-5 flex items-center gap-3 sm:gap-4 shadow-sm">
          <div className="w-10 h-10 sm:w-12 sm:h-12 bg-blue-950/80 border border-sky-500/30 text-sky-400 flex items-center justify-center rounded-lg shrink-0">
            <Award className="w-5 h-5 sm:w-6 sm:h-6" />
          </div>
          <div>
            <p className="text-[9px] sm:text-[10px] uppercase tracking-wider font-semibold text-slate-400">Rata-Rata KPI</p>
            <h3 className="text-2xl sm:text-3xl font-extrabold text-white leading-none mt-1 font-mono">{stats.avgKPI}%</h3>
            <p className="text-[8px] sm:text-[9px] text-indigo-300 uppercase tracking-wider font-semibold mt-1">Kategori: (A) SANGAT BAIK</p>
          </div>
        </div>
      </div>

      {/* Secondary Strategic HR Metrics Grid */}
      <div className="grid grid-cols-2 lg:grid-cols-4 gap-4" id="secondary-hr-grid">
        <div className="bg-[#0a0a0a] border border-[#222] rounded-none p-4 flex flex-col justify-between">
          <div className="flex items-center justify-between mb-2">
            <span className="text-[10px] uppercase tracking-widest font-black text-slate-500">Gender Ratio</span>
            <span className="w-2.5 h-2.5 bg-[#facc15]"></span>
          </div>
          <div className="flex items-baseline gap-2 font-mono">
            <span className="text-lg font-black text-white">L: {stats.male}</span>
            <span className="text-xs text-[#333]">/</span>
            <span className="text-lg font-black text-rose-500">P: {stats.female}</span>
          </div>
          <div className="w-full bg-[#111] h-2 rounded-none mt-3 overflow-hidden flex border border-[#222]">
            <div className="bg-[#facc15]" style={{ width: `${(stats.male/stats.total)*100}%` }}></div>
            <div className="bg-rose-600" style={{ width: `${(stats.female/stats.total)*100}%` }}></div>
          </div>
        </div>

        <div className="bg-[#0a0a0a] border border-[#222] rounded-none p-4 flex flex-col justify-between">
          <div className="flex items-center justify-between mb-2">
            <span className="text-[10px] uppercase tracking-widest font-black text-slate-500">Ulang Tahun</span>
            <Cake className="w-4 h-4 text-[#facc15]" />
          </div>
          <div>
            <h4 className="text-xs font-black uppercase text-white leading-tight">
              {stats.birthdayToday.length > 0 
                ? `${stats.birthdayToday.length} Hari Ini 🎂` 
                : `${stats.birthdayMonth.length} Bulan Ini`}
            </h4>
            <p className="text-[9px] text-slate-500 uppercase tracking-wider font-bold mt-1">Apresiasi Kepegawaian</p>
          </div>
        </div>

        <div className="bg-[#0a0a0a] border border-[#222] rounded-none p-4 flex flex-col justify-between">
          <div className="flex items-center justify-between mb-2">
            <span className="text-[10px] uppercase tracking-widest font-black text-slate-500">Loyalitas Tinggi</span>
            <Clock className="w-4 h-4 text-green-400" />
          </div>
          <div>
            <h4 className="text-xs font-black uppercase text-white leading-tight">{stats.tenureOver10.length} Pegawai &gt; 10 Th</h4>
            <p className="text-[9px] text-slate-500 uppercase tracking-wider font-bold mt-1">Stabilitas Operasional</p>
          </div>
        </div>

        <div className="bg-[#0a0a0a] border border-[#222] rounded-none p-4 flex flex-col justify-between">
          <div className="flex items-center justify-between mb-2">
            <span className="text-[10px] uppercase tracking-widest font-black text-red-500">Akan Pensiun</span>
            <CalendarClock className="w-4 h-4 text-red-400" />
          </div>
          <div>
            <h4 className="text-xs font-black uppercase text-red-400 leading-tight">{stats.retiringThisYear.length} Orang Th Ini</h4>
            <p className="text-[9px] text-slate-500 uppercase tracking-wider font-bold mt-1">Perencanaan Suksesi</p>
          </div>
        </div>
      </div>

      {/* Recharts Line Chart: KPI Score Trend per Division */}
      <div className="bg-[#0a0a0a] border border-[#222] rounded-none p-6 space-y-4" id="kpi-score-trend-section">
        <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-2 border-b border-[#222] pb-4">
          <div>
            <div className="flex items-center gap-2 mb-1">
              <span className="text-[10px] uppercase tracking-[0.2em] text-[#facc15] font-black bg-[#141414] px-2 py-0.5 border border-[#222]">
                ANALISIS KINERJA PEGAWAI
              </span>
              <span className="text-[10px] font-mono text-slate-400">Riwayat Evaluasi KPI</span>
            </div>
            <h3 className="text-xl font-black text-white uppercase tracking-tighter flex items-center gap-2">
              <TrendingUp className="w-5 h-5 text-[#facc15]" />
              Tren KPI Score Berdasarkan Divisi
            </h3>
            <p className="text-xs text-slate-500 font-mono mt-0.5">
              Visualisasi time-series perkembangan nilai KPI pegawai per periode evaluasi (riwayatKPI)
            </p>
          </div>

          <div className="flex items-center gap-2 font-mono text-xs">
            <span className="px-3 py-1 bg-[#050505] border border-[#222] text-[#facc15] font-black uppercase">
              Rata-Rata Enterprise: {stats.avgKPI}%
            </span>
          </div>
        </div>

        {/* Recharts Responsive Line Chart */}
        <div className="h-80 w-full pt-2">
          <ResponsiveContainer width="100%" height="100%">
            <LineChart data={kpiTrendData} margin={{ top: 10, right: 20, left: -10, bottom: 0 }}>
              <CartesianGrid strokeDasharray="3 3" stroke="#222" vertical={false} />
              <XAxis 
                dataKey="period" 
                stroke="#666" 
                tick={{ fill: '#94a3b8', fontSize: 11, fontFamily: 'monospace' }}
                tickLine={{ stroke: '#333' }}
              />
              <YAxis 
                domain={[60, 100]} 
                stroke="#666" 
                tick={{ fill: '#94a3b8', fontSize: 11, fontFamily: 'monospace' }}
                tickLine={{ stroke: '#333' }}
                unit=" Pts"
              />
              <Tooltip content={<CustomKpiTooltip />} />
              <Legend 
                wrapperStyle={{ paddingTop: '12px', fontSize: '11px', fontFamily: 'monospace' }}
                formatter={(value) => <span className="text-slate-300 font-bold">{value}</span>}
              />
              {trackedDivisions.map((division, idx) => {
                const color = DIVISION_COLORS[division] || DEFAULT_LINE_COLORS[idx % DEFAULT_LINE_COLORS.length];
                return (
                  <Line
                    key={division}
                    type="monotone"
                    dataKey={division}
                    name={division}
                    stroke={color}
                    strokeWidth={2.5}
                    dot={{ r: 4, fill: color, stroke: '#0a0a0a', strokeWidth: 2 }}
                    activeDot={{ r: 7, fill: '#fff', stroke: color, strokeWidth: 2 }}
                  />
                );
              })}
            </LineChart>
          </ResponsiveContainer>
        </div>
      </div>

      {/* Main Charts & Visualizations Row */}
      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        {/* Left: Graphic for Turnover Trend */}
        <div className="lg:col-span-2 bg-[#0a0a0a] border border-[#222] rounded-none p-6">
          <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-2 mb-4">
            <div>
              <p className="text-[10px] uppercase tracking-widest text-[#facc15] font-black">Turnover & Rekrutmen</p>
              <h3 className="text-md font-black text-white uppercase tracking-tighter">Tren Penambahan & Pengurangan Pegawai</h3>
            </div>
            <div className="flex items-center gap-4 text-[10px] font-mono uppercase font-bold text-slate-400">
              <span className="flex items-center gap-1.5">
                <span className="w-3 h-3 bg-[#facc15] inline-block"></span>
                Hires
              </span>
              <span className="flex items-center gap-1.5">
                <span className="w-3 h-3 bg-red-950 border border-red-800 inline-block"></span>
                Exits
              </span>
            </div>
          </div>

          {/* Custom CSS Chart for turnoverTrend */}
          <div className="h-48 flex items-end justify-between gap-2 pt-6 border-b border-[#222] px-2">
            {turnoverTrend.map((t, idx) => {
              const maxVal = 7;
              const hireHeight = (t.hires / maxVal) * 100;
              const exitHeight = (t.exits / maxVal) * 100;
              return (
                <div key={idx} className="flex flex-col items-center flex-1 group">
                  <div className="w-full flex justify-center items-end gap-1.5 h-36">
                    {/* Hire Bar */}
                    <div 
                      className="w-5 bg-[#facc15] rounded-none hover:bg-yellow-500 transition-all duration-300 relative"
                      style={{ height: `${hireHeight}%` }}
                    >
                      <div className="opacity-0 group-hover:opacity-100 absolute -top-8 left-1/2 -translate-x-1/2 bg-black border border-[#222] text-[#facc15] text-[9px] py-0.5 px-1.5 rounded-none transition-opacity pointer-events-none z-10 font-mono font-bold">
                        +{t.hires}
                      </div>
                    </div>
                    {/* Exit Bar */}
                    <div 
                      className="w-5 bg-red-950 border border-red-800 rounded-none hover:bg-red-900 transition-all duration-300 relative"
                      style={{ height: `${exitHeight}%` }}
                    >
                      <div className="opacity-0 group-hover:opacity-100 absolute -top-8 left-1/2 -translate-x-1/2 bg-black border border-[#222] text-red-500 text-[9px] py-0.5 px-1.5 rounded-none transition-opacity pointer-events-none z-10 font-mono font-bold">
                        -{t.exits}
                      </div>
                    </div>
                  </div>
                  <span className="text-[10px] font-black uppercase text-slate-500 mt-2 tracking-wider">{t.month}</span>
                </div>
              );
            })}
          </div>

          <div className="flex items-center justify-between text-[10px] uppercase font-bold text-slate-500 mt-4 pt-1">
            <span className="flex items-center gap-1 text-[#facc15]">
              <TrendingUp className="w-3.5 h-3.5" />
              Retensi Pegawai: 94.2%
            </span>
            <span className="font-mono">Rasio Turnover: ~3.1%</span>
          </div>
        </div>

        {/* Right: Lowongan & Priority Actions */}
        <div className="bg-[#0a0a0a] border border-[#222] rounded-none p-5 flex flex-col justify-between">
          <div>
            <h3 className="text-xs font-black uppercase text-white tracking-wider mb-4 flex items-center gap-1.5">
              <Briefcase className="w-4 h-4 text-[#facc15]" />
              Kebutuhan SDM / Lowongan
            </h3>
            <div className="space-y-3">
              <div className="border border-[#222] bg-[#050505] p-3 hover:border-[#facc15] transition-colors">
                <div className="flex justify-between items-start mb-1">
                  <h4 className="text-xs font-black text-white uppercase tracking-tighter">Full-stack Developer (ERP)</h4>
                  <span className="text-[8px] font-mono font-bold px-1.5 py-0.5 bg-red-950 text-red-500 border border-red-900">URGENT</span>
                </div>
                <p className="text-[9px] text-slate-500 uppercase tracking-widest font-bold">Divisi: BI / IT</p>
                <div className="w-full bg-[#111] h-2 mt-2 overflow-hidden border border-[#222]">
                  <div className="bg-[#facc15] h-full" style={{ width: '80%' }}></div>
                </div>
                <div className="flex justify-between text-[9px] text-slate-500 mt-1 font-mono uppercase">
                  <span>Progres: 2 dari 3 Tahap</span>
                  <span>Target: 20-Jul</span>
                </div>
              </div>

              <div className="border border-[#222] bg-[#050505] p-3 hover:border-[#facc15] transition-colors">
                <div className="flex justify-between items-start mb-1">
                  <h4 className="text-xs font-black text-white uppercase tracking-tighter">Supervisor Fleet Operations</h4>
                  <span className="text-[8px] font-mono font-bold px-1.5 py-0.5 bg-amber-950 text-amber-500 border border-amber-900">INTERVIEW</span>
                </div>
                <p className="text-[9px] text-slate-500 uppercase tracking-widest font-bold">Divisi: Fleet Management</p>
                <div className="w-full bg-[#111] h-2 mt-2 overflow-hidden border border-[#222]">
                  <div className="bg-[#facc15] h-full" style={{ width: '45%' }}></div>
                </div>
                <div className="flex justify-between text-[9px] text-slate-500 mt-1 font-mono uppercase">
                  <span>Progres: Screening Awal</span>
                  <span>Target: 30-Jul</span>
                </div>
              </div>

              <div className="border border-[#222] bg-[#050505] p-3 hover:border-[#facc15] transition-colors">
                <div className="flex justify-between items-start mb-1">
                  <h4 className="text-xs font-black text-white uppercase tracking-tighter">HR Compensation Specialist</h4>
                  <span className="text-[8px] font-mono font-bold px-1.5 py-0.5 bg-slate-900 text-slate-400 border border-[#333]">SOURCING</span>
                </div>
                <p className="text-[9px] text-slate-500 uppercase tracking-widest font-bold">Divisi: Compensation & Payroll</p>
                <div className="w-full bg-[#111] h-2 mt-2 overflow-hidden border border-[#222]">
                  <div className="bg-slate-700 h-full" style={{ width: '15%' }}></div>
                </div>
                <div className="flex justify-between text-[9px] text-slate-500 mt-1 font-mono uppercase">
                  <span>Progres: Sourcing</span>
                  <span>Target: 15-Agu</span>
                </div>
              </div>
            </div>
          </div>

          <div className="border-t border-[#222] pt-3 mt-4 text-center font-mono text-[9px] uppercase tracking-wider text-slate-500">
            Total Anggaran Rekrutmen Terpakai: 24%
          </div>
        </div>
      </div>

      {/* SECTION NOTIFIKASI / ALERT MASA BERLAKU SK & SERTIFIKASI (< 30 HARI) */}
      <div className="bg-[#0f172a] border-2 border-rose-500/50 rounded-xl p-5 shadow-2xl space-y-4 font-sans relative overflow-hidden">
        {/* Glowing accent backdrop */}
        <div className="absolute -top-10 -right-10 w-48 h-48 bg-rose-500/10 pointer-events-none rounded-full blur-3xl"></div>

        {/* Header Title & Summary Pills */}
        <div className="flex flex-col md:flex-row md:items-center justify-between gap-3 border-b border-[#1e3a8a]/70 pb-4">
          <div className="flex items-center gap-3">
            <div className="p-2.5 bg-rose-500/15 border border-rose-500/40 text-rose-400 rounded-xl shrink-0 shadow-md">
              <ShieldAlert className="w-6 h-6 text-rose-400 animate-pulse" />
            </div>
            <div>
              <div className="flex items-center gap-2 flex-wrap">
                <span className="text-[10px] font-black uppercase tracking-wider bg-rose-500 text-white px-2.5 py-0.5 rounded font-mono shadow-sm">
                  ALERT KEPEGAWAIAN CRITICAL
                </span>
                <span className="text-[10px] font-bold uppercase tracking-wider bg-amber-500/20 text-amber-300 border border-amber-500/30 px-2 py-0.5 rounded font-mono">
                  Masa Berlaku ≤ 30 Hari
                </span>
              </div>
              <h3 className="text-lg sm:text-xl font-black text-white uppercase tracking-tight mt-1 flex items-center gap-2">
                Peringatan Masa Berlaku SK & Sertifikasi Pegawai
              </h3>
              <p className="text-xs text-slate-300 mt-0.5 font-mono">
                Monitoring terpusat pegawai yang memerlukan perpanjangan Surat Keputusan (SK) atau Re-Sertifikasi Kompetensi.
              </p>
            </div>
          </div>

          {/* Metric Badge Summary */}
          <div className="flex items-center gap-2 shrink-0 font-mono">
            <div className="bg-[#080d1a] border border-[#1e3a8a] px-3 py-2 rounded-lg text-center">
              <span className="text-[9px] text-slate-400 uppercase block">Total Alert</span>
              <span className="text-lg font-black text-white">{expiringDocAlerts.length}</span>
            </div>
            <div className="bg-[#080d1a] border border-amber-500/40 px-3 py-2 rounded-lg text-center">
              <span className="text-[9px] text-amber-400 uppercase block">Proses SK</span>
              <span className="text-lg font-black text-amber-300">{skCount}</span>
            </div>
            <div className="bg-[#080d1a] border border-emerald-500/40 px-3 py-2 rounded-lg text-center">
              <span className="text-[9px] text-emerald-400 uppercase block">Sertifikasi</span>
              <span className="text-lg font-black text-emerald-300">{certCount}</span>
            </div>
            <div className="bg-[#080d1a] border border-rose-500/50 px-3 py-2 rounded-lg text-center">
              <span className="text-[9px] text-rose-400 uppercase block">Urgent (≤10 H)</span>
              <span className="text-lg font-black text-rose-400">{urgentCount}</span>
            </div>
          </div>
        </div>

        {/* Filter Tabs & Search Filter Bar */}
        <div className="flex flex-col sm:flex-row items-center justify-between gap-3 bg-[#080d1a] p-2.5 rounded-lg border border-[#1e3a8a]/60">
          {/* Filter Buttons */}
          <div className="flex items-center gap-1.5 w-full sm:w-auto overflow-x-auto no-scrollbar font-mono text-xs">
            <button
              type="button"
              onClick={() => setDocAlertFilter("all")}
              className={`px-3 py-1.5 rounded-md font-bold uppercase transition-all whitespace-nowrap cursor-pointer ${
                docAlertFilter === "all"
                  ? "bg-rose-500 text-white font-black shadow-md"
                  : "bg-slate-800/80 text-slate-300 hover:bg-slate-700"
              }`}
            >
              Semua ({expiringDocAlerts.length})
            </button>
            <button
              type="button"
              onClick={() => setDocAlertFilter("SK")}
              className={`px-3 py-1.5 rounded-md font-bold uppercase transition-all whitespace-nowrap cursor-pointer ${
                docAlertFilter === "SK"
                  ? "bg-amber-500 text-slate-950 font-black shadow-md"
                  : "bg-slate-800/80 text-slate-300 hover:bg-slate-700"
              }`}
            >
              📄 SK ({skCount})
            </button>
            <button
              type="button"
              onClick={() => setDocAlertFilter("Sertifikasi")}
              className={`px-3 py-1.5 rounded-md font-bold uppercase transition-all whitespace-nowrap cursor-pointer ${
                docAlertFilter === "Sertifikasi"
                  ? "bg-emerald-500 text-slate-950 font-black shadow-md"
                  : "bg-slate-800/80 text-slate-300 hover:bg-slate-700"
              }`}
            >
              📜 Sertifikasi ({certCount})
            </button>
            <button
              type="button"
              onClick={() => setDocAlertFilter("urgent")}
              className={`px-3 py-1.5 rounded-md font-bold uppercase transition-all whitespace-nowrap cursor-pointer ${
                docAlertFilter === "urgent"
                  ? "bg-rose-600 text-white font-black shadow-md"
                  : "bg-slate-800/80 text-rose-300 hover:bg-slate-700"
              }`}
            >
              🚨 Urgent ≤10 Hari ({urgentCount})
            </button>
          </div>

          {/* Search Box */}
          <div className="relative w-full sm:w-64">
            <Search className="w-4 h-4 text-slate-400 absolute left-3 top-1/2 -translate-y-1/2" />
            <input
              type="text"
              value={docAlertSearch}
              onChange={(e) => setDocAlertSearch(e.target.value)}
              placeholder="Cari nama pegawai, NIP, SK..."
              className="w-full pl-9 pr-3 py-1.5 bg-[#0f172a] border border-[#1e3a8a] text-xs font-mono text-white placeholder-slate-400 rounded-md focus:outline-none focus:border-rose-400"
            />
            {docAlertSearch && (
              <button
                type="button"
                onClick={() => setDocAlertSearch("")}
                className="absolute right-2.5 top-1/2 -translate-y-1/2 text-slate-400 hover:text-white text-xs font-bold"
              >
                ×
              </button>
            )}
          </div>
        </div>

        {/* Alert List Grid */}
        <div className="grid grid-cols-1 md:grid-cols-2 gap-3 max-h-96 overflow-y-auto pr-1">
          {filteredDocAlerts.length === 0 ? (
            <div className="col-span-full bg-[#080d1a] border border-[#1e3a8a]/60 p-8 rounded-lg text-center space-y-2">
              <CheckCircle2 className="w-10 h-10 text-emerald-400 mx-auto opacity-80" />
              <h4 className="text-sm font-bold text-white uppercase">Tidak ada dokumen yang kadaluarsa</h4>
              <p className="text-xs text-slate-400 font-mono">
                Seluruh dokumen SK dan sertifikasi pegawai dalam batas aman (masa berlaku &gt; 30 hari).
              </p>
            </div>
          ) : (
            filteredDocAlerts.map((alert) => {
              const isUrgent = alert.daysRemaining <= 10;
              const isExpired = alert.daysRemaining <= 0;

              return (
                <div
                  key={alert.id}
                  className={`p-4 rounded-xl border transition-all flex flex-col justify-between space-y-3 relative overflow-hidden ${
                    isExpired
                      ? "bg-rose-950/20 border-rose-500/80 shadow-lg shadow-rose-900/20"
                      : isUrgent
                      ? "bg-amber-950/20 border-amber-500/70 shadow-md shadow-amber-900/20"
                      : "bg-[#080d1a] border-[#1e3a8a] hover:border-sky-500/60"
                  }`}
                >
                  {/* Top Employee Info & Document Type Badge */}
                  <div className="flex items-start justify-between gap-2">
                    <div className="flex items-center gap-3">
                      <div className={`w-10 h-10 rounded-lg font-black text-sm flex items-center justify-center shrink-0 shadow-sm ${
                        alert.docType === 'SK' 
                          ? "bg-amber-500/20 text-amber-300 border border-amber-500/40" 
                          : "bg-emerald-500/20 text-emerald-300 border border-emerald-500/40"
                      }`}>
                        {alert.docType === 'SK' ? 'SK' : 'CERT'}
                      </div>
                      <div>
                        <div className="flex items-center gap-2">
                          <span className="text-[9px] font-bold font-mono text-slate-400">
                            NIP: {alert.employeeNip}
                          </span>
                          <span className={`text-[9px] font-extrabold uppercase px-1.5 py-0.5 rounded font-mono border ${
                            alert.docType === 'SK'
                              ? "bg-amber-400/10 text-amber-300 border-amber-400/30"
                              : "bg-emerald-400/10 text-emerald-300 border-emerald-400/30"
                          }`}>
                            {alert.docType}
                          </span>
                        </div>
                        <h4 className="text-sm font-bold text-white uppercase tracking-tight line-clamp-1 mt-0.5">
                          {alert.employeeName}
                        </h4>
                        <p className="text-[11px] text-slate-300 font-mono">
                          {alert.employeePosition} • {alert.employeeDivision}
                        </p>
                      </div>
                    </div>

                    {/* Countdown Pill Badge */}
                    <div className="shrink-0 text-right font-mono">
                      {isExpired ? (
                        <span className="inline-flex items-center gap-1 text-[10px] font-black uppercase px-2.5 py-1 bg-rose-600 text-white rounded-md border border-rose-400 animate-pulse shadow-md">
                          <AlertTriangle className="w-3 h-3" />
                          KADALUARSA
                        </span>
                      ) : isUrgent ? (
                        <span className="inline-flex items-center gap-1 text-[10px] font-black uppercase px-2.5 py-1 bg-amber-500 text-slate-950 rounded-md shadow-md">
                          <Clock className="w-3 h-3" />
                          {alert.daysRemaining} HARI LAGI
                        </span>
                      ) : (
                        <span className="inline-flex items-center gap-1 text-[10px] font-bold uppercase px-2.5 py-1 bg-sky-500/20 text-sky-300 border border-sky-500/40 rounded-md">
                          <CalendarClock className="w-3 h-3" />
                          {alert.daysRemaining} HARI LAGI
                        </span>
                      )}
                    </div>
                  </div>

                  {/* Document Details Box */}
                  <div className="bg-[#0f172a] border border-[#1e3a8a]/60 p-2.5 rounded-lg text-xs font-mono space-y-1">
                    <div className="flex items-center justify-between text-slate-200 font-bold">
                      <span className="truncate pr-2">{alert.docTitle}</span>
                    </div>
                    <div className="flex items-center justify-between text-[11px] text-slate-400 pt-0.5 border-t border-[#1e3a8a]/40">
                      <span>Masa Berlaku s/d: <strong className="text-rose-300">{alert.expiryDate}</strong></span>
                      {alert.providerOrType && (
                        <span className="text-slate-400 truncate max-w-[140px]">Penerbit: {alert.providerOrType}</span>
                      )}
                    </div>
                  </div>

                  {/* Action Footer Button */}
                  <div className="flex items-center justify-between pt-1 border-t border-[#1e3a8a]/40">
                    <span className="text-[10px] text-slate-400 font-mono flex items-center gap-1">
                      <Clock className="w-3 h-3 text-sky-400" />
                      Target Perpanjangan: {alert.expiryDate}
                    </span>
                    <button
                      type="button"
                      onClick={() => onSelectEmployee(alert.employeeId)}
                      className={`px-3 py-1.5 text-xs font-bold uppercase tracking-wider rounded-lg transition-all flex items-center gap-1.5 shadow-md cursor-pointer ${
                        isUrgent || isExpired
                          ? "bg-gradient-to-r from-rose-600 to-amber-600 hover:from-rose-500 hover:to-amber-500 text-white font-extrabold"
                          : "bg-sky-600 hover:bg-sky-500 text-white font-bold"
                      }`}
                    >
                      <span>Proses Perpanjangan</span>
                      <ArrowRight className="w-3.5 h-3.5" />
                    </button>
                  </div>
                </div>
              );
            })
          )}
        </div>
      </div>

      {/* Critial Warnings & Dynamic Events bar */}
      <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
        {/* Left Actionable Alerts */}
        <div className="bg-red-950/10 border border-red-900/30 rounded-none p-5">
          <h3 className="text-xs font-black text-red-500 uppercase tracking-wider mb-3.5 flex items-center gap-1.5">
            <AlertTriangle className="w-4 h-4" />
            Alert Kepegawaian Penting
          </h3>
          <div className="space-y-2 max-h-40 overflow-y-auto pr-1">
            {stats.contractExpiring.length > 0 ? (
              stats.contractExpiring.map(e => (
                <div key={e.id} className="flex justify-between items-center text-xs p-3 rounded-none bg-[#0a0a0a] border border-[#222]">
                  <div className="flex flex-col">
                    <span className="font-bold text-white uppercase tracking-tighter">{e.name}</span>
                    <span className="text-[10px] text-slate-500 font-mono mt-0.5">{e.position} — TMT: {e.tmtKerja}</span>
                  </div>
                  <button 
                    onClick={() => onSelectEmployee(e.id)}
                    className="text-[9px] font-black uppercase tracking-widest text-[#facc15] hover:text-white bg-[#050505] border border-[#222] hover:border-[#facc15] px-3 py-1.5 transition-colors"
                  >
                    Proses Kontrak
                  </button>
                </div>
              ))
            ) : (
              <p className="text-xs text-slate-500 italic">Tidak ada kontrak pegawai yang akan habis dalam waktu dekat.</p>
            )}

            {stats.retiringThisYear.map(e => (
              <div key={e.id} className="flex justify-between items-center text-xs p-3 rounded-none bg-[#0a0a0a] border border-[#222]">
                <div className="flex flex-col">
                  <span className="font-bold text-white uppercase tracking-tighter">{e.name} (Pensiun)</span>
                  <span className="text-[10px] text-slate-500 mt-0.5">Umur akan mencapai batas pensiun tahun ini</span>
                </div>
                <button 
                  onClick={() => onSelectEmployee(e.id)}
                  className="text-[9px] font-black uppercase tracking-widest text-slate-400 hover:text-white bg-[#050505] border border-[#222] px-3 py-1.5 transition-colors"
                >
                  Lihat Profil
                </button>
              </div>
            ))}
          </div>
        </div>

        {/* Right Pending Approval & Workflows shortcut */}
        <div className="bg-indigo-950/10 border border-[#222] rounded-none p-5 flex flex-col justify-between">
          <div>
            <h3 className="text-xs font-black text-[#facc15] uppercase tracking-wider mb-2 flex items-center gap-1.5">
              <GraduationCap className="w-4 h-4" />
              Pelatihan Bulan Ini
            </h3>
            {stats.trainingThisMonth > 0 ? (
              <p className="text-xs text-slate-400 leading-relaxed text-justify">
                Ada <span className="text-[#facc15] font-bold font-mono">{stats.trainingThisMonth}</span> pegawai yang memiliki agenda pelatihan aktif pada bulan Juli 2026 ini. Program: Advanced ERP & Technical Operations.
              </p>
            ) : (
              <p className="text-xs text-slate-500 italic">Tidak ada pelatihan yang dijadwalkan bulan ini.</p>
            )}
          </div>

          <div className="bg-[#050505] border border-[#222] p-3.5 flex items-center justify-between mt-4">
            <div className="flex items-center gap-2">
              <span className="flex h-2.5 w-2.5 bg-[#facc15] relative">
                <span className="animate-ping absolute inline-flex h-full w-full bg-[#facc15] opacity-75"></span>
              </span>
              <span className="text-[10px] font-black uppercase tracking-wider text-slate-400">Menunggu Approval Direksi</span>
            </div>
            <span className="text-xs font-mono font-black px-2.5 py-0.5 bg-[#facc15] text-black">
              {pendingApprovalsCount} DOKUMEN
            </span>
          </div>
        </div>
      </div>
    </div>
  );
}
