const { useState, useMemo, useEffect } = React;

window.AdminPlanilla = function({ globalUsers = [], absences = [], logs = [], vacations = [], settings = {}, refreshData }) {
    const [activeTab, setActiveTab] = useState('payroll');

    const [periodFilter, setPeriodFilter] = useState('current_fortnight');
    const [startDate, setStartDate] = useState('');
    const [endDate, setEndDate] = useState('');

    // Variables guardadas en base de datos por colaborador
    const [payrollVariables, setPayrollVariables] = useState({});
    const [savingVarId, setSavingVarId] = useState(null);

    // Modal de Calendario de Asistencia
    const [calendarModalUser, setCalendarModalUser] = useState(null);

    // Configuración de cortes
    const [cutStartDayQ1, setCutStartDayQ1] = useState(settings?.cutStartDayQ1 || 1);
    const [cutEndDayQ1, setCutEndDayQ1] = useState(settings?.cutEndDayQ1 || 15);
    const [cutStartDayQ2, setCutStartDayQ2] = useState(settings?.cutStartDayQ2 || 16);
    const [cutEndDayQ2, setCutEndDayQ2] = useState(settings?.cutEndDayQ2 || 30);
    const [isSavingConfig, setIsSavingConfig] = useState(false);

    // Estado Finiquito
    const [selectedSeveranceUser, setSelectedSeveranceUser] = useState(null);
    const [sevTermDate, setSevTermDate] = useState(window.getNICDate());
    const [sevReason, setSevReason] = useState('despido_sin_causa_art45');
    const [sevAvgVariable, setSevAvgVariable] = useState(0);
    const [sevVacDaysPending, setSevVacDaysPending] = useState(0);

    const todayStr = window.getNICDate();
    const [curYear, curMonth, curDay] = todayStr.split('-').map(Number);

    const applyPeriodPreset = (preset) => {
        setPeriodFilter(preset);
        const y = curYear;
        const m = curMonth;

        if (preset === 'today_accumulated') {
            const qStart = curDay <= 15 ? 1 : 16;
            setStartDate(`${y}-${String(m).padStart(2,'0')}-${String(qStart).padStart(2,'0')}`);
            setEndDate(todayStr);
        } else if (preset === 'current_fortnight') {
            if (curDay <= 15) {
                setStartDate(`${y}-${String(m).padStart(2,'0')}-01`);
                setEndDate(`${y}-${String(m).padStart(2,'0')}-15`);
            } else {
                const lastDay = new Date(y, m, 0).getDate();
                setStartDate(`${y}-${String(m).padStart(2,'0')}-16`);
                setEndDate(`${y}-${String(m).padStart(2,'0')}-${lastDay}`);
            }
        } else if (preset === 'last_fortnight') {
            if (curDay <= 15) {
                const prevM = m === 1 ? 12 : m - 1;
                const prevY = m === 1 ? y - 1 : y;
                const lastDay = new Date(prevY, prevM, 0).getDate();
                setStartDate(`${prevY}-${String(prevM).padStart(2,'0')}-16`);
                setEndDate(`${prevY}-${String(prevM).padStart(2,'0')}-${lastDay}`);
            } else {
                setStartDate(`${y}-${String(m).padStart(2,'0')}-01`);
                setEndDate(`${y}-${String(m).padStart(2,'0')}-15`);
            }
        } else if (preset === 'current_month') {
            const lastDay = new Date(y, m, 0).getDate();
            setStartDate(`${y}-${String(m).padStart(2,'0')}-01`);
            setEndDate(`${y}-${String(m).padStart(2,'0')}-${lastDay}`);
        } else if (preset === 'last_month') {
            const prevM = m === 1 ? 12 : m - 1;
            const prevY = m === 1 ? y - 1 : y;
            const lastDay = new Date(prevY, prevM, 0).getDate();
            setStartDate(`${prevY}-${String(prevM).padStart(2,'0')}-01`);
            setEndDate(`${prevY}-${String(prevM).padStart(2,'0')}-${lastDay}`);
        }
    };

    useEffect(() => {
        applyPeriodPreset('current_fortnight');
    }, []);

    // Cargar variables guardadas en BD cada vez que cambian las fechas de corte
    const loadPayrollVariablesFromDB = async () => {
        if (!startDate || !endDate) return;
        try {
            const res = await window.apiCall('get_payroll_items', {
                period_start: startDate,
                period_end: endDate
            });
            if (res && res.success && res.items) {
                const map = {};
                res.items.forEach(it => {
                    map[it.user_id] = {
                        overtime: parseFloat(it.overtime_hours || 0),
                        holidays: parseFloat(it.holidays_worked || 0),
                        commissions: parseFloat(it.commissions || 0),
                        bonuses: parseFloat(it.bonuses || 0)
                    };
                });
                setPayrollVariables(map);
            }
        } catch (e) {}
    };

    useEffect(() => {
        loadPayrollVariablesFromDB();
    }, [startDate, endDate]);

    const periodDaysCount = useMemo(() => {
        if (!startDate || !endDate) return 15;
        return window.getDaysDiff(startDate, endDate);
    }, [startDate, endDate]);

    // Guardar variable en base de datos al cambiar valor
    const handleSaveVariable = async (userId, field, value) => {
        const numVal = parseFloat(value) || 0;
        const current = payrollVariables[userId] || { overtime: 0, holidays: 0, commissions: 0, bonuses: 0 };
        const updated = { ...current, [field]: numVal };

        setPayrollVariables(prev => ({ ...prev, [userId]: updated }));
        setSavingVarId(userId);

        await window.apiCall('save_payroll_item', {
            user_id: userId,
            period_start: startDate,
            period_end: endDate,
            overtime_hours: updated.overtime || 0,
            holidays_worked: updated.holidays || 0,
            commissions: updated.commissions || 0,
            bonuses: updated.bonuses || 0
        });

        setTimeout(() => setSavingVarId(null), 800);
    };

    const activeWorkersList = useMemo(() => {
        return (globalUsers || []).filter(u => u.status === 'activo');
    }, [globalUsers]);

    const processedPayroll = useMemo(() => {
        return activeWorkersList.map(u => {
            const vars = payrollVariables[u.id] || {};
            const calc = window.calculatePayrollRowAdv(u, {
                payrollPeriod: periodDaysCount > 20 ? 'mensual' : 'quincenal',
                periodDays: periodDaysCount,
                startDate,
                endDate,
                totalActiveWorkers: activeWorkersList.length,
                absences,
                logs,
                vacations,
                overtimeHours: vars.overtime || 0,
                holidaysWorkedManual: vars.holidays || 0,
                commissions: vars.commissions || 0,
                bonuses: vars.bonuses || 0,
                inssPatronalRateCustom: settings?.inssPatronalRate || null
            });

            return { user: u, calc, vars };
        });
    }, [activeWorkersList, payrollVariables, periodDaysCount, startDate, endDate, absences, logs, vacations, settings]);

    const totalsSummary = useMemo(() => {
        let gross = 0, inssLab = 0, ir = 0, net = 0, inssPat = 0, inatec = 0, totalCost = 0;
        processedPayroll.forEach(p => {
            gross += parseFloat(p.calc.grossSalary);
            inssLab += parseFloat(p.calc.inssLaboral);
            ir += parseFloat(p.calc.irDGI);
            net += parseFloat(p.calc.netSalary);
            inssPat += parseFloat(p.calc.inssPatronal);
            inatec += parseFloat(p.calc.inatecPatronal);
            totalCost += parseFloat(p.calc.totalCostEmployer);
        });
        return { gross, inssLab, ir, net, inssPat, inatec, totalCost };
    }, [processedPayroll]);

    const severanceResult = useMemo(() => {
        if (!selectedSeveranceUser) return null;
        return window.calculateSeveranceNI({
            user: selectedSeveranceUser,
            hiringDate: selectedSeveranceUser.hiringDate || window.getNICDate(),
            terminationDate: sevTermDate,
            reason: sevReason,
            monthlyBaseSalary: parseFloat(selectedSeveranceUser.baseSalary || 0),
            averageVariableSalary: parseFloat(sevAvgVariable || 0),
            vacationDaysPending: parseFloat(sevVacDaysPending || 0)
        });
    }, [selectedSeveranceUser, sevTermDate, sevReason, sevAvgVariable, sevVacDaysPending]);

    const handleOpenSeveranceForUser = (u) => {
        setSelectedSeveranceUser(u);
        const vacBal = parseFloat(window.calculateVacationBalance(u, settings?.vacationRate || 2.5, vacations));
        setSevVacDaysPending(vacBal);
        setSevAvgVariable(0);
        setSevTermDate(window.getNICDate());
        setActiveTab('severance');
    };

    const handleSaveCutConfig = async (e) => {
        e.preventDefault();
        setIsSavingConfig(true);
        const res = await window.apiCall('update_settings', {
            cut_start_q1: parseInt(cutStartDayQ1),
            cut_end_q1: parseInt(cutEndDayQ1),
            cut_start_q2: parseInt(cutStartDayQ2),
            cut_end_q2: parseInt(cutEndDayQ2)
        });
        setIsSavingConfig(false);
        if (res && res.success) {
            alert("Ventanas de corte actualizadas.");
            if (refreshData) await refreshData();
        }
    };

    const exportCSVReport = () => {
        const headers = [
            "ID", "Empleado", "Correo", "Salario Base Mensual (C$)", "Días Corte", 
            "Faltas Injust.", "Días Deducidos", "Salario Período", "Horas Extras (C$)", 
            "Feriados (C$)", "Comisiones/Bonos (C$)", "Salario Bruto (C$)", 
            "INSS Laboral 7%", "IR DGI", "Neto a Pagar (C$)", 
            `INSS Patronal (${activeWorkersList.length >= 20 ? '22.5%' : '21.5%'})`, "INATEC 2%", "Costo Empresa (C$)"
        ];
        const rows = processedPayroll.map(p => [
            p.user.id, p.user.name, p.user.email, p.user.baseSalary || 0, periodDaysCount,
            p.calc.unjustifiedCount, p.calc.deductedDays, p.calc.basePeriodPay, p.calc.overtimePay,
            p.calc.holidayPay, p.calc.variablePay, p.calc.grossSalary,
            p.calc.inssLaboral, p.calc.irDGI, p.calc.netSalary,
            p.calc.inssPatronal, p.calc.inatecPatronal, p.calc.totalCostEmployer
        ]);
        window.exportToCSV(`Planilla_${startDate}_al_${endDate}`, headers, rows);
    };

    return (
        <div className="space-y-6 fade-in">
            {/* ENCABEZADO */}
            <div className="bg-white p-6 sm:p-8 rounded-[3rem] shadow-sm border border-slate-100 flex flex-col md:flex-row justify-between items-start md:items-center gap-4">
                <div>
                    <h2 className="text-2xl font-black text-slate-900 tracking-tight">Planilla y Nómina Oficial (Nicaragua)</h2>
                    <p className="text-slate-400 font-bold uppercase text-[10px] mt-0.5 tracking-widest">
                        Auditoría Real de Bitácora • Deducción Séptimo Día • Horas Extras • Finiquitos
                    </p>
                </div>

                <div className="flex bg-slate-100 p-1.5 rounded-2xl border overflow-x-auto max-w-full no-scrollbar">
                    <button onClick={() => setActiveTab('payroll')} className={`px-4 py-2 rounded-xl text-xs font-black uppercase tracking-wider transition-all whitespace-nowrap ${activeTab === 'payroll' ? 'bg-white text-indigo-600 shadow-sm' : 'text-slate-500'}`}>Planilla Período</button>
                    <button onClick={() => setActiveTab('severance')} className={`px-4 py-2 rounded-xl text-xs font-black uppercase tracking-wider transition-all whitespace-nowrap ${activeTab === 'severance' ? 'bg-white text-indigo-600 shadow-sm' : 'text-slate-500'}`}>Finiquito / Liquidación</button>
                    <button onClick={() => setActiveTab('cut_config')} className={`px-4 py-2 rounded-xl text-xs font-black uppercase tracking-wider transition-all whitespace-nowrap ${activeTab === 'cut_config' ? 'bg-white text-indigo-600 shadow-sm' : 'text-slate-500'}`}>Cortes de Asistencia</button>
                </div>
            </div>

            {/* PESTAÑA 1: PLANILLA DEL PERÍODO */}
            {activeTab === 'payroll' && (
                <div className="space-y-6">
                    {/* BARRA DE FILTROS TEMPORALES */}
                    <div className="bg-white p-6 rounded-[2.5rem] shadow-sm border border-slate-100 space-y-4">
                        <div className="flex flex-wrap items-center justify-between gap-3 border-b pb-3">
                            <div className="flex flex-wrap gap-1.5">
                                <button onClick={() => applyPeriodPreset('today_accumulated')} className={`px-3 py-1.5 rounded-xl font-black text-[10px] uppercase border ${periodFilter === 'today_accumulated' ? 'bg-indigo-600 text-white border-indigo-600 shadow-xs' : 'bg-slate-50 text-slate-600'}`}>Acumulado al Día de Hoy</button>
                                <button onClick={() => applyPeriodPreset('current_fortnight')} className={`px-3 py-1.5 rounded-xl font-black text-[10px] uppercase border ${periodFilter === 'current_fortnight' ? 'bg-indigo-600 text-white border-indigo-600 shadow-xs' : 'bg-slate-50 text-slate-600'}`}>Quincena Actual</button>
                                <button onClick={() => applyPeriodPreset('last_fortnight')} className={`px-3 py-1.5 rounded-xl font-black text-[10px] uppercase border ${periodFilter === 'last_fortnight' ? 'bg-indigo-600 text-white border-indigo-600 shadow-xs' : 'bg-slate-50 text-slate-600'}`}>Quincena Pasada</button>
                                <button onClick={() => applyPeriodPreset('current_month')} className={`px-3 py-1.5 rounded-xl font-black text-[10px] uppercase border ${periodFilter === 'current_month' ? 'bg-indigo-600 text-white border-indigo-600 shadow-xs' : 'bg-slate-50 text-slate-600'}`}>Mes Actual</button>
                                <button onClick={() => applyPeriodPreset('last_month')} className={`px-3 py-1.5 rounded-xl font-black text-[10px] uppercase border ${periodFilter === 'last_month' ? 'bg-indigo-600 text-white border-indigo-600 shadow-xs' : 'bg-slate-50 text-slate-600'}`}>Mes Pasado</button>
                            </div>

                            <div className="flex items-center gap-2">
                                <button onClick={exportCSVReport} className="px-4 py-2 bg-emerald-600 hover:bg-emerald-700 text-white font-black rounded-xl text-[10px] uppercase shadow-sm">Exportar CSV</button>
                                <button onClick={() => window.print()} className="px-4 py-2 bg-slate-900 text-white font-black rounded-xl text-[10px] uppercase shadow-sm">Imprimir</button>
                            </div>
                        </div>

                        <div className="flex flex-col sm:flex-row items-center gap-3">
                            <span className="text-[10px] font-black uppercase text-slate-400">Rango de Corte:</span>
                            <input type="date" value={startDate} onChange={e => { setStartDate(e.target.value); setPeriodFilter('custom'); }} className="p-2 bg-slate-50 border rounded-xl font-bold text-xs outline-none" />
                            <span className="text-xs font-bold text-slate-400">al</span>
                            <input type="date" value={endDate} onChange={e => { setEndDate(e.target.value); setPeriodFilter('custom'); }} className="p-2 bg-slate-50 border rounded-xl font-bold text-xs outline-none" />
                            <span className="text-xs font-bold text-indigo-600 bg-indigo-50 px-3 py-1.5 rounded-xl">
                                {periodDaysCount} Día(s) del Período
                            </span>
                        </div>
                    </div>

                    {/* TARJETAS RESUMEN DE NÓMINA */}
                    <div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
                        <div className="bg-white p-5 rounded-3xl border border-slate-100 shadow-sm">
                            <span className="text-[9px] font-black uppercase text-slate-400">Masa Bruta (TIG)</span>
                            <h4 className="text-xl font-black text-slate-900 mt-1">C$ {totalsSummary.gross.toLocaleString('en-US', { minimumFractionDigits: 2 })}</h4>
                        </div>
                        <div className="bg-white p-5 rounded-3xl border border-slate-100 shadow-sm">
                            <span className="text-[9px] font-black uppercase text-red-500">INSS Laboral (7%)</span>
                            <h4 className="text-xl font-black text-red-600 mt-1">- C$ {totalsSummary.inssLab.toLocaleString('en-US', { minimumFractionDigits: 2 })}</h4>
                        </div>
                        <div className="bg-white p-5 rounded-3xl border border-slate-100 shadow-sm">
                            <span className="text-[9px] font-black uppercase text-emerald-600">Neto a Desembolsar</span>
                            <h4 className="text-xl font-black text-emerald-600 mt-1">C$ {totalsSummary.net.toLocaleString('en-US', { minimumFractionDigits: 2 })}</h4>
                        </div>
                        <div className="bg-white p-5 rounded-3xl border border-slate-100 shadow-sm">
                            <span className="text-[9px] font-black uppercase text-indigo-600">Costo Patronal Total</span>
                            <h4 className="text-xl font-black text-indigo-600 mt-1">C$ {totalsSummary.totalCost.toLocaleString('en-US', { minimumFractionDigits: 2 })}</h4>
                            <p className="text-[8px] font-bold text-slate-400 mt-0.5">INSS ({activeWorkersList.length >= 20 ? '22.5%' : '21.5%'}) + INATEC 2%</p>
                        </div>
                    </div>

                    {/* TABLA DE PLANILLA */}
                    <div className="bg-white rounded-[3rem] shadow-sm overflow-hidden border border-slate-100">
                        <div className="overflow-x-auto">
                            <table className="w-full text-left print-table text-xs">
                                <thead className="bg-slate-50 text-[9px] font-black text-slate-400 uppercase tracking-widest border-b border-slate-100">
                                    <tr>
                                        <th className="p-4">Colaborador</th>
                                        <th className="p-4">Salario Base</th>
                                        <th className="p-4">Auditoría Asistencia</th>
                                        <th className="p-4">Horas Extras</th>
                                        <th className="p-4">Comisiones / Bonos</th>
                                        <th className="p-4">Total Bruto</th>
                                        <th className="p-4 text-red-500">INSS (7%)</th>
                                        <th className="p-4 text-red-500">IR DGI</th>
                                        <th className="p-4 text-emerald-600 font-black">Neto</th>
                                        <th className="p-4 text-indigo-600">Cargas Patronales</th>
                                        <th className="p-4 text-center">Acciones</th>
                                    </tr>
                                </thead>
                                <tbody className="divide-y divide-slate-100 font-bold">
                                    {processedPayroll.map(({ user: u, calc, vars }) => (
                                        <tr key={u.id} className="hover:bg-slate-50/50 transition-colors">
                                            <td className="p-4">
                                                <p className="font-black text-slate-900">{u.name}</p>
                                                <p className="text-[9px] text-slate-400 uppercase">@{u.alias} • {u.positionTitle || u.role}</p>
                                            </td>
                                            <td className="p-4 text-slate-700">
                                                C$ {parseFloat(u.baseSalary || 0).toFixed(2)}
                                            </td>
                                            <td className="p-4">
                                                <button 
                                                    onClick={() => setCalendarModalUser({ user: u, calc })}
                                                    className="px-2.5 py-1 rounded-xl text-[10px] font-black flex items-center gap-1.5 transition-all bg-slate-50 hover:bg-indigo-50 text-slate-700 border border-slate-200"
                                                    title="Ver calendario detallado de asistencia"
                                                >
                                                    {calc.deductedDays > 0 ? (
                                                        <span className="text-red-600 font-black">
                                                            ⚠️ -{calc.deductedDays} d ({calc.unjustifiedCount} f = -{calc.unjustifiedCount * 2} d)
                                                        </span>
                                                    ) : (
                                                        <span className="text-emerald-600">
                                                            ✅ {calc.effectiveWorkedDays} d efectivos
                                                        </span>
                                                    )}
                                                    <span className="text-[9px] text-indigo-600 underline ml-1">Ver</span>
                                                </button>
                                            </td>
                                            <td className="p-4">
                                                <div className="flex items-center gap-1">
                                                    <input 
                                                        type="number" 
                                                        min="0" 
                                                        step="0.5" 
                                                        value={vars.overtime || ''} 
                                                        placeholder="0"
                                                        onChange={e => handleSaveVariable(u.id, 'overtime', e.target.value)} 
                                                        className="w-14 p-1.5 bg-slate-50 border rounded-lg text-center font-black text-xs outline-none focus:border-indigo-600" 
                                                    />
                                                    <span className="text-[9px] text-slate-400">h = C${calc.overtimePay}</span>
                                                </div>
                                            </td>
                                            <td className="p-4">
                                                <div className="flex items-center gap-1">
                                                    <input 
                                                        type="number" 
                                                        min="0" 
                                                        step="50" 
                                                        value={vars.commissions || ''} 
                                                        placeholder="0.00"
                                                        onChange={e => handleSaveVariable(u.id, 'commissions', e.target.value)} 
                                                        className="w-20 p-1.5 bg-slate-50 border rounded-lg text-center font-black text-xs outline-none focus:border-indigo-600" 
                                                    />
                                                </div>
                                            </td>
                                            <td className="p-4 text-slate-900 font-black">
                                                C$ {calc.grossSalary}
                                            </td>
                                            <td className="p-4 text-red-500">
                                                - C$ {calc.inssLaboral}
                                            </td>
                                            <td className="p-4 text-red-500">
                                                - C$ {calc.irDGI}
                                            </td>
                                            <td className="p-4 text-emerald-600 font-black text-sm">
                                                C$ {calc.netSalary}
                                            </td>
                                            <td className="p-4 text-indigo-700 text-[10px]">
                                                <p>INSS: C$ {calc.inssPatronal}</p>
                                                <p className="text-slate-400">INATEC: C$ {calc.inatecPatronal}</p>
                                            </td>
                                            <td className="p-4 text-center">
                                                <button 
                                                    onClick={() => handleOpenSeveranceForUser(u)} 
                                                    className="px-3 py-1.5 bg-indigo-50 hover:bg-indigo-600 hover:text-white text-indigo-700 rounded-xl font-black text-[9px] uppercase transition-all shadow-xs"
                                                >
                                                    Finiquito
                                                </button>
                                            </td>
                                        </tr>
                                    ))}
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            )}

            {/* MODAL CALENDARIO AUDITORÍA DE ASISTENCIA */}
            {calendarModalUser && (
                <div className="fixed inset-0 bg-slate-900/80 z-[140] flex items-center justify-center p-4 fade-in" onClick={() => setCalendarModalUser(null)}>
                    <div className="bg-white rounded-[3rem] w-full max-w-2xl p-6 sm:p-8 shadow-2xl space-y-5 border-t-[10px] border-indigo-600 max-h-[90vh] overflow-y-auto" onClick={e=>e.stopPropagation()}>
                        <div className="flex justify-between items-center border-b pb-3">
                            <div>
                                <h3 className="font-black text-xl text-slate-900">{calendarModalUser.user.name}</h3>
                                <p className="text-[10px] font-black uppercase text-slate-400 tracking-wider">
                                    Auditoría de Asistencia del Período ({startDate} al {endDate})
                                </p>
                            </div>
                            <button onClick={() => setCalendarModalUser(null)} className="p-2 bg-slate-50 rounded-full text-slate-400">
                                <svg className="w-5 h-5" fill="none" stroke="currentColor" strokeWidth="2" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" d="M6 18L18 6M6 6l12 12"/></svg>
                            </button>
                        </div>

                        <div className="grid grid-cols-2 sm:grid-cols-4 gap-2 text-center text-xs">
                            <div className="p-3 bg-emerald-50 text-emerald-800 rounded-2xl border border-emerald-200">
                                <span className="text-[9px] font-black uppercase block">Trabajados</span>
                                <strong className="text-lg">{calendarModalUser.calc.audit.workedDaysCount} d</strong>
                            </div>
                            <div className="p-3 bg-red-50 text-red-800 rounded-2xl border border-red-200">
                                <span className="text-[9px] font-black uppercase block">Faltas Injust.</span>
                                <strong className="text-lg">{calendarModalUser.calc.audit.unexcusedAbsenceCount} f (-{calendarModalUser.calc.audit.unexcusedAbsenceCount * 2}d)</strong>
                            </div>
                            <div className="p-3 bg-indigo-50 text-indigo-800 rounded-2xl border border-indigo-200">
                                <span className="text-[9px] font-black uppercase block">Días Libres</span>
                                <strong className="text-lg">{calendarModalUser.calc.audit.offDaysCount} d</strong>
                            </div>
                            <div className="p-3 bg-amber-50 text-amber-800 rounded-2xl border border-amber-200">
                                <span className="text-[9px] font-black uppercase block">Dobles / Feriados</span>
                                <strong className="text-lg">{calendarModalUser.calc.audit.holidayWorkedCount} d</strong>
                            </div>
                        </div>

                        <div className="space-y-2">
                            <h4 className="text-xs font-black uppercase text-slate-700 tracking-wider">Bitácora Día por Día</h4>
                            <div className="space-y-1.5 max-h-64 overflow-y-auto no-scrollbar">
                                {calendarModalUser.calc.audit.dayBreakdown.map((d, i) => (
                                    <div key={i} className={`p-3 rounded-2xl border flex items-center justify-between text-xs ${
                                        d.status === 'injustificada' ? 'bg-red-50/70 border-red-200' :
                                        d.status === 'doble' ? 'bg-amber-50 border-amber-200' :
                                        d.status === 'vacacion' ? 'bg-indigo-50 border-indigo-200' :
                                        d.status === 'descanso' ? 'bg-slate-50 border-slate-200 opacity-60' :
                                        'bg-white border-slate-200'
                                    }`}>
                                        <div>
                                            <span className="font-black text-slate-900">{window.formatDateToNIC(d.date)} ({d.dayCode.toUpperCase()})</span>
                                            <span className="text-[10px] text-slate-400 block">{d.label}</span>
                                        </div>
                                        <div className="text-right">
                                            <span className={`px-2 py-0.5 rounded-lg text-[9px] font-black uppercase ${
                                                d.status === 'injustificada' ? 'bg-red-600 text-white' :
                                                d.status === 'doble' ? 'bg-amber-500 text-white' :
                                                d.status === 'vacacion' ? 'bg-indigo-600 text-white' :
                                                d.status === 'descanso' ? 'bg-slate-200 text-slate-600' :
                                                'bg-emerald-100 text-emerald-800'
                                            }`}>
                                                {d.punchesCount > 0 ? `${d.punchesCount} Marcaje(s)` : d.status.toUpperCase()}
                                            </span>
                                        </div>
                                    </div>
                                ))}
                            </div>
                        </div>

                        <button onClick={() => setCalendarModalUser(null)} className="w-full py-3.5 bg-slate-100 text-slate-700 font-black rounded-2xl uppercase text-[10px]">
                            Cerrar
                        </button>
                    </div>
                </div>
            )}

            {/* PESTAÑA 2: MOTOR DE LIQUIDACIÓN / FINIQUITO */}
            {activeTab === 'severance' && (
                <div className="grid lg:grid-cols-3 gap-6">
                    <div className="bg-white p-8 rounded-[3rem] shadow-sm border border-slate-100 space-y-4 h-fit border-t-[12px] border-indigo-600">
                        <h3 className="font-black text-lg text-slate-900">Parámetros de Liquidación</h3>
                        <p className="text-xs text-slate-400 font-medium">Cálculo de Prestaciones Sociales según el Código del Trabajo de Nicaragua.</p>

                        <div>
                            <label className="text-[10px] font-black uppercase text-slate-400 block mb-1">Colaborador a Liquidar</label>
                            <select 
                                value={selectedSeveranceUser ? selectedSeveranceUser.id : ''} 
                                onChange={e => {
                                    const u = globalUsers.find(usr => Number(usr.id) === Number(e.target.value));
                                    handleOpenSeveranceForUser(u);
                                }} 
                                className="w-full p-3.5 bg-slate-50 border rounded-2xl font-bold text-xs"
                            >
                                <option value="">Selecciona colaborador...</option>
                                {globalUsers.map(u => (
                                    <option key={u.id} value={u.id}>{u.name} (Ingreso: {u.hiringDate})</option>
                                ))}
                            </select>
                        </div>

                        <div>
                            <label className="text-[10px] font-black uppercase text-slate-400 block mb-1">Causa de Retiro Laboral</label>
                            <select 
                                value={sevReason} 
                                onChange={e => setSevReason(e.target.value)} 
                                className="w-full p-3.5 bg-slate-50 border rounded-2xl font-bold text-xs text-indigo-700"
                            >
                                <option value="despido_sin_causa_art45">Despido Injustificado / Art. 45 (Aplica Indemnización)</option>
                                <option value="renuncia">Renuncia Voluntaria (Vacaciones + Aguinaldo)</option>
                                <option value="despido_con_causa">Despido Justificado / Art. 48 (Sin Indemnización)</option>
                            </select>
                        </div>

                        <div className="grid grid-cols-2 gap-3">
                            <div>
                                <label className="text-[9px] font-black uppercase text-slate-400 block mb-1">Último Día de Trabajo</label>
                                <input type="date" value={sevTermDate} onChange={e => setSevTermDate(e.target.value)} className="w-full p-3 bg-slate-50 border rounded-xl font-bold text-xs" />
                            </div>
                            <div>
                                <label className="text-[9px] font-black uppercase text-slate-400 block mb-1">Vacaciones Pendientes (Días)</label>
                                <input type="number" step="0.5" value={sevVacDaysPending} onChange={e => setSevVacDaysPending(e.target.value)} className="w-full p-3 bg-slate-50 border rounded-xl font-bold text-xs" />
                            </div>
                        </div>

                        <div>
                            <label className="text-[9px] font-black uppercase text-slate-400 block mb-1">Promedio Variables Últimos 6 Meses (C$)</label>
                            <input 
                                type="number" 
                                step="0.01" 
                                value={sevAvgVariable} 
                                onChange={e => setSevAvgVariable(e.target.value)} 
                                placeholder="0.00 (Si aplica salario variable)" 
                                className="w-full p-3 bg-slate-50 border rounded-xl font-bold text-xs" 
                            />
                            <span className="text-[8px] text-slate-400 mt-1 block">Deja en 0 si solo devengó salario básico fijo.</span>
                        </div>
                    </div>

                    <div className="lg:col-span-2 space-y-4">
                        {!selectedSeveranceUser || !severanceResult ? (
                            <div className="bg-white p-12 rounded-[3rem] text-center border border-slate-100 shadow-sm">
                                <p className="text-slate-400 font-bold text-xs">Selecciona un colaborador para calcular su finiquito legal.</p>
                            </div>
                        ) : (
                            <div className="bg-white p-8 rounded-[3rem] shadow-sm border border-slate-100 space-y-6">
                                <div className="flex justify-between items-start border-b pb-4">
                                    <div>
                                        <h3 className="font-black text-xl text-slate-900">{selectedSeveranceUser.name}</h3>
                                        <p className="text-[10px] text-slate-400 font-black uppercase tracking-widest mt-0.5">
                                            Ingreso: {window.formatDateToNIC(selectedSeveranceUser.hiringDate)} • Salida: {window.formatDateToNIC(sevTermDate)}
                                        </p>
                                        <p className="text-xs text-indigo-600 font-bold mt-1">Antigüedad Total: {severanceResult.yearsWorkedText} ({severanceResult.totalDaysWorked} días laborados)</p>
                                    </div>
                                    <button onClick={() => window.print()} className="px-4 py-2 bg-slate-900 text-white font-black rounded-xl text-[9px] uppercase shadow-sm">Imprimir Finiquito</button>
                                </div>

                                <div className="space-y-3 text-xs">
                                    <div className="p-4 bg-slate-50 rounded-2xl flex justify-between items-center">
                                        <div>
                                            <p className="font-black text-slate-800 uppercase">1. Vacaciones No Gozadas (Art. 76 CT)</p>
                                            <p className="text-[10px] text-slate-500 font-bold">{severanceResult.vacationDaysPending} días pendientes × C$ {severanceResult.dailyRate} (Deduce INSS e IR)</p>
                                        </div>
                                        <div className="text-right">
                                            <p className="font-black text-slate-900 text-sm">C$ {severanceResult.vacationGross}</p>
                                            <p className="text-[9px] text-red-500 font-bold">- C$ {severanceResult.vacationInssLaboral} (INSS) - C$ {severanceResult.vacationIR} (IR)</p>
                                        </div>
                                    </div>

                                    <div className="p-4 bg-slate-50 rounded-2xl flex justify-between items-center">
                                        <div>
                                            <p className="font-black text-slate-800 uppercase">2. Décimo Tercer Mes / Aguinaldo (Art. 93 CT)</p>
                                            <p className="text-[10px] text-emerald-600 font-bold">{severanceResult.aguinaldoDays} días proporcionales • Exento de INSS e IR</p>
                                        </div>
                                        <p className="font-black text-slate-900 text-sm">C$ {severanceResult.aguinaldoGross}</p>
                                    </div>

                                    <div className="p-4 bg-slate-50 rounded-2xl flex justify-between items-center">
                                        <div>
                                            <p className="font-black text-slate-800 uppercase">3. Indemnización por Antigüedad (Art. 45 CT)</p>
                                            <p className="text-[10px] text-slate-500 font-bold">
                                                {sevReason === 'despido_sin_causa_art45' ? '1 mes/año (1-3 años) + 20 días/año posterior (Tope 5 meses) • Exento' : 'No aplica por causa de retiro'}
                                            </p>
                                        </div>
                                        <p className="font-black text-slate-900 text-sm">C$ {severanceResult.indemnityGross}</p>
                                    </div>
                                </div>

                                <div className="p-6 bg-emerald-50 rounded-3xl border border-emerald-200 flex justify-between items-center">
                                    <div>
                                        <p className="text-[10px] font-black uppercase tracking-widest text-emerald-800">Total Neto a Entregar</p>
                                        <p className="text-xs text-emerald-600 font-bold mt-0.5">Bruto: C$ {severanceResult.totalGross} • Retenciones: C$ {severanceResult.totalDeductions}</p>
                                    </div>
                                    <h3 className="text-3xl font-black text-emerald-700">C$ {severanceResult.totalNetToPay}</h3>
                                </div>
                            </div>
                        )}
                    </div>
                </div>
            )}

            {/* PESTAÑA 3: CONFIGURACIÓN DE VENTANA DE CORTES */}
            {activeTab === 'cut_config' && (
                <div className="bg-white p-8 rounded-[3rem] shadow-sm border border-slate-100 max-w-2xl space-y-6">
                    <div>
                        <h3 className="text-xl font-black text-slate-900">Ventana de Cortes de Asistencia</h3>
                        <p className="text-slate-400 text-xs font-medium mt-1">Configura los días de corte en que el sistema consolida las asistencias, incidencias y extras para la planilla de tu empresa.</p>
                    </div>

                    <form onSubmit={handleSaveCutConfig} className="space-y-4">
                        <div className="p-5 bg-slate-50 rounded-2xl border space-y-3">
                            <h4 className="font-black text-xs uppercase text-indigo-700">Primera Quincena</h4>
                            <div className="grid grid-cols-2 gap-3">
                                <div>
                                    <label className="text-[9px] font-black uppercase text-slate-400 block mb-1">Día Inicio Corte</label>
                                    <input type="number" min="1" max="31" value={cutStartDayQ1} onChange={e => setCutStartDayQ1(e.target.value)} className="w-full p-3 bg-white border rounded-xl font-bold text-xs" />
                                </div>
                                <div>
                                    <label className="text-[9px] font-black uppercase text-slate-400 block mb-1">Día Fin Corte</label>
                                    <input type="number" min="1" max="31" value={cutEndDayQ1} onChange={e => setCutEndDayQ1(e.target.value)} className="w-full p-3 bg-white border rounded-xl font-bold text-xs" />
                                </div>
                            </div>
                        </div>

                        <div className="p-5 bg-slate-50 rounded-2xl border space-y-3">
                            <h4 className="font-black text-xs uppercase text-indigo-700">Segunda Quincena</h4>
                            <div className="grid grid-cols-2 gap-3">
                                <div>
                                    <label className="text-[9px] font-black uppercase text-slate-400 block mb-1">Día Inicio Corte</label>
                                    <input type="number" min="1" max="31" value={cutStartDayQ2} onChange={e => setCutStartDayQ2(e.target.value)} className="w-full p-3 bg-white border rounded-xl font-bold text-xs" />
                                </div>
                                <div>
                                    <label className="text-[9px] font-black uppercase text-slate-400 block mb-1">Día Fin Corte</label>
                                    <input type="number" min="1" max="31" value={cutEndDayQ2} onChange={e => setCutEndDayQ2(e.target.value)} className="w-full p-3 bg-white border rounded-xl font-bold text-xs" />
                                </div>
                            </div>
                        </div>

                        <button type="submit" disabled={isSavingConfig} className="px-8 py-4 bg-indigo-600 hover:bg-indigo-700 text-white font-black rounded-2xl uppercase tracking-widest text-[10px] shadow-lg">
                            {isSavingConfig ? "Guardando..." : "Guardar Ventana de Cortes"}
                        </button>
                    </form>
                </div>
            )}
        </div>
    );
};