const { useState, useEffect, useMemo } = React;

const ALL_DAYS = [
    { code: 'lun', label: 'Lunes' },
    { code: 'mar', label: 'Martes' },
    { code: 'mie', label: 'Miércoles' },
    { code: 'jue', label: 'Jueves' },
    { code: 'vie', label: 'Viernes' },
    { code: 'sab', label: 'Sábado' },
    { code: 'dom', label: 'Domingo' }
];

window.AdminPersonal = function({ globalUsers = [], roles = [], logs = [], handleUserSubmit, editingUser, setEditingUser, deleteUser, toggleLock, confirmAction, isReadOnly = false }) {
    const [showModal, setShowModal] = useState(false);
    const [searchTerm, setSearchTerm] = useState('');
    const [filterRole, setFilterRole] = useState('ALL');
    const [isSubmittingUser, setIsSubmittingUser] = useState(false); // BLOQUEO ANTI DOBLE CLIC

    // Horarios e Identidad
    const [selectedScheduleDays, setSelectedScheduleDays] = useState(['lun', 'mar', 'mie', 'jue', 'vie']);
    const [scheduleCustom, setScheduleCustom] = useState({});
    const [baseStart, setBaseStart] = useState('08:00');
    const [baseEnd, setBaseEnd] = useState('17:00');

    // INSS e Impuestos
    const [hasInss, setHasInss] = useState(false);
    const [inssNumber, setInssNumber] = useState('');
    const [appliesInss, setAppliesInss] = useState(true);
    const [appliesIr, setAppliesIr] = useState(true);
    const [gpsTracking, setGpsTracking] = useState(false);

    const [avatarBase64, setAvatarBase64] = useState('');
    const [avatarPreview, setAvatarPreview] = useState('');

    const isUserLockedToday = (user) => {
        const todayLogs = (logs || []).filter(l => Number(l.userId) === Number(user.id) && l.date === window.getNICDate());
        const hasSalida = todayLogs.some(l => l.type === 'salida');
        return Boolean(user.manualLock) || (hasSalida && !user.overrideCheckOut);
    };

    useEffect(() => {
        if (editingUser) {
            setSelectedScheduleDays(editingUser.scheduleDays || ['lun', 'mar', 'mie', 'jue', 'vie']);
            setScheduleCustom(editingUser.scheduleCustom || {});
            setBaseStart(editingUser.scheduleStart || '08:00');
            setBaseEnd(editingUser.scheduleEnd || '17:00');
            setHasInss(Boolean(editingUser.hasInss));
            setInssNumber(editingUser.inssNumber || '');
            setAppliesInss(editingUser.appliesInss !== undefined ? Boolean(editingUser.appliesInss) : true);
            setAppliesIr(editingUser.appliesIr !== undefined ? Boolean(editingUser.appliesIr) : true);
            setGpsTracking(Boolean(editingUser.gpsTrackingEnabled));
            setAvatarPreview(editingUser.avatarUrl || '');
            setAvatarBase64('');
            setIsSubmittingUser(false);
            setShowModal(true);
        } else {
            setSelectedScheduleDays(['lun', 'mar', 'mie', 'jue', 'vie']);
            setScheduleCustom({});
            setBaseStart('08:00');
            setBaseEnd('17:00');
            setHasInss(false);
            setInssNumber('');
            setAppliesInss(true);
            setAppliesIr(true);
            setGpsTracking(false);
            setAvatarPreview('');
            setAvatarBase64('');
            setIsSubmittingUser(false);
        }
    }, [editingUser]);

    const openNewUserModal = () => {
        if (isReadOnly) return alert("Modo supervisión: no tienes permisos para crear empleados.");
        setEditingUser(null);
        setSelectedScheduleDays(['lun', 'mar', 'mie', 'jue', 'vie']);
        setScheduleCustom({});
        setBaseStart('08:00');
        setBaseEnd('17:00');
        setHasInss(false);
        setInssNumber('');
        setAppliesInss(true);
        setAppliesIr(true);
        setGpsTracking(false);
        setAvatarPreview('');
        setAvatarBase64('');
        setIsSubmittingUser(false);
        setShowModal(true);
    };

    const closeModal = () => {
        if (isSubmittingUser) return; // Evitar cerrar mientras se procesa
        setEditingUser(null);
        setShowModal(false);
    };

    const handleAvatarFile = (e) => {
        const file = e.target.files[0];
        if (!file) return;
        const reader = new FileReader();
        reader.onload = (ev) => {
            setAvatarBase64(ev.target.result);
            setAvatarPreview(ev.target.result);
        };
        reader.readAsDataURL(file);
    };

    const handleToggleDay = (dayCode) => {
        setSelectedScheduleDays(prev => 
            prev.includes(dayCode) ? prev.filter(d => d !== dayCode) : [...prev, dayCode]
        );
    };

    const handleToggleCustomDay = (dayCode) => {
        setScheduleCustom(prev => {
            const copy = { ...prev };
            if (copy[dayCode]) {
                delete copy[dayCode];
            } else {
                copy[dayCode] = { start: '08:00', end: '12:00', isHalfDay: true };
            }
            return copy;
        });
    };

    const handleCustomDayChange = (dayCode, field, val) => {
        setScheduleCustom(prev => ({
            ...prev,
            [dayCode]: {
                ...prev[dayCode],
                [field]: val
            }
        }));
    };

    const dbRolesList = useMemo(() => {
        const roleSet = new Map();
        roleSet.set('propietario', 'PROPIETARIO / ADMIN');
        roleSet.set('empleado', 'EMPLEADO');

        (roles || []).forEach(r => {
            const rawName = (typeof r === 'object' ? r.name : r) || '';
            const key = rawName.toLowerCase().trim();
            if (key) {
                if (key.includes('propietario') || key.includes('admin') || key.includes('dueño')) {
                    roleSet.set('propietario', 'PROPIETARIO / ADMIN');
                } else if (key === 'empleado') {
                    roleSet.set('empleado', 'EMPLEADO');
                } else {
                    roleSet.set(key, rawName.toUpperCase());
                }
            }
        });
        return Array.from(roleSet.entries()).map(([key, label]) => ({ key, label }));
    }, [roles]);

    const filteredUsers = useMemo(() => {
        return (globalUsers || []).filter(u => {
            const matchText = (u.name || '').toLowerCase().includes(searchTerm.toLowerCase()) ||
                              (u.email || '').toLowerCase().includes(searchTerm.toLowerCase()) ||
                              (u.alias || '').toLowerCase().includes(searchTerm.toLowerCase());
            const userRoleKey = (u.role || u.role_name || '').toLowerCase().trim();
            const matchRole = filterRole === 'ALL' || userRoleKey === filterRole.toLowerCase().trim();
            return matchText && matchRole;
        });
    }, [globalUsers, searchTerm, filterRole]);

    const ownersAndAdmins = filteredUsers.filter(u => {
        const r = (u.role || u.role_name || '').toLowerCase().trim();
        return r === 'propietario' || r === 'admin' || r === 'dueño' || r === 'owner';
    });

    const regularEmployees = filteredUsers.filter(u => {
        const r = (u.role || u.role_name || '').toLowerCase().trim();
        return r !== 'propietario' && r !== 'admin' && r !== 'dueño' && r !== 'owner';
    });

    // Control seguro de envío con bloqueo de doble clic
    const onFormSubmit = async (e) => {
        e.preventDefault();
        if (isSubmittingUser) return;
        setIsSubmittingUser(true);

        try {
            await handleUserSubmit(e);
            closeModal();
        } catch (err) {
            console.error("Error al procesar usuario:", err);
        } finally {
            setIsSubmittingUser(false);
        }
    };

    const renderUserRowCard = (u, isOwner = false) => {
        const isLocked = isUserLockedToday(u);
        const activeDaysStr = (u.scheduleDays || []).join(', ').toUpperCase();
        const hasCustom = u.scheduleCustom && Object.keys(u.scheduleCustom).length > 0;

        return (
            <div 
                key={u.id} 
                className={`p-4 sm:p-5 rounded-3xl border transition-all duration-200 flex flex-col lg:flex-row items-start lg:items-center justify-between gap-4 relative overflow-hidden shadow-sm hover:shadow-md ${
                    isOwner 
                        ? 'bg-gradient-to-r from-indigo-50/90 via-white to-white border-indigo-100 hover:border-indigo-300' 
                        : 'bg-white border-slate-200/80 hover:border-slate-300'
                }`}
            >
                <div className={`absolute left-0 top-0 bottom-0 w-1.5 ${
                    u.status === 'activo' ? 'bg-emerald-500' : u.status === 'baja' ? 'bg-red-500' : 'bg-orange-500'
                }`}></div>

                <div className="flex items-center gap-3.5 min-w-[220px] pl-1">
                    {u.avatarUrl ? (
                        <img src={u.avatarUrl} alt={u.name} className="w-12 h-12 rounded-2xl object-cover border-2 border-white shadow-sm flex-shrink-0" />
                    ) : (
                        <div className={`w-12 h-12 rounded-2xl flex items-center justify-center font-black text-base shadow-sm flex-shrink-0 ${
                            isOwner ? 'bg-indigo-600 text-white' : 'bg-slate-100 text-slate-700'
                        }`}>
                            {u.name ? u.name[0].toUpperCase() : 'U'}
                        </div>
                    )}
                    <div className="overflow-hidden">
                        <div className="flex items-center gap-2">
                            <h4 className="font-black text-slate-900 text-sm truncate">{u.name}</h4>
                            {u.gpsTrackingEnabled ? (
                                <span className="w-2 h-2 rounded-full bg-emerald-500 animate-ping flex-shrink-0" title="GPS en Vivo Activo"></span>
                            ) : null}
                        </div>
                        <p className="text-[11px] text-slate-400 font-medium truncate">{u.email}</p>
                    </div>
                </div>

                <div className="flex flex-wrap items-center gap-2 sm:gap-3">
                    <span className="px-2.5 py-1 bg-slate-100 text-slate-600 rounded-xl text-[10px] font-black tracking-wider uppercase">
                        @{u.alias}
                    </span>
                    <span className={`px-2.5 py-1 rounded-xl text-[10px] font-black tracking-wider uppercase ${
                        isOwner ? 'bg-indigo-100 text-indigo-700 font-black' : 'bg-slate-100 text-slate-700 font-black'
                    }`}>
                        {u.role}
                    </span>
                    <span className="px-2.5 py-1 bg-emerald-50 text-emerald-700 border border-emerald-200/60 rounded-xl text-[10px] font-black">
                        C$ {parseFloat(u.baseSalary || 0).toLocaleString('en-US', { minimumFractionDigits: 2 })}
                    </span>
                    {u.hasInss && u.inssNumber ? (
                        <span className="px-2.5 py-1 bg-blue-50 text-blue-700 border border-blue-200/60 rounded-xl text-[10px] font-black" title="Número de Seguro Social">
                            INSS: {u.inssNumber}
                        </span>
                    ) : null}
                </div>

                <div className="text-[10px] text-slate-500 font-semibold bg-slate-50 px-3 py-1.5 rounded-xl border border-slate-100">
                    <span className="text-slate-400 uppercase tracking-widest block text-[8px] font-black">Jornada:</span>
                    <span>{activeDaysStr || 'SIN DÍAS'} ({u.scheduleStart || '08:00'} - {u.scheduleEnd || '17:00'})</span>
                    {hasCustom && <span className="ml-1 text-indigo-600 font-black">• Con Horario Especial</span>}
                </div>

                {!isReadOnly ? (
                    <div className="flex items-center gap-2 w-full lg:w-auto justify-end pt-2 lg:pt-0 border-t lg:border-t-0 border-slate-100">
                        <button 
                            onClick={() => setEditingUser(u)} 
                            className="p-2.5 bg-slate-50 hover:bg-indigo-50 text-slate-600 hover:text-indigo-600 rounded-xl border border-slate-200/80 transition-colors shadow-sm" 
                            title="Editar Empleado"
                        >
                            <svg className="w-4 h-4" fill="none" stroke="currentColor" strokeWidth="2" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"></path></svg>
                        </button>

                        <button 
                            onClick={() => confirmAction(`¿Estás seguro de eliminar a ${u.name}? Se perderán sus registros.`, () => deleteUser(u.id))} 
                            className="p-2.5 bg-slate-50 hover:bg-red-50 text-slate-400 hover:text-red-600 rounded-xl border border-slate-200/80 transition-colors shadow-sm" 
                            title="Eliminar Empleado"
                        >
                            <svg className="w-4 h-4" fill="none" stroke="currentColor" strokeWidth="2" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" d="M6 18L18 6M6 6l12 12"></path></svg>
                        </button>

                        {isLocked ? (
                            <button 
                                onClick={() => toggleLock(u, false)} 
                                className="px-3.5 py-2 bg-emerald-50 hover:bg-emerald-100 text-emerald-700 rounded-xl font-black uppercase text-[9px] tracking-wider transition-colors active:scale-95 flex-1 lg:flex-none text-center"
                            >
                                Desbloquear Acceso
                            </button>
                        ) : (
                            <button 
                                onClick={() => toggleLock(u, true)} 
                                className="px-3.5 py-2 bg-orange-50 hover:bg-orange-100 text-orange-700 rounded-xl font-black uppercase text-[9px] tracking-wider transition-colors active:scale-95 flex-1 lg:flex-none text-center"
                            >
                                Bloquear Acceso
                            </button>
                        )}
                    </div>
                ) : (
                    <div className="flex items-center gap-1.5 px-3 py-1 bg-slate-50 rounded-xl border border-slate-100 text-[9px] font-black uppercase text-slate-400">
                        <span>👁️ Inspección</span>
                    </div>
                )}
            </div>
        );
    };

    return (
        <div className="space-y-6 fade-in">
            <div className="bg-white p-6 sm:p-8 rounded-[3rem] shadow-sm border border-slate-100 space-y-4">
                <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
                    <div>
                        <h2 className="text-2xl font-black text-slate-900 tracking-tight">Personal y Horarios</h2>
                        <p className="text-slate-400 font-bold uppercase text-[10px] mt-0.5 tracking-widest">
                            Gestión de colaboradores, salarios, turnos y emisión de contratos
                        </p>
                    </div>
                    {!isReadOnly && (
                        <button 
                            onClick={openNewUserModal} 
                            className="px-6 py-3.5 bg-indigo-600 hover:bg-indigo-700 text-white font-black rounded-2xl uppercase tracking-widest text-[10px] flex items-center justify-center gap-2 shadow-lg active:scale-95 transition-all"
                        >
                            <svg className="w-4 h-4" fill="none" stroke="currentColor" strokeWidth="2.5" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" d="M12 4v16m8-8H4"></path></svg>
                            Nuevo Empleado
                        </button>
                    )}
                </div>

                <div className="flex flex-col sm:flex-row gap-3 pt-2">
                    <input 
                        type="text" 
                        value={searchTerm} 
                        onChange={e => setSearchTerm(e.target.value)} 
                        placeholder="Buscar por Nombre, Correo o Código (@)..." 
                        className="flex-1 p-3.5 bg-slate-50 border rounded-2xl font-bold outline-none text-xs focus:border-indigo-500 transition-colors" 
                    />
                    <select 
                        value={filterRole} 
                        onChange={e => setFilterRole(e.target.value)} 
                        className="p-3.5 bg-slate-50 border rounded-2xl font-bold text-xs uppercase outline-none focus:border-indigo-500 transition-colors sm:w-56"
                    >
                        <option value="ALL">TODOS LOS ROLES</option>
                        {dbRolesList.map(r => (
                            <option key={r.key} value={r.key}>{r.label}</option>
                        ))}
                    </select>
                </div>
            </div>

            {/* SECCIÓN 1: ADMINISTRACIÓN */}
            <div className="space-y-3">
                <h3 className="font-black text-xs uppercase tracking-widest text-slate-500 px-2">
                    Administración del Portal ({ownersAndAdmins.length})
                </h3>
                <div className="space-y-2.5">
                    {ownersAndAdmins.map(u => renderUserRowCard(u, true))}
                </div>
            </div>

            {/* SECCIÓN 2: PERSONAL */}
            <div className="space-y-3 pt-2">
                <h3 className="font-black text-xs uppercase tracking-widest text-slate-500 px-2">
                    Personal de Campo y Oficina ({regularEmployees.length})
                </h3>
                <div className="space-y-2.5">
                    {regularEmployees.map(u => renderUserRowCard(u, false))}
                </div>
            </div>

            {/* MODAL EDITAR FICHA DE EMPLEADO (PROTECCIÓN DOBLE CLIC + PLACEHOLDERS EN GRIS) */}
            {showModal && (
                <div className="fixed inset-0 bg-slate-900/60 z-[110] flex items-center justify-center p-4 fade-in" onClick={closeModal}>
                    <div className="bg-white rounded-[3rem] shadow-2xl max-w-6xl w-full max-h-[94vh] overflow-y-auto p-8 border-t-[12px] border-indigo-600" onClick={e => e.stopPropagation()}>
                        <div className="flex justify-between items-center mb-6 border-b border-slate-100 pb-4">
                            <div>
                                <h3 className="font-black text-2xl text-slate-900">{editingUser ? "Editar Ficha de Empleado" : "Alta de Nuevo Colaborador"}</h3>
                                <p className="text-slate-400 font-bold text-[10px] uppercase tracking-widest mt-1">Configuración de rol de acceso, permisos y datos laborales</p>
                            </div>
                            <button onClick={closeModal} disabled={isSubmittingUser} className="p-3 bg-slate-50 text-slate-400 hover:text-slate-600 rounded-full disabled:opacity-40">
                                <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"></path></svg>
                            </button>
                        </div>

                        <form onSubmit={onFormSubmit} className="space-y-6">
                            <div className="grid md:grid-cols-2 lg:grid-cols-4 gap-6">
                                
                                {/* COLUMNA 1: IDENTIDAD & PERSONAL */}
                                <div className="space-y-3.5">
                                    <h4 className="font-black text-[10px] uppercase text-indigo-600 tracking-widest border-b pb-2">1. Identidad & Personal</h4>
                                    
                                    <div className="flex items-center gap-3 bg-slate-50 p-2.5 rounded-2xl border">
                                        {avatarPreview ? (
                                            <img src={avatarPreview} className="w-11 h-11 rounded-xl object-cover border shadow-sm" />
                                        ) : (
                                            <div className="w-11 h-11 bg-indigo-100 text-indigo-600 font-black rounded-xl flex items-center justify-center text-base">
                                                {editingUser?.name ? editingUser.name[0] : '+'}
                                            </div>
                                        )}
                                        <div className="flex-1 overflow-hidden">
                                            <label className="text-[9px] font-black uppercase text-slate-400 block mb-1">Foto Perfil</label>
                                            <input type="file" accept="image/*" onChange={handleAvatarFile} className="text-[9px] text-slate-500 w-full file:mr-2 file:py-1 file:px-2 file:rounded-lg file:border-0 file:text-[8px] file:font-black file:bg-indigo-50 file:text-indigo-600 cursor-pointer" />
                                        </div>
                                    </div>
                                    <input type="hidden" name="avatar_base64" value={avatarBase64} />

                                    <div>
                                        <label className="text-[9px] font-black uppercase text-slate-400 block mb-1">Nombre Completo</label>
                                        <input name="name" defaultValue={editingUser?.name || ''} placeholder="Ej. Carlos Alberto Mendoza" className="w-full p-3 bg-slate-50 rounded-2xl font-bold outline-none border text-xs placeholder:text-slate-300" required />
                                    </div>
                                    <div>
                                        <label className="text-[9px] font-black uppercase text-slate-400 block mb-1">Cédula de Identidad</label>
                                        <input name="id_card" defaultValue={editingUser?.idCard || editingUser?.id_card || ''} placeholder="Ej. 001-150895-0004J" className="w-full p-3 bg-slate-50 rounded-2xl font-bold outline-none border text-xs placeholder:text-slate-300" />
                                    </div>

                                    {/* CAMPO DINÁMICO NÚMERO INSS */}
                                    <div className="p-3 bg-slate-50 rounded-2xl border space-y-2">
                                        <label className="flex items-center gap-2 text-[9px] font-black uppercase text-slate-700 cursor-pointer">
                                            <input 
                                                type="checkbox" 
                                                checked={hasInss} 
                                                onChange={e => setHasInss(e.target.checked)} 
                                                className="w-3.5 h-3.5 accent-indigo-600" 
                                            />
                                            <span>¿Posee Número INSS?</span>
                                        </label>
                                        <input type="hidden" name="hasInss" value={hasInss ? 1 : 0} />
                                        
                                        {hasInss && (
                                            <div>
                                                <label className="text-[8px] font-black uppercase text-indigo-600 block mb-1">Número de Seguro Social</label>
                                                <input 
                                                    name="inssNumber" 
                                                    value={inssNumber} 
                                                    onChange={e => setInssNumber(e.target.value)} 
                                                    placeholder="Ej. 1234567-8" 
                                                    className="w-full p-2 bg-white rounded-xl border text-xs font-bold outline-none focus:border-indigo-500 placeholder:text-slate-300" 
                                                    required={hasInss}
                                                />
                                            </div>
                                        )}
                                    </div>

                                    <div>
                                        <label className="text-[9px] font-black uppercase text-slate-400 block mb-1">Estado Civil</label>
                                        <select name="civil_status" defaultValue={editingUser?.civilStatus || 'Soltero(a)'} className="w-full p-3 bg-slate-50 rounded-2xl font-bold outline-none border text-xs">
                                            <option value="Soltero(a)">Soltero(a)</option>
                                            <option value="Casado(a)">Casado(a)</option>
                                            <option value="Unión de Hecho">Unión de Hecho</option>
                                        </select>
                                    </div>

                                    <div>
                                        <label className="text-[9px] font-black uppercase text-slate-400 block mb-1">Profesión u Oficio</label>
                                        <input name="profession" defaultValue={editingUser?.profession || ''} placeholder="Ej. Licenciado en Administración" className="w-full p-3 bg-slate-50 rounded-2xl font-bold outline-none border text-xs placeholder:text-slate-300" />
                                    </div>

                                    <div>
                                        <label className="text-[9px] font-black uppercase text-slate-400 block mb-1">Domicilio / Dirección</label>
                                        <input name="home_address" defaultValue={editingUser?.homeAddress || editingUser?.home_address || ''} placeholder="Ej. De la rotonda 2c al sur, Managua" className="w-full p-3 bg-slate-50 rounded-2xl font-bold outline-none border text-xs placeholder:text-slate-300" />
                                    </div>
                                </div>

                                {/* COLUMNA 2: JORNADA Y HORARIOS */}
                                <div className="space-y-3.5">
                                    <h4 className="font-black text-[10px] uppercase text-indigo-600 tracking-widest border-b pb-2">2. Jornada y Horarios</h4>
                                    
                                    <div className="grid grid-cols-2 gap-2 p-3 bg-slate-50 rounded-2xl border">
                                        <div>
                                            <label className="text-[8px] font-black uppercase text-slate-500 block">Entrada Regular</label>
                                            <input 
                                                type="time" 
                                                name="schedule_start" 
                                                value={baseStart} 
                                                onChange={e => setBaseStart(e.target.value)} 
                                                className="w-full p-2 bg-white rounded-xl font-bold text-xs border" 
                                            />
                                        </div>
                                        <div>
                                            <label className="text-[8px] font-black uppercase text-slate-500 block">Salida Regular</label>
                                            <input 
                                                type="time" 
                                                name="schedule_end" 
                                                value={baseEnd} 
                                                onChange={e => setBaseEnd(e.target.value)} 
                                                className="w-full p-2 bg-white rounded-xl font-bold text-xs border" 
                                            />
                                        </div>
                                    </div>

                                    <div className="space-y-2">
                                        <label className="text-[9px] font-black uppercase text-slate-400 block">Días Laborales y Horarios Especiales</label>
                                        <div className="space-y-1.5 max-h-[340px] overflow-y-auto pr-1">
                                            {ALL_DAYS.map(d => {
                                                const isActive = selectedScheduleDays.includes(d.code);
                                                const custom = scheduleCustom[d.code];

                                                return (
                                                    <div key={d.code} className={`p-2 rounded-2xl border transition-all flex flex-col gap-1.5 ${
                                                        isActive ? 'bg-slate-50 border-slate-200' : 'bg-slate-50/40 border-slate-100 opacity-60'
                                                    }`}>
                                                        <div className="flex items-center justify-between">
                                                            <button 
                                                                type="button" 
                                                                onClick={() => handleToggleDay(d.code)} 
                                                                className={`px-2.5 py-1 rounded-lg font-black text-[9px] uppercase transition-all ${
                                                                    isActive ? 'bg-indigo-600 text-white shadow-sm' : 'bg-slate-200 text-slate-500'
                                                                }`}
                                                            >
                                                                {d.label}
                                                            </button>
                                                            
                                                            {isActive && (
                                                                <button 
                                                                    type="button" 
                                                                    onClick={() => handleToggleCustomDay(d.code)} 
                                                                    className={`px-2 py-0.5 rounded-md text-[8px] font-black uppercase border transition-all ${
                                                                        custom ? 'bg-amber-100 text-amber-800 border-amber-300' : 'bg-white text-slate-600'
                                                                    }`}
                                                                >
                                                                    {custom ? 'Quitar Especial' : '+ Medio Día / Especial'}
                                                                </button>
                                                            )}
                                                        </div>

                                                        {isActive && custom && (
                                                            <div className="flex items-center justify-end gap-1 pt-1 border-t border-slate-200">
                                                                <input 
                                                                    type="time" 
                                                                    value={custom.start || '08:00'} 
                                                                    onChange={e => handleCustomDayChange(d.code, 'start', e.target.value)} 
                                                                    className="p-1 bg-white rounded-md text-[9px] font-bold border" 
                                                                />
                                                                <span className="text-slate-400 text-xs">-</span>
                                                                <input 
                                                                    type="time" 
                                                                    value={custom.end || '12:00'} 
                                                                    onChange={e => handleCustomDayChange(d.code, 'end', e.target.value)} 
                                                                    className="p-1 bg-white rounded-md text-[9px] font-bold border" 
                                                                />
                                                            </div>
                                                        )}
                                                    </div>
                                                );
                                            })}
                                        </div>

                                        <input type="hidden" name="scheduleDays" value={JSON.stringify(selectedScheduleDays)} />
                                        <input type="hidden" name="scheduleCustom" value={JSON.stringify(scheduleCustom)} />
                                    </div>
                                </div>

                                {/* COLUMNA 3: CONTRATO Y SALARIO */}
                                <div className="space-y-3.5">
                                    <h4 className="font-black text-[10px] uppercase text-emerald-600 tracking-widest border-b pb-2">3. Contrato y Salario</h4>
                                    
                                    <div>
                                        <label className="text-[9px] font-black uppercase text-slate-500 block mb-1">Rol de Acceso (Permisos de Sistema)</label>
                                        <select 
                                            name="role" 
                                            defaultValue={
                                                ['propietario', 'admin', 'dueño', 'owner'].includes((editingUser?.role || editingUser?.role_name || '').toLowerCase()) 
                                                    ? 'propietario' 
                                                    : (editingUser?.role || editingUser?.role_name || 'empleado').toLowerCase()
                                            } 
                                            className="w-full p-3 bg-slate-50 rounded-2xl font-bold uppercase outline-none text-xs text-indigo-700 border border-slate-200"
                                        >
                                            {dbRolesList.map(r => (
                                                <option key={r.key} value={r.key}>{r.label}</option>
                                            ))}
                                        </select>
                                    </div>

                                    <div>
                                        <label className="text-[9px] font-black uppercase text-slate-400 block mb-1">Cargo / Puesto Nominal (Contrato)</label>
                                        <input name="position_title" defaultValue={editingUser?.positionTitle || editingUser?.position_title || ''} placeholder="Ej. Asesor de Ventas" className="w-full p-3 bg-slate-50 border rounded-2xl font-bold text-xs outline-none placeholder:text-slate-300" />
                                    </div>

                                    <div>
                                        <label className="text-[9px] font-black uppercase text-slate-400 block mb-1">Salario Base Mensual (C$)</label>
                                        <input name="base_salary" type="number" step="0.01" defaultValue={editingUser ? (editingUser.baseSalary || 0) : ''} placeholder="Ej. 10000.00" className="w-full p-3 bg-emerald-50 rounded-2xl font-black text-emerald-700 outline-none text-xs border border-emerald-200 placeholder:text-emerald-300" />
                                    </div>

                                    <div>
                                        <label className="text-[9px] font-black uppercase text-slate-400 block mb-1">Modalidad de Pago</label>
                                        <select name="payment_frequency" defaultValue={editingUser?.paymentFrequency || 'Quincenal'} className="w-full p-3 bg-slate-50 border rounded-2xl font-bold text-xs outline-none">
                                            <option value="Quincenal">Quincenal (15 y 30)</option>
                                            <option value="Mensual">Mensual</option>
                                            <option value="Semanal">Semanal</option>
                                        </select>
                                    </div>

                                    {/* DEDUCCIONES DE LEY */}
                                    <div className="p-3 bg-slate-50 rounded-2xl border space-y-2 pt-2">
                                        <label className="flex items-center gap-2 text-[9px] font-black uppercase text-slate-700 cursor-pointer">
                                            <input 
                                                type="checkbox" 
                                                name="applies_inss" 
                                                checked={appliesInss} 
                                                onChange={e => setAppliesInss(e.target.checked)} 
                                                className="w-3.5 h-3.5 accent-emerald-600 rounded" 
                                            />
                                            <span>Deducir INSS (7%)</span>
                                        </label>

                                        <label className="flex items-center gap-2 text-[9px] font-black uppercase text-slate-700 cursor-pointer">
                                            <input 
                                                type="checkbox" 
                                                name="applies_ir" 
                                                checked={appliesIr} 
                                                onChange={e => setAppliesIr(e.target.checked)} 
                                                className="w-3.5 h-3.5 accent-emerald-600 rounded" 
                                            />
                                            <span>Deducir IR DGI (Ley 822)</span>
                                        </label>
                                    </div>
                                </div>

                                {/* COLUMNA 4: ACCESO Y CAMPO */}
                                <div className="space-y-3.5">
                                    <h4 className="font-black text-[10px] uppercase text-indigo-600 tracking-widest border-b pb-2">4. Acceso y Campo</h4>
                                    
                                    <div>
                                        <label className="text-[9px] font-black uppercase text-slate-400 block mb-1">Código / Alias (Login)</label>
                                        <input name="alias" defaultValue={editingUser?.alias || ''} placeholder="Ej. cmendoza" className="w-full p-3 bg-slate-50 border rounded-2xl font-bold text-xs placeholder:text-slate-300" required />
                                    </div>

                                    <div>
                                        <label className="text-[9px] font-black uppercase text-slate-400 block mb-1">Correo de Acceso</label>
                                        <input name="email" defaultValue={editingUser?.email || ''} type="email" placeholder="Ej. colaborador@empresa.com" className="w-full p-3 bg-slate-50 border rounded-2xl font-bold text-xs placeholder:text-slate-300" required />
                                    </div>

                                    <div>
                                        <label className="text-[9px] font-black uppercase text-slate-400 block mb-1">PIN / Clave</label>
                                        <input name="pass" defaultValue="" placeholder={editingUser ? "•••••••• (Sin cambios)" : "Ingresa contraseña o PIN"} className="w-full p-3 bg-slate-50 border rounded-2xl font-bold text-xs placeholder:text-slate-300" required={!editingUser} />
                                    </div>

                                    <div>
                                        <label className="text-[9px] font-black uppercase text-slate-400 block mb-1">Fecha de Ingreso</label>
                                        <input name="date" type="date" defaultValue={editingUser?.hiringDate || editingUser?.hiring_date || window.getNICDate()} className="w-full p-3 bg-slate-50 border rounded-2xl font-bold text-xs" />
                                    </div>

                                    <div>
                                        <label className="text-[9px] font-black uppercase text-slate-400 block mb-1">Días de Vacaciones Usados (Manual)</label>
                                        <input name="vused" type="number" step="0.5" defaultValue={editingUser?.vacationDaysUsed || 0} className="w-full p-3 bg-slate-50 border rounded-2xl font-bold text-xs" />
                                    </div>

                                    <div className="p-3 bg-indigo-50/60 rounded-2xl border border-indigo-100">
                                        <label className="flex items-center gap-2 text-[9px] font-black uppercase text-indigo-900 cursor-pointer">
                                            <input 
                                                type="checkbox" 
                                                name="gps_tracking_enabled" 
                                                checked={gpsTracking} 
                                                onChange={e => setGpsTracking(e.target.checked)} 
                                                className="w-3.5 h-3.5 accent-indigo-600 rounded" 
                                            />
                                            <span>Rastreo GPS en Vivo (Campo)</span>
                                        </label>
                                    </div>
                                </div>

                            </div>

                            <div className="flex gap-4 pt-4 border-t">
                                <button type="button" onClick={closeModal} disabled={isSubmittingUser} className="flex-1 py-4 bg-slate-100 text-slate-600 rounded-2xl font-black uppercase text-[10px] disabled:opacity-50">
                                    Cancelar
                                </button>
                                <button 
                                    type="submit" 
                                    disabled={isSubmittingUser} 
                                    className="flex-1 py-4 bg-indigo-600 hover:bg-indigo-700 text-white font-black rounded-2xl uppercase tracking-widest shadow-xl text-[10px] active:scale-95 transition-all disabled:opacity-60 flex items-center justify-center gap-2"
                                >
                                    {isSubmittingUser ? (
                                        <React.Fragment>
                                            <div className="w-4 h-4 border-2 border-white border-t-transparent rounded-full animate-spin"></div>
                                            <span>Guardando Colaborador...</span>
                                        </React.Fragment>
                                    ) : (
                                        editingUser ? "Actualizar Colaborador" : "Guardar Colaborador"
                                    )}
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
            )}
        </div>
    );
};