/**
 * =========================================================================
 * PLATEFORME ECO-PANNEAU.FR - VERSION 1.0.0
 * Modales d'authentification (Login, Register, 2FA, Password Reset)
 * =========================================================================
 */

const AuthInput = ({ type, name, value, onChange, placeholder, icon }) => (
    <div className="relative">
        <div className="absolute inset-y-0 left-0 pl-4 flex items-center pointer-events-none text-slate-400">
            {icon}
        </div>
        <input 
            type={type} 
            name={name}
            value={value} 
            onChange={onChange} 
            required 
            placeholder={placeholder} 
            className="w-full pl-11 pr-4 py-3.5 bg-slate-50 border-2 border-slate-100 rounded-xl outline-none focus:border-emerald-500 focus:bg-white transition text-sm font-medium text-slate-800" 
        />
    </div>
);

window.pano_AuthModal = ({ initialView = 'login', token = '', onClose, onLoginSuccess, showToast }) => {
    const { useState } = React;
    const [view, setView] = useState(initialView);
    const [loading, setLoading] = useState(false);
    const [formData, setFormData] = useState({ email: '', password: '', company: '', code: '', remember_duration: 0 });

    const { XIcon, LockIcon, MailIcon, KeyRoundIcon, LoaderIcon, BuildingIcon, RefreshCwIcon, ShieldIcon } = window.pano_getIcons();
    const Button = window.pano_Button || (() => null);

    const handleInputChange = (e) => {
        setFormData({ ...formData, [e.target.name]: e.target.value });
    };

    const executeAuth = async (endpoint, dataObj, onSuccessCallback) => {
        const d = await window.pano_apiFetch(endpoint, {
            body: dataObj,
            setLoading: setLoading
        });
        if (d) {
            onSuccessCallback(d);
        }
    };

    const handleLogin = (e) => { 
        e.preventDefault(); 
        
        const payload = { 
            login: formData.email, 
            password: formData.password, 
            remember_duration: formData.remember_duration 
        };
        
        executeAuth('auth/login', payload, d => { 
            if (d.data['2fa_required']) { 
                setView('2fa'); 
                showToast("Veuillez saisir votre code de sécurité.", "info"); 
            } else { 
                setFormData(prev => ({ ...prev, password: '' }));
                onLoginSuccess(d.data.role); 
            } 
        }); 
    };

    const handleResend2FA = async () => {
        if (loading) return;
        const d = await window.pano_apiFetch('auth/login', {
            body: { login: formData.email, password: formData.password, remember_duration: formData.remember_duration },
            setLoading: setLoading
        });
        if (d && d.data['2fa_required']) {
            showToast("Un nouveau code de sécurité vous a été envoyé.", "success");
        }
    };
    
    const handleVerify2FA = (e) => { 
        e.preventDefault(); 
        
        executeAuth('auth/verify_2fa', { code: formData.code }, d => {
            setFormData(prev => ({ ...prev, password: '', code: '' }));
            onLoginSuccess(d.data.role);
        }); 
    };
    
    const handleRegisterRequest = (e) => { 
        if (e) e.preventDefault(); 
        
        executeAuth('auth/register_request', { email: formData.email, company: formData.company }, () => {
            setView('register_sent');
            showToast("E-mail envoyé !", "success");
        }); 
    };
    
    const handleRegisterConfirm = (e) => { 
        e.preventDefault(); 
        
        executeAuth('auth/register_confirm', { token, password: formData.password }, d => { 
            showToast("Compte créé avec succès !", "success"); 
            setFormData(prev => ({ ...prev, password: '' })); 
            onLoginSuccess(d.data.role); 
        }); 
    };
    
    const handleForgotRequest = (e) => { 
        if (e) e.preventDefault(); 
        
        executeAuth('auth/forgot_password', { email: formData.email }, () => {
            setView('forgot_sent');
            showToast("E-mail envoyé !", "success");
        }); 
    };
    
    const handleResetConfirm = (e) => { 
        e.preventDefault(); 
        
        executeAuth('auth/reset_password', { token, password: formData.password }, () => { 
            showToast("Mot de passe modifié avec succès.", "success"); 
            setFormData(prev => ({ ...prev, password: '' })); 
            setView('login'); 
        }); 
    };

    return (
        <div className="fixed inset-0 bg-slate-900/60 backdrop-blur-sm z-[999] flex items-center justify-center p-4 animate-in fade-in duration-200" onMouseDown={onClose}>
            <div className="bg-white rounded-[2rem] w-full max-w-md shadow-2xl overflow-hidden" onMouseDown={e => e.stopPropagation()}>
                <div className="p-8 pb-6 text-center relative">
                    <Button variant="ghost" shape="square" icon={XIcon} onClick={onClose} className="absolute top-6 right-6 text-slate-400 hover:text-slate-700 bg-slate-50 hover:bg-slate-100 border-none shadow-none" title="Fermer" />
                    
                    <div className="w-16 h-16 bg-emerald-100 text-emerald-600 rounded-2xl flex items-center justify-center mx-auto mb-4 rotate-3">
                        {LockIcon && <LockIcon className="w-8 h-8"/>}
                    </div>
                    <h2 className="text-2xl font-black text-slate-800">
                        {view === 'login' ? 'Connexion' : view === 'register' ? 'Créer un compte' : view === '2fa' ? 'Sécurité 2FA' : view.includes('forgot') ? 'Mot de passe oublié' : 'Nouveau mot de passe'}
                    </h2>
                </div>

                <div className="px-8 pb-8">
                    {view === 'login' && (
                        <form onSubmit={handleLogin} className="space-y-4">
                            <AuthInput 
                                type="email" 
                                name="email" 
                                value={formData.email} 
                                onChange={handleInputChange} 
                                placeholder="Adresse e-mail" 
                                icon={MailIcon && <MailIcon className="w-4 h-4"/>} 
                            />
                            <AuthInput 
                                type="password" 
                                name="password" 
                                value={formData.password} 
                                onChange={handleInputChange} 
                                placeholder="Mot de passe" 
                                icon={KeyRoundIcon && <KeyRoundIcon className="w-4 h-4"/>} 
                            />
                            
                            <div className="flex items-center justify-between mt-2 px-1">
                                <label className="flex items-center gap-2 cursor-pointer select-none">
                                    <input 
                                        type="checkbox" 
                                        checked={formData.remember_duration > 0} 
                                        onChange={(e) => setFormData({...formData, remember_duration: e.target.checked ? 1296000 : 0})} 
                                        className="w-4 h-4 accent-emerald-600 cursor-pointer" 
                                    />
                                    <span className="text-xs font-bold text-slate-600">Rester connecté</span>
                                </label>
                                {formData.remember_duration > 0 && (
                                    <select 
                                        value={formData.remember_duration} 
                                        onChange={(e) => setFormData({...formData, remember_duration: Number(e.target.value)})} 
                                        className="text-xs border border-slate-200 rounded-lg py-1 px-2 outline-none text-slate-600 bg-white font-bold cursor-pointer"
                                    >
                                        <option value={1296000}>15 jours</option>
                                        <option value={7776000}>3 mois</option>
                                        <option value={15552000}>6 mois</option>
                                        <option value={315360000}>Permanent (déconseillé)</option>
                                    </select>
                                )}
                            </div>

                            <div className="flex justify-end pt-2">
                                <div role="button" tabIndex={0} onClick={() => setView('forgot')} className="text-xs font-bold text-emerald-600 hover:text-emerald-700 cursor-pointer">
                                    Mot de passe oublié ?
                                </div>
                            </div>
                            
                            <Button type="submit" variant="primary" disabled={loading} icon={loading ? LoaderIcon : null} className="w-full py-4 uppercase tracking-widest mt-2 bg-slate-900 hover:bg-slate-800 text-white">
                                Se connecter
                            </Button>
                            
                            <p className="text-center text-sm font-medium text-slate-500 mt-4">
                                Pas encore de compte ? <span role="button" tabIndex={0} onClick={() => setView('register')} className="text-emerald-600 font-bold hover:underline cursor-pointer inline-block">Inscrivez-vous</span>
                            </p>
                        </form>
                    )}

                    {view === 'register' && (
                        <form onSubmit={handleRegisterRequest} className="space-y-4">
                            <AuthInput 
                                type="text" 
                                name="company" 
                                value={formData.company} 
                                onChange={handleInputChange} 
                                placeholder="Nom complet ou raison sociale" 
                                icon={BuildingIcon && <BuildingIcon className="w-4 h-4"/>} 
                            />
                            <AuthInput 
                                type="email" 
                                name="email" 
                                value={formData.email} 
                                onChange={handleInputChange} 
                                placeholder="Adresse e-mail pro" 
                                icon={MailIcon && <MailIcon className="w-4 h-4"/>} 
                            />
                            
                            <Button type="submit" variant="primary" disabled={loading} icon={loading ? LoaderIcon : null} className="w-full py-4 uppercase tracking-widest mt-2">
                                Commencer gratuitement
                            </Button>
                            
                            <p className="text-center text-sm font-medium text-slate-500 mt-4">
                                Déjà inscrit ? <span role="button" tabIndex={0} onClick={() => setView('login')} className="text-slate-800 font-bold hover:underline cursor-pointer inline-block">Connectez-vous</span>
                            </p>
                        </form>
                    )}

                    {view === 'register_sent' && (
                        <div className="text-center space-y-4 py-4">
                            <div className="bg-emerald-50 text-emerald-800 p-4 rounded-xl text-sm font-medium border border-emerald-100">
                                Un lien magique a été envoyé à <strong>{formData.email}</strong>. Cliquez dessus pour activer votre compte.
                            </div>
                            <div className="flex flex-col gap-3 pt-4 border-t border-slate-100">
                                <Button variant="secondary" onClick={handleRegisterRequest} disabled={loading} icon={loading ? LoaderIcon : RefreshCwIcon} className="w-full py-3 justify-center">
                                    Renvoyer l'e-mail
                                </Button>
                                <div role="button" tabIndex={0} onClick={() => setView('login')} className="text-sm font-bold text-slate-500 hover:text-slate-800 transition cursor-pointer">
                                    Retour à la connexion
                                </div>
                            </div>
                        </div>
                    )}

                    {view === 'register_confirm' && (
                        <form onSubmit={handleRegisterConfirm} className="space-y-4">
                            <p className="text-sm text-slate-600 text-center mb-4">
                                Dernière étape : choisissez un mot de passe sécurisé pour protéger votre compte.
                            </p>
                            <AuthInput 
                                type="password" 
                                name="password" 
                                value={formData.password} 
                                onChange={handleInputChange} 
                                placeholder="Votre mot de passe (min 8 car.)" 
                                icon={LockIcon && <LockIcon className="w-4 h-4"/>} 
                            />
                            <Button type="submit" variant="primary" disabled={loading} icon={loading ? LoaderIcon : null} className="w-full py-4 uppercase tracking-widest mt-2">
                                Valider et accéder
                            </Button>
                        </form>
                    )}

                    {view === '2fa' && (
                        <form onSubmit={handleVerify2FA} className="space-y-4">
                            <p className="text-sm text-slate-600 text-center mb-4">
                                Un code de sécurité vous a été envoyé par e-mail ou est disponible sur votre application d'authentification.
                            </p>
                            <AuthInput 
                                type="text" 
                                name="code" 
                                value={formData.code} 
                                onChange={handleInputChange} 
                                placeholder="Code à 6 chiffres" 
                                icon={ShieldIcon && <ShieldIcon className="w-4 h-4"/>} 
                            />
                            <Button type="submit" variant="primary" disabled={loading} icon={loading ? LoaderIcon : null} className="w-full py-4 uppercase tracking-widest mt-2 bg-slate-900 hover:bg-slate-800 text-white">
                                Vérifier
                            </Button>
                            
                            <div className="flex justify-between items-center mt-3 pt-3 border-t border-slate-100">
                                <div role="button" tabIndex={0} onClick={handleResend2FA} className={`text-xs font-bold text-emerald-600 hover:text-emerald-700 transition flex items-center gap-1 cursor-pointer ${loading ? 'opacity-50 pointer-events-none' : ''}`}>
                                    {RefreshCwIcon && <RefreshCwIcon size={12}/>} Renvoyer le code
                                </div>
                                <div role="button" tabIndex={0} onClick={() => setView('login')} className={`text-xs font-bold text-slate-500 hover:text-slate-800 transition cursor-pointer ${loading ? 'opacity-50 pointer-events-none' : ''}`}>
                                    Annuler
                                </div>
                            </div>
                        </form>
                    )}

                    {view === 'forgot' && (
                        <form onSubmit={handleForgotRequest} className="space-y-4">
                            <p className="text-sm text-slate-600 text-center mb-4">
                                Saisissez l'adresse e-mail associée à votre compte pour recevoir un lien de réinitialisation.
                            </p>
                            <AuthInput 
                                type="email" 
                                name="email" 
                                value={formData.email} 
                                onChange={handleInputChange} 
                                placeholder="Adresse e-mail" 
                                icon={MailIcon && <MailIcon className="w-4 h-4"/>} 
                            />
                            <Button type="submit" variant="primary" disabled={loading} icon={loading ? LoaderIcon : null} className="w-full py-4 uppercase tracking-widest mt-2 bg-slate-900 hover:bg-slate-800 text-white">
                                Envoyer le lien
                            </Button>
                            <div role="button" tabIndex={0} onClick={() => setView('login')} className="w-full text-center text-sm font-bold text-slate-500 mt-4 hover:text-slate-800 transition cursor-pointer">
                                Retour à la connexion
                            </div>
                        </form>
                    )}

                    {view === 'forgot_sent' && (
                        <div className="text-center space-y-4 py-4">
                            <div className="bg-blue-50 text-blue-800 p-4 rounded-xl text-sm font-medium border border-blue-100">
                                Si un compte existe pour cet e-mail, un lien de réinitialisation vous a été envoyé.
                            </div>
                            <div className="flex flex-col gap-3 pt-4 border-t border-slate-100">
                                <Button variant="secondary" onClick={handleForgotRequest} disabled={loading} icon={loading ? LoaderIcon : RefreshCwIcon} className="w-full py-3 justify-center">
                                    Renvoyer l'e-mail
                                </Button>
                                <div role="button" tabIndex={0} onClick={() => setView('login')} className="text-sm font-bold text-slate-500 hover:text-slate-800 transition cursor-pointer">
                                    Retour à la connexion
                                </div>
                            </div>
                        </div>
                    )}

                    {view === 'reset' && (
                        <form onSubmit={handleResetConfirm} className="space-y-4">
                            <p className="text-sm text-slate-600 text-center mb-4">
                                Saisissez votre nouveau mot de passe (8 caractères minimum avec majuscule et chiffre).
                            </p>
                            <AuthInput 
                                type="password" 
                                name="password" 
                                value={formData.password} 
                                onChange={handleInputChange} 
                                placeholder="Nouveau mot de passe" 
                                icon={KeyRoundIcon && <KeyRoundIcon className="w-4 h-4"/>} 
                            />
                            <Button type="submit" variant="primary" disabled={loading} icon={loading ? LoaderIcon : null} className="w-full py-4 uppercase tracking-widest mt-2">
                                Modifier le mot de passe
                            </Button>
                        </form>
                    )}
                </div>
            </div>
        </div>
    );
};

/* EOF ========== [_react/_auth_modals.jsx] */