const { useState, useEffect, useRef, useMemo } = React;

window.AdminContratos = function({ globalUsers = [], settings = {}, currentUser, isMaster = false, isReadOnly = false, refreshData, showToast }) {
    const [subTab, setSubTab] = useState('emit'); // 'emit', 'templates', 'modalities', 'history', 'employer_data'
    const [contracts, setContracts] = useState([]);
    const [dbTemplates, setDbTemplates] = useState([]);
    const [modalities, setModalities] = useState([]);
    
    const [selectedUser, setSelectedUser] = useState(null);
    const [selectedTemplateId, setSelectedTemplateId] = useState('');
    const [selectedModalityCode, setSelectedModalityCode] = useState('indeterminado');
    const [previewContract, setPreviewContract] = useState(null);
    
    // Modal de Emisión / Edición WYSIWYG
    const [showEditorModal, setShowEditorModal] = useState(false);
    const [editingContractId, setEditingContractId] = useState(null);
    const [isSavingContract, setIsSavingContract] = useState(false);
    
    // Modal de Gestión de Plantillas
    const [showTemplateModal, setShowTemplateModal] = useState(false);
    const [editingTemplate, setEditingTemplate] = useState(null);
    const [templateTitle, setTemplateTitle] = useState('');
    const [templateType, setTemplateType] = useState('indeterminado');
    const [isEditingMasterGlobal, setIsEditingMasterGlobal] = useState(false);
    const [previewTemplateItem, setPreviewTemplateItem] = useState(null);

    // Modal de Eliminación Segura de Expediente con PIN/Clave
    const [deleteTargetContract, setDeleteTargetContract] = useState(null);
    const [securityPass, setSecurityPass] = useState('');
    const [isDeletingContract, setIsDeletingContract] = useState(false);

    // Modal de Modalidades Personalizables
    const [showModalityModal, setShowModalityModal] = useState(false);
    const [editingModality, setEditingModality] = useState(null);

    // Datos del Empleador
    const [companyName, setCompanyName] = useState(settings?.companyName || window.SHIFT_CONFIG?.companyName || '');
    const [rucNumber, setRucNumber] = useState(settings?.rucNumber || settings?.ruc_number || '');
    const [ownerName, setOwnerName] = useState(settings?.ownerName || settings?.owner_name || '');
    const [legalRepId, setLegalRepId] = useState(settings?.legalRepId || settings?.legal_rep_id || '');
    const [ownerCivilStatus, setOwnerCivilStatus] = useState(settings?.ownerCivilStatus || 'Casado(a)');
    const [businessAddress, setBusinessAddress] = useState(settings?.businessAddress || settings?.business_address || '');
    const [municipality, setMunicipality] = useState(settings?.municipality || 'Managua');

    const isFormLoadedRef = useRef(false);
    const editorRef = useRef(null);
    const templateEditorRef = useRef(null);

    const companyRegime = settings?.taxRegime || settings?.tax_regime || 'cuota_fija';
    const isCuotaFija = companyRegime === 'cuota_fija';

    useEffect(() => {
        if (!isFormLoadedRef.current && settings && Object.keys(settings).length > 0) {
            setCompanyName(settings?.companyName || window.SHIFT_CONFIG?.companyName || '');
            setRucNumber(settings?.rucNumber || settings?.ruc_number || '');
            setOwnerName(settings?.ownerName || settings?.owner_name || '');
            setLegalRepId(settings?.legalRepId || settings?.legal_rep_id || '');
            setOwnerCivilStatus(settings?.ownerCivilStatus || 'Casado(a)');
            setBusinessAddress(settings?.businessAddress || settings?.business_address || '');
            setMunicipality(settings?.municipality || 'Managua');
            isFormLoadedRef.current = true;
        }
    }, [settings]);

    const loadAllData = async () => {
        try {
            const [resCont, resTpl, resMod] = await Promise.all([
                window.apiCall('get_contracts', {}),
                window.apiCall('get_contract_templates', {}),
                window.apiCall('get_contract_modalities', {})
            ]);

            if (resCont && resCont.success) {
                setContracts(resCont.contracts || []);
            }

            if (resTpl && resTpl.success) {
                const list = resTpl.templates || [];
                setDbTemplates(list);
            }

            if (resMod && resMod.success) {
                const modOpts = resMod.modalities || [];
                setModalities(modOpts);
                if (modOpts.length > 0 && !selectedModalityCode) {
                    setSelectedModalityCode(modOpts[0].code || 'indeterminado');
                }
            }
        } catch (err) {
            console.error("Error al cargar datos de contratos:", err);
        }
    };

    useEffect(() => {
        loadAllData();
    }, []);

    // 1. Plantillas filtradas para esta empresa por régimen
    const availableTemplates = useMemo(() => {
        return dbTemplates.filter(t => t.tax_regime === companyRegime || isMaster);
    }, [dbTemplates, companyRegime, isMaster]);

    // 2. Plantillas filtradas ESTRICTAMENTE por la Modalidad Activa seleccionada
    const templatesBySelectedModality = useMemo(() => {
        return availableTemplates.filter(t => {
            const tCode = (t.contract_type || 'indeterminado').toLowerCase().trim();
            const mCode = (selectedModalityCode || 'indeterminado').toLowerCase().trim();
            return tCode === mCode;
        });
    }, [availableTemplates, selectedModalityCode]);

    // Sincronizar selectedTemplateId cuando cambia la modalidad
    useEffect(() => {
        if (templatesBySelectedModality.length > 0) {
            const exists = templatesBySelectedModality.some(t => String(t.id) === String(selectedTemplateId));
            if (!exists) {
                setSelectedTemplateId(String(templatesBySelectedModality[0].id));
            }
        } else {
            setSelectedTemplateId('');
        }
    }, [templatesBySelectedModality, selectedModalityCode]);

    const numeroALetrasCordobas = (num) => {
        const valor = parseFloat(num) || 0;
        return `${valor.toLocaleString('es-NI', { minimumFractionDigits: 2 })} CÓRDOBAS NETOS`;
    };

    // Obtener la plantilla activa
    const getActiveTemplateHtml = (tplId = null) => {
        const targetId = tplId || selectedTemplateId;
        const found = dbTemplates.find(t => String(t.id) === String(targetId));
        if (found && found.template_html) return found.template_html;
        if (templatesBySelectedModality.length > 0) return templatesBySelectedModality[0].template_html;
        return `<h2>CONTRATO INDIVIDUAL DE TRABAJO</h2><p>Contrato entre {{EMPRESA_NOMBRE}} y {{EMPLEADO_NOMBRE}}.</p>`;
    };

    // Compilar e inyectar variables de forma limpia
    const compileContractHtml = (user, customTplId = null, customModalityCode = null) => {
        let tpl = getActiveTemplateHtml(customTplId);
        const salary = parseFloat(user?.baseSalary || 0).toFixed(2);
        const days = Array.isArray(user?.scheduleDays) ? user.scheduleDays.join(', ').toUpperCase() : 'LUNES A VIERNES';
        const sabadoSchedule = user?.saturdaySchedule ? `${user?.saturdayScheduleStart || '08:00'} a ${user?.saturdayScheduleEnd || '12:00'}` : '';

        const empName = ownerName || window.SHIFT_CONFIG?.contactName || 'REPRESENTANTE LEGAL';
        const empRuc = rucNumber || 'J0000000000000';
        const empBizName = companyName || window.SHIFT_CONFIG?.companyName || 'EMPRESA CONTRATANTE';
        const empCedula = legalRepId || '000-000000-0000A';
        const empDir = businessAddress || 'Sede Comercial de la Empresa';
        const empMuni = municipality || 'Managua';

        const modCode = customModalityCode || selectedModalityCode || 'indeterminado';
        const modObj = modalities.find(m => m.code === modCode);
        const modalityLabel = modObj ? modObj.name : 'Tiempo Indeterminado';

        const variables = {
            '{{EMPRESA_NOMBRE}}': empBizName,
            '{{EMPRESA_RUC}}': empRuc,
            '{{EMPRESA_DIRECCION}}': empDir,
            '{{REPRESENTANTE_NOMBRE}}': empName,
            '{{REPRESENTANTE_CEDULA}}': empCedula,
            '{{REPRESENTANTE_ESTADO_CIVIL}}': ownerCivilStatus,
            '{{LUGAR_TRABAJO}}': empDir,
            '{{MUNICIPIO}}': empMuni,
            '{{FECHA_HOY}}': window.formatDateToNIC(window.getNICDate()),
            '{{EMPLEADO_NOMBRE}}': user?.name || 'NOMBRE DEL COLABORADOR',
            '{{EMPLEADO_CEDULA}}': user?.idCard || user?.id_card || '000-000000-0000X',
            '{{EMPLEADO_ESTADO_CIVIL}}': user?.civilStatus || user?.civil_status || 'Soltero(a)',
            '{{EMPLEADO_PROFESION}}': user?.profession || 'Trabajador(a)',
            '{{EMPLEADO_DIRECCION}}': user?.homeAddress || user?.home_address || 'Managua, Nicaragua',
            '{{EMPLEADO_CARGO}}': (user?.positionTitle || user?.position_title || user?.role || 'Colaborador').toUpperCase(),
            '{{SALARIO_NUMEROS}}': salary,
            '{{SALARIO_LETRAS}}': numeroALetrasCordobas(salary),
            '{{FORMA_PAGO}}': (user?.paymentFrequency || user?.payment_frequency || 'Quincenal').toUpperCase(),
            '{{DIAS_TRABAJO}}': days,
            '{{HORARIO_TRABAJO}}': `${user?.scheduleStart || '08:00'} a ${user?.scheduleEnd || '17:00'}`,
            '{{HORARIO_SABADO}}': sabadoSchedule,
            '{{FECHA_INGRESO}}': window.formatDateToNIC(user?.hiringDate || user?.hiring_date || window.getNICDate()),
            '{{MODALIDAD_CONTRATO}}': modalityLabel
        };

        Object.keys(variables).forEach(k => {
            tpl = tpl.split(k).join(variables[k]);
        });

        return tpl;
    };

    const handleGenerateContract = (u) => {
        if (templatesBySelectedModality.length === 0) {
            const modObj = modalities.find(m => m.code === selectedModalityCode);
            alert(`⚠️ No hay ninguna plantilla registrada para la modalidad "${modObj?.name || selectedModalityCode}".\n\nPor favor ve a la pestaña "Plantillas", crea o duplica una plantilla y asígnala a esta modalidad.`);
            return;
        }

        setSelectedUser(u);
        setEditingContractId(null);
        const compiled = compileContractHtml(u, selectedTemplateId, selectedModalityCode);
        setShowEditorModal(true);
        setTimeout(() => {
            if (editorRef.current) editorRef.current.innerHTML = compiled;
        }, 100);
    };

    const handleOpenEditExistingContract = (cnt) => {
        const linkedUser = globalUsers.find(u => Number(u.id) === Number(cnt.user_id)) || {
            name: cnt.employee_name,
            positionTitle: cnt.position_title
        };
        setSelectedUser(linkedUser);
        setEditingContractId(cnt.id);
        setShowEditorModal(true);
        setTimeout(() => {
            if (editorRef.current) editorRef.current.innerHTML = cnt.contract_html;
        }, 100);
    };

    const handleLiveTemplateChange = (tplId, modCode) => {
        setSelectedTemplateId(tplId);
        setSelectedModalityCode(modCode);
        if (selectedUser && editorRef.current) {
            const compiled = compileContractHtml(selectedUser, tplId, modCode);
            editorRef.current.innerHTML = compiled;
        }
    };

    const handleInsertVariable = (variableTag, isTemplate = false) => {
        const targetRef = isTemplate ? templateEditorRef : editorRef;
        if (!targetRef.current) return;
        
        if (isTemplate) {
            document.execCommand('insertText', false, variableTag);
        } else {
            const tempUser = selectedUser || {};
            const salary = parseFloat(tempUser.baseSalary || 0).toFixed(2);
            const modObj = modalities.find(m => m.code === selectedModalityCode);
            const modalityLabel = modObj ? modObj.name : 'Tiempo Indeterminado';

            const map = {
                '{{EMPRESA_NOMBRE}}': companyName || 'EMPRESA CONTRATANTE',
                '{{EMPRESA_RUC}}': rucNumber || 'J0000000000000',
                '{{REPRESENTANTE_NOMBRE}}': ownerName || 'REPRESENTANTE LEGAL',
                '{{REPRESENTANTE_CEDULA}}': legalRepId || '000-000000-0000A',
                '{{REPRESENTANTE_ESTADO_CIVIL}}': ownerCivilStatus,
                '{{EMPRESA_DIRECCION}}': businessAddress || 'Sede Central',
                '{{MUNICIPIO}}': municipality || 'Managua',
                '{{EMPLEADO_NOMBRE}}': tempUser.name || 'NOMBRE DEL COLABORADOR',
                '{{EMPLEADO_CEDULA}}': tempUser.idCard || tempUser.id_card || '000-000000-0000X',
                '{{EMPLEADO_ESTADO_CIVIL}}': tempUser.civilStatus || 'Soltero(a)',
                '{{EMPLEADO_PROFESION}}': tempUser.profession || 'Trabajador(a)',
                '{{EMPLEADO_DIRECCION}}': tempUser.homeAddress || 'Managua, Nicaragua',
                '{{EMPLEADO_CARGO}}': (tempUser.positionTitle || tempUser.role || 'Colaborador').toUpperCase(),
                '{{SALARIO_NUMEROS}}': salary,
                '{{SALARIO_LETRAS}}': numeroALetrasCordobas(salary),
                '{{FORMA_PAGO}}': (tempUser.paymentFrequency || 'Quincenal').toUpperCase(),
                '{{FECHA_INGRESO}}': window.formatDateToNIC(tempUser.hiringDate || window.getNICDate()),
                '{{FECHA_HOY}}': window.formatDateToNIC(window.getNICDate()),
                '{{MODALIDAD_CONTRATO}}': modalityLabel
            };
            document.execCommand('insertText', false, map[variableTag] || variableTag);
        }
    };

    const handleSaveAndPrintContract = async () => {
        const htmlContent = editorRef.current ? editorRef.current.innerHTML : '';
        if (!htmlContent.trim()) return showToast("El contrato no puede estar vacío.");

        setIsSavingContract(true);
        const payload = {
            id: editingContractId,
            userId: selectedUser ? selectedUser.id : null,
            employeeName: selectedUser ? selectedUser.name : 'Contrato Emitido',
            positionTitle: selectedUser ? (selectedUser.positionTitle || selectedUser.role || 'General') : 'General',
            taxRegime: companyRegime,
            contractHtml: htmlContent
        };

        const res = await window.apiCall('save_contract_document', payload);
        setIsSavingContract(false);
        if (res && res.success) {
            showToast("Contrato guardado en el expediente exitosamente.");
            setShowEditorModal(false);
            loadAllData();
            if (refreshData) await refreshData();
            handlePrintClean(htmlContent, selectedUser?.name);
        } else {
            showToast("Error al guardar contrato.");
        }
    };

    // ELIMINACIÓN SEGURA CON PIN O CLAVE
    const handleExecuteSecureDelete = async () => {
        if (!securityPass.trim()) {
            return alert("Debes ingresar tu contraseña o PIN para autorizar la eliminación.");
        }
        setIsDeletingContract(true);
        try {
            const res = await window.apiCall('delete_contract_secure', {
                id: deleteTargetContract.id,
                password: securityPass,
                userId: currentUser?.id
            });

            if (res && res.success) {
                showToast("Expediente eliminado con éxito.");
                setDeleteTargetContract(null);
                setSecurityPass('');
                loadAllData();
            } else {
                alert(res?.error || "Contraseña o PIN incorrecto.");
            }
        } catch (e) {
            alert("Error al eliminar expediente: " + e.message);
        } finally {
            setIsDeletingContract(false);
        }
    };

    // CRUD PLANTILLAS
    const handleOpenCreateTemplate = () => {
        setEditingTemplate(null);
        setTemplateTitle('Nueva Plantilla de Contrato');
        setTemplateType(selectedModalityCode || 'indeterminado');
        setIsEditingMasterGlobal(false);
        setShowTemplateModal(true);
        setTimeout(() => {
            if (templateEditorRef.current) {
                templateEditorRef.current.innerHTML = getActiveTemplateHtml();
            }
        }, 100);
    };

    const handleOpenEditTemplate = (tpl) => {
        setEditingTemplate(tpl);
        setTemplateTitle(tpl.title);
        setTemplateType(tpl.contract_type || 'indeterminado');
        setIsEditingMasterGlobal(Number(tpl.client_id) === 0);
        setShowTemplateModal(true);
        setTimeout(() => {
            if (templateEditorRef.current) {
                templateEditorRef.current.innerHTML = tpl.template_html;
            }
        }, 100);
    };

    const handleDuplicateTemplate = (tpl) => {
        setEditingTemplate(null);
        setTemplateTitle(`${tpl.title} (Copia Personalizada)`);
        setTemplateType(tpl.contract_type || 'indeterminado');
        setIsEditingMasterGlobal(false);
        setShowTemplateModal(true);
        setTimeout(() => {
            if (templateEditorRef.current) {
                templateEditorRef.current.innerHTML = tpl.template_html;
            }
        }, 100);
    };

    const handleSaveTemplateToDB = async () => {
        const htmlContent = templateEditorRef.current ? templateEditorRef.current.innerHTML : '';
        if (!htmlContent.trim()) return showToast("La plantilla no puede estar vacía.");

        const payload = {
            id: editingTemplate ? editingTemplate.id : null,
            templateKey: `${companyRegime}_${templateType}_${Date.now()}`,
            title: templateTitle,
            taxRegime: companyRegime,
            contractType: templateType,
            templateHtml: htmlContent,
            isMasterGlobal: isEditingMasterGlobal && isMaster
        };

        const res = await window.apiCall('save_contract_template', payload);
        if (res && res.success) {
            showToast("Plantilla guardada en base de datos.");
            setShowTemplateModal(false);
            loadAllData();
        } else {
            showToast("Error al guardar plantilla.");
        }
    };

    const handleDeleteTemplate = async (tplId) => {
        if (!confirm("¿Deseas eliminar esta plantilla personalizada?")) return;
        const res = await window.apiCall('delete_contract_template', { id: tplId });
        if (res && res.success) {
            showToast("Plantilla eliminada.");
            loadAllData();
        }
    };

    // CRUD MODALIDADES
    const handleSaveModality = async (e) => {
        e.preventDefault();
        const fd = new FormData(e.target);
        const name = fd.get('name');
        const code = fd.get('code');
        try {
            const res = await window.apiCall('save_contract_modality', {
                id: editingModality?.id,
                name,
                code,
                isMasterGlobal: isMaster
            });
            if (res && res.success) {
                showToast("Modalidad guardada.");
                setShowModalityModal(false);
                setEditingModality(null);
                loadAllData();
            }
        } catch (err) {
            alert("Error: " + err.message);
        }
    };

    const handleDeleteModality = async (id) => {
        if (!confirm("¿Deseas eliminar esta modalidad?")) return;
        try {
            const res = await window.apiCall('delete_contract_modality', { id });
            if (res && res.success) {
                showToast("Modalidad eliminada.");
                loadAllData();
            }
        } catch (e) {
            alert("Error: " + e.message);
        }
    };

    // DATOS FISCALES DEL EMPLEADOR
    const handleSaveEmployerData = async (e) => {
        e.preventDefault();
        const payload = {
            company_name: companyName,
            tax_regime: companyRegime,
            ruc_number: rucNumber,
            owner_name: ownerName,
            legal_rep_id: legalRepId,
            business_address: businessAddress,
            municipality: municipality
        };

        const res = await window.apiCall('save_employer_tax_data', payload);
        if (res && res.success) {
            if (window.SHIFT_CONFIG) {
                window.SHIFT_CONFIG.companyName = companyName;
            }
            showToast("Datos fiscales actualizados y sincronizados con éxito.");
            if (refreshData) await refreshData();
        } else {
            showToast("Error: " + (res?.error || "No se pudo sincronizar"));
        }
    };

    // IMPRESIÓN LIMPIA MEDIANTE IFRAME
    const handlePrintClean = (htmlContent, docTitle = 'Contrato') => {
        const iframe = document.createElement('iframe');
        iframe.style.position = 'fixed';
        iframe.style.right = '0';
        iframe.style.bottom = '0';
        iframe.style.width = '0';
        iframe.style.height = '0';
        iframe.style.border = '0';
        document.body.appendChild(iframe);

        const doc = iframe.contentWindow.document;
        doc.open();
        doc.write(`
            <!DOCTYPE html>
            <html>
                <head>
                    <title>${docTitle}</title>
                    <style>
                        @page { size: letter portrait; margin: 15mm; }
                        body { font-family: Arial, Helvetica, sans-serif; line-height: 1.6; color: #111; font-size: 11pt; margin: 0; padding: 0; }
                        table { width: 100%; border-collapse: collapse; }
                    </style>
                </head>
                <body>
                    ${htmlContent}
                </body>
            </html>
        `);
        doc.close();

        iframe.contentWindow.focus();
        setTimeout(() => {
            iframe.contentWindow.print();
            setTimeout(() => document.body.removeChild(iframe), 1000);
        }, 300);
    };

    return (
        <div className="space-y-6 fade-in">
            {/* BARRA SUPERIOR DE SUB-PESTAÑAS */}
            <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">Contratos Individuales de Trabajo</h2>
                    <p className="text-slate-400 font-bold uppercase text-[10px] mt-0.5 tracking-widest">
                        Régimen Asignado: <span className="text-indigo-600 font-black uppercase">{isCuotaFija ? 'Cuota Fija (Persona Natural)' : 'Régimen General'}</span>
                    </p>
                </div>

                <div className="flex flex-wrap items-center gap-2">
                    <div className="flex bg-slate-100 p-1.5 rounded-2xl border">
                        <button onClick={() => setSubTab('emit')} className={`px-4 py-2 rounded-xl text-xs font-black uppercase tracking-wider transition-all ${subTab === 'emit' ? 'bg-white text-indigo-600 shadow-sm' : 'text-slate-500'}`}>Emitir</button>
                        <button onClick={() => setSubTab('templates')} className={`px-4 py-2 rounded-xl text-xs font-black uppercase tracking-wider transition-all ${subTab === 'templates' ? 'bg-white text-indigo-600 shadow-sm' : 'text-slate-500'}`}>Plantillas ({availableTemplates.length})</button>
                        <button onClick={() => setSubTab('modalidades')} className={`px-4 py-2 rounded-xl text-xs font-black uppercase tracking-wider transition-all ${subTab === 'modalidades' ? 'bg-white text-indigo-600 shadow-sm' : 'text-slate-500'}`}>Modalidades ({modalities.length})</button>
                        <button onClick={() => setSubTab('history')} className={`px-4 py-2 rounded-xl text-xs font-black uppercase tracking-wider transition-all ${subTab === 'history' ? 'bg-white text-indigo-600 shadow-sm' : 'text-slate-500'}`}>Expedientes ({contracts.length})</button>
                        <button onClick={() => setSubTab('employer_data')} className={`px-4 py-2 rounded-xl text-xs font-black uppercase tracking-wider transition-all ${subTab === 'employer_data' ? 'bg-white text-indigo-600 shadow-sm' : 'text-slate-500'}`}>Datos Empleador</button>
                    </div>

                    {!isReadOnly && (
                        <button 
                            onClick={handleOpenCreateTemplate}
                            className="px-5 py-3.5 bg-emerald-600 hover:bg-emerald-700 text-white rounded-2xl font-black uppercase text-[10px] tracking-widest shadow-md active:scale-95 transition-all flex items-center gap-1.5"
                        >
                            <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>
                            + Nueva Plantilla
                        </button>
                    )}
                </div>
            </div>

            {/* SUB-PESTAÑA 1: EMITIR CONTRATOS A COLABORADORES */}
            {subTab === 'emit' && (
                <div className="bg-white p-8 rounded-[3rem] shadow-sm border border-slate-100 space-y-5">
                    <div className="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-3 border-b pb-4">
                        <div>
                            <h3 className="text-sm font-black text-slate-900 uppercase tracking-wider">Colaboradores en Nómina</h3>
                            <p className="text-slate-400 text-xs font-medium">Selecciona la modalidad para filtrar las plantillas disponibles y emitir el contrato</p>
                        </div>
                        <div className="flex flex-wrap items-center gap-3">
                            {/* SELECTOR DE MODALIDAD (FILTRO PRINCIPAL) */}
                            <div className="flex items-center gap-2">
                                <span className="text-[10px] font-black uppercase text-slate-400">Modalidad:</span>
                                <select 
                                    value={selectedModalityCode} 
                                    onChange={e => setSelectedModalityCode(e.target.value)} 
                                    className="p-2.5 bg-slate-50 border rounded-xl font-bold text-xs outline-none focus:border-emerald-500 max-w-[200px]"
                                >
                                    {modalities.map(m => (
                                        <option key={m.id} value={m.code}>{m.name}</option>
                                    ))}
                                </select>
                            </div>

                            {/* SELECTOR DE PLANTILLA (FILTRADA POR LA MODALIDAD) */}
                            <div className="flex items-center gap-2">
                                <span className="text-[10px] font-black uppercase text-slate-400">Plantilla:</span>
                                <select 
                                    value={selectedTemplateId} 
                                    onChange={e => setSelectedTemplateId(e.target.value)} 
                                    disabled={templatesBySelectedModality.length === 0}
                                    className={`p-2.5 bg-slate-50 border rounded-xl font-bold text-xs outline-none focus:border-indigo-500 max-w-[260px] ${
                                        templatesBySelectedModality.length === 0 ? 'text-red-500 bg-red-50 border-red-200 cursor-not-allowed' : 'text-slate-800'
                                    }`}
                                >
                                    {templatesBySelectedModality.length === 0 ? (
                                        <option value="">⚠️ Sin plantillas para esta modalidad</option>
                                    ) : (
                                        templatesBySelectedModality.map(t => (
                                            <option key={t.id} value={t.id}>
                                                {Number(t.client_id) === 0 ? '❖ [MASTER] ' : '★ [EMPRESA] '} {t.title}
                                            </option>
                                        ))
                                    )}
                                </select>
                            </div>
                        </div>
                    </div>

                    <div className="grid md:grid-cols-2 lg:grid-cols-3 gap-4">
                        {globalUsers.map(u => (
                            <div key={u.id} className="p-5 rounded-3xl border bg-slate-50/50 hover:bg-white hover:border-indigo-300 shadow-sm flex justify-between items-center gap-3 transition-all">
                                <div className="overflow-hidden">
                                    <h4 className="font-black text-slate-900 text-sm truncate">{u.name}</h4>
                                    <p className="text-[10px] text-slate-400 font-bold uppercase">@{u.alias} • {u.positionTitle || u.role}</p>
                                    <p className="text-[10px] text-emerald-600 font-black mt-1">C$ {parseFloat(u.baseSalary || 0).toLocaleString('en-US', { minimumFractionDigits: 2 })}</p>
                                </div>
                                <button 
                                    onClick={() => handleGenerateContract(u)} 
                                    className="px-4 py-2.5 bg-indigo-600 hover:bg-indigo-700 text-white rounded-xl text-[9px] font-black uppercase tracking-widest shadow-md active:scale-95 transition-all whitespace-nowrap"
                                >
                                    Emitir
                                </button>
                            </div>
                        ))}
                    </div>
                </div>
            )}

            {/* SUB-PESTAÑA 2: GESTOR DE PLANTILLAS */}
            {subTab === 'templates' && (
                <div className="bg-white p-8 rounded-[3rem] shadow-sm border border-slate-100 space-y-4">
                    <div className="flex justify-between items-center border-b pb-4">
                        <div>
                            <h3 className="text-sm font-black text-slate-900 uppercase tracking-wider">Plantillas Guardadas en Base de Datos</h3>
                            <p className="text-slate-400 text-xs font-medium">Cada plantilla está vinculada a una modalidad de contrato y al régimen de la empresa.</p>
                        </div>
                    </div>

                    <div className="grid md:grid-cols-2 lg:grid-cols-3 gap-4">
                        {availableTemplates.map(t => {
                            const isMasterTpl = Number(t.client_id) === 0;
                            const modObj = modalities.find(m => m.code === t.contract_type);
                            const modLabel = modObj ? modObj.name : (t.contract_type || 'Indeterminado');

                            return (
                                <div key={t.id} className="p-6 rounded-3xl border bg-slate-50 flex flex-col justify-between space-y-4 hover:border-indigo-200 transition-all">
                                    <div>
                                        <div className="flex justify-between items-start mb-2">
                                            <span className={`px-2.5 py-1 rounded-lg text-[8px] font-black uppercase tracking-wider ${isMasterTpl ? 'bg-purple-100 text-purple-700' : 'bg-emerald-100 text-emerald-700'}`}>
                                                {isMasterTpl ? 'Plantilla Máster Global' : 'Personalizada de Empresa'}
                                            </span>
                                            <span className="text-[9px] font-black uppercase text-indigo-600 bg-indigo-50 px-2 py-0.5 rounded-md border border-indigo-100">{modLabel}</span>
                                        </div>
                                        <h4 className="font-black text-slate-900 text-base">{t.title}</h4>
                                        <p className="text-[10px] text-slate-500 font-medium mt-1">Régimen: {t.tax_regime.toUpperCase()}</p>
                                    </div>
                                    <div className="flex items-center gap-2 pt-2 border-t border-slate-200">
                                        <button onClick={() => setPreviewTemplateItem(t)} className="flex-1 py-2.5 bg-indigo-50 hover:bg-indigo-100 text-indigo-700 rounded-xl text-[9px] font-black uppercase border border-indigo-200 shadow-sm">Vista Previa</button>
                                        
                                        {!isReadOnly && (
                                            <button onClick={() => handleDuplicateTemplate(t)} className="flex-1 py-2.5 bg-white hover:bg-slate-100 text-slate-700 rounded-xl text-[9px] font-black uppercase border shadow-sm">Duplicar</button>
                                        )}

                                        {!isReadOnly && (isMaster || !isMasterTpl) && (
                                            <button onClick={() => handleOpenEditTemplate(t)} className="p-2.5 bg-indigo-50 hover:bg-indigo-100 text-indigo-700 rounded-xl" title="Editar">
                                                <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>
                                        )}
                                        
                                        {!isReadOnly && !isMasterTpl && (
                                            <button onClick={() => handleDeleteTemplate(t.id)} className="p-2.5 bg-red-50 hover:bg-red-100 text-red-600 rounded-xl" title="Eliminar">
                                                <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>
                                        )}
                                    </div>
                                </div>
                            );
                        })}
                    </div>
                </div>
            )}

            {/* SUB-PESTAÑA 3: MODALIDADES PERSONALIZABLES */}
            {subTab === 'modalidades' && (
                <div className="bg-white p-8 rounded-[3rem] shadow-sm border border-slate-100 space-y-4">
                    <div className="flex justify-between items-center border-b pb-4">
                        <div>
                            <h3 className="text-sm font-black text-slate-900 uppercase tracking-wider">Modalidades de Contratación</h3>
                            <p className="text-slate-400 text-xs font-medium">Configura las modalidades disponibles para los contratos de tu empresa.</p>
                        </div>
                        {!isReadOnly && (
                            <button 
                                onClick={() => { setEditingModality(null); setShowModalityModal(true); }} 
                                className="px-4 py-2.5 bg-indigo-600 hover:bg-indigo-700 text-white font-black rounded-2xl uppercase tracking-wider text-[10px] shadow-sm"
                            >
                                + Nueva Modalidad
                            </button>
                        )}
                    </div>

                    <div className="grid md:grid-cols-2 lg:grid-cols-3 gap-4">
                        {modalities.map(m => (
                            <div key={m.id} className="p-5 rounded-3xl border bg-slate-50 flex items-center justify-between">
                                <div>
                                    <h4 className="font-black text-sm text-slate-900">{m.name}</h4>
                                    <p className="text-[10px] text-slate-400 font-bold uppercase tracking-wider mt-0.5">Código: {m.code}</p>
                                </div>
                                {!isReadOnly && (
                                    <div className="flex items-center gap-1.5">
                                        <button 
                                            onClick={() => { setEditingModality(m); setShowModalityModal(true); }} 
                                            className="p-2 bg-white hover:bg-indigo-50 text-slate-600 rounded-xl border"
                                            title="Editar Modalidad"
                                        >
                                            <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>
                                        {m.code !== 'indeterminado' && (
                                            <button 
                                                onClick={() => handleDeleteModality(m.id)} 
                                                className="p-2 bg-white hover:bg-red-50 text-red-500 rounded-xl border"
                                                title="Eliminar Modalidad"
                                            >
                                                <svg className="w-4 h-4" fill="none" stroke="currentColor" strokeWidth="2" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"></path></svg>
                                            </button>
                                        )}
                                    </div>
                                )}
                            </div>
                        ))}
                    </div>
                </div>
            )}

            {/* SUB-PESTAÑA 4: EXPEDIENTES / HISTORIAL */}
            {subTab === 'history' && (
                <div className="bg-white p-8 rounded-[3rem] shadow-sm border border-slate-100 space-y-4">
                    <h3 className="text-sm font-black text-slate-900 uppercase tracking-wider">Expedientes Guardados en Servidor</h3>
                    {contracts.length === 0 ? (
                        <p className="text-center py-8 text-slate-400 font-bold text-xs">No hay contratos guardados aún.</p>
                    ) : (
                        <div className="space-y-3">
                            {contracts.map(c => (
                                <div key={c.id} className="p-5 rounded-3xl border bg-slate-50 flex flex-col md:flex-row justify-between items-start md:items-center gap-4 hover:border-indigo-200 transition-all">
                                    <div>
                                        <h4 className="font-black text-slate-900 text-sm">{c.employee_name}</h4>
                                        <p className="text-[10px] text-slate-500 font-bold uppercase mt-0.5">
                                            {c.position_title} • Régimen: <span className="text-indigo-600 font-black">{c.tax_regime ? c.tax_regime.toUpperCase() : 'GENERAL'}</span>
                                        </p>
                                        <p className="text-[9px] text-slate-400 mt-1">Guardado: {window.formatNICTimeFull ? window.formatNICTimeFull(c.created_at) : new Date(Number(c.created_at)).toLocaleString()}</p>
                                    </div>
                                    <div className="flex items-center gap-2">
                                        <button onClick={() => setPreviewContract(c)} className="px-3.5 py-2 bg-white text-slate-700 rounded-xl border text-[10px] font-black uppercase shadow-sm">Ver</button>
                                        
                                        {!isReadOnly && (
                                            <button onClick={() => handleOpenEditExistingContract(c)} className="px-3.5 py-2 bg-indigo-50 text-indigo-700 hover:bg-indigo-100 rounded-xl border border-indigo-200 text-[10px] font-black uppercase shadow-sm">Editar</button>
                                        )}

                                        <button onClick={() => handlePrintClean(c.contract_html, c.employee_name)} className="px-3.5 py-2 bg-emerald-600 hover:bg-emerald-700 text-white rounded-xl text-[10px] font-black uppercase shadow-sm">Descargar PDF</button>

                                        {!isReadOnly && (
                                            <button 
                                                onClick={() => { setDeleteTargetContract(c); setSecurityPass(''); }} 
                                                className="p-2 bg-red-50 hover:bg-red-100 text-red-600 rounded-xl border border-red-200" 
                                                title="Eliminar Expediente con PIN"
                                            >
                                                <svg className="w-4 h-4" fill="none" stroke="currentColor" strokeWidth="2" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"></path></svg>
                                            </button>
                                        )}
                                    </div>
                                </div>
                            ))}
                        </div>
                    )}
                </div>
            )}

            {/* SUB-PESTAÑA 5: DATOS DEL NEGOCIO / EMPLEADOR */}
            {subTab === 'employer_data' && (
                <div className="bg-white p-8 rounded-[3rem] shadow-sm border border-slate-100 max-w-4xl space-y-6">
                    <div>
                        <h3 className="text-xl font-black text-slate-900">Datos Fiscales del Empleador (Negocio)</h3>
                        <p className="text-slate-400 text-xs font-medium mt-1">Estos datos alimentan automáticamente las cláusulas legales de todos los contratos.</p>
                    </div>

                    <form onSubmit={handleSaveEmployerData} className="space-y-4">
                        <div className="grid md:grid-cols-2 gap-4">
                            <div>
                                <label className="text-[10px] font-black uppercase text-slate-400 ml-2 mb-1 block">Razón Social / Nombre Negocio</label>
                                <input value={companyName} onChange={e=>setCompanyName(e.target.value)} disabled={isReadOnly} className="w-full p-3.5 bg-slate-50 border rounded-2xl font-bold text-xs outline-none disabled:opacity-60" required />
                            </div>
                            <div>
                                <label className="text-[10px] font-black uppercase text-slate-400 ml-2 mb-1 block">Número RUC</label>
                                <input value={rucNumber} onChange={e=>setRucNumber(e.target.value)} disabled={isReadOnly} placeholder="J0310000000001" className="w-full p-3.5 bg-slate-50 border rounded-2xl font-bold text-xs outline-none disabled:opacity-60" required />
                            </div>
                            <div>
                                <label className="text-[10px] font-black uppercase text-slate-400 ml-2 mb-1 block">Nombre del Propietario / Rep. Legal</label>
                                <input value={ownerName} onChange={e=>setOwnerName(e.target.value)} disabled={isReadOnly} placeholder="Nombre del representante" className="w-full p-3.5 bg-slate-50 border rounded-2xl font-bold text-xs outline-none disabled:opacity-60" required />
                            </div>
                            <div>
                                <label className="text-[10px] font-black uppercase text-slate-400 ml-2 mb-1 block">Cédula del Representante</label>
                                <input value={legalRepId} onChange={e=>setLegalRepId(e.target.value)} disabled={isReadOnly} placeholder="001-000000-0000A" className="w-full p-3.5 bg-slate-50 border rounded-2xl font-bold text-xs outline-none disabled:opacity-60" required />
                            </div>
                            <div>
                                <label className="text-[10px] font-black uppercase text-slate-400 ml-2 mb-1 block">Estado Civil del Representante</label>
                                <select value={ownerCivilStatus} onChange={e=>setOwnerCivilStatus(e.target.value)} disabled={isReadOnly} className="w-full p-3.5 bg-slate-50 border rounded-2xl font-bold text-xs outline-none disabled:opacity-60">
                                    <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-[10px] font-black uppercase text-slate-400 ml-2 mb-1 block">Municipio / Departamento</label>
                                <input value={municipality} onChange={e=>setMunicipality(e.target.value)} disabled={isReadOnly} placeholder="Managua" className="w-full p-3.5 bg-slate-50 border rounded-2xl font-bold text-xs outline-none disabled:opacity-60" required />
                            </div>
                            <div className="md:col-span-2">
                                <label className="text-[10px] font-black uppercase text-slate-400 ml-2 mb-1 block">Dirección Comercial Completa (Sede de Trabajo)</label>
                                <input value={businessAddress} onChange={e=>setBusinessAddress(e.target.value)} disabled={isReadOnly} placeholder="Dirección exacta del negocio..." className="w-full p-3.5 bg-slate-50 border rounded-2xl font-bold text-xs outline-none disabled:opacity-60" required />
                            </div>
                        </div>

                        {!isReadOnly && (
                            <button type="submit" 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 active:scale-95 transition-all">
                                Guardar y Sincronizar Datos
                            </button>
                        )}
                    </form>
                </div>
            )}

            {/* MODAL EDITOR VISUAL WYSIWYG AUTORRELLENADO CON SELECTORES EN VIVO */}
            {showEditorModal && (
                <div className="fixed inset-0 bg-slate-900/70 z-[120] flex items-center justify-center p-4 fade-in">
                    <div className="bg-white rounded-[3rem] w-full max-w-6xl max-h-[94vh] flex flex-col overflow-hidden shadow-2xl border-t-[12px] border-indigo-600">
                        <div className="p-6 border-b flex flex-col md:flex-row justify-between items-start md:items-center gap-4 bg-white">
                            <div>
                                <h3 className="text-xl font-black text-slate-900">Emisión de Contrato: {selectedUser?.name}</h3>
                                <p className="text-[10px] font-black text-slate-400 uppercase tracking-widest mt-0.5">Todos los datos han sido autocompletados. Cambia la modalidad o plantilla para ver los cambios.</p>
                            </div>

                            <div className="flex flex-wrap items-center gap-2.5">
                                <div className="flex items-center gap-1.5">
                                    <span className="text-[9px] font-black uppercase text-slate-400">Modalidad:</span>
                                    <select 
                                        value={selectedModalityCode} 
                                        onChange={e => handleLiveTemplateChange(selectedTemplateId, e.target.value)}
                                        className="p-2 bg-slate-50 border rounded-xl font-bold text-xs outline-none text-emerald-700 max-w-[180px]"
                                    >
                                        {modalities.map(m => <option key={m.id} value={m.code}>{m.name}</option>)}
                                    </select>
                                </div>

                                <div className="flex items-center gap-1.5">
                                    <span className="text-[9px] font-black uppercase text-slate-400">Plantilla:</span>
                                    <select 
                                        value={selectedTemplateId} 
                                        onChange={e => handleLiveTemplateChange(e.target.value, selectedModalityCode)}
                                        disabled={templatesBySelectedModality.length === 0}
                                        className={`p-2 bg-slate-50 border rounded-xl font-bold text-xs outline-none max-w-[220px] ${
                                            templatesBySelectedModality.length === 0 ? 'text-red-500 bg-red-50 border-red-200' : 'text-indigo-700'
                                        }`}
                                    >
                                        {templatesBySelectedModality.length === 0 ? (
                                            <option value="">⚠️ Sin plantillas</option>
                                        ) : (
                                            templatesBySelectedModality.map(t => <option key={t.id} value={t.id}>{t.title}</option>)
                                        )}
                                    </select>
                                </div>

                                <button onClick={() => setShowEditorModal(false)} className="p-2.5 bg-slate-50 text-slate-400 hover:text-slate-600 rounded-full">
                                    <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>
                        </div>

                        <div className="flex-1 flex flex-col lg:flex-row overflow-hidden">
                            <div className="flex-1 p-6 overflow-y-auto bg-slate-50">
                                <div className="flex gap-2 mb-3 bg-white p-2 rounded-2xl border shadow-sm">
                                    <button type="button" onClick={() => document.execCommand('bold')} className="px-3 py-1 bg-slate-100 rounded-lg font-black text-xs">B</button>
                                    <button type="button" onClick={() => document.execCommand('italic')} className="px-3 py-1 bg-slate-100 rounded-lg italic text-xs">I</button>
                                    <button type="button" onClick={() => document.execCommand('underline')} className="px-3 py-1 bg-slate-100 rounded-lg underline text-xs">U</button>
                                    <button type="button" onClick={() => document.execCommand('justifyLeft')} className="px-3 py-1 bg-slate-100 rounded-lg text-xs">Izq</button>
                                    <button type="button" onClick={() => document.execCommand('justifyCenter')} className="px-3 py-1 bg-slate-100 rounded-lg text-xs">Centrado</button>
                                    <button type="button" onClick={() => document.execCommand('justifyFull')} className="px-3 py-1 bg-slate-100 rounded-lg text-xs">Justificado</button>
                                </div>
                                <div 
                                    ref={editorRef} 
                                    contentEditable={!isReadOnly} 
                                    className="bg-white p-8 sm:p-12 rounded-2xl border min-h-[500px] outline-none shadow-sm font-serif leading-relaxed text-sm focus:ring-2 focus:ring-indigo-100"
                                />
                            </div>

                            <div className="w-full lg:w-80 p-6 bg-white border-l overflow-y-auto space-y-6">
                                <div>
                                    <h4 className="font-black text-xs uppercase text-indigo-600 tracking-wider mb-2">Datos del Empleador</h4>
                                    <div className="flex flex-wrap gap-1.5">
                                        {[
                                            { label: 'Nombre Negocio', tag: '{{EMPRESA_NOMBRE}}' },
                                            { label: 'RUC', tag: '{{EMPRESA_RUC}}' },
                                            { label: 'Representante', tag: '{{REPRESENTANTE_NOMBRE}}' },
                                            { label: 'Cédula Rep.', tag: '{{REPRESENTANTE_CEDULA}}' },
                                            { label: 'Dirección Comercial', tag: '{{EMPRESA_DIRECCION}}' },
                                            { label: 'Municipio', tag: '{{MUNICIPIO}}' }
                                        ].map(v => (
                                            <button key={v.tag} type="button" onClick={() => handleInsertVariable(v.tag)} className="px-2.5 py-1.5 bg-indigo-50 hover:bg-indigo-100 text-indigo-700 rounded-xl text-[10px] font-bold transition-colors">+ {v.label}</button>
                                        ))}
                                    </div>
                                </div>

                                <div>
                                    <h4 className="font-black text-xs uppercase text-emerald-600 tracking-wider mb-2">Datos del Colaborador</h4>
                                    <div className="flex flex-wrap gap-1.5">
                                        {[
                                            { label: 'Nombre Completo', tag: '{{EMPLEADO_NOMBRE}}' },
                                            { label: 'Cédula', tag: '{{EMPLEADO_CEDULA}}' },
                                            { label: 'Estado Civil', tag: '{{EMPLEADO_ESTADO_CIVIL}}' },
                                            { label: 'Profesión', tag: '{{EMPLEADO_PROFESION}}' },
                                            { label: 'Domicilio', tag: '{{EMPLEADO_DIRECCION}}' },
                                            { label: 'Cargo', tag: '{{EMPLEADO_CARGO}}' },
                                            { label: 'Salario (Números)', tag: '{{SALARIO_NUMEROS}}' },
                                            { label: 'Salario (Letras)', tag: '{{SALARIO_LETRAS}}' },
                                            { label: 'Frecuencia Pago', tag: '{{FORMA_PAGO}}' },
                                            { label: 'Fecha Ingreso', tag: '{{FECHA_INGRESO}}' },
                                            { label: 'Fecha Hoy', tag: '{{FECHA_HOY}}' },
                                            { label: 'Modalidad', tag: '{{MODALIDAD_CONTRATO}}' }
                                        ].map(v => (
                                            <button key={v.tag} type="button" onClick={() => handleInsertVariable(v.tag)} className="px-2.5 py-1.5 bg-emerald-50 hover:bg-emerald-100 text-emerald-700 rounded-xl text-[10px] font-bold transition-colors">+ {v.label}</button>
                                        ))}
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div className="p-6 border-t bg-slate-50 flex justify-end gap-3">
                            <button onClick={() => setShowEditorModal(false)} className="px-6 py-3.5 bg-white border rounded-2xl font-black uppercase text-[10px] text-slate-600">Cancelar</button>
                            <button 
                                onClick={handleSaveAndPrintContract} 
                                disabled={isSavingContract}
                                className="px-8 py-3.5 bg-indigo-600 hover:bg-indigo-700 text-white rounded-2xl font-black uppercase text-[10px] shadow-lg flex items-center gap-2"
                            >
                                <svg className="w-4 h-4" fill="none" stroke="currentColor" strokeWidth="2" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" d="M17 17h2a2 2 0 002-2v-4a2 2 0 00-2-2H5a2 2 0 00-2 2v4a2 2 0 002 2h2m2 4h6a2 2 0 002-2v-4a2 2 0 00-2-2H9a2 2 0 00-2 2v4a2 2 0 002 2zm8-12V5a2 2 0 00-2-2H9a2 2 0 00-2 2v4h10z"></path></svg>
                                {isSavingContract ? "Guardando..." : "Guardar en Servidor y Descargar PDF"}
                            </button>
                        </div>
                    </div>
                </div>
            )}

            {/* MODAL GESTIÓN DE PLANTILLAS */}
            {showTemplateModal && (
                <div className="fixed inset-0 bg-slate-900/70 z-[125] flex items-center justify-center p-4 fade-in">
                    <div className="bg-white rounded-[3rem] w-full max-w-6xl max-h-[94vh] flex flex-col overflow-hidden shadow-2xl border-t-[12px] border-emerald-500">
                        <div className="p-6 border-b flex justify-between items-center bg-white">
                            <div>
                                <h3 className="text-xl font-black text-slate-900">{editingTemplate ? `Editar: ${templateTitle}` : 'Nueva Plantilla de Contrato'}</h3>
                                <p className="text-[10px] font-black text-slate-400 uppercase tracking-widest mt-0.5">
                                    {isEditingMasterGlobal ? 'Guardará la Plantilla Máster Global (client_id = 0)' : 'Guardará una Plantilla Personalizada para tu Empresa'}
                                </p>
                            </div>
                            <button onClick={() => setShowTemplateModal(false)} className="p-3 bg-slate-50 text-slate-400 hover:text-slate-600 rounded-full">
                                <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>

                        <div className="flex-1 flex flex-col lg:flex-row overflow-hidden">
                            <div className="flex-1 p-6 overflow-y-auto bg-slate-50">
                                <div className="grid grid-cols-2 gap-3 mb-3">
                                    <div>
                                        <label className="text-[10px] font-black uppercase text-slate-400 block mb-1">Nombre de la Plantilla</label>
                                        <input value={templateTitle} onChange={e=>setTemplateTitle(e.target.value)} className="w-full p-3 bg-white border rounded-xl font-bold text-xs outline-none" required />
                                    </div>
                                    <div>
                                        <label className="text-[10px] font-black uppercase text-slate-400 block mb-1">Modalidad Vinculada</label>
                                        <select value={templateType} onChange={e=>setTemplateType(e.target.value)} className="w-full p-3 bg-white border rounded-xl font-bold text-xs outline-none uppercase">
                                            {modalities.map(m => (
                                                <option key={m.id} value={m.code}>{m.name}</option>
                                            ))}
                                        </select>
                                    </div>
                                </div>
                                <div 
                                    ref={templateEditorRef} 
                                    contentEditable={true} 
                                    className="bg-white p-8 rounded-2xl border min-h-[500px] outline-none shadow-sm font-serif leading-relaxed text-sm"
                                />
                            </div>

                            <div className="w-full lg:w-80 p-6 bg-white border-l overflow-y-auto space-y-4">
                                <h4 className="font-black text-xs uppercase text-indigo-600 tracking-wider">Variables Dinámicas</h4>
                                <div className="flex flex-wrap gap-1.5">
                                    {[
                                        '{{EMPRESA_NOMBRE}}', '{{EMPRESA_RUC}}', '{{REPRESENTANTE_NOMBRE}}', '{{REPRESENTANTE_CEDULA}}', '{{REPRESENTANTE_ESTADO_CIVIL}}', '{{EMPRESA_DIRECCION}}', '{{MUNICIPIO}}',
                                        '{{EMPLEADO_NOMBRE}}', '{{EMPLEADO_CEDULA}}', '{{EMPLEADO_ESTADO_CIVIL}}', '{{EMPLEADO_PROFESION}}', '{{EMPLEADO_DIRECCION}}',
                                        '{{EMPLEADO_CARGO}}', '{{SALARIO_NUMEROS}}', '{{SALARIO_LETRAS}}', '{{FORMA_PAGO}}', '{{DIAS_TRABAJO}}', '{{HORARIO_TRABAJO}}', '{{HORARIO_SABADO}}', '{{FECHA_INGRESO}}', '{{FECHA_HOY}}', '{{MODALIDAD_CONTRATO}}'
                                    ].map(tag => (
                                        <button key={tag} type="button" onClick={() => handleInsertVariable(tag, true)} className="px-2 py-1 bg-slate-100 hover:bg-indigo-50 text-indigo-700 rounded-lg text-[9px] font-mono font-bold">+ {tag}</button>
                                    ))}
                                </div>
                            </div>
                        </div>

                        <div className="p-6 border-t bg-slate-50 flex justify-end gap-3">
                            <button onClick={() => setShowTemplateModal(false)} className="px-6 py-3.5 bg-white border rounded-2xl font-black uppercase text-[10px] text-slate-600">Cancelar</button>
                            <button onClick={handleSaveTemplateToDB} className="px-8 py-3.5 bg-emerald-600 hover:bg-emerald-700 text-white rounded-2xl font-black uppercase text-[10px] shadow-lg">Guardar Plantilla en BD</button>
                        </div>
                    </div>
                </div>
            )}

            {/* MODAL VISTA PREVIA DE PLANTILLA */}
            {previewTemplateItem && (
                <div className="fixed inset-0 bg-slate-900/70 z-[130] flex items-center justify-center p-4 fade-in" onClick={() => setPreviewTemplateItem(null)}>
                    <div className="bg-white rounded-[3rem] w-full max-w-4xl max-h-[90vh] flex flex-col overflow-hidden shadow-2xl border-t-[12px] border-indigo-600" onClick={e=>e.stopPropagation()}>
                        <div className="p-6 border-b flex justify-between items-center bg-white">
                            <div>
                                <h3 className="font-black text-xl text-slate-900">Vista Previa: {previewTemplateItem.title}</h3>
                                <p className="text-[10px] text-slate-400 font-bold uppercase tracking-wider">Muestra cómo se verá el documento con datos de ejemplo</p>
                            </div>
                            <button onClick={() => setPreviewTemplateItem(null)} className="p-3 bg-slate-50 rounded-full text-slate-400 hover:text-slate-600">
                                <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>
                        <div 
                            className="flex-1 p-8 overflow-y-auto bg-slate-50 font-serif leading-relaxed text-sm" 
                            dangerouslySetInnerHTML={{ 
                                __html: compileContractHtml({
                                    name: 'Juan Alberto Pérez',
                                    idCard: '001-120590-0002A',
                                    civilStatus: 'Soltero(a)',
                                    profession: 'Especialista',
                                    homeAddress: 'Managua, Nicaragua',
                                    positionTitle: 'Técnico Operativo',
                                    baseSalary: 18000,
                                    scheduleStart: '08:00',
                                    scheduleEnd: '17:00',
                                    scheduleDays: ['lun', 'mar', 'mie', 'jue', 'vie'],
                                    paymentFrequency: 'Quincenal',
                                    hiringDate: window.getNICDate()
                                }, previewTemplateItem.id, previewTemplateItem.contract_type || 'indeterminado') 
                            }} 
                        />
                        <div className="p-6 border-t bg-white flex justify-end">
                            <button onClick={() => setPreviewTemplateItem(null)} className="px-8 py-3.5 bg-indigo-600 text-white font-black rounded-2xl uppercase text-[10px] shadow-md">Cerrar Vista Previa</button>
                        </div>
                    </div>
                </div>
            )}

            {/* MODAL VISTA PREVIA DE EXPEDIENTE */}
            {previewContract && (
                <div className="fixed inset-0 bg-slate-900/70 z-[120] flex items-center justify-center p-4 fade-in" onClick={() => setPreviewContract(null)}>
                    <div className="bg-white rounded-[3rem] w-full max-w-4xl max-h-[90vh] flex flex-col overflow-hidden shadow-2xl" onClick={e=>e.stopPropagation()}>
                        <div className="p-6 border-b flex justify-between items-center">
                            <h3 className="font-black text-xl text-slate-900">{previewContract.employee_name}</h3>
                            <button onClick={() => setPreviewContract(null)} className="p-3 bg-slate-50 rounded-full">
                                <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>
                        <div className="flex-1 p-8 overflow-y-auto font-serif text-sm leading-relaxed" dangerouslySetInnerHTML={{ __html: previewContract.contract_html }} />
                        <div className="p-6 border-t flex justify-end">
                            <button onClick={() => handlePrintClean(previewContract.contract_html, previewContract.employee_name)} className="px-8 py-3.5 bg-emerald-600 text-white font-black rounded-2xl uppercase text-[10px]">Imprimir / Descargar PDF</button>
                        </div>
                    </div>
                </div>
            )}

            {/* MODAL DE ELIMINACIÓN SEGURA CON PIN O CLAVE */}
            {deleteTargetContract && (
                <div className="fixed inset-0 bg-slate-900/80 z-[130] flex items-center justify-center p-4 fade-in" onClick={() => setDeleteTargetContract(null)}>
                    <div className="bg-white rounded-[3rem] w-full max-w-md p-6 sm:p-8 shadow-2xl border-t-[10px] border-red-600 space-y-4" onClick={e=>e.stopPropagation()}>
                        <div className="text-center space-y-1">
                            <div className="w-12 h-12 bg-red-50 text-red-600 rounded-2xl flex items-center justify-center mx-auto mb-2">
                                <svg className="w-6 h-6" fill="none" stroke="currentColor" strokeWidth="2" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z"></path></svg>
                            </div>
                            <h3 className="font-black text-lg text-slate-900">Autorizar Eliminación de Expediente</h3>
                            <p className="text-xs text-slate-500">¿Estás seguro de eliminar el contrato de <strong>{deleteTargetContract.employee_name}</strong>?</p>
                        </div>

                        <div>
                            <label className="text-[9px] font-black uppercase text-slate-400 block mb-1">Ingresa tu Contraseña o PIN</label>
                            <input 
                                type="password" 
                                value={securityPass} 
                                onChange={e => setSecurityPass(e.target.value)} 
                                placeholder="••••••••" 
                                className="w-full p-3.5 bg-slate-50 border rounded-2xl font-bold text-xs outline-none focus:border-red-500" 
                                autoFocus
                            />
                        </div>

                        <div className="flex gap-3 pt-2">
                            <button onClick={() => setDeleteTargetContract(null)} className="flex-1 py-3 bg-slate-100 text-slate-600 rounded-2xl font-black uppercase text-[10px]">
                                Cancelar
                            </button>
                            <button 
                                onClick={handleExecuteSecureDelete} 
                                disabled={isDeletingContract}
                                className="flex-1 py-3 bg-red-600 hover:bg-red-700 text-white font-black rounded-2xl uppercase tracking-widest text-[10px] shadow-lg active:scale-95 transition-all"
                            >
                                {isDeletingContract ? "Verificando..." : "Eliminar"}
                            </button>
                        </div>
                    </div>
                </div>
            )}

            {/* MODAL CREAR/EDITAR MODALIDAD */}
            {showModalityModal && (
                <div className="fixed inset-0 bg-slate-900/70 z-[120] flex items-center justify-center p-4 fade-in" onClick={() => setShowModalityModal(false)}>
                    <div className="bg-white rounded-[3rem] w-full max-w-md p-6 sm:p-8 shadow-2xl border-t-[10px] border-indigo-600 space-y-4" onClick={e=>e.stopPropagation()}>
                        <h3 className="font-black text-lg text-slate-900">{editingModality ? "Editar Modalidad" : "Nueva Modalidad de Contrato"}</h3>
                        <form onSubmit={handleSaveModality} className="space-y-3.5">
                            <div>
                                <label className="text-[9px] font-black uppercase text-slate-400 block mb-1">Nombre Visible</label>
                                <input name="name" defaultValue={editingModality?.name} placeholder="Ej. Tiempo Indeterminado" className="w-full p-3.5 bg-slate-50 border rounded-2xl font-bold text-xs" required />
                            </div>
                            <div>
                                <label className="text-[9px] font-black uppercase text-slate-400 block mb-1">Código Identificador</label>
                                <input name="code" defaultValue={editingModality?.code} placeholder="indeterminado" className="w-full p-3.5 bg-slate-50 border rounded-2xl font-bold text-xs" required />
                            </div>
                            <div className="flex gap-3 pt-3 border-t">
                                <button type="button" onClick={() => setShowModalityModal(false)} className="flex-1 py-3.5 bg-slate-100 text-slate-600 rounded-2xl font-black uppercase text-[10px]">Cancelar</button>
                                <button type="submit" className="flex-1 py-3.5 bg-indigo-600 hover:bg-indigo-700 text-white font-black rounded-2xl uppercase tracking-widest text-[10px] shadow-lg">Guardar</button>
                            </div>
                        </form>
                    </div>
                </div>
            )}
        </div>
    );
};