const { useState } = React;

window.AdminSaaS = function({ 
    masterClients = [], 
    activeClientId, 
    setActiveClientId, 
    editingClient, 
    setEditingClient, 
    showClientModal, 
    setShowClientModal, 
    refreshData 
}) {
    const [logoBase64, setLogoBase64] = useState('');
    const [logoPreview, setLogoPreview] = useState('');
    const [taxRegime, setTaxRegime] = useState('cuota_fija');

    const handleOpenEdit = (c) => {
        setEditingClient(c);
        setTaxRegime(c.tax_regime || 'cuota_fija');
        setLogoPreview(c.company_logo || '');
        setLogoBase64('');
        setShowClientModal(true);
    };

    const handleOpenCreate = () => {
        setEditingClient(null);
        setTaxRegime('cuota_fija');
        setLogoPreview('');
        setLogoBase64('');
        setShowClientModal(true);
    };

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

    const handleSubmitClient = async (e) => {
        e.preventDefault();
        const f = new FormData(e.target);

        const payload = {
            id: editingClient ? editingClient.id : null,
            company_name: f.get('company_name'),
            shift_subdomain: f.get('shift_subdomain'),
            contact_name: f.get('contact_name'),
            contact_email: f.get('contact_email'),
            contact_phone: f.get('contact_phone'),
            admin_password: f.get('admin_password'),
            tax_regime: taxRegime,
            ruc_number: f.get('ruc_number'),
            owner_name: f.get('owner_name'),
            legal_rep_id: f.get('legal_rep_id'),
            business_address: f.get('business_address'),
            municipality: f.get('municipality') || 'Managua',
            module_shift: f.get('module_shift') ? 1 : 0,
            logo_base64: logoBase64
        };

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

    return (
        <div className="space-y-8 fade-in">
            <div className="bg-white p-8 rounded-[3rem] shadow-sm border border-slate-100 flex flex-col md:flex-row justify-between items-center gap-4">
                <div>
                    <h2 className="text-2xl font-black text-slate-900 tracking-tight">Gestión de Portales Corporativos (SaaS)</h2>
                    <p className="text-slate-400 font-bold uppercase text-[10px] mt-0.5 tracking-widest">
                        Alta de clientes, régimen tributario, configuración fiscal y control de licencias
                    </p>
                </div>
                <button 
                    onClick={handleOpenCreate} 
                    className="px-6 py-4 bg-indigo-600 hover:bg-indigo-700 text-white font-black rounded-2xl uppercase tracking-widest text-[10px] flex items-center gap-2 shadow-lg active:scale-95 transition-all"
                >
                    <svg className="w-4 h-4" fill="none" stroke="currentColor" strokeWidth="2.5" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" d="M12 4v16m8-8H4"></path></svg>
                    Nueva Empresa
                </button>
            </div>

            <div className="grid md:grid-cols-2 lg:grid-cols-3 gap-6">
                {masterClients.map(c => (
                    <div key={c.id} className="bg-white p-7 rounded-[2.5rem] border border-slate-200/80 hover:border-indigo-300 shadow-sm flex flex-col justify-between space-y-5 transition-all">
                        <div>
                            <div className="flex justify-between items-start mb-2">
                                <span className={`px-3 py-1 rounded-xl text-[9px] font-black uppercase tracking-wider ${
                                    c.module_shift ? 'bg-emerald-50 text-emerald-600 border border-emerald-200' : 'bg-red-50 text-red-600'
                                }`}>
                                    {c.module_shift ? 'Módulo Activo' : 'Inactivo'}
                                </span>
                                <span className="px-2.5 py-1 bg-indigo-50 text-indigo-700 rounded-lg text-[9px] font-black uppercase">
                                    {c.tax_regime === 'regimen_general' ? 'Régimen General' : 'Cuota Fija'}
                                </span>
                                <button onClick={() => handleOpenEdit(c)} className="p-2 hover:bg-slate-100 rounded-xl text-slate-400 hover:text-indigo-600">
                                    <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>
                            </div>
                            <h3 className="font-black text-xl text-slate-900">{c.company_name}</h3>
                            <p className="text-[11px] font-bold text-indigo-600 mt-0.5">{c.shift_subdomain}.shift.marcasnicaragua.com</p>
                            <div className="mt-4 space-y-1 text-xs text-slate-500 font-medium">
                                <p><strong>Contacto:</strong> {c.contact_name || 'N/A'}</p>
                                <p><strong>Correo Admin:</strong> {c.contact_email || 'N/A'}</p>
                                <p><strong>RUC:</strong> {c.ruc_number || 'Sin registrar'}</p>
                            </div>
                        </div>

                        <button 
                            onClick={() => setActiveClientId(c.id)} 
                            className="w-full py-3.5 bg-slate-900 hover:bg-black text-white font-black rounded-2xl uppercase tracking-widest text-[10px] shadow-sm active:scale-95 transition-all"
                        >
                            Ingresar al Portal
                        </button>
                    </div>
                ))}
            </div>

            {/* MODAL CONFIGURACIÓN COMPLETA DE EMPRESA */}
            {showClientModal && (
                <div className="fixed inset-0 bg-slate-900/60 z-[120] flex items-center justify-center p-4 fade-in" onClick={() => setShowClientModal(false)}>
                    <div className="bg-white rounded-[3rem] w-full max-w-3xl max-h-[92vh] overflow-y-auto p-8 border-t-[12px] border-indigo-600 shadow-2xl" onClick={e=>e.stopPropagation()}>
                        <div className="flex justify-between items-center border-b pb-4 mb-6">
                            <div>
                                <h3 className="font-black text-2xl text-slate-900">{editingClient ? "Editar Empresa (Workspace)" : "Alta de Nueva Empresa"}</h3>
                                <p className="text-slate-400 font-bold text-[10px] uppercase tracking-widest mt-1">Configuración fiscal y credenciales de acceso</p>
                            </div>
                            <button onClick={() => setShowClientModal(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>

                        <form onSubmit={handleSubmitClient} className="space-y-6">
                            <div className="grid md:grid-cols-2 gap-5">
                                <div>
                                    <label className="text-[10px] font-black uppercase text-slate-400 ml-2 mb-1 block">Nombre Comercial / Empresa</label>
                                    <input name="company_name" defaultValue={editingClient?.company_name} placeholder="Ej. CleanDent" className="w-full p-4 bg-slate-50 border rounded-2xl font-bold text-xs outline-none focus:border-indigo-500" required />
                                </div>
                                <div>
                                    <label className="text-[10px] font-black uppercase text-slate-400 ml-2 mb-1 block">Subdominio (Sin espacios)</label>
                                    <input name="shift_subdomain" defaultValue={editingClient?.shift_subdomain} placeholder="cleandent" className="w-full p-4 bg-slate-50 border rounded-2xl font-bold text-xs outline-none focus:border-indigo-500" required />
                                </div>
                                <div>
                                    <label className="text-[10px] font-black uppercase text-slate-400 ml-2 mb-1 block">Nombre del Contacto / Dueño</label>
                                    <input name="contact_name" defaultValue={editingClient?.contact_name} placeholder="Veronica Arguello" className="w-full p-4 bg-slate-50 border rounded-2xl font-bold text-xs outline-none focus:border-indigo-500" required />
                                </div>
                                <div>
                                    <label className="text-[10px] font-black uppercase text-slate-400 ml-2 mb-1 block">Correo de Acceso Principal (Admin)</label>
                                    <input name="contact_email" defaultValue={editingClient?.contact_email} type="email" placeholder="admin@empresa.com" className="w-full p-4 bg-slate-50 border rounded-2xl font-bold text-xs outline-none focus:border-indigo-500" required />
                                </div>
                                <div>
                                    <label className="text-[10px] font-black uppercase text-slate-400 ml-2 mb-1 block">Teléfono de Contacto</label>
                                    <input name="contact_phone" defaultValue={editingClient?.contact_phone} placeholder="8888-8888" className="w-full p-4 bg-slate-50 border rounded-2xl font-bold text-xs outline-none focus:border-indigo-500" />
                                </div>
                                <div>
                                    <label className="text-[10px] font-black uppercase text-slate-400 ml-2 mb-1 block">Contraseña / PIN Master</label>
                                    <input name="admin_password" type="password" placeholder={editingClient ? "Dejar vacío para no cambiar" : "Contraseña inicial"} className="w-full p-4 bg-slate-50 border rounded-2xl font-bold text-xs outline-none focus:border-indigo-500" required={!editingClient} />
                                </div>
                            </div>

                            {/* RÉGIMEN FISCAL Y DATOS TRIBUTARIOS */}
                            <div className="p-6 bg-indigo-50/60 rounded-3xl border border-indigo-100 space-y-4">
                                <h4 className="font-black text-xs uppercase text-indigo-950 tracking-wider">Configuración Fiscal & Contratos (Nicaragua)</h4>
                                <div className="grid md:grid-cols-2 gap-4">
                                    <div>
                                        <label className="text-[10px] font-black uppercase text-slate-500 block mb-1">Régimen Tributario DGI</label>
                                        <div className="flex bg-white p-1 rounded-2xl border">
                                            <button 
                                                type="button" 
                                                onClick={() => setTaxRegime('cuota_fija')} 
                                                className={`flex-1 py-2.5 rounded-xl font-black text-[10px] uppercase transition-all ${taxRegime === 'cuota_fija' ? 'bg-indigo-600 text-white shadow-sm' : 'text-slate-400'}`}
                                            >
                                                Cuota Fija
                                            </button>
                                            <button 
                                                type="button" 
                                                onClick={() => setTaxRegime('regimen_general')} 
                                                className={`flex-1 py-2.5 rounded-xl font-black text-[10px] uppercase transition-all ${taxRegime === 'regimen_general' ? 'bg-indigo-600 text-white shadow-sm' : 'text-slate-400'}`}
                                            >
                                                Régimen General
                                            </button>
                                        </div>
                                    </div>
                                    <div>
                                        <label className="text-[10px] font-black uppercase text-slate-500 block mb-1">Número RUC</label>
                                        <input name="ruc_number" defaultValue={editingClient?.ruc_number} placeholder="Ej. J0310000000001" className="w-full p-3.5 bg-white border rounded-2xl font-bold text-xs outline-none" />
                                    </div>
                                    <div>
                                        <label className="text-[10px] font-black uppercase text-slate-500 block mb-1">Cédula del Representante Legal</label>
                                        <input name="legal_rep_id" defaultValue={editingClient?.legal_rep_id} placeholder="001-000000-0000A" className="w-full p-3.5 bg-white border rounded-2xl font-bold text-xs outline-none" />
                                    </div>
                                    <div>
                                        <label className="text-[10px] font-black uppercase text-slate-500 block mb-1">Municipio / Departamento</label>
                                        <input name="municipality" defaultValue={editingClient?.municipality || 'Managua'} placeholder="Managua" className="w-full p-3.5 bg-white 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-500 block mb-1">Dirección Comercial Completa</label>
                                        <input name="business_address" defaultValue={editingClient?.business_address} placeholder="De donde fue el banco 2c al lago..." className="w-full p-3.5 bg-white border rounded-2xl font-bold text-xs outline-none" />
                                    </div>
                                </div>
                            </div>

                            {/* SUBIDA DE LOGO DIRECTA */}
                            <div className="p-5 bg-slate-50 rounded-3xl border space-y-3">
                                <label className="text-[10px] font-black uppercase text-slate-500 block">Subir Logo Corporativo a Servidor</label>
                                <div className="flex items-center gap-4">
                                    {logoPreview ? (
                                        <img src={logoPreview} className="h-12 w-auto object-contain max-w-[120px] p-1 bg-white rounded-xl border" />
                                    ) : null}
                                    <input type="file" accept="image/*" onChange={handleLogoUpload} className="text-xs text-slate-500 file:mr-3 file:py-2 file:px-4 file:rounded-xl file:border-0 file:text-[10px] file:font-black file:uppercase file:bg-indigo-600 file:text-white cursor-pointer" />
                                </div>
                            </div>

                            <div className="flex items-center gap-2 px-2">
                                <input type="checkbox" name="module_shift" defaultChecked={editingClient ? Boolean(editingClient.module_shift) : true} className="w-4 h-4 accent-indigo-600" />
                                <label className="text-xs font-black uppercase text-slate-700">Mantener Módulo y Licencia Activa</label>
                            </div>

                            <div className="flex gap-3 pt-4 border-t">
                                <button type="button" onClick={() => setShowClientModal(false)} className="flex-1 py-4 bg-slate-100 text-slate-600 font-black rounded-2xl uppercase text-[10px]">
                                    Cancelar
                                </button>
                                <button type="submit" className="flex-1 py-4 bg-indigo-600 hover:bg-indigo-700 text-white font-black rounded-2xl uppercase tracking-widest text-[10px] shadow-lg">
                                    Guardar Empresa
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
            )}
        </div>
    );
};