const { useState, useEffect, useMemo } = React;

window.AdminSaaS = function({ activeViewTab = 'saas_clients', refreshData }) {
    const [saasData, setSaasData] = useState({ clients: [], invoices: [], masterGeminiApiKey: '' });
    const [selectedClient, setSelectedClient] = useState(null);
    const [showModuleModal, setShowModuleModal] = useState(false);
    const [showInvoiceModal, setShowInvoiceModal] = useState(false);
    
    // Modal de Nueva / Editar Empresa
    const [showCompanyModal, setShowCompanyModal] = useState(false);
    const [editingCompany, setEditingCompany] = useState(null);

    const [masterKeyInput, setMasterKeyInput] = useState('');
    const [isSaving, setIsSaving] = useState(false);
    const [showKey, setShowKey] = useState(false);
    const [saveFeedback, setSaveFeedback] = useState('');

    const loadMasterData = async () => {
        const res = await window.apiCall('get_master_dashboard_data', {}, 0);
        if (res && res.success) {
            setSaasData(res);
            setMasterKeyInput(res.masterGeminiApiKey || '');
        }
    };

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

    const metrics = useMemo(() => {
        const totalClients = saasData.clients.length;
        const activeClients = saasData.clients.filter(c => c.service_status === 'active').length;
        const suspendedClients = saasData.clients.filter(c => c.service_status === 'suspended').length;
        
        let mrrUSD = 0;
        saasData.clients.forEach(c => {
            if (c.service_status === 'active') {
                mrrUSD += parseFloat(c.monthly_fee || 0);
            }
        });

        const today = new Date().toISOString().split('T')[0];
        const overdueInvoices = saasData.invoices.filter(inv => {
            if (inv.status !== 'unpaid') return false;
            const diffDays = Math.floor((new Date(today) - new Date(inv.due_date)) / (1000 * 60 * 60 * 24));
            return diffDays >= 5;
        });

        return { totalClients, activeClients, suspendedClients, mrrUSD, overdueInvoices };
    }, [saasData]);

    const handleSaveMasterKey = async () => {
        if (!masterKeyInput.trim()) return alert("Ingresa la API Key Maestra de Google Gemini.");
        setIsSaving(true);
        setSaveFeedback('');
        try {
            const res = await window.apiCall('save_master_gemini_key', { gemini_api_key: masterKeyInput.trim() }, 0);
            if (res && res.success) {
                setSaveFeedback('API Key Maestra guardada correctamente en el servidor.');
                await loadMasterData();
            } else {
                setSaveFeedback('Error: ' + (res?.error || 'No se pudo guardar'));
            }
        } catch (err) {
            setSaveFeedback('Error de conexión: ' + err.message);
        } finally {
            setIsSaving(false);
        }
    };

    const handleOpenNewCompany = () => {
        setEditingCompany(null);
        setShowCompanyModal(true);
    };

    const handleOpenEditCompany = (cl) => {
        setEditingCompany(cl);
        setShowCompanyModal(true);
    };

    const handleSaveCompanySubmit = async (e) => {
        e.preventDefault();
        const fd = new FormData(e.target);
        const payload = {
            id: editingCompany ? editingCompany.id : null,
            company_name: fd.get('company_name'),
            shift_subdomain: fd.get('shift_subdomain'),
            contact_name: fd.get('contact_name'),
            contact_email: fd.get('contact_email'),
            contact_phone: fd.get('contact_phone'),
            admin_password: fd.get('admin_password'),
            tax_regime: fd.get('tax_regime'),
            ruc_number: fd.get('ruc_number'),
            owner_name: fd.get('owner_name'),
            legal_rep_id: fd.get('legal_rep_id'),
            business_address: fd.get('business_address'),
            municipality: fd.get('municipality'),
            module_shift: 1
        };

        setIsSaving(true);
        const res = await window.apiCall('save_master_client', payload, 0);
        setIsSaving(false);
        if (res && res.success) {
            setShowCompanyModal(false);
            await loadMasterData();
            if (refreshData) await refreshData(0);
        } else {
            alert("Error al guardar empresa: " + (res?.error || ""));
        }
    };

    const handleOpenModules = (cl) => {
        setSelectedClient(cl);
        setShowModuleModal(true);
    };

    const handleSaveModulesAndBilling = async (e) => {
        e.preventDefault();
        const fd = new FormData(e.target);
        const payload = {
            id: selectedClient.id,
            account_type: fd.get('account_type'),
            monthly_fee: fd.get('monthly_fee'),
            currency: fd.get('currency'),
            billing_day: fd.get('billing_day'),
            service_status: fd.get('service_status'),
            service_paid_until: fd.get('service_paid_until'),
            module_asistencia: fd.get('module_asistencia') ? 1 : 0,
            module_personal: fd.get('module_personal') ? 1 : 0,
            module_contratos: fd.get('module_contratos') ? 1 : 0,
            module_planilla: fd.get('module_planilla') ? 1 : 0,
            module_vacaciones: fd.get('module_vacaciones') ? 1 : 0,
            module_ausencias: fd.get('module_ausencias') ? 1 : 0,
            module_ai: fd.get('module_ai') ? 1 : 0,
            module_facial: fd.get('module_facial') ? 1 : 0
        };

        setIsSaving(true);
        const res = await window.apiCall('save_client_modules_and_billing', payload, 0);
        setIsSaving(false);
        if (res && res.success) {
            setShowModuleModal(false);
            await loadMasterData();
            if (refreshData) await refreshData(0);
        }
    };

    const handleToggleSuspension = async (client, currentStatus) => {
        const nextStatus = currentStatus === 'suspended' ? 'active' : 'suspended';
        const msg = nextStatus === 'suspended' 
            ? `¿Deseas SUSPENDER el acceso al portal de ${client.company_name}?` 
            : `¿Deseas REACTIVAR el acceso al portal de ${client.company_name}?`;
        if (!confirm(msg)) return;

        const res = await window.apiCall('toggle_service_suspension', { client_id: client.id, status: nextStatus }, 0);
        if (res && res.success) {
            await loadMasterData();
            if (refreshData) await refreshData(0);
        }
    };

    const handleMarkPaid = async (inv) => {
        const ref = prompt("Referencia bancaria o método de pago (ej. Transferencia BAC #9482):", "Transferencia BAC");
        if (ref === null) return;

        const res = await window.apiCall('mark_invoice_paid', {
            invoice_id: inv.id,
            payment_method: 'Transferencia Bancaria',
            payment_reference: ref
        }, 0);

        if (res && res.success) {
            alert(`Factura ${inv.invoice_number} marcada como PAGADA.`);
            await loadMasterData();
        }
    };

    const handleCreateInvoice = async (e) => {
        e.preventDefault();
        const fd = new FormData(e.target);
        const clId = fd.get('client_id');
        const cl = saasData.clients.find(c => Number(c.id) === Number(clId));

        const payload = {
            client_id: clId,
            company_name: cl ? cl.company_name : 'Empresa Cliente',
            amount: fd.get('amount'),
            currency: fd.get('currency'),
            issue_date: fd.get('issue_date'),
            due_date: fd.get('due_date'),
            period_start: fd.get('period_start'),
            period_end: fd.get('period_end'),
            status: 'unpaid'
        };

        setIsSaving(true);
        const res = await window.apiCall('create_client_invoice', payload, 0);
        setIsSaving(false);
        if (res && res.success) {
            setShowInvoiceModal(false);
            await loadMasterData();
        }
    };

    return (
        <div className="space-y-8 fade-in">
            {/* ENCABEZADO */}
            <div className="bg-white 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">Centro de Control SaaS • Shift Master</h2>
                    <p className="text-slate-400 font-bold uppercase text-[10px] tracking-widest mt-0.5">
                        Administración central de empresas, cobros recurrentes y motor de Inteligencia Artificial
                    </p>
                </div>
                <div className="px-4 py-2 bg-indigo-50 border border-indigo-200 rounded-2xl text-xs font-black uppercase text-indigo-700">
                    MRR Activo: ${metrics.mrrUSD.toLocaleString('en-US', { minimumFractionDigits: 2 })} USD
                </div>
            </div>

            {/* ALERTA DE MORAS */}
            {metrics.overdueInvoices.length > 0 && (
                <div className="bg-red-600 text-white p-6 rounded-[2.5rem] shadow-lg space-y-3">
                    <div className="flex items-center gap-3">
                        <div className="w-10 h-10 bg-white/20 rounded-2xl flex items-center justify-center font-black">
                            <svg className="w-5 h-5 text-white" fill="none" stroke="currentColor" strokeWidth="2.5" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"/></svg>
                        </div>
                        <div>
                            <h3 className="font-black text-sm uppercase tracking-wider">Atención: {metrics.overdueInvoices.length} Factura(s) con más de 5 días de mora</h3>
                            <p className="text-xs text-red-100 font-medium mt-0.5">Aplica suspensión o registra el cobro de estas empresas.</p>
                        </div>
                    </div>
                    <div className="flex flex-wrap gap-2 pt-1">
                        {metrics.overdueInvoices.map(inv => (
                            <div key={inv.id} className="bg-white text-slate-900 px-4 py-2 rounded-2xl text-xs font-black flex items-center gap-3 shadow-sm">
                                <span>{inv.company_name} ({inv.currency} ${parseFloat(inv.amount).toFixed(2)})</span>
                                <button onClick={() => handleMarkPaid(inv)} className="px-2.5 py-1 bg-emerald-600 text-white rounded-lg text-[9px] uppercase font-black">Marcar Pagado</button>
                            </div>
                        ))}
                    </div>
                </div>
            )}

            {/* SECCIÓN 1: EMPRESAS & PLANES */}
            {activeViewTab === 'saas_clients' && (
                <div className="space-y-6">
                    <div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
                        <div className="bg-white p-6 rounded-[2rem] border border-slate-100 shadow-sm">
                            <p className="text-[10px] font-black uppercase text-slate-400">Total Empresas</p>
                            <h3 className="text-2xl font-black text-slate-800 mt-1">{metrics.totalClients}</h3>
                        </div>
                        <div className="bg-white p-6 rounded-[2rem] border border-slate-100 shadow-sm">
                            <p className="text-[10px] font-black uppercase text-slate-400">Empresas Activas</p>
                            <h3 className="text-2xl font-black text-indigo-600 mt-1">{metrics.activeClients}</h3>
                        </div>
                        <div className="bg-white p-6 rounded-[2rem] border border-slate-100 shadow-sm">
                            <p className="text-[10px] font-black uppercase text-slate-400">Suspendidas</p>
                            <h3 className="text-2xl font-black text-red-600 mt-1">{metrics.suspendedClients}</h3>
                        </div>
                        <div className="bg-white p-6 rounded-[2rem] border border-slate-100 shadow-sm">
                            <p className="text-[10px] font-black uppercase text-slate-400">Facturación Proyectada</p>
                            <h3 className="text-2xl font-black text-emerald-600 mt-1">${metrics.mrrUSD.toFixed(2)} USD</h3>
                        </div>
                    </div>

                    <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="font-black text-slate-900 text-sm uppercase tracking-wider">Directorio de Empresas SaaS</h3>
                                <p className="text-slate-400 text-xs font-medium">Gestión de portales, subdominios y planes</p>
                            </div>
                            <button 
                                onClick={handleOpenNewCompany}
                                className="px-5 py-3 bg-indigo-600 hover:bg-indigo-700 text-white font-black rounded-2xl uppercase tracking-widest text-[10px] shadow-md flex items-center gap-2 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"/></svg>
                                + Nueva Empresa
                            </button>
                        </div>

                        <div className="space-y-3">
                            {saasData.clients.map(c => {
                                const isSuspended = c.service_status === 'suspended';
                                const isDemo = c.account_type === 'demo';
                                const hasFacial = Boolean(c.module_facial);
                                return (
                                    <div key={c.id} className="p-6 rounded-3xl border bg-slate-50 flex flex-col lg:flex-row justify-between items-start lg:items-center gap-4 hover:border-indigo-300 transition-all">
                                        <div>
                                            <div className="flex items-center gap-2 flex-wrap">
                                                <h4 className="font-black text-slate-900 text-base">{c.company_name}</h4>
                                                <span className={`px-2 py-0.5 rounded-lg text-[9px] font-black uppercase ${isDemo ? 'bg-purple-100 text-purple-700' : 'bg-blue-100 text-blue-700'}`}>
                                                    {isDemo ? 'DEMO' : 'CLIENTE PAGO'}
                                                </span>
                                                {hasFacial && (
                                                    <span className="px-2 py-0.5 bg-teal-100 text-teal-800 rounded-lg text-[9px] font-black uppercase">
                                                        BIOMETRÍA FACIAL ACTIVA
                                                    </span>
                                                )}
                                                <span className={`px-2 py-0.5 rounded-lg text-[9px] font-black uppercase ${isSuspended ? 'bg-red-100 text-red-700' : 'bg-emerald-100 text-emerald-700'}`}>
                                                    {isSuspended ? 'SUSPENDIDO' : 'ACTIVO'}
                                                </span>
                                            </div>
                                            <p className="text-[10px] text-slate-400 font-bold uppercase mt-1">
                                                {c.shift_subdomain}.shift.marcasnicaragua.com • Contacto: {c.contact_name} ({c.contact_email})
                                            </p>
                                            <p className="text-[10px] text-indigo-700 font-black mt-1">
                                                Tarifa: {c.currency} ${parseFloat(c.monthly_fee || 0).toFixed(2)}/mes • Día de Cobro: {c.billing_day} • Pagado hasta: {c.service_paid_until || 'Sin registrar'}
                                            </p>
                                        </div>

                                        <div className="flex items-center gap-2">
                                            <button onClick={() => handleOpenEditCompany(c)} className="p-2.5 bg-white hover:bg-slate-100 text-slate-600 rounded-2xl border font-black uppercase text-[10px] shadow-sm" title="Editar Datos Completos">
                                                <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"/></svg>
                                            </button>
                                            <button onClick={() => handleOpenModules(c)} className="px-4 py-2.5 bg-white hover:bg-indigo-50 text-indigo-600 rounded-2xl border font-black uppercase text-[10px] shadow-sm">
                                                Módulos & Cobro
                                            </button>
                                            <button 
                                                onClick={() => handleToggleSuspension(c, c.service_status)} 
                                                className={`px-4 py-2.5 rounded-2xl font-black uppercase text-[10px] shadow-sm text-white ${isSuspended ? 'bg-emerald-600 hover:bg-emerald-700' : 'bg-red-600 hover:bg-red-700'}`}
                                            >
                                                {isSuspended ? 'Reactivar' : 'Suspender'}
                                            </button>
                                        </div>
                                    </div>
                                );
                            })}
                        </div>
                    </div>
                </div>
            )}

            {/* SECCIÓN 2: COBROS & FACTURACIÓN */}
            {activeViewTab === 'saas_invoices' && (
                <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="font-black text-slate-900 text-sm uppercase tracking-wider">Historial de Facturación y Cobros</h3>
                            <p className="text-slate-400 text-xs font-medium">Control mensual de facturas generadas a las empresas clientes</p>
                        </div>
                        <button onClick={() => setShowInvoiceModal(true)} className="px-5 py-3 bg-emerald-600 hover:bg-emerald-700 text-white font-black rounded-2xl uppercase tracking-widest text-[10px] shadow-md">
                            + Emitir Factura
                        </button>
                    </div>

                    <div className="space-y-3">
                        {saasData.invoices.length === 0 ? (
                            <p className="text-center py-8 text-slate-400 font-bold text-xs">No hay facturas emitidas aún.</p>
                        ) : (
                            saasData.invoices.map(inv => {
                                const isPaid = inv.status === 'paid';
                                return (
                                    <div key={inv.id} className="p-5 rounded-3xl border bg-slate-50 flex flex-col lg:flex-row justify-between items-start lg:items-center gap-4">
                                        <div>
                                            <div className="flex items-center gap-2">
                                                <h4 className="font-black text-slate-900 text-sm">{inv.invoice_number} • {inv.company_name}</h4>
                                                <span className={`px-2 py-0.5 rounded-md text-[8px] font-black uppercase ${isPaid ? 'bg-emerald-100 text-emerald-700' : 'bg-amber-100 text-amber-700'}`}>
                                                    {isPaid ? 'PAGADA' : 'PENDIENTE'}
                                                </span>
                                            </div>
                                            <p className="text-[10px] text-slate-500 font-medium mt-1">
                                                Periodo: {inv.period_start} al {inv.period_end} • Vence: {inv.due_date}
                                            </p>
                                            {isPaid && <p className="text-[9px] text-emerald-700 font-bold mt-0.5">Pagado con: {inv.payment_method} ({inv.payment_reference})</p>}
                                        </div>

                                        <div className="flex items-center gap-3">
                                            <span className="text-base font-black text-slate-900">{inv.currency} ${parseFloat(inv.amount).toFixed(2)}</span>
                                            {!isPaid && (
                                                <button onClick={() => handleMarkPaid(inv)} className="px-4 py-2 bg-emerald-600 hover:bg-emerald-700 text-white rounded-xl text-[9px] font-black uppercase shadow-sm">
                                                    Marcar Pagado
                                                </button>
                                            )}
                                        </div>
                                    </div>
                                );
                            })
                        )}
                    </div>
                </div>
            )}

            {/* SECCIÓN 3: MOTOR IA MAESTRO */}
            {activeViewTab === 'saas_ai' && (
                <div className="bg-gradient-to-r from-slate-900 via-indigo-950 to-slate-900 p-8 sm:p-10 rounded-[3rem] shadow-xl text-white space-y-6 border border-indigo-500/20 max-w-4xl">
                    <div className="flex items-center gap-4">
                        <div className="w-14 h-14 rounded-3xl bg-indigo-600 flex items-center justify-center text-white shadow-xl">
                            <svg className="w-8 h-8 animate-pulse" fill="none" stroke="currentColor" strokeWidth="2.5" viewBox="0 0 24 24">
                                <path strokeLinecap="round" strokeLinejoin="round" d="M13 10V3L4 14h7v7l9-11h-7z" />
                            </svg>
                        </div>
                        <div>
                            <h3 className="text-2xl font-black text-white">API Key Maestra de Google Gemini</h3>
                            <p className="text-xs text-indigo-300 font-medium mt-1">
                                Esta clave central abastece el asistente de inteligencia artificial para todas las empresas de tu SaaS con aislamiento de datos.
                            </p>
                        </div>
                    </div>

                    <div className="space-y-3 pt-2">
                        <label className="text-[10px] font-black uppercase tracking-widest text-indigo-300 block">Google Gemini API Key Central</label>
                        <div className="relative">
                            <input 
                                type={showKey ? "text" : "password"} 
                                value={masterKeyInput} 
                                onChange={e => setMasterKeyInput(e.target.value)} 
                                placeholder="Pega tu clave maestra: AIzaSy..." 
                                className="w-full p-4 bg-white/10 border border-white/20 rounded-2xl text-xs font-mono font-bold text-white outline-none focus:border-indigo-400" 
                            />
                            <button type="button" onClick={() => setShowKey(!showKey)} className="absolute right-4 top-1/2 -translate-y-1/2 text-slate-400 text-[10px] font-black uppercase">
                                {showKey ? "Ocultar" : "Mostrar"}
                            </button>
                        </div>

                        {saveFeedback && (
                            <p className="text-xs font-bold mt-1 text-indigo-200">{saveFeedback}</p>
                        )}

                        <button 
                            onClick={handleSaveMasterKey} 
                            disabled={isSaving} 
                            className="px-8 py-4 bg-indigo-600 hover:bg-indigo-700 text-white font-black rounded-2xl uppercase tracking-widest text-xs shadow-lg active:scale-95 transition-all"
                        >
                            {isSaving ? "Guardando en Base de Datos..." : "Guardar API Key Maestra"}
                        </button>
                    </div>
                </div>
            )}

            {/* MODAL COMPLETO DE ALTA / EDICIÓN DE EMPRESA */}
            {showCompanyModal && (
                <div className="fixed inset-0 bg-slate-900/80 z-[130] flex items-center justify-center p-4 fade-in" onClick={() => setShowCompanyModal(false)}>
                    <div className="bg-white rounded-[3rem] w-full max-w-3xl p-8 shadow-2xl space-y-6 border-t-[10px] border-indigo-600 max-h-[92vh] overflow-y-auto" onClick={e=>e.stopPropagation()}>
                        <div className="flex justify-between items-center border-b pb-3">
                            <div>
                                <h3 className="font-black text-xl text-slate-900">{editingCompany ? "Editar Ficha de Empresa" : "Alta de Nueva Empresa SaaS"}</h3>
                                <p className="text-slate-400 text-xs font-medium">Información corporativa, fiscal y credenciales de acceso administrativo</p>
                            </div>
                            <button onClick={() => setShowCompanyModal(false)} className="p-2 bg-slate-50 rounded-full text-slate-400"><svg className="w-5 h-5" fill="none" stroke="currentColor" strokeWidth="2" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" d="M6 18L18 6M6 6l12 12"></path></svg></button>
                        </div>

                        <form onSubmit={handleSaveCompanySubmit} className="space-y-4">
                            <div className="grid md:grid-cols-2 gap-4">
                                <div>
                                    <label className="text-[10px] font-black uppercase text-slate-400 block mb-1">Nombre Comercial de la Empresa</label>
                                    <input name="company_name" defaultValue={editingCompany?.company_name || ''} placeholder="Ej. CleanDent Dental" className="w-full p-3.5 bg-slate-50 border rounded-2xl font-bold text-xs outline-none" required />
                                </div>
                                <div>
                                    <label className="text-[10px] font-black uppercase text-slate-400 block mb-1">Subdominio (Espacio de Trabajo)</label>
                                    <div className="flex items-center bg-slate-50 border rounded-2xl p-3.5">
                                        <input name="shift_subdomain" defaultValue={editingCompany?.shift_subdomain || ''} placeholder="cleandent" className="flex-1 bg-transparent font-bold text-xs outline-none" required />
                                        <span className="text-[10px] font-black text-slate-400">.shift...</span>
                                    </div>
                                </div>
                                <div>
                                    <label className="text-[10px] font-black uppercase text-slate-400 block mb-1">Régimen Fiscal</label>
                                    <select name="tax_regime" defaultValue={editingCompany?.tax_regime || 'cuota_fija'} className="w-full p-3.5 bg-slate-50 border rounded-2xl font-bold text-xs outline-none">
                                        <option value="cuota_fija">Cuota Fija (Persona Natural)</option>
                                        <option value="regimen_general">Régimen General (Sociedad / SA)</option>
                                    </select>
                                </div>
                                <div>
                                    <label className="text-[10px] font-black uppercase text-slate-400 block mb-1">Número RUC</label>
                                    <input name="ruc_number" defaultValue={editingCompany?.ruc_number || ''} placeholder="J0310000000001" className="w-full p-3.5 bg-slate-50 border rounded-2xl font-bold text-xs outline-none" />
                                </div>
                                <div>
                                    <label className="text-[10px] font-black uppercase text-slate-400 block mb-1">Nombre del Propietario / Rep. Legal</label>
                                    <input name="owner_name" defaultValue={editingCompany?.owner_name || editingCompany?.contact_name || ''} placeholder="Nombre del representante legal" className="w-full p-3.5 bg-slate-50 border rounded-2xl font-bold text-xs outline-none" />
                                </div>
                                <div>
                                    <label className="text-[10px] font-black uppercase text-slate-400 block mb-1">Cédula del Representante</label>
                                    <input name="legal_rep_id" defaultValue={editingCompany?.legal_rep_id || ''} placeholder="001-000000-0000A" className="w-full p-3.5 bg-slate-50 border rounded-2xl font-bold text-xs outline-none" />
                                </div>
                                <div>
                                    <label className="text-[10px] font-black uppercase text-slate-400 block mb-1">Nombre de Contacto Operativo</label>
                                    <input name="contact_name" defaultValue={editingCompany?.contact_name || ''} placeholder="Responsable de cuenta" className="w-full p-3.5 bg-slate-50 border rounded-2xl font-bold text-xs outline-none" required />
                                </div>
                                <div>
                                    <label className="text-[10px] font-black uppercase text-slate-400 block mb-1">Correo Electrónico (Login Admin)</label>
                                    <input name="contact_email" type="email" defaultValue={editingCompany?.contact_email || ''} placeholder="admin@empresa.com" className="w-full p-3.5 bg-slate-50 border rounded-2xl font-bold text-xs outline-none" required />
                                </div>
                                <div>
                                    <label className="text-[10px] font-black uppercase text-slate-400 block mb-1">Teléfono / WhatsApp</label>
                                    <input name="contact_phone" defaultValue={editingCompany?.contact_phone || ''} placeholder="+505 8888-8888" className="w-full p-3.5 bg-slate-50 border rounded-2xl font-bold text-xs outline-none" />
                                </div>
                                <div>
                                    <label className="text-[10px] font-black uppercase text-slate-400 block mb-1">Municipio / Departamento</label>
                                    <input name="municipality" defaultValue={editingCompany?.municipality || 'Managua'} placeholder="Managua" className="w-full p-3.5 bg-slate-50 border rounded-2xl font-bold text-xs outline-none" />
                                </div>
                                <div className="md:col-span-2">
                                    <label className="text-[10px] font-black uppercase text-slate-400 block mb-1">Dirección Comercial (Sede Principal)</label>
                                    <input name="business_address" defaultValue={editingCompany?.business_address || ''} placeholder="Dirección exacta de la empresa..." className="w-full p-3.5 bg-slate-50 border rounded-2xl font-bold text-xs outline-none" />
                                </div>
                                <div className="md:col-span-2">
                                    <label className="text-[10px] font-black uppercase text-slate-400 block mb-1">Contraseña de Administrador Inicial</label>
                                    <input name="admin_password" type="password" placeholder={editingCompany ? "Dejar en blanco para mantener la contraseña actual" : "Contraseña de acceso inicial"} className="w-full p-3.5 bg-slate-50 border rounded-2xl font-bold text-xs outline-none" required={!editingCompany} />
                                </div>
                            </div>

                            <div className="flex gap-3 pt-3 border-t">
                                <button type="button" onClick={() => setShowCompanyModal(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" disabled={isSaving} className="flex-1 py-3.5 bg-indigo-600 hover:bg-indigo-700 text-white font-black rounded-2xl uppercase text-[10px] shadow-lg">
                                    {editingCompany ? "Guardar Cambios" : "Crear Empresa"}
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
            )}

            {/* MODAL CONFIGURACIÓN DE MÓDULOS (INCLUYE RECONOCIMIENTO FACIAL BIOMÉTRICO) */}
            {showModuleModal && selectedClient && (
                <div className="fixed inset-0 bg-slate-900/80 z-[130] flex items-center justify-center p-4 fade-in" onClick={() => setShowModuleModal(false)}>
                    <div className="bg-white rounded-[3rem] w-full max-w-2xl p-8 shadow-2xl space-y-6 border-t-[10px] border-indigo-600 max-h-[90vh] overflow-y-auto" onClick={e=>e.stopPropagation()}>
                        <div className="flex justify-between items-center border-b pb-3">
                            <div>
                                <h3 className="font-black text-xl text-slate-900">Plan & Módulos: {selectedClient.company_name}</h3>
                                <p className="text-[10px] text-slate-400 font-bold uppercase tracking-wider">Activa o desactiva las secciones según el plan contratado</p>
                            </div>
                            <button onClick={() => setShowModuleModal(false)} className="p-2 bg-slate-50 rounded-full text-slate-400"><svg className="w-5 h-5" fill="none" stroke="currentColor" strokeWidth="2" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" d="M6 18L18 6M6 6l12 12"></path></svg></button>
                        </div>

                        <form onSubmit={handleSaveModulesAndBilling} className="space-y-5">
                            <div>
                                <label className="text-[10px] font-black uppercase text-slate-400 block mb-1">Tipo de Cuenta</label>
                                <select name="account_type" defaultValue={selectedClient.account_type || 'demo'} className="w-full p-3.5 bg-slate-50 border rounded-2xl font-bold text-xs text-indigo-700 outline-none">
                                    <option value="demo">Cliente Demo (Muestra módulos bloqueados con candado)</option>
                                    <option value="subscription">Cliente de Pago (Oculta módulos no contratados)</option>
                                </select>
                            </div>

                            <div className="space-y-2">
                                <label className="text-[10px] font-black uppercase tracking-widest text-slate-400 block">Módulos Habilitados</label>
                                <div className="grid grid-cols-2 gap-3">
                                    {[
                                        { name: 'module_asistencia', label: 'Asistencia y Marcajes' },
                                        { name: 'module_personal', label: 'Gestión de Personal' },
                                        { name: 'module_contratos', label: 'Contratos Laborales' },
                                        { name: 'module_planilla', label: 'Planilla de Sueldos (NI)' },
                                        { name: 'module_vacaciones', label: 'Control de Vacaciones' },
                                        { name: 'module_ausencias', label: 'Registro de Ausencias' },
                                        { name: 'module_ai', label: 'Shift Copilot AI' },
                                        { name: 'module_facial', label: 'Reconocimiento Facial Biométrico' }
                                    ].map(mod => (
                                        <label key={mod.name} className="flex items-center gap-2.5 p-3 bg-slate-50 border rounded-2xl cursor-pointer text-xs font-bold text-slate-700">
                                            <input type="checkbox" name={mod.name} defaultChecked={Boolean(selectedClient[mod.name])} className="w-4 h-4 accent-indigo-600 rounded" />
                                            <span>{mod.label}</span>
                                        </label>
                                    ))}
                                </div>
                            </div>

                            <div className="grid md:grid-cols-3 gap-3 border-t pt-4">
                                <div>
                                    <label className="text-[9px] font-black uppercase text-slate-400 block mb-1">Tarifa Mensual</label>
                                    <input name="monthly_fee" type="number" step="0.01" defaultValue={selectedClient.monthly_fee || 0} className="w-full p-3 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">Moneda</label>
                                    <select name="currency" defaultValue={selectedClient.currency || 'USD'} className="w-full p-3 bg-slate-50 border rounded-2xl font-bold text-xs">
                                        <option value="USD">USD ($)</option>
                                        <option value="NIO">Córdobas (C$)</option>
                                    </select>
                                </div>
                                <div>
                                    <label className="text-[9px] font-black uppercase text-slate-400 block mb-1">Día de Cobro Mensual</label>
                                    <input name="billing_day" type="number" min="1" max="31" defaultValue={selectedClient.billing_day || 23} className="w-full p-3 bg-slate-50 border rounded-2xl font-bold text-xs" required />
                                </div>
                            </div>

                            <div className="grid md:grid-cols-2 gap-3">
                                <div>
                                    <label className="text-[9px] font-black uppercase text-slate-400 block mb-1">Estado de Servicio</label>
                                    <select name="service_status" defaultValue={selectedClient.service_status || 'active'} className="w-full p-3 bg-slate-50 border rounded-2xl font-bold text-xs">
                                        <option value="active">Activo / Al Día</option>
                                        <option value="past_due">En Gracia / Por Vencer</option>
                                        <option value="suspended">Suspendido</option>
                                    </select>
                                </div>
                                <div>
                                    <label className="text-[9px] font-black uppercase text-slate-400 block mb-1">Servicio Pagado Hasta</label>
                                    <input type="date" name="service_paid_until" defaultValue={selectedClient.service_paid_until || ''} className="w-full p-3 bg-slate-50 border rounded-2xl font-bold text-xs" />
                                </div>
                            </div>

                            <div className="flex gap-3 pt-2">
                                <button type="button" onClick={() => setShowModuleModal(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" disabled={isSaving} className="flex-1 py-3.5 bg-indigo-600 hover:bg-indigo-700 text-white font-black rounded-2xl uppercase text-[10px] shadow-lg">Guardar Configuración</button>
                            </div>
                        </form>
                    </div>
                </div>
            )}

            {/* MODAL EMISIÓN DE FACTURA */}
            {showInvoiceModal && (
                <div className="fixed inset-0 bg-slate-900/80 z-[130] flex items-center justify-center p-4 fade-in" onClick={() => setShowInvoiceModal(false)}>
                    <div className="bg-white rounded-[3rem] w-full max-w-lg p-8 shadow-2xl space-y-5 border-t-[10px] border-emerald-600" onClick={e=>e.stopPropagation()}>
                        <h3 className="font-black text-xl text-slate-900">Nueva Factura de Servicio</h3>
                        <form onSubmit={handleCreateInvoice} className="space-y-4">
                            <div>
                                <label className="text-[9px] font-black uppercase text-slate-400 block mb-1">Empresa Cliente</label>
                                <select name="client_id" className="w-full p-3.5 bg-slate-50 border rounded-2xl font-bold text-xs">
                                    {saasData.clients.map(cl => (
                                        <option key={cl.id} value={cl.id}>{cl.company_name} ({cl.currency} ${cl.monthly_fee})</option>
                                    ))}
                                </select>
                            </div>
                            <div className="grid grid-cols-2 gap-3">
                                <div>
                                    <label className="text-[9px] font-black uppercase text-slate-400 block mb-1">Monto a Cobrar</label>
                                    <input type="number" step="0.01" name="amount" defaultValue="50.00" className="w-full p-3 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">Moneda</label>
                                    <select name="currency" className="w-full p-3 bg-slate-50 border rounded-2xl font-bold text-xs">
                                        <option value="USD">USD ($)</option>
                                        <option value="NIO">Córdobas (C$)</option>
                                    </select>
                                </div>
                            </div>
                            <div className="grid grid-cols-2 gap-3">
                                <div>
                                    <label className="text-[9px] font-black uppercase text-slate-400 block mb-1">Fecha de Emisión</label>
                                    <input type="date" name="issue_date" defaultValue={new Date().toISOString().split('T')[0]} className="w-full p-3 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">Fecha de Vencimiento</label>
                                    <input type="date" name="due_date" defaultValue={new Date(Date.now() + 5*24*60*60*1000).toISOString().split('T')[0]} className="w-full p-3 bg-slate-50 border rounded-2xl font-bold text-xs" required />
                                </div>
                            </div>
                            <div className="grid grid-cols-2 gap-3">
                                <div>
                                    <label className="text-[9px] font-black uppercase text-slate-400 block mb-1">Inicio de Periodo</label>
                                    <input type="date" name="period_start" defaultValue={new Date().toISOString().split('T')[0]} className="w-full p-3 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">Fin de Periodo (1 Mes)</label>
                                    <input type="date" name="period_end" defaultValue={new Date(Date.now() + 30*24*60*60*1000).toISOString().split('T')[0]} className="w-full p-3 bg-slate-50 border rounded-2xl font-bold text-xs" required />
                                </div>
                            </div>
                            <div className="flex gap-3 pt-3 border-t">
                                <button type="button" onClick={() => setShowInvoiceModal(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" disabled={isSaving} className="flex-1 py-3.5 bg-emerald-600 hover:bg-emerald-700 text-white font-black rounded-2xl uppercase text-[10px] shadow-lg">Emitir Factura</button>
                            </div>
                        </form>
                    </div>
                </div>
            )}
        </div>
    );
};