/**
 * =========================================================================
 * PLATEFORME ECO-PANNEAU.FR - VERSION 1.0.0
 * Socle Riverains - Onglet : Newsletter / Actualités du chantier
 * =========================================================================
 */

const { useState } = React;

window.pano_RiverainNewsletterTab = ({ panneau, themeColor, showToast }) => {
    const { MailIcon, LoaderIcon, CheckCircleIcon, ArrowRightIcon } = window.pano_getIcons();
    const Button = window.pano_Button || (() => null);

    const [email, setEmail] = useState('');
    const [status, setStatus] = useState('idle'); // idle, requesting, verifying, success
    const [verifySession, setVerifySession] = useState('');
    const [verifyCode, setVerifyCode] = useState('');
    const [submitting, setSubmitting] = useState(false);

    const handleSubscribeRequest = async (e) => {
        e.preventDefault();
        if (!email.trim() || !email.includes('@')) {
            if (showToast) showToast("Veuillez saisir une adresse e-mail valide.", "error");
            return;
        }

        const d = await window.pano_apiFetch('newsletter/subscribe_request', {
            body: { email: email.trim(), panneau_id: panneau.id },
            setLoading: setSubmitting,
            successMessage: "Un code de vérification a été envoyé à votre adresse e-mail."
        });

        if (d && d.data && d.data.verify_session) {
            setVerifySession(d.data.verify_session);
            setStatus('verifying');
        }
    };

    const handleVerifyCode = async (e) => {
        e.preventDefault();
        if (verifyCode.length !== 6) return;

        const d = await window.pano_apiFetch('newsletter/subscribe_confirm', {
            body: { verify_session: verifySession, code: verifyCode },
            setLoading: setSubmitting,
            successMessage: "Inscription confirmée avec succès !"
        });

        if (d) {
            setStatus('success');
        }
    };

    if (status === 'success') {
        return (
            <div className="p-6 text-center flex flex-col items-center justify-center h-full animate-in zoom-in-95 duration-300">
                <div className="w-16 h-16 rounded-2xl flex items-center justify-center mb-4" style={{ backgroundColor: `${themeColor}15`, color: themeColor }}>
                    <CheckCircleIcon size={32} />
                </div>
                <h3 className="text-xl font-black text-slate-800 mb-2">Inscription validée !</h3>
                <p className="text-sm text-slate-600 font-medium leading-relaxed">
                    Vous recevrez désormais les actualités et les informations importantes concernant ce chantier directement par e-mail.
                </p>
            </div>
        );
    }

    if (status === 'verifying') {
        return (
            <div className="p-4 space-y-4 animate-in fade-in slide-in-from-right-4 duration-300 h-full flex flex-col justify-center">
                <div className="bg-white rounded-2xl shadow-sm border border-slate-100 p-6 text-center">
                    <MailIcon size={32} className="mx-auto mb-3" style={{ color: themeColor }} />
                    <h3 className="font-black text-lg text-slate-800 mb-2">Vérification de l'e-mail</h3>
                    <p className="text-sm text-slate-600 mb-6 leading-relaxed">
                        Un code à 6 chiffres a été envoyé à <strong>{email}</strong>. Saisissez-le ci-dessous pour confirmer votre inscription.
                    </p>
                    <form onSubmit={handleVerifyCode}>
                        <input 
                            type="text" 
                            value={verifyCode} 
                            onChange={e => setVerifyCode(e.target.value.replace(/\D/g, '').slice(0, 6))} 
                            className="w-full border-2 border-slate-200 rounded-xl p-3 text-center text-3xl tracking-[0.25em] font-black outline-none focus:border-slate-800 mb-4" 
                            placeholder="000000" 
                            autoFocus
                        />
                        <Button 
                            type="submit" 
                            disabled={verifyCode.length !== 6 || submitting} 
                            className="w-full py-4 uppercase tracking-widest justify-center text-white border-none shadow-md"
                            style={{ backgroundColor: themeColor }}
                        >
                            {submitting ? <LoaderIcon className="animate-spin w-5 h-5"/> : 'Confirmer mon inscription'}
                        </Button>
                    </form>
                    <div role="button" tabIndex={0} onClick={() => setStatus('idle')} className="mt-4 text-xs font-bold text-slate-400 hover:text-slate-600 transition cursor-pointer inline-block">
                        Annuler / Modifier l'e-mail
                    </div>
                </div>
            </div>
        );
    }

    return (
        <div className="p-3 h-full flex flex-col animate-in fade-in slide-in-from-bottom-2 duration-300">
            <div className="bg-white rounded-2xl shadow-sm border border-slate-100 p-5 flex-1 flex flex-col justify-center">
                <div className="w-12 h-12 rounded-xl flex items-center justify-center mb-4" style={{ backgroundColor: `${themeColor}15`, color: themeColor }}>
                    <MailIcon size={24} />
                </div>
                <h3 className="text-lg font-black text-slate-800 mb-2">Rester informé</h3>
                <p className="text-sm text-slate-600 mb-6 leading-relaxed">
                    Inscrivez-vous à la newsletter du chantier pour recevoir les alertes importantes (coupures de route, livraisons exceptionnelles, etc.) directement dans votre boîte mail.
                </p>
                
                <form onSubmit={handleSubscribeRequest} className="space-y-3">
                    <input 
                        type="email" 
                        value={email} 
                        onChange={e => setEmail(e.target.value)} 
                        required 
                        disabled={submitting}
                        placeholder="Votre adresse e-mail" 
                        className="w-full border-2 rounded-xl p-3 text-sm outline-none transition border-slate-200 focus:border-slate-800 disabled:opacity-50" 
                    />
                    <Button 
                        type="submit" 
                        disabled={submitting || !email.trim()} 
                        className="w-full py-3.5 font-black uppercase tracking-widest text-xs transition shadow-md border-none justify-center text-white" 
                        style={{ backgroundColor: themeColor }}
                    >
                        {submitting ? <LoaderIcon className="animate-spin w-4 h-4"/> : (
                            <>S'inscrire aux alertes <ArrowRightIcon size={16} /></>
                        )}
                    </Button>
                </form>
                <p className="text-[10px] text-slate-400 text-center mt-4">
                    Votre e-mail ne sera utilisé que pour les communications relatives à ce chantier. Vous pourrez vous désinscrire à tout moment.
                </p>
            </div>
        </div>
    );
};

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