import AuthenticatedLayout from '@/Layouts/AuthenticatedLayout';
import { Head, Link, usePage } from '@inertiajs/react';
import { useEffect, useMemo, useState } from 'react';
import {
    ResponsiveContainer,
    BarChart,
    Bar,
    AreaChart,
    Area,
    PieChart,
    Pie,
    Cell,
    XAxis,
    YAxis,
    CartesianGrid,
    Tooltip,
    Legend,
} from 'recharts';

// Respeta las mismas propiedades que envia el controlador actual de Laravel.
// No agrega datos inventados ni requiere nuevas dependencias.
const COLORS = {
    navy: '#2563EB',
    navyLight: '#0284C7',
    teal: '#0D9488',
    cyan: '#06B6D4',
    gold: '#F59E0B',
    violet: '#7C3AED',
    rose: '#F43F5E',
    slate: '#6366F1',
};
// Contrastes mas notorios para distinguir cada serie.
const PIE_COLORS = [COLORS.teal, COLORS.gold, COLORS.violet, COLORS.rose, COLORS.cyan, COLORS.navy];
const PIE_LEGEND_BACKGROUNDS = [
    'bg-teal-50 border-teal-100', 'bg-amber-50 border-amber-100',
    'bg-violet-50 border-violet-100', 'bg-rose-50 border-rose-100',
    'bg-cyan-50 border-cyan-100', 'bg-blue-50 border-blue-100',
];

const numberFormatter = new Intl.NumberFormat('es-PE', { maximumFractionDigits: 0 });
const decimalFormatter = new Intl.NumberFormat('es-PE', { maximumFractionDigits: 1 });

function numberOrZero(value) {
    const parsed = Number(value);
    return Number.isFinite(parsed) ? parsed : 0;
}

function formatCount(value) {
    if (value === null || value === undefined || value === '') return '—';
    const parsed = Number(value);
    return Number.isFinite(parsed) ? numberFormatter.format(parsed) : '—';
}

function safeArray(value) {
    return Array.isArray(value) ? value.filter((entry) => entry && typeof entry === 'object') : [];
}

function textSearch(value) {
    return String(value ?? '')
        .normalize('NFD')
        .replace(/[\u0300-\u036f]/g, '')
        .toLowerCase()
        .trim();
}

function shortLabel(label, maxLength = 23) {
    const value = String(label ?? 'Sin nombre');
    return value.length > maxLength ? `${value.slice(0, maxLength - 1)}…` : value;
}

function routeExists(routeName) {
    try {
        return typeof route === 'function' && route().has(routeName);
    } catch {
        return false;
    }
}

function Icon({ name, className = 'h-5 w-5' }) {
    const common = {
        className,
        viewBox: '0 0 24 24',
        fill: 'none',
        stroke: 'currentColor',
        strokeWidth: 1.8,
        strokeLinecap: 'round',
        strokeLinejoin: 'round',
        'aria-hidden': true,
    };
    const paths = {
        users: <><path d="M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/><path d="M22 21v-2a4 4 0 0 0-3-3.87M16 3.13a4 4 0 0 1 0 7.75"/></>,
        academic: <><path d="m3 10 9-5 9 5-9 5-9-5Z"/><path d="M7 12.5V17c3 2 7 2 10 0v-4.5M21 10v6"/></>,
        calendar: <><rect x="3" y="5" width="18" height="16" rx="2"/><path d="M16 3v4M8 3v4M3 10h18"/></>,
        arrow: <><path d="M5 12h14m-6-6 6 6-6 6"/></>,
        file: <><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8Z"/><path d="M14 2v6h6M8 13h8M8 17h6"/></>,
        chart: <><path d="M3 3v18h18M7 16l4-5 4 3 5-7"/></>,
        refresh: <><path d="M20 11a8 8 0 1 0-2.34 5.66M20 4v7h-7"/></>,
        teacher: <><circle cx="9" cy="7" r="4"/><path d="M3 21v-2a6 6 0 0 1 12 0v2M16 8l2 2 4-4"/></>,
        award: <><circle cx="12" cy="8" r="6"/><path d="M15.5 12.9 17 22l-5-3-5 3 1.5-9.1"/></>,
        check: <><path d="M22 11.1V12a10 10 0 1 1-5.9-9.1M22 4 12 14 9 11"/></>,
        search: <><circle cx="11" cy="11" r="7"/><path d="m20 20-3.5-3.5"/></>,
        star: <><path d="m12 3 2.8 5.9 6.5.9-4.7 4.6 1.1 6.5L12 17.9 6.3 21l1.1-6.5-4.7-4.6 6.5-.9Z"/></>,
        book: <><path d="M2 3h7a3 3 0 0 1 3 3v15a3 3 0 0 0-3-3H2V3Zm20 0h-7a3 3 0 0 0-3 3v15a3 3 0 0 1 3-3h7V3Z"/></>,
        clock: <><circle cx="12" cy="12" r="9"/><path d="M12 7v5l4 2"/></>,
        layers: <><path d="m12 2 9 5-9 5-9-5 9-5Zm-9 9 9 5 9-5M3 15l9 5 9-5"/></>,
        settings: <><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.6 1.6 0 0 0 .3 1.8l-2 2a1.6 1.6 0 0 0-1.8-.3 1.6 1.6 0 0 0-1 1.5v.5h-2.8V20a1.6 1.6 0 0 0-1-1.5 1.6 1.6 0 0 0-1.8.3l-2-2a1.6 1.6 0 0 0 .3-1.8 1.6 1.6 0 0 0-1.5-1H5.6v-2.8h.5a1.6 1.6 0 0 0 1.5-1 1.6 1.6 0 0 0-.3-1.8l2-2a1.6 1.6 0 0 0 1.8.3 1.6 1.6 0 0 0 1-1.5v-.5h2.8v.5a1.6 1.6 0 0 0 1 1.5 1.6 1.6 0 0 0 1.8-.3l2 2a1.6 1.6 0 0 0-.3 1.8 1.6 1.6 0 0 0 1.5 1h.5V14h-.5a1.6 1.6 0 0 0-1.5 1Z" transform="translate(-1.5 -1.5) scale(1.12)"/></>,
        bolt: <><path d="m13 2-9 12h7l-1 8 10-12h-7l0-8Z"/></>,
        trend: <><path d="m3 17 6-6 4 4 8-8M15 7h6v6"/></>,
        dots: <><circle cx="5" cy="12" r="1"/><circle cx="12" cy="12" r="1"/><circle cx="19" cy="12" r="1"/></>,
        filter: <><path d="M4 6h16M7 12h10M10 18h4"/></>,
        target: <><circle cx="12" cy="12" r="9"/><circle cx="12" cy="12" r="5"/><circle cx="12" cy="12" r="1"/></>,
        shield: <><path d="M12 3 5 6v5c0 4.6 2.8 8.3 7 10 4.2-1.7 7-5.4 7-10V6l-7-3Z"/><path d="m9 12 2 2 4-4"/></>,
    };
    return <svg {...common}>{paths[name] || paths.file}</svg>;
}

const QUICK_ACTIONS = [
    { label: 'Usuarios', detail: 'Cuentas y permisos', icon: 'users', routeName: 'usuarios.index', tone: 'sky' },
    { label: 'Docentes', detail: 'Perfiles del personal', icon: 'teacher', routeName: 'docentes.index', tone: 'violet' },
    { label: 'Admisión', detail: 'Procesos y postulantes', icon: 'academic', routeName: 'admisiones.index', tone: 'teal' },
    { label: 'Matrículas', detail: 'Registros del periodo', icon: 'calendar', routeName: 'matriculas.index', tone: 'orange' },
    { label: 'Planes de estudio', detail: 'Estructura académica', icon: 'layers', routeName: 'planes-estudio.index', tone: 'indigo' },
    { label: 'Unidades didácticas', detail: 'Cursos y contenidos', icon: 'book', routeName: 'cursos.index', tone: 'rose' },
    { label: 'Horarios', detail: 'Programación académica', icon: 'clock', routeName: 'horarios.index', tone: 'cyan' },
    { label: 'Convalidaciones', detail: 'Control de expedientes', icon: 'check', routeName: 'convalidaciones.index', tone: 'emerald' },
    { label: 'Titulación', detail: 'Expedientes y grados', icon: 'award', routeName: 'titulaciones.index', tone: 'amber' },
    { label: 'Indicadores KPI', detail: 'Seguimiento y reportes', icon: 'chart', routeName: 'reportes.kpi.index', tone: 'sky' },
];

// Paleta especifica por grupo de indicadores, accesos y graficos.
// Los nombres de clase son literales para que Tailwind los encuentre al compilar.
const TONES = {
    sky: {
        ink: 'text-sky-900', line: 'bg-sky-500',
        metric: 'border-sky-200 bg-gradient-to-br from-[#F0FAFF] via-[#DDF3FF] to-[#BFEBFF]',
        tile: 'border-sky-200 bg-gradient-to-br from-[#EAF7FF] via-[#D9EFFF] to-[#BFE6FF]',
        icon: 'bg-gradient-to-br from-[#0EA5E9] to-[#2563EB]',
        hover: 'hover:border-sky-400 hover:shadow-sky-200/60',
        chartBorder: 'border-sky-200', chartHeader: 'bg-gradient-to-r from-[#D9F0FF] to-[#E8F7FF]',
        chartBody: 'bg-gradient-to-br from-[#F4FBFF] via-white to-[#EAF6FF]',
    },
    teal: {
        ink: 'text-teal-900', line: 'bg-teal-500',
        metric: 'border-teal-200 bg-gradient-to-br from-[#E9FFFC] via-[#CEFBF4] to-[#ABF2E7]',
        tile: 'border-teal-200 bg-gradient-to-br from-[#E8FFFA] via-[#CDF9EF] to-[#B1F1E4]',
        icon: 'bg-gradient-to-br from-[#0D9488] to-[#06B6D4]',
        hover: 'hover:border-teal-400 hover:shadow-teal-200/60',
        chartBorder: 'border-teal-200', chartHeader: 'bg-gradient-to-r from-[#C7F9EE] to-[#E1FFF8]',
        chartBody: 'bg-gradient-to-br from-[#F0FFFB] via-white to-[#E2FAF6]',
    },
    violet: {
        ink: 'text-violet-900', line: 'bg-violet-500',
        metric: 'border-violet-200 bg-gradient-to-br from-[#F7F3FF] via-[#EDE2FF] to-[#DCD0FF]',
        tile: 'border-violet-200 bg-gradient-to-br from-[#F4EDFF] via-[#EADFFF] to-[#DCCBFF]',
        icon: 'bg-gradient-to-br from-[#8B5CF6] to-[#6D28D9]',
        hover: 'hover:border-violet-400 hover:shadow-violet-200/60',
        chartBorder: 'border-violet-200', chartHeader: 'bg-gradient-to-r from-[#E5D8FF] to-[#F2EBFF]',
        chartBody: 'bg-gradient-to-br from-[#FBF9FF] via-white to-[#F3EDFF]',
    },
    orange: {
        ink: 'text-orange-900', line: 'bg-orange-500',
        metric: 'border-orange-200 bg-gradient-to-br from-[#FFF8EF] via-[#FFEBCD] to-[#FFDBB5]',
        tile: 'border-orange-200 bg-gradient-to-br from-[#FFF5E9] via-[#FFE8CB] to-[#FFD8AF]',
        icon: 'bg-gradient-to-br from-[#F97316] to-[#EA580C]',
        hover: 'hover:border-orange-400 hover:shadow-orange-200/60',
        chartBorder: 'border-orange-200', chartHeader: 'bg-gradient-to-r from-[#FFE4C2] to-[#FFF2E1]',
        chartBody: 'bg-gradient-to-br from-[#FFF8F1] via-white to-[#FFF1DF]',
    },
    rose: {
        ink: 'text-rose-900', line: 'bg-rose-500',
        metric: 'border-rose-200 bg-gradient-to-br from-[#FFF2F6] via-[#FFE0E8] to-[#FFC9D9]',
        tile: 'border-rose-200 bg-gradient-to-br from-[#FFF0F5] via-[#FFDEE8] to-[#FFCBDC]',
        icon: 'bg-gradient-to-br from-[#FB7185] to-[#E11D48]',
        hover: 'hover:border-rose-400 hover:shadow-rose-200/60',
        chartBorder: 'border-rose-200', chartHeader: 'bg-gradient-to-r from-[#FFDAE6] to-[#FFF0F5]',
        chartBody: 'bg-gradient-to-br from-[#FFF7FA] via-white to-[#FFEFF4]',
    },
    emerald: {
        ink: 'text-emerald-900', line: 'bg-emerald-500',
        metric: 'border-emerald-200 bg-gradient-to-br from-[#EAFFF3] via-[#CBF9DE] to-[#A8EDC8]',
        tile: 'border-emerald-200 bg-gradient-to-br from-[#E8FFF2] via-[#CEF9E0] to-[#B3F0D0]',
        icon: 'bg-gradient-to-br from-[#10B981] to-[#059669]',
        hover: 'hover:border-emerald-400 hover:shadow-emerald-200/60',
        chartBorder: 'border-emerald-200', chartHeader: 'bg-gradient-to-r from-[#CBF7DF] to-[#E9FFF3]',
        chartBody: 'bg-gradient-to-br from-[#F2FFF7] via-white to-[#E8FFF1]',
    },
    indigo: {
        ink: 'text-indigo-900', line: 'bg-indigo-500',
        metric: 'border-indigo-200 bg-gradient-to-br from-[#F0F3FF] via-[#E1E7FF] to-[#C9D4FF]',
        tile: 'border-indigo-200 bg-gradient-to-br from-[#EDF2FF] via-[#DFE6FF] to-[#C9D6FF]',
        icon: 'bg-gradient-to-br from-[#6366F1] to-[#4338CA]',
        hover: 'hover:border-indigo-400 hover:shadow-indigo-200/60',
        chartBorder: 'border-indigo-200', chartHeader: 'bg-gradient-to-r from-[#DCE5FF] to-[#F0F3FF]',
        chartBody: 'bg-gradient-to-br from-[#F6F7FF] via-white to-[#EDF1FF]',
    },
    cyan: {
        ink: 'text-cyan-900', line: 'bg-cyan-500',
        metric: 'border-cyan-200 bg-gradient-to-br from-[#E9FCFF] via-[#CFF5FB] to-[#ADEBF7]',
        tile: 'border-cyan-200 bg-gradient-to-br from-[#E5FBFF] via-[#CAF4FC] to-[#B2EAF7]',
        icon: 'bg-gradient-to-br from-[#06B6D4] to-[#0284C7]',
        hover: 'hover:border-cyan-400 hover:shadow-cyan-200/60',
        chartBorder: 'border-cyan-200', chartHeader: 'bg-gradient-to-r from-[#C9F4FC] to-[#E8FCFF]',
        chartBody: 'bg-gradient-to-br from-[#F2FDFF] via-white to-[#E8F9FC]',
    },
    amber: {
        ink: 'text-amber-900', line: 'bg-amber-500',
        metric: 'border-amber-200 bg-gradient-to-br from-[#FFFAEA] via-[#FFF0C9] to-[#FFE3A0]',
        tile: 'border-amber-200 bg-gradient-to-br from-[#FFF8E5] via-[#FFEDC1] to-[#FFDEA0]',
        icon: 'bg-gradient-to-br from-[#F59E0B] to-[#D97706]',
        hover: 'hover:border-amber-400 hover:shadow-amber-200/60',
        chartBorder: 'border-amber-200', chartHeader: 'bg-gradient-to-r from-[#FFE9AE] to-[#FFF6E3]',
        chartBody: 'bg-gradient-to-br from-[#FFFCF2] via-white to-[#FFF5DD]',
    },
};

function SectionHeader({ eyebrow, title, subtitle, children, icon = 'chart', tone = 'teal' }) {
    const color = TONES[tone] || TONES.teal;
    return (
        <div className="mb-4 flex flex-col justify-between gap-4 sm:flex-row sm:items-center">
            <div className="flex min-w-0 items-start gap-3.5">
                <span className={`flex h-12 w-12 shrink-0 items-center justify-center rounded-2xl text-white shadow-lg shadow-slate-200/50 ${color.icon}`}>
                    <Icon name={icon} className="h-6 w-6" />
                </span>
                <div>
                    {eyebrow && <p className={`text-[10px] font-black uppercase tracking-[0.17em] ${color.ink}`}>{eyebrow}</p>}
                    <h2 className="mt-0.5 text-lg font-black tracking-tight text-slate-900 sm:text-xl">{title}</h2>
                    {subtitle && <p className="mt-1 text-xs leading-relaxed text-slate-600 sm:text-sm">{subtitle}</p>}
                </div>
            </div>
            {children}
        </div>
    );
}

function MetricCard({ title, value, detail, icon, tone, ordinal }) {
    const color = TONES[tone] || TONES.sky;
    return (
        <article className={`group relative min-w-0 overflow-hidden rounded-[22px] border p-4 shadow-sm transition-all duration-200 hover:-translate-y-1 hover:shadow-xl sm:p-5 ${color.metric} ${color.hover}`}>
            <span className={`absolute inset-x-0 top-0 h-1.5 ${color.line}`} />
            <span className="pointer-events-none absolute -right-8 -top-12 h-32 w-32 rounded-full bg-white/40" />
            <div className="relative flex items-start justify-between gap-2">
                <span className={`flex h-12 w-12 items-center justify-center rounded-2xl text-white shadow-lg shadow-black/10 transition-transform duration-200 group-hover:scale-110 ${color.icon}`}>
                    <Icon name={icon} className="h-6 w-6" />
                </span>
                <span className={`rounded-full border border-white/70 bg-white/60 px-2 py-1 text-[10px] font-bold ${color.ink}`}>{ordinal}</span>
            </div>
            <p className={`relative mt-5 text-[29px] font-black leading-none tracking-tight sm:text-[32px] ${color.ink}`}>{formatCount(value)}</p>
            <h3 className="relative mt-3 text-[13px] font-extrabold text-slate-900">{title}</h3>
            <p className="relative mt-1 text-[11px] leading-snug text-slate-600">{detail}</p>
        </article>
    );
}

function ChartCard({ title, subtitle, icon, children, actions, className = '', tone = 'teal' }) {
    const color = TONES[tone] || TONES.teal;
    return (
        <article className={`min-w-0 overflow-hidden rounded-[25px] border shadow-md shadow-slate-200/50 ${color.chartBorder} ${className}`}>
            <div className={`h-1.5 ${color.line}`} />
            <div className={`flex flex-wrap items-center justify-between gap-3 border-b border-white/70 px-5 py-4 sm:px-6 sm:py-5 ${color.chartHeader}`}>
                <div className="flex min-w-0 items-start gap-3">
                    <span className={`flex h-11 w-11 shrink-0 items-center justify-center rounded-2xl text-white shadow-md shadow-black/10 ${color.icon}`}>
                        <Icon name={icon} className="h-5 w-5" />
                    </span>
                    <div>
                        <h3 className="text-sm font-extrabold tracking-tight text-slate-900 sm:text-[15px]">{title}</h3>
                        <p className="mt-1 text-xs text-slate-600">{subtitle}</p>
                    </div>
                </div>
                {actions}
            </div>
            <div className={`px-4 py-5 sm:px-6 sm:py-6 ${color.chartBody}`}>{children}</div>
        </article>
    );
}

function EmptyState({ message }) {
    return (
        <div className="flex min-h-[260px] flex-col items-center justify-center rounded-2xl border border-dashed border-teal-200 bg-gradient-to-br from-teal-50/70 via-sky-50/60 to-violet-50/70 px-5 text-center">
            <span className="flex h-12 w-12 items-center justify-center rounded-2xl bg-gradient-to-br from-teal-500 to-sky-500 text-white shadow-md"><Icon name="chart" className="h-6 w-6" /></span>
            <p className="mt-3 max-w-xs text-sm font-semibold text-slate-600">Sin datos para mostrar</p>
            <p className="mt-1 max-w-sm text-xs leading-relaxed text-slate-400">{message}</p>
        </div>
    );
}

function GraphicTooltip({ active, payload, label, suffix = '' }) {
    if (!active || !payload?.length) return null;
    return (
        <div className="min-w-[150px] max-w-[260px] rounded-2xl border border-teal-200 bg-white/95 p-3 shadow-xl shadow-teal-900/10 backdrop-blur">
            <p className="mb-2 break-words text-xs font-bold text-[#134E4A]">{label || payload[0]?.payload?.carrera || payload[0]?.payload?.curso || payload[0]?.payload?.docente}</p>
            <div className="space-y-1.5 border-t border-teal-100 pt-2">
                {payload.map((entry, index) => (
                    <div key={`${entry.dataKey}-${index}`} className="flex items-center justify-between gap-4 text-xs">
                        <span className="flex min-w-0 items-center gap-1.5 text-slate-500">
                            <i className="h-2 w-2 shrink-0 rounded-full" style={{ background: entry.color || entry.fill }} />
                            <span className="truncate">{entry.name}</span>
                        </span>
                        <b className="shrink-0 text-slate-800">{numberFormatter.format(numberOrZero(entry.value))}{suffix}</b>
                    </div>
                ))}
            </div>
        </div>
    );
}

function ShowMoreButton({ all, onClick, total, visible }) {
    if (total <= visible && !all) return null;
    return (
        <button type="button" onClick={onClick} className="rounded-xl border border-teal-200 bg-white/75 px-3 py-2 text-[11px] font-bold text-teal-800 shadow-sm transition hover:border-teal-400 hover:bg-white">
            {all ? 'Mostrar menos' : `Ver todos (${total})`}
        </button>
    );
}

export default function AdminDashboard() {
    const {
        auth,
        periodo = 'Sin periodo activo',
        lastUpdated,
        summary = {},
        dataAdmisionMatricula = [],
        dataEgresadosTitulados = [],
        dataRepitenciaCursos = [],
        dataConvalidaciones = [],
        dataCargaDocente = [],
    } = usePage().props;

    const user = auth?.user ?? {};
    const displayName = user.nombre_completo || user.username || user.name || 'Administrador';
    const [quickSearch, setQuickSearch] = useState('');
    const [favorites, setFavorites] = useState([]);
    const [showAllAdmission, setShowAllAdmission] = useState(false);
    const [showAllRepitencia, setShowAllRepitencia] = useState(false);
    const [showAllCarga, setShowAllCarga] = useState(false);
    const [onlyFavorites, setOnlyFavorites] = useState(false);

    useEffect(() => {
        try {
            const stored = JSON.parse(window.localStorage.getItem('admin_dashboard_favoritos_v1') || '[]');
            if (Array.isArray(stored)) setFavorites(stored.filter((item) => typeof item === 'string'));
        } catch {
            // El panel funciona aun si el navegador bloquea el almacenamiento.
        }
    }, []);

    const toggleFavorite = (routeName) => {
        setFavorites((current) => {
            const next = current.includes(routeName)
                ? current.filter((item) => item !== routeName)
                : [...current, routeName];
            try { window.localStorage.setItem('admin_dashboard_favoritos_v1', JSON.stringify(next)); } catch { /* Opcional */ }
            return next;
        });
    };

    const availableActions = QUICK_ACTIONS.filter((item) => routeExists(item.routeName));
    const filteredActions = availableActions
        .filter((item) => !onlyFavorites || favorites.includes(item.routeName))
        .filter((item) => textSearch(`${item.label} ${item.detail}`).includes(textSearch(quickSearch)))
        .sort((a, b) => Number(favorites.includes(b.routeName)) - Number(favorites.includes(a.routeName)));

    const admission = useMemo(() => safeArray(dataAdmisionMatricula).map((item) => ({
        ...item,
        carrera: String(item.carrera ?? 'Sin programa'),
        postulantes: numberOrZero(item.postulantes),
        ingresantes: numberOrZero(item.ingresantes),
        matriculados: numberOrZero(item.matriculados),
    })), [dataAdmisionMatricula]);

    const graduation = useMemo(() => safeArray(dataEgresadosTitulados).map((item) => ({
        ...item,
        periodo: String(item.periodo ?? 'Sin periodo'),
        expedientes: numberOrZero(item.expedientes),
        titulados: numberOrZero(item.titulados),
    })), [dataEgresadosTitulados]);

    const repetition = useMemo(() => safeArray(dataRepitenciaCursos).map((item) => ({
        ...item,
        curso: String(item.curso ?? 'Sin curso'),
        desaprobados: numberOrZero(item.desaprobados),
    })).sort((a, b) => b.desaprobados - a.desaprobados), [dataRepitenciaCursos]);

    const validation = useMemo(() => safeArray(dataConvalidaciones).map((item) => ({
        ...item,
        tipo: String(item.tipo ?? 'Sin estado'),
        total: numberOrZero(item.total),
    })), [dataConvalidaciones]);

    const teaching = useMemo(() => safeArray(dataCargaDocente).map((item) => ({
        ...item,
        docente: String(item.docente ?? 'Sin docente'),
        horas_lectivas: numberOrZero(item.horas_lectivas),
    })).sort((a, b) => b.horas_lectivas - a.horas_lectivas), [dataCargaDocente]);

    const admissionVisible = showAllAdmission ? admission : admission.slice(0, 8);
    const repetitionVisible = showAllRepitencia ? repetition : repetition.slice(0, 6);
    const teachingVisible = showAllCarga ? teaching : teaching.slice(0, 6);
    const totalPostulantes = admission.reduce((sum, item) => sum + item.postulantes, 0);
    const totalIngresantes = admission.reduce((sum, item) => sum + item.ingresantes, 0);
    const totalMatriculados = admission.reduce((sum, item) => sum + item.matriculados, 0);
    const validationTotal = validation.reduce((sum, item) => sum + item.total, 0);
    const conversion = totalPostulantes > 0 ? (totalMatriculados / totalPostulantes) * 100 : null;

    const metrics = [
        { title: 'Usuarios activos', value: summary?.usuarios_activos, detail: 'Cuentas habilitadas', icon: 'users', tone: 'sky' },
        { title: 'Postulantes', value: summary?.postulantes, detail: 'Registros de admisión', icon: 'academic', tone: 'violet' },
        { title: 'Matriculados', value: summary?.matriculados, detail: 'Periodo seleccionado', icon: 'calendar', tone: 'teal' },
        { title: 'Docentes activos', value: summary?.docentes, detail: 'Personal docente', icon: 'teacher', tone: 'indigo' },
        { title: 'Convalidados', value: summary?.convalidados, detail: 'Trámites aprobados', icon: 'check', tone: 'orange' },
        { title: 'Titulados', value: summary?.titulados, detail: 'Expedientes concluidos', icon: 'award', tone: 'rose' },
    ];

    return (
        <AuthenticatedLayout>
            <Head title="Panel administrativo" />
            <div className="mx-auto max-w-[1640px] space-y-7 rounded-[30px] bg-gradient-to-br from-[#E9FFF9] via-[#F1F6FF] to-[#FFF1F9] px-3 py-5 sm:space-y-8 sm:px-5 sm:py-6">
                {/* Bienvenida y periodo, en vez de repetir el encabezado del layout. */}
                <section className="relative overflow-hidden rounded-[28px] border border-white/25 bg-gradient-to-r from-[#0D9488] via-[#0891B2] to-[#4F46E5] p-6 text-white shadow-xl shadow-cyan-200/70 sm:p-8">
                    <div className="pointer-events-none absolute -right-10 -top-24 h-64 w-64 rounded-full bg-[#67E8F9]/35 blur-3xl" />
                    <div className="pointer-events-none absolute bottom-0 right-1/4 h-32 w-32 rounded-full bg-fuchsia-300/20 blur-2xl" />
                    <div className="pointer-events-none absolute right-[10%] top-[-70px] h-48 w-48 rounded-full border-[30px] border-white/10" />
                    <div className="relative flex flex-col justify-between gap-6 lg:flex-row lg:items-center">
                        <div className="min-w-0">
                            <span className="inline-flex items-center gap-2 rounded-full border border-white/30 bg-white/20 px-3 py-1 text-[10px] font-black uppercase tracking-[0.15em] text-white backdrop-blur-sm">
                                <Icon name="shield" className="h-3.5 w-3.5" /> Centro de gestión institucional
                            </span>
                            <h1 className="mt-4 text-2xl font-black tracking-tight sm:text-3xl lg:text-[34px]">
                                Panel administrativo
                            </h1>
                            <p className="mt-2 max-w-2xl text-sm leading-relaxed text-white/90">
                                Bienvenido, <span className="font-extrabold text-white">{displayName}</span>. Consulta indicadores, compara resultados y accede a las funciones principales del sistema.
                            </p>
                        </div>
                        <div className="flex shrink-0 flex-wrap gap-2 lg:justify-end">
                            <div className="rounded-2xl border border-white/25 bg-white/20 px-4 py-3 shadow-sm backdrop-blur-sm">
                                <p className="text-[10px] font-bold uppercase tracking-wider text-white/80">Periodo académico</p>
                                <p className="mt-1 flex items-center gap-2 text-sm font-extrabold"><Icon name="calendar" className="h-4 w-4" /> {periodo}</p>
                            </div>
                            <div className="rounded-2xl border border-white/25 bg-white/20 px-4 py-3 shadow-sm backdrop-blur-sm">
                                <p className="text-[10px] font-bold uppercase tracking-wider text-white/80">Última actualización</p>
                                <p className="mt-1 flex items-center gap-2 text-sm font-semibold"><Icon name="refresh" className="h-4 w-4" />{lastUpdated || 'No informada'}</p>
                            </div>
                        </div>
                    </div>
                </section>

                {/* Cifras reales recibidas desde Laravel. */}
                <section>
                    <SectionHeader eyebrow="Panorama general" title="Indicadores del sistema" subtitle="Resumen operativo enviado por el controlador de Laravel." icon="chart" tone="sky" />
                    <div className="grid grid-cols-2 gap-3 md:grid-cols-3 xl:grid-cols-6 xl:gap-4">
                        {metrics.map((item, index) => <MetricCard key={item.title} {...item} ordinal={String(index + 1).padStart(2, '0')} />)}
                    </div>
                </section>

                {/* Accesos rapidos al inicio, con busqueda y favoritos funcionales. */}
                <section>
                    <SectionHeader eyebrow="Acceso directo" title="Tu espacio de trabajo" subtitle="Abre las secciones que utilizas con mayor frecuencia o marca tus favoritas." icon="bolt" tone="violet">
                        <div className="flex w-full flex-col gap-2 sm:w-auto sm:flex-row sm:items-center">
                            <label className="relative block sm:w-64">
                                <Icon name="search" className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-slate-400" />
                                <input type="search" value={quickSearch} onChange={(event) => setQuickSearch(event.target.value)} placeholder="Buscar un acceso..." aria-label="Buscar accesos directos" className="w-full rounded-xl border border-violet-200 bg-white/90 py-2.5 pl-9 pr-3 text-xs text-slate-700 shadow-sm outline-none transition focus:border-violet-400 focus:ring-2 focus:ring-violet-100" />
                            </label>
                            <button type="button" onClick={() => setOnlyFavorites((value) => !value)} aria-pressed={onlyFavorites} className={`inline-flex items-center justify-center gap-2 rounded-xl border px-3 py-2.5 text-xs font-bold shadow-sm transition ${onlyFavorites ? 'border-amber-300 bg-amber-100 text-amber-900' : 'border-violet-200 bg-violet-100 text-violet-800 hover:bg-violet-200'}`}>
                                <Icon name="star" className="h-4 w-4" /> {onlyFavorites ? 'Ver todos' : 'Favoritos'}
                            </button>
                        </div>
                    </SectionHeader>
                    {filteredActions.length > 0 ? (
                        <div className="grid gap-3 rounded-[25px] border border-violet-200/60 bg-gradient-to-br from-[#EADFFF] via-[#DDF5FF] to-[#D7F8ED] p-3 shadow-inner sm:grid-cols-2 sm:p-4 lg:grid-cols-3 2xl:grid-cols-5">
                            {filteredActions.map((item) => {
                                const tone = TONES[item.tone] || TONES.sky;
                                const isFavorite = favorites.includes(item.routeName);
                                return (
                                    <div key={item.routeName} className={`group relative flex min-h-[110px] min-w-0 items-center gap-1 overflow-hidden rounded-[20px] border p-2 shadow-sm transition duration-200 hover:-translate-y-1 hover:shadow-lg ${tone.tile} ${tone.hover}`}>
                                        <span className={`absolute left-4 right-4 top-0 h-1 rounded-b-full opacity-90 ${tone.line}`} />
                                        <Link href={route(item.routeName)} className="relative flex min-w-0 flex-1 items-center gap-3 rounded-xl px-2 py-2.5 focus-visible:outline focus-visible:outline-2 focus-visible:outline-teal-500">
                                            <span className={`flex h-12 w-12 shrink-0 items-center justify-center rounded-2xl text-white shadow-md shadow-black/10 transition-transform group-hover:scale-110 ${tone.icon}`}><Icon name={item.icon} className="h-6 w-6" /></span>
                                            <span className="min-w-0 flex-1">
                                                <span className={`block truncate text-[13px] font-extrabold ${tone.ink}`}>{item.label}</span>
                                                <span className="mt-1 block text-[11px] leading-snug text-slate-700">{item.detail}</span>
                                            </span>
                                        </Link>
                                        <button type="button" onClick={() => toggleFavorite(item.routeName)} title={isFavorite ? `Quitar ${item.label} de favoritos` : `Marcar ${item.label} como favorito`} aria-label={isFavorite ? `Quitar ${item.label} de favoritos` : `Marcar ${item.label} como favorito`} aria-pressed={isFavorite} className={`relative shrink-0 rounded-lg bg-white/50 p-2 transition ${isFavorite ? 'text-amber-600 hover:bg-white' : 'text-slate-500 hover:bg-white hover:text-amber-600'}`}>
                                            <Icon name="star" className="h-4 w-4" />
                                        </button>
                                    </div>
                                );
                            })}
                        </div>
                    ) : (
                        <div className="rounded-2xl border border-dashed border-slate-200 bg-white px-5 py-7 text-center text-sm text-slate-500">
                            {availableActions.length === 0 ? 'No hay accesos configurados con rutas disponibles.' : 'No hay accesos que coincidan con tu búsqueda o filtro.'}
                            {(quickSearch || onlyFavorites) && <button type="button" className="ml-2 font-bold text-teal-700 hover:underline" onClick={() => { setQuickSearch(''); setOnlyFavorites(false); }}>Limpiar filtros</button>}
                        </div>
                    )}
                </section>

                {/* Analitica principal. */}
                <section>
                    <SectionHeader eyebrow="Analítica académica" title="Admisiones y resultados" subtitle="Compara postulantes, ingresantes, matrículas y expedientes de titulación." icon="trend" tone="cyan" />
                    <div className="grid gap-5 xl:grid-cols-[1.25fr_1fr]">
                        <ChartCard title="Admisiones y matrículas por programa" subtitle="Comparativa de postulantes, ingresantes y matriculados" icon="academic" tone="indigo"
                            actions={<ShowMoreButton all={showAllAdmission} onClick={() => setShowAllAdmission((value) => !value)} total={admission.length} visible={8} />}>
                            {admission.length ? (
                                <>
                                    <div className="mb-4 grid grid-cols-3 gap-2">
                                        {[
                                            { label: 'Postulantes', value: totalPostulantes, color: 'text-violet-800', bg: 'border-violet-200 bg-violet-100/80', icon: 'users' },
                                            { label: 'Ingresantes', value: totalIngresantes, color: 'text-cyan-800', bg: 'border-cyan-200 bg-cyan-100/80', icon: 'academic' },
                                            { label: 'Matriculados', value: totalMatriculados, color: 'text-teal-800', bg: 'border-teal-200 bg-teal-100/80', icon: 'calendar' },
                                        ].map((item) => (
                                            <div key={item.label} className={`rounded-xl border px-3 py-3 shadow-sm ${item.bg}`}>
                                                <p className={`flex items-center gap-1.5 text-[10px] font-semibold ${item.color}`}><Icon name={item.icon} className="h-3.5 w-3.5" />{item.label}</p>
                                                <p className={`mt-1 text-lg font-black ${item.color}`}>{formatCount(item.value)}</p>
                                            </div>
                                        ))}
                                    </div>
                                    <div className="w-full overflow-x-auto pb-1">
                                        <div className="min-w-[565px]" style={{ height: Math.max(300, admissionVisible.length * 54 + 75) }}>
                                            <ResponsiveContainer width="100%" height="100%">
                                                <BarChart data={admissionVisible} layout="vertical" barGap={2} barCategoryGap="24%" margin={{ top: 4, right: 22, left: 2, bottom: 2 }}>
                                                    <CartesianGrid stroke="#D8DFF9" strokeDasharray="4 5" horizontal={false} />
                                                    <XAxis type="number" allowDecimals={false} tick={{ fontSize: 11, fill: '#94A3B8' }} axisLine={false} tickLine={false} />
                                                    <YAxis type="category" dataKey="carrera" width={128} tickFormatter={(name) => shortLabel(name, 21)} tick={{ fontSize: 10, fill: '#475569' }} axisLine={false} tickLine={false} />
                                                    <Tooltip content={<GraphicTooltip />} cursor={{ fill: '#E0E7FF' }} />
                                                    <Legend verticalAlign="top" height={38} iconType="circle" wrapperStyle={{ fontSize: 11 }} />
                                                    <Bar dataKey="postulantes" name="Postulantes" fill={COLORS.violet} radius={[0, 4, 4, 0]} maxBarSize={11} />
                                                    <Bar dataKey="ingresantes" name="Ingresantes" fill={COLORS.cyan} radius={[0, 4, 4, 0]} maxBarSize={11} />
                                                    <Bar dataKey="matriculados" name="Matriculados" fill={COLORS.teal} radius={[0, 4, 4, 0]} maxBarSize={11} />
                                                </BarChart>
                                            </ResponsiveContainer>
                                        </div>
                                    </div>
                                </>
                            ) : <EmptyState message="El controlador no ha enviado registros de admisión para graficar." />}
                        </ChartCard>

                        <ChartCard title="Titulación por periodo" subtitle="Evolución de expedientes y titulados" icon="award" tone="amber">
                            {graduation.length ? (
                                <>
                                    <div className="mb-5 flex flex-wrap items-center gap-3 text-[11px] text-slate-700">
                                        <span className="flex items-center gap-2 rounded-full bg-teal-100 px-3 py-1.5 font-bold text-teal-800"><span className="h-2.5 w-2.5 rounded-full bg-teal-600" /> Expedientes</span>
                                        <span className="flex items-center gap-2 rounded-full bg-amber-100 px-3 py-1.5 font-bold text-amber-800"><span className="h-2.5 w-2.5 rounded-full bg-amber-500" /> Titulados</span>
                                    </div>
                                    <div className="h-[355px] w-full min-w-0">
                                        <ResponsiveContainer width="100%" height="100%">
                                            <AreaChart data={graduation} margin={{ top: 20, right: 18, left: -13, bottom: 20 }}>
                                                <defs>
                                                    <linearGradient id="dashGradientExp" x1="0" y1="0" x2="0" y2="1"><stop offset="0%" stopColor={COLORS.teal} stopOpacity={0.42} /><stop offset="95%" stopColor={COLORS.teal} stopOpacity={0.01} /></linearGradient>
                                                    <linearGradient id="dashGradientTit" x1="0" y1="0" x2="0" y2="1"><stop offset="0%" stopColor={COLORS.gold} stopOpacity={0.38} /><stop offset="95%" stopColor={COLORS.gold} stopOpacity={0} /></linearGradient>
                                                </defs>
                                                <CartesianGrid vertical={false} stroke="#E9EFF4" strokeDasharray="4 5" />
                                                <XAxis dataKey="periodo" tick={{ fontSize: 10, fill: '#64748B' }} axisLine={false} tickLine={false} interval="preserveStartEnd" minTickGap={20} />
                                                <YAxis allowDecimals={false} tick={{ fontSize: 10, fill: '#94A3B8' }} axisLine={false} tickLine={false} />
                                                <Tooltip content={<GraphicTooltip />} />
                                                <Area dataKey="expedientes" type="monotone" name="Expedientes" stroke={COLORS.teal} strokeWidth={3} fill="url(#dashGradientExp)" activeDot={{ r: 6 }} dot={{ r: 2, strokeWidth: 0 }} />
                                                <Area dataKey="titulados" type="monotone" name="Titulados" stroke={COLORS.gold} strokeWidth={3} fill="url(#dashGradientTit)" activeDot={{ r: 6 }} dot={{ r: 2, strokeWidth: 0 }} />
                                            </AreaChart>
                                        </ResponsiveContainer>
                                    </div>
                                    <p className="mt-1 text-[11px] leading-relaxed text-slate-400">Los valores corresponden a los periodos proporcionados por el servidor.</p>
                                </>
                            ) : <EmptyState message="No hay datos históricos de titulación en la respuesta de Laravel." />}
                        </ChartCard>
                    </div>
                    {admission.length > 0 && (
                        <div className="mt-4 flex flex-wrap items-center gap-3 rounded-2xl border border-teal-200 bg-gradient-to-r from-[#BDF5E9] via-[#D9F5FF] to-[#DFD7FF] px-5 py-4 shadow-sm">
                            <div className="flex h-10 w-10 shrink-0 items-center justify-center rounded-xl bg-gradient-to-br from-teal-500 to-sky-500 text-white shadow-md"><Icon name="trend" /></div>
                            <div className="min-w-0 flex-1">
                                <p className="text-xs font-extrabold text-[#134E4A]">Relación entre matriculados y postulantes</p>
                                <p className="mt-1 text-[11px] text-slate-500">Calculada a partir de la suma de programas recibidos; no es una tasa de admisión oficial.</p>
                            </div>
                            <span className="text-xl font-black text-teal-700">{conversion !== null ? `${decimalFormatter.format(conversion)}%` : 'N/D'}</span>
                        </div>
                    )}
                </section>

                {/* Tres paneles complementarios, etiquetas legibles y controles para ver mas. */}
                <section>
                    <SectionHeader eyebrow="Seguimiento y control" title="Calidad académica y gestión docente" subtitle="Identifica repitencia, distribución de convalidaciones y carga lectiva." icon="shield" tone="orange" />
                    <div className="grid gap-5 xl:grid-cols-3">
                        <ChartCard title="Cursos con mayor repitencia" subtitle="Cantidad de estudiantes desaprobados" icon="book" tone="rose"
                            actions={<ShowMoreButton all={showAllRepitencia} onClick={() => setShowAllRepitencia((value) => !value)} total={repetition.length} visible={6} />}>
                            {repetition.length ? (
                                <div className="w-full overflow-x-auto pb-1">
                                    <div className="min-w-[365px]" style={{ height: Math.max(270, repetitionVisible.length * 49 + 44) }}>
                                        <ResponsiveContainer width="100%" height="100%">
                                            <BarChart data={repetitionVisible} layout="vertical" margin={{ top: 8, right: 18, left: 3, bottom: 0 }} barCategoryGap="35%">
                                                <CartesianGrid horizontal={false} stroke="#EBF0F3" strokeDasharray="4 5" />
                                                <XAxis type="number" allowDecimals={false} tick={{ fontSize: 10, fill: '#94A3B8' }} axisLine={false} tickLine={false} />
                                                <YAxis type="category" dataKey="curso" width={120} tickFormatter={(label) => shortLabel(label, 19)} tick={{ fontSize: 10, fill: '#475569' }} axisLine={false} tickLine={false} />
                                                <Tooltip content={<GraphicTooltip />} cursor={{ fill: '#FFF1F2' }} />
                                                <Bar dataKey="desaprobados" name="Desaprobados" fill={COLORS.rose} radius={[0, 7, 7, 0]} maxBarSize={21} />
                                            </BarChart>
                                        </ResponsiveContainer>
                                    </div>
                                </div>
                            ) : <EmptyState message="No se recibieron datos de repitencia de cursos." />}
                        </ChartCard>

                        <ChartCard title="Convalidaciones" subtitle="Distribución de trámites por estado o tipo" icon="check" tone="teal">
                            {validation.length && validationTotal > 0 ? (
                                <>
                                    <div className="relative mx-auto h-[245px] w-full max-w-[340px]">
                                        <ResponsiveContainer width="100%" height="100%">
                                            <PieChart>
                                                <Pie data={validation} dataKey="total" nameKey="tipo" cx="50%" cy="50%" innerRadius={75} outerRadius={105} paddingAngle={3} strokeWidth={0}>
                                                    {validation.map((item, index) => <Cell key={`${item.tipo}-${index}`} fill={PIE_COLORS[index % PIE_COLORS.length]} />)}
                                                </Pie>
                                                <Tooltip formatter={(value, name) => [formatCount(value), name]} contentStyle={{ borderRadius: 14, border: '1px solid #E2E8F0', fontSize: 12 }} />
                                            </PieChart>
                                        </ResponsiveContainer>
                                        <div className="pointer-events-none absolute inset-0 flex flex-col items-center justify-center">
                                            <span className="text-3xl font-black text-[#134E4A]">{formatCount(validationTotal)}</span>
                                            <span className="mt-1 text-[10px] font-bold uppercase tracking-wider text-slate-400">Registros</span>
                                        </div>
                                    </div>
                                    <div className="mt-3 space-y-2">
                                        {validation.map((item, index) => (
                                            <div key={`${item.tipo}-${index}`} className={`flex items-center justify-between gap-3 rounded-xl border px-3 py-2.5 text-xs ${PIE_LEGEND_BACKGROUNDS[index % PIE_LEGEND_BACKGROUNDS.length]}`}>
                                                <span className="flex min-w-0 items-center gap-2 text-slate-600"><span className="h-2.5 w-2.5 shrink-0 rounded-full" style={{ backgroundColor: PIE_COLORS[index % PIE_COLORS.length] }} /><span className="truncate" title={item.tipo}>{item.tipo}</span></span>
                                                <span className="shrink-0 font-extrabold text-[#134E4A]">{formatCount(item.total)} <span className="font-normal text-slate-400">({decimalFormatter.format((item.total / validationTotal) * 100)}%)</span></span>
                                            </div>
                                        ))}
                                    </div>
                                </>
                            ) : <EmptyState message="No hay convalidaciones con valores disponibles para el gráfico." />}
                        </ChartCard>

                        <ChartCard title="Carga horaria docente" subtitle="Horas lectivas semanales asignadas" icon="teacher" tone="sky"
                            actions={<ShowMoreButton all={showAllCarga} onClick={() => setShowAllCarga((value) => !value)} total={teaching.length} visible={6} />}>
                            {teaching.length ? (
                                <div className="w-full overflow-x-auto pb-1">
                                    <div className="min-w-[365px]" style={{ height: Math.max(270, teachingVisible.length * 49 + 44) }}>
                                        <ResponsiveContainer width="100%" height="100%">
                                            <BarChart data={teachingVisible} layout="vertical" margin={{ top: 8, right: 18, left: 3, bottom: 0 }} barCategoryGap="35%">
                                                <CartesianGrid horizontal={false} stroke="#EBF0F3" strokeDasharray="4 5" />
                                                <XAxis type="number" allowDecimals={false} tick={{ fontSize: 10, fill: '#94A3B8' }} axisLine={false} tickLine={false} />
                                                <YAxis type="category" dataKey="docente" width={120} tickFormatter={(name) => shortLabel(name, 19)} tick={{ fontSize: 10, fill: '#475569' }} axisLine={false} tickLine={false} />
                                                <Tooltip content={<GraphicTooltip suffix=" h" />} cursor={{ fill: '#DBEAFE' }} />
                                                <Bar dataKey="horas_lectivas" name="Horas lectivas" fill={COLORS.navy} radius={[0, 7, 7, 0]} maxBarSize={21} />
                                            </BarChart>
                                        </ResponsiveContainer>
                                    </div>
                                </div>
                            ) : <EmptyState message="El controlador no envió carga lectiva de docentes." />}
                        </ChartCard>
                    </div>
                </section>

                <footer className="flex flex-col justify-between gap-2 border-t border-teal-200 pt-4 text-[11px] text-slate-600 sm:flex-row sm:items-center">
                    <span>Panel administrativo • Estadísticas obtenidas de las propiedades Inertia enviadas por Laravel.</span>
                    <span>Periodo: {periodo}</span>
                </footer>
            </div>
        </AuthenticatedLayout>
    );
}
