/**
 * =========================================================================
 * PLATEFORME ECO-PANNEAU.FR - VERSION 1.0.0
 * Composant : Formulaire de premier contact (Riverains et Public) avec OTP
 * =========================================================================
 */

const { useState, useEffect, useRef } = React;

const BasePublicContactForm = ({ panneauId, showToast, onSuccess, isPreview, hideAttachments = false, settings = {}, themeColor = '#059669' }) => {
    
    // FACTORISATION : Utilisation du Hook global de gestion des modales par URL
    const { activeDialog: routerActiveDialog, openDialog: routerOpenDialog, closeCurrentLayer: routerCloseLayer } = window.useUrlModal();

    // FACTORISATION : Récupération sécurisée et propre des icônes
    const {
        ArrowUpIcon, LoaderIcon, MessageSquareIcon, FileTextIcon, 
        ImageIcon, PaperclipIcon, MailIcon, XIcon
    } = window.getIcons();

    const Button = window.Button || (() => null);
    const ModerationModal = window.ModerationModal || (() => null);

    const [submitting, setSubmitting] = useState(false);
    const [mountTime] = useState(Math.floor(Date.now() / 1000));
    const [selectedFiles, setSelectedFiles] = useState([]);
    const [message, setMessage] = useState('');
    const [isDragging, setIsDragging] = useState(false);
    const [dragCounter, setDragCounter] = useState(0);
    const textareaRef = useRef(null);

    // États de vérification
    const [verificationState, setVerificationState] = useState('idle'); // idle, requesting, verifying, verifying_alert
    const [verifySession, setVerifySession] = useState('');
    const [verifyCode, setVerifyCode] = useState('');
    const [targetEmail, setTargetEmail] = useState('');
    
    // États gérés par l'URL
    const [moderationWarning, setModerationWarning] = useState(null);

    useEffect(() => {
        if (routerActiveDialog !== 'verify_email') setVerificationState('idle');
        if (routerActiveDialog !== 'moderation_warning') setModerationWarning(null);
    }, [routerActiveDialog]);

    useEffect(() => {
        if (textareaRef.current) {
            textareaRef.current.style.height = ''; 
            const scrollH = textareaRef.current.scrollHeight;
            const clientH = textareaRef.current.clientHeight;
            
            if (scrollH > clientH) {
                textareaRef.current.style.height = `${scrollH}px`;
            }
        }
    }, [message]);

    const addFiles = (fileList) => {
        const validTypes = ['image/jpeg', 'image/png', 'image/webp', 'application/pdf'];
        const files = Array.from(fileList).filter(f => validTypes.includes(f.type));
        if (files.length === 0) return;

        if (selectedFiles.length + files.length > 20) {
            if (showToast) showToast("Maximum 20 fichiers autorisés.", "error");
            return;
        }
        
        const validFiles = [];
        for (let f of files) {
            if (f.size > 5 * 1024 * 1024) {
                if (showToast) showToast("Un ou plusieurs fichiers dépassent 5 Mo.", "error");
                return;
            }
            validFiles.push(f);
        }
        setSelectedFiles(prev => [...prev, ...validFiles]);
    };

    const handleFileChange = (e) => { addFiles(e.target.files); e.target.value = null; };
    const handlePaste = (e) => { if (!hideAttachments && e.clipboardData && e.clipboardData.files && e.clipboardData.files.length > 0) addFiles(e.clipboardData.files); };
    const handleDragEnter = (e) => { if (hideAttachments) return; e.preventDefault(); e.stopPropagation(); setDragCounter(prev => prev + 1); setIsDragging(true); };
    const handleDragLeave = (e) => { if (hideAttachments) return; e.preventDefault(); e.stopPropagation(); setDragCounter(prev => { const nc = prev - 1; if (nc === 0) setIsDragging(false); return nc; }); };
    const handleDragOver = (e) => { if (hideAttachments) return; e.preventDefault(); e.stopPropagation(); };
    
    const handleDrop = (e) => {
        if (hideAttachments) return; e.preventDefault(); e.stopPropagation();
        setDragCounter(0); setIsDragging(false);
        if (e.dataTransfer && e.dataTransfer.files && e.dataTransfer.files.length > 0) addFiles(e.dataTransfer.files);
    };

    const removeFile = (index) => {
        const newFiles = [...selectedFiles];
        newFiles.splice(index, 1);
        setSelectedFiles(newFiles);
    };

    const executeSubmit = async (authorEmail, existingToken, session, code, isPendingControl = false) => {
        setSubmitting(true);
        let finalDetail = message.trim();
        
        if (!hideAttachments) {
            for (let file of selectedFiles) {
                const fileType = file.type.includes('pdf') ? 'pdf' : 'image';
                try {
                    const fileId = await window.uploadFile(file, fileType, null, true, false, null, panneauId);
                    finalDetail += `\n[ATTACHMENT:${fileId}:${fileType}]`;
                } catch(err) {
                    if (showToast) showToast("Erreur lors de l'upload : " + err.message, 'error');
                    setSubmitting(false);
                    return;
                }
            }
        }

        const payload = { 
            panneauId, 
            detail: finalDetail, 
            author: authorEmail, 
            isAlert: isPendingControl ? 2 : 0, 
            hp_text: document.querySelector('input[name="hp_text"]')?.value || '', 
            hp_time: mountTime,
            verification_token: existingToken,
            verify_session: session,
            verify_code: code
        };
        
        const d = await window.apiFetch('interactions', {
            body: payload, 
            setLoading: setSubmitting,
            errorMessage: "Erreur lors de l'envoi"
        });
        
        if (d) {
            if (d.data && d.data.verification_token) {
                localStorage.setItem('eco_riverain_token_' + authorEmail, d.data.verification_token);
            }
            setMessage(''); setSelectedFiles([]); setVerificationState('idle'); setVerifyCode('');
            if (onSuccess) onSuccess();
        } else {
            setVerificationState('idle');
        }
    };

    const startVerificationFlow = (isPendingControl = false) => {
        const email = document.querySelector('input[name="email"]')?.value || '';
        if (!email) return;
        setTargetEmail(email);
        
        const existingToken = localStorage.getItem('eco_riverain_token_' + email);
        if (existingToken) {
            executeSubmit(email, existingToken, null, null, isPendingControl);
            return;
        }

        setVerificationState('requesting');
        window.apiFetch('interactions/verify_request', {
            body: { email },
            successMessage: "Un code a été envoyé à votre adresse e-mail.",
            errorMessage: "Veuillez patienter avant de demander un nouveau code."
        }).then(d => {
            if (d && d.data && d.data.verify_session) {
                setVerifySession(d.data.verify_session);
                setVerificationState(isPendingControl ? 'verifying_alert' : 'verifying');
                routerOpenDialog('verify_email');
            } else {
                setVerificationState('idle');
            }
        });
    };

    const handleInitialSubmit = (e) => {
        if (e && e.preventDefault) e.preventDefault(); 
        if (isPreview) {
            if (showToast) showToast("Ceci est un aperçu interactif. La messagerie n'est pas fonctionnelle ici.", "info");
            return;
        }

        const word = window.checkForBlacklist ? window.checkForBlacklist(message, settings) : null;
        if (word) { 
            setModerationWarning(word); 
            routerOpenDialog('moderation_warning');
            return; 
        }
        
        // BYPASS: Si c'est le formulaire public du site, on envoie directement (le Honeypot protège déjà).
        if (panneauId === 'CONTACT_PUBLIC') {
            const email = document.querySelector('input[name="email"]')?.value || '';
            executeSubmit(email, null, null, null, false);
        } else {
            startVerificationFlow(false);
        }
    };

    return (
        <form onSubmit={handleInitialSubmit} onDragEnter={handleDragEnter} onDragLeave={handleDragLeave} onDragOver={handleDragOver} onDrop={handleDrop} className="space-y-3 flex flex-col min-h-full p-2 relative">
            {isDragging && !hideAttachments && (
                <div className="absolute inset-0 z-[100] bg-emerald-500/20 backdrop-blur-sm border-4 border-emerald-500 border-dashed rounded-2xl flex flex-col items-center justify-center pointer-events-none">
                    <div className="bg-white p-6 rounded-2xl shadow-xl flex flex-col items-center text-center">
                        <ArrowUpIcon size={48} className="text-emerald-500 mb-4 animate-bounce" />
                        <span className="text-xl font-black text-slate-800">Relâchez vos fichiers ici</span>
                    </div>
                </div>
            )}

            {routerActiveDialog === 'moderation_warning' && moderationWarning && ModerationModal && (
                <ModerationModal word={moderationWarning} onModify={routerCloseLayer} onRequestControl={() => { 
                    routerCloseLayer(); 
                    setTimeout(() => {
                        if (panneauId === 'CONTACT_PUBLIC') {
                            const email = document.querySelector('input[name="email"]')?.value || '';
                            executeSubmit(email, null, null, null, true);
                        } else {
                            startVerificationFlow(true);
                        }
                    }, 100); 
                }} />
            )}

            {routerActiveDialog === 'verify_email' && verificationState.startsWith('verifying') && (
                <div className="fixed inset-0 z-[999999] bg-slate-900/80 backdrop-blur-sm flex items-center justify-center p-4 animate-in fade-in rounded-2xl" onMouseDown={routerCloseLayer}>
                    <div className="bg-white rounded-2xl p-6 max-w-md w-full shadow-2xl flex flex-col items-center text-center" onMouseDown={e => e.stopPropagation()}>
                        <MailIcon size={32} className="text-emerald-600 mb-3" />
                        <h3 className="font-black text-xl 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>{targetEmail}</strong>. Veuillez le saisir pour confirmer que cette adresse vous appartient.</p>
                        <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-emerald-500 mb-6" placeholder="000000" />
                        <div className="flex gap-3 w-full">
                            <Button variant="secondary" type="button" onClick={routerCloseLayer} className="flex-1 py-3 justify-center">Annuler</Button>
                            <Button variant="primary" type="button" onClick={() => { routerCloseLayer(); setTimeout(() => executeSubmit(targetEmail, null, verifySession, verifyCode, verificationState === 'verifying_alert'), 100); }} disabled={verifyCode.length !== 6 || submitting} className="flex-1 py-3 justify-center">
                                {submitting ? <LoaderIcon className="animate-spin w-5 h-5"/> : 'Valider'}
                            </Button>
                        </div>
                    </div>
                </div>
            )}

            <input type="text" name="hp_text" className="absolute opacity-0 -z-10 w-0 h-0" tabIndex="-1" autoComplete="off" />
            <input type="hidden" name="hp_time" value={mountTime} />

            <input name="email" type="email" required placeholder="Votre e-mail (pour recevoir la réponse)" disabled={verificationState === 'requesting' || submitting} className="w-full border-2 rounded-xl p-3 text-sm outline-none transition shrink-0 border-slate-200 focus:border-slate-800 disabled:opacity-50" />
            
            {hideAttachments && selectedFiles.length > 0 && (
                <div className="bg-white border border-slate-200 rounded-xl p-2 flex flex-col gap-2 max-h-32 overflow-y-auto custom-scrollbar shrink-0 mt-2">
                    {selectedFiles.map((f, i) => (
                        <div key={i} className="bg-slate-50 p-2 rounded-lg border border-slate-200 flex items-center justify-between shadow-sm shrink-0">
                            <span className="text-xs font-bold text-slate-600 flex items-center gap-2">{f.type.includes('pdf') ? <FileTextIcon size={16}/> : <ImageIcon size={16}/>}<span className="truncate max-w-[200px]">{f.name}</span></span>
                            <div role="button" tabIndex={0} onClick={() => { if(!submitting) removeFile(i); }} className={`text-red-500 hover:text-red-700 bg-red-50 p-1.5 rounded-lg transition ${submitting ? 'opacity-50 cursor-not-allowed' : 'cursor-pointer'}`}><XIcon size={14}/></div>
                        </div>
                    ))}
                </div>
            )}

            <textarea 
                ref={textareaRef} 
                name="detail" 
                value={message} 
                onChange={(e) => setMessage(e.target.value)} 
                onPaste={handlePaste} 
                onKeyDown={(e) => {
                    if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') {
                        e.preventDefault();
                        if (!(submitting || verificationState === 'requesting' || (hideAttachments ? !message.trim() : (selectedFiles.length === 0 && !message.trim())))) {
                            handleInitialSubmit(e);
                        }
                    }
                }}
                required={hideAttachments || selectedFiles.length === 0} 
                disabled={verificationState === 'requesting' || submitting}
                placeholder="Votre message... (Ctrl+Entrée pour envoyer, coller ou glisser des images est accepté)" 
                className="w-full border-2 rounded-xl p-3 text-sm outline-none transition resize-none flex-1 border-slate-200 focus:border-slate-800 overflow-hidden min-h-[120px] disabled:opacity-50">
            </textarea>
            
            {!hideAttachments && selectedFiles.length > 0 && (
                <div className="bg-white border border-slate-200 rounded-xl p-2 flex flex-col gap-2 max-h-32 overflow-y-auto custom-scrollbar shrink-0 mt-2">
                    {selectedFiles.map((f, i) => (
                        <div key={i} className="bg-slate-50 p-2 rounded-lg border border-slate-200 flex items-center justify-between shadow-sm shrink-0">
                            <span className="text-xs font-bold text-slate-600 flex items-center gap-2">{f.type.includes('pdf') ? <FileTextIcon size={16}/> : <ImageIcon size={16}/>}<span className="truncate max-w-[200px]">{f.name}</span></span>
                            <div role="button" tabIndex={0} onClick={() => { if(!submitting) removeFile(i); }} className={`text-red-500 hover:text-red-700 bg-red-50 p-1.5 rounded-lg transition ${submitting ? 'opacity-50 cursor-not-allowed' : 'cursor-pointer'}`}><XIcon size={14}/></div>
                        </div>
                    ))}
                </div>
            )}
            
            <div className="flex gap-2 items-center shrink-0 mt-1">
                {!hideAttachments && (
                    <label className={`cursor-pointer w-[46px] h-[46px] rounded-xl transition shadow-sm flex items-center justify-center shrink-0 border ${submitting || verificationState === 'requesting' || selectedFiles.length >= 20 ? 'bg-slate-50 border-slate-100 text-slate-400 opacity-50' : 'bg-white border-slate-200 hover:bg-slate-50'}`} style={(!submitting && verificationState !== 'requesting' && selectedFiles.length < 20) ? { color: themeColor } : {}} title="Joindre des photos ou PDF (max 20)">
                        <PaperclipIcon size={20} />
                        <input type="file" multiple className="hidden" accept="image/jpeg, image/png, image/webp, application/pdf" disabled={submitting || verificationState === 'requesting' || selectedFiles.length >= 20} onChange={handleFileChange} />
                    </label>
                )}
                <Button 
                    type="submit" 
                    disabled={submitting || verificationState === 'requesting' || (hideAttachments ? !message.trim() : (selectedFiles.length === 0 && !message.trim()))} 
                    className="flex-1 h-[46px] text-white font-black uppercase tracking-widest text-xs transition shadow-md border-none justify-center" 
                    style={{ backgroundColor: themeColor }}
                >
                    {submitting || verificationState === 'requesting' ? <LoaderIcon className="animate-spin w-4 h-4"/> : <MessageSquareIcon size={14}/>} Envoyer
                </Button>
            </div>
        </form>
    );
};

window.PublicContactForm = (props) => {
    return (
        <div className="flex flex-col h-full relative">
            <BasePublicContactForm {...props} />
        </div>
    );
};

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