/**
 * =========================================================================
 * PLATEFORME ECO-PANNEAU.FR - VERSION 1.0.0
 * Paramètres du compte client - Sous-onglet : Sécurité et 2FA
 * =========================================================================
 */

const FallbackNull = () => null;

const FallbackCardGrid = ({children, className}) => (
    <div className={`grid gap-4 ${className}`}>{children}</div>
);

const FallbackTextLogo = ({ className = "" }) => <span className={className}>eco-panneau.fr</span>;

window.pano_ClientSettingsSecurity = ({ myClientData, showToast, refreshData, openLocalDialog, closeCurrentLayer, activeDialog }) => {
    const { useState } = React;

    const [isSaving, setIsSaving] = useState(false);
    const [passwordData, setPasswordData] = useState({ current: '', new: '', confirm: '' });
    
    const [twoFactorSetup, setTwoFactorSetup] = useState(null); 
    const [twoFactorCode, setTwoFactorCode] = useState('');
    const [twoFactorSecret, setTwoFactorSecret] = useState('');
    const [twoFactorQr, setTwoFactorQr] = useState('');
    
    const [confirmConfig, setConfirmConfig] = useState(null);

    const {
        LockIcon, ShieldCheckIcon, ShieldAlertIcon, QrCodeIcon, MailIcon, CopyIcon
    } = window.pano_getIcons();

    const FormInput = window.pano_FormInput || FallbackNull;
    const NativeQRCode = window.pano_NativeQRCode || FallbackNull;
    const Button = window.pano_Button || FallbackNull;
    const ConfirmModal = window.pano_ConfirmModal || FallbackNull;
    const TextLogo = window.pano_TextLogo || FallbackTextLogo;
    const CardGrid = window.pano_CardGrid || FallbackCardGrid;

    const handlePasswordChange = async (e) => {
        e.preventDefault();
        if (passwordData.new !== passwordData.confirm) {
            showToast("Les nouveaux mots de passe ne correspondent pas.", "error");
            return;
        }
        if (passwordData.new.length < 8) {
            showToast("Le mot de passe doit contenir au moins 8 caractères.", "error");
            return;
        }

        const d = await window.pano_apiFetch('clients/password/update', {
            body: { oldPassword: passwordData.current, password: passwordData.new },
            setLoading: setIsSaving,
            successMessage: "Mot de passe mis à jour."
        });

        if (d) setPasswordData({ current: '', new: '', confirm: '' });
    };

    const start2FASetup = async (type) => {
        if (type === 'email') {
            setTwoFactorSetup('email');
            return;
        }
        
        const d = await window.pano_apiFetch('clients/profile/setup_totp', { setLoading: setIsSaving });
        
        if (d) {
            setTwoFactorSecret(d.data.secret);
            setTwoFactorQr(d.data.otpauth);
            setTwoFactorSetup('authenticator');
        }
    };

    const confirm2FASetup = async (e) => {
        e.preventDefault();
        if (twoFactorSetup === 'authenticator' && twoFactorCode.length !== 6) return;
        
        const method = twoFactorSetup === 'authenticator' ? 'totp' : 'email';
        
        const d = await window.pano_apiFetch('clients/profile/update_2fa', {
            body: { method: method },
            setLoading: setIsSaving,
            successMessage: "Authentification à double facteur activée !"
        });

        if (d) {
            setTwoFactorSetup(null);
            setTwoFactorCode('');
            refreshData();
        }
    };

    const disable2FA = () => {
        setConfirmConfig({
            title: "Désactiver la 2FA",
            message: "Êtes-vous sûr de vouloir désactiver l'authentification à double facteur ? Votre compte sera beaucoup moins sécurisé en cas de vol de mot de passe.",
            confirmText: "Oui, désactiver",
            cancelText: "Annuler",
            isDestructive: true,
            onConfirm: async () => {
                closeCurrentLayer();
                
                const d = await window.pano_apiFetch('clients/profile/update_2fa', {
                    body: { method: 'none' },
                    setLoading: setIsSaving,
                    successMessage: "Authentification à double facteur désactivée."
                });
                if (d) refreshData();
            }
        });
        openLocalDialog('confirm_security');
    };

    const handleCancel2FA = () => {
        setTwoFactorSetup(null);
        setTwoFactorCode('');
        setTwoFactorSecret('');
        setTwoFactorQr('');
    };

    return (
        <div className="space-y-8 max-w-4xl animate-in fade-in">
            <form onSubmit={handlePasswordChange} className="bg-white border border-slate-200 rounded-2xl p-6 shadow-sm space-y-4">
                <h3 className="font-black text-slate-800 text-lg flex items-center gap-2 border-b border-slate-100 pb-3"><LockIcon size={20} className="text-blue-600"/> Modifier le mot de passe</h3>
                
                <FormInput label="Mot de passe actuel" type="password" value={passwordData.current} onChange={e => setPasswordData({...passwordData, current: e.target.value})} required />
                <CardGrid minWidth="200px" className="gap-4">
                    <FormInput label="Nouveau mot de passe" type="password" value={passwordData.new} onChange={e => setPasswordData({...passwordData, new: e.target.value})} required />
                    <FormInput label="Confirmer le nouveau" type="password" value={passwordData.confirm} onChange={e => setPasswordData({...passwordData, confirm: e.target.value})} required />
                </CardGrid>
                
                <Button type="submit" variant="dark" disabled={isSaving || !passwordData.current || !passwordData.new} className="w-full sm:w-auto mt-4 py-3 px-6 uppercase tracking-widest text-sm">
                    Mettre à jour
                </Button>
            </form>

            <div className="bg-white border border-slate-200 rounded-2xl p-6 shadow-sm space-y-4">
                <div className="flex justify-between items-start border-b border-slate-100 pb-3">
                    <div>
                        <h3 className="font-black text-slate-800 text-lg flex items-center gap-2"><ShieldCheckIcon size={20} className={myClientData.twoFactorEnabled ? "text-emerald-600" : "text-slate-400"}/> Authentification à double facteur</h3>
                        <p className="text-sm text-slate-500 mt-1">Sécurisez l'accès à vos panneaux et à votre coffre-fort légal sur <a href="https://eco-panneau.fr" target="_blank" rel="noopener noreferrer" className="hover:opacity-80 transition"><TextLogo className="text-sm" /></a>.</p>
                    </div>
                    {myClientData.twoFactorEnabled && (
                        <span className="bg-emerald-100 text-emerald-800 text-xs font-black uppercase px-3 py-1 rounded-lg">Activé</span>
                    )}
                </div>

                {myClientData.twoFactorEnabled ? (
                    <div className="space-y-4 animate-in fade-in">
                        <div className="bg-emerald-50 border border-emerald-200 p-4 rounded-xl flex items-start gap-3">
                            <ShieldCheckIcon size={24} className="text-emerald-600 shrink-0"/>
                            <p className="text-sm text-emerald-800 font-medium min-w-0 leading-relaxed">Votre compte est protégé par la double authentification. Vous devez saisir un code unique à chaque connexion depuis un nouvel appareil.</p>
                        </div>
                        <Button variant="danger" icon={ShieldAlertIcon} onClick={disable2FA} disabled={isSaving} className="w-full sm:w-auto py-3 px-6">
                            Désactiver la 2FA
                        </Button>
                    </div>
                ) : (
                    <div className="animate-in fade-in">
                        {!twoFactorSetup ? (
                            <CardGrid minWidth="200px" className="pt-2">
                                <div role="button" tabIndex={0} className="border border-slate-200 p-4 rounded-xl hover:border-blue-400 hover:bg-blue-50 transition cursor-pointer" onClick={() => start2FASetup('authenticator')}>
                                    <QrCodeIcon size={24} className="text-blue-600 mb-2"/>
                                    <h4 className="font-bold text-slate-800 break-words leading-tight">Application (recommandé)</h4>
                                    <p className="text-xs text-slate-500 mt-1">Utilisez Google Authenticator ou Authy pour générer des codes hors-ligne.</p>
                                </div>
                                <div role="button" tabIndex={0} className="border border-slate-200 p-4 rounded-xl hover:border-blue-400 hover:bg-blue-50 transition cursor-pointer" onClick={() => start2FASetup('email')}>
                                    <MailIcon size={24} className="text-blue-600 mb-2"/>
                                    <h4 className="font-bold text-slate-800 break-words leading-tight">Par e-mail</h4>
                                    <p className="text-xs text-slate-500 mt-1">Recevez un code de sécurité par e-mail à chaque connexion.</p>
                                </div>
                            </CardGrid>
                        ) : (
                            <form onSubmit={confirm2FASetup} className="space-y-4 bg-slate-50 p-4 rounded-xl border border-slate-200 animate-in slide-in-from-top-4">
                                <h4 className="font-black text-slate-800 break-words leading-tight">Configuration {twoFactorSetup === 'email' ? 'par e-mail' : 'via application'}</h4>
                                
                                {twoFactorSetup === 'authenticator' && (
                                    <div className="flex flex-col items-center p-4 bg-white rounded-xl border border-slate-200 space-y-4">
                                        <p className="text-sm text-center text-slate-600 font-medium">Scannez ce QR Code avec votre application d'authentification :</p>
                                        <div className="w-48 h-48 border border-slate-100 rounded-lg shadow-sm flex items-center justify-center p-2 bg-white">
                                            {NativeQRCode ? <NativeQRCode value={twoFactorQr} size={176} /> : <QrCodeIcon size={48} className="text-slate-300"/>}
                                        </div>
                                        <div className="w-full">
                                            <p className="text-xs text-slate-500 font-bold uppercase text-center mb-1">Ou saisissez la clé manuellement :</p>
                                            <div className="flex gap-2">
                                                <input type="text" value={twoFactorSecret} readOnly className="flex-1 min-w-0 border border-slate-200 rounded-xl p-2 text-sm text-center font-mono bg-slate-50 outline-none" />
                                                <Button variant="secondary" shape="square" type="button" onClick={() => { navigator.clipboard.writeText(twoFactorSecret); showToast("Clé copiée", "success"); }} className="p-2 shadow-none shrink-0" icon={CopyIcon} title="Copier la clé" />
                                            </div>
                                        </div>
                                    </div>
                                )}
                                
                                {twoFactorSetup === 'email' && (
                                    <p className="text-sm text-slate-600 bg-white p-3 rounded-lg border border-slate-200 font-medium">
                                        Vous allez recevoir un code de vérification à l'adresse e-mail de votre compte pour chaque connexion.
                                    </p>
                                )}

                                {twoFactorSetup === 'authenticator' && (
                                    <div className="space-y-2">
                                        <label className="text-xs font-bold text-slate-500 uppercase block">Saisissez le code à 6 chiffres (Optionnel mais recommandé pour vérifier la configuration)</label>
                                        <input type="text" value={twoFactorCode} onChange={e => setTwoFactorCode(e.target.value.replace(/[^0-9]/g, '').slice(0,6))} placeholder="000000" className="w-full border-2 border-slate-200 rounded-xl p-3 focus:border-blue-500 outline-none transition font-black text-center text-xl tracking-[0.5em]" />
                                    </div>
                                )}
                                
                                <div className="flex gap-3">
                                    <Button variant="secondary" type="button" onClick={handleCancel2FA} disabled={isSaving} className="flex-1 py-3 text-sm justify-center">Annuler</Button>
                                    <Button variant="primary" type="submit" disabled={isSaving || (twoFactorSetup === 'authenticator' && twoFactorCode.length > 0 && twoFactorCode.length !== 6)} className="flex-1 py-3 text-sm justify-center uppercase tracking-widest">Activer</Button>
                                </div>
                            </form>
                        )}
                    </div>
                )}
            </div>

            {activeDialog === 'confirm_security' && confirmConfig && ConfirmModal && (
                <ConfirmModal 
                    {...confirmConfig} 
                    onCancel={() => {
                        setConfirmConfig(null);
                        closeCurrentLayer();
                    }} 
                    zIndex="z-[350]" 
                />
            )}
        </div>
    );
};

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