/**
 * =========================================================================
 * PLATEFORME ECO-PANNEAU.FR - VERSION 1.0.0
 * Paramètres du compte client - Sous-onglet : Profil et Facturation
 * =========================================================================
 */

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_ClientSettingsProfile = ({ myClientData, data, showToast, refreshData }) => {
    const { useState } = React;

    const [isSaving, setIsSaving] = useState(false);
    const [emailChangeConfig, setEmailChangeConfig] = useState(null);

    const [profileData, setProfileData] = useState({
        name: myClientData.name || '',
        full_name: myClientData.full_name || '',
        email: myClientData.email || '',
        phone: myClientData.phone || '',
        address: myClientData.address || '',
        siret: myClientData.siret || '',
        tva: myClientData.tva || ''
    });

    const adminSettings = data.settings || {};
    const optCollab = adminSettings.opt_collab || 'active';
    const optMessaging = adminSettings.opt_messaging || 'active';
    const optNewsletter = adminSettings.opt_newsletter || 'active';

    const hasOptionalFeatures = [optCollab, optMessaging, optNewsletter].some(opt => opt === 'optional_on' || opt === 'optional_off' || opt === 'optional');

    const getInitialOption = (adminOpt, savedVal) => {
        if (savedVal !== undefined) return savedVal;
        if (adminOpt === 'optional_on') return true; 
        return false; 
    };

    let parsedOpts = {};
    try {
        if (myClientData.uiMode && myClientData.uiMode.startsWith('{')) {
            parsedOpts = JSON.parse(myClientData.uiMode);
        }
    } catch(e) {}

    const [clientOptions, setClientOptions] = useState({
        collab: getInitialOption(optCollab, parsedOpts.collab),
        messaging: getInitialOption(optMessaging, parsedOpts.messaging),
        newsletter: getInitialOption(optNewsletter, parsedOpts.newsletter)
    });

    const {
        FileTextIcon, SaveIcon, LoaderIcon, SearchIcon, SettingsIcon, RefreshCwIcon
    } = window.pano_getIcons();

    const FormInput = window.pano_FormInput || FallbackNull;
    const FormTextarea = window.pano_FormTextarea || FallbackNull;
    const Modal = window.pano_Modal || FallbackNull;
    const Button = window.pano_Button || FallbackNull;
    const Toggle = window.pano_Toggle || FallbackNull;
    const TextLogo = window.pano_TextLogo || FallbackTextLogo;
    const CardGrid = window.pano_CardGrid || FallbackCardGrid;

    const hasCollaborations = (data.panneaux || []).some(p => 
        (p.client_uid === myClientData.id && p.collaborators && p.collaborators.length > 0) || 
        (p.client_uid !== myClientData.id)
    );

    const handleProfileSave = async (e) => {
        e.preventDefault();
        
        if (!profileData.name.trim()) {
            showToast("Le nom de la société est obligatoire.", "error");
            return;
        }

        if (hasCollaborations && !profileData.full_name.trim()) {
            showToast("Vous ne pouvez pas effacer votre nom complet car vous participez à des projets collaboratifs.", "error");
            return;
        }
        
        const payload = {
            ...profileData,
            uiMode: JSON.stringify(clientOptions)
        };

        const d = await window.pano_apiFetch('clients/profile/update', { 
            body: payload, 
            setLoading: setIsSaving, 
            successMessage: "Profil et options mis à jour avec succès." 
        });
        
        if (d) refreshData();
    };

    const handleSiretLookup = async () => {
        if (!profileData.siret || profileData.siret.length < 9) {
            showToast("Veuillez saisir un SIREN (9 chiffres) ou SIRET (14 chiffres) valide.", "error");
            return;
        }

        const d = await window.pano_apiFetch('systeme/siret_lookup', { 
            body: { siret: profileData.siret }, 
            setLoading: setIsSaving,
            successMessage: "Informations récupérées avec succès !"
        });

        if (d) {
            setProfileData({
                ...profileData,
                name: d.data.name || profileData.name,
                address: d.data.address || profileData.address,
                tva: d.data.tva || profileData.tva,
                siret: d.data.siret || profileData.siret
            });
        }
    };

    const handleEmailChangeRequest = async (e) => {
        e.preventDefault();
        if (!emailChangeConfig.newEmail.trim() || !emailChangeConfig.newEmail.includes('@')) {
            showToast("Veuillez saisir un e-mail valide.", "error");
            return;
        }
        const d = await window.pano_apiFetch('clients/profile/request_email', {
            body: { email: emailChangeConfig.newEmail },
            setLoading: setIsSaving,
            successMessage: "Un code de vérification a été envoyé à cette nouvelle adresse."
        });
        if (d) {
            setEmailChangeConfig({ ...emailChangeConfig, step: 'verify' });
        }
    };

    const handleEmailChangeVerify = async (e) => {
        e.preventDefault();
        if (emailChangeConfig.code.length !== 6) return;
        const d = await window.pano_apiFetch('clients/profile/update_email', {
            body: { code: emailChangeConfig.code },
            setLoading: setIsSaving,
            successMessage: "Votre adresse e-mail a été mise à jour avec succès. Veuillez vous reconnecter."
        });
        if (d) {
            setEmailChangeConfig(null);
            setTimeout(() => window.location.href = '?', 1500);
        }
    };

    const renderOption = (id, label, desc, adminStatus, clientValue, toggleKey) => {
        if (adminStatus === 'active' || adminStatus === 'disabled') return null;
        
        return (
            <div className="flex items-center justify-between p-4 bg-slate-50 border border-slate-200 rounded-xl shadow-sm animate-in fade-in">
                <div>
                    <span className="font-bold text-slate-700 text-sm block">{label}</span>
                    <span className="text-xs text-slate-500">{desc}</span>
                </div>
                <Toggle checked={clientValue} onChange={v => setClientOptions({...clientOptions, [toggleKey]: v})} />
            </div>
        );
    };

    return (
        <div className="space-y-6 max-w-4xl animate-in fade-in">
            <form onSubmit={handleProfileSave} className="space-y-6">
                <div className="bg-blue-50 border border-blue-200 p-4 rounded-xl text-blue-800 text-sm mb-6">
                    Le nom de la société est obligatoire. Cette information sera utilisée pour la facturation et apparaîtra lors de vos invitations collaboratives sur <a href="https://eco-panneau.fr" target="_blank" rel="noopener noreferrer" className="hover:opacity-80 transition ml-1"><TextLogo className="text-sm" /></a>.
                </div>

                <CardGrid minWidth="200px" className="gap-6">
                    <FormInput label="Société" value={profileData.name} onChange={e => setProfileData({...profileData, name: e.target.value})} required />
                    <FormInput 
                        label="Nom complet (contact)" 
                        value={profileData.full_name} 
                        onChange={e => setProfileData({...profileData, full_name: e.target.value})} 
                        required={hasCollaborations}
                        hint={hasCollaborations 
                            ? "Vous ne pouvez pas effacer ce champ car vous participez à des projets collaboratifs." 
                            : "Obligatoire uniquement pour inviter ou rejoindre des collaborateurs."} 
                    />
                </CardGrid>

                <CardGrid minWidth="200px" className="gap-6 items-start">
                    <div className="space-y-1">
                        <label className="text-xs font-bold text-slate-500 uppercase block">Adresse e-mail de connexion</label>
                        <div className="flex gap-2">
                            <input type="email" value={profileData.email} disabled className="flex-1 border-2 border-slate-200 bg-slate-50 text-slate-500 rounded-xl p-3 text-sm outline-none font-bold cursor-not-allowed" />
                            <Button variant="secondary" type="button" onClick={() => setEmailChangeConfig({ step: 'request', newEmail: '', code: '' })} disabled={isSaving} className="px-4 py-3 shrink-0">
                                Modifier
                            </Button>
                        </div>
                        <p className="text-xs text-slate-400 mt-1">Une vérification de sécurité sera exigée pour modifier votre e-mail.</p>
                    </div>
                    
                    <FormInput label="Téléphone" type="tel" value={profileData.phone} onChange={e => setProfileData({...profileData, phone: e.target.value})} />
                </CardGrid>

                <div className="space-y-2 pt-6 border-t border-slate-100">
                    <h3 className="font-black text-slate-800 text-lg mb-4 flex items-center gap-2"><FileTextIcon size={20} className="text-blue-600"/> Informations de facturation</h3>
                    <CardGrid minWidth="200px" className="gap-6 items-end">
                        <div className="space-y-1 col-span-full">
                            <label className="text-xs font-bold text-slate-500 uppercase block">N° SIRET</label>
                            <div className="flex gap-2">
                                <input type="text" value={profileData.siret} onChange={e => setProfileData({...profileData, siret: e.target.value.replace(/\s/g, '')})} placeholder="14 chiffres" className="flex-1 min-w-0 border-2 border-slate-200 rounded-xl p-3 focus:border-emerald-500 outline-none transition font-bold" maxLength={14} />
                                <Button variant="info" icon={SearchIcon} type="button" onClick={handleSiretLookup} disabled={isSaving || profileData.siret.length < 9} className="px-4 py-3 shrink-0">
                                    <span className="hidden sm:inline">Rechercher</span>
                                </Button>
                            </div>
                        </div>
                        <FormInput label="N° TVA intracommunautaire" value={profileData.tva} onChange={e => setProfileData({...profileData, tva: e.target.value})} className="col-span-full" />
                    </CardGrid>
                </div>
                
                <FormTextarea label="Adresse de facturation / siège social" value={profileData.address} onChange={e => setProfileData({...profileData, address: e.target.value})} rows={3} />

                {hasOptionalFeatures && (
                    <div className="space-y-4 pt-6 border-t border-slate-100">
                        <h3 className="font-black text-slate-800 text-lg flex items-center gap-2"><SettingsIcon size={20} className="text-emerald-600"/> Fonctionnalités du compte</h3>
                        <p className="text-sm text-slate-500 mb-4">Gérez les options additionnelles de votre espace et de vos panneaux.</p>
                        <div className="grid grid-cols-1 gap-4">
                            {renderOption('opt_collab', 'Travail en collaboration', 'Inviter des membres sur vos panneaux.', optCollab, clientOptions.collab, 'collab')}
                            {renderOption('opt_messaging', 'Messagerie des riverains', 'Recevoir et répondre aux messages du voisinage.', optMessaging, clientOptions.messaging, 'messaging')}
                            {renderOption('opt_newsletter', 'Info riverains', 'Informer les riverains abonnés des événements.', optNewsletter, clientOptions.newsletter, 'newsletter')}
                        </div>
                    </div>
                )}

                <Button type="submit" variant="primary" disabled={isSaving} icon={isSaving ? LoaderIcon : SaveIcon} className="w-full sm:w-auto uppercase tracking-widest text-sm py-3 px-6 mt-4">
                    Enregistrer les modifications
                </Button>
            </form>

            {emailChangeConfig && Modal && (
                <Modal title="Modifier l'adresse e-mail" onClose={() => setEmailChangeConfig(null)} preventClose={isSaving} zIndex="z-[250]">
                    {emailChangeConfig.step === 'request' ? (
                        <form onSubmit={handleEmailChangeRequest} className="space-y-4">
                            <p className="text-sm text-slate-600">Saisissez votre nouvelle adresse e-mail. Un code de vérification y sera envoyé pour confirmer qu'elle vous appartient bien.</p>
                            <input 
                                type="email" 
                                value={emailChangeConfig.newEmail} 
                                onChange={e => setEmailChangeConfig({...emailChangeConfig, newEmail: e.target.value})} 
                                placeholder="Nouvelle adresse e-mail" 
                                required 
                                className="w-full border-2 border-slate-200 rounded-xl p-3 focus:border-emerald-500 outline-none transition font-bold" 
                                autoFocus 
                            />
                            <div className="flex gap-3 pt-4 border-t border-slate-100">
                                <Button variant="secondary" type="button" onClick={() => setEmailChangeConfig(null)} disabled={isSaving} className="flex-1 py-3 justify-center">Annuler</Button>
                                <Button type="submit" variant="primary" disabled={isSaving || !emailChangeConfig.newEmail} icon={isSaving ? LoaderIcon : null} className="flex-1 py-3 justify-center">Envoyer le code</Button>
                            </div>
                        </form>
                    ) : (
                        <form onSubmit={handleEmailChangeVerify} className="space-y-4">
                            <p className="text-sm text-slate-600">Saisissez le code à 6 chiffres envoyé à <strong>{emailChangeConfig.newEmail}</strong>.</p>
                            <input 
                                type="text" 
                                value={emailChangeConfig.code} 
                                onChange={e => setEmailChangeConfig({...emailChangeConfig, code: e.target.value.replace(/\D/g, '').slice(0, 6)})} 
                                placeholder="000000" 
                                required 
                                className="w-full border-2 border-slate-200 rounded-xl p-3 focus:border-emerald-500 outline-none transition text-center text-3xl tracking-[0.25em] font-black" 
                                autoFocus 
                            />
                            <div className="flex justify-between items-center mt-3 pt-3 border-t border-slate-100">
                                <div role="button" tabIndex={0} onClick={handleEmailChangeRequest} className={`text-xs font-bold text-emerald-600 hover:text-emerald-700 transition flex items-center gap-1 cursor-pointer ${isSaving ? 'opacity-50 pointer-events-none' : ''}`}>
                                    {RefreshCwIcon && <RefreshCwIcon size={12}/>} Renvoyer le code
                                </div>
                                <div role="button" tabIndex={0} onClick={() => setEmailChangeConfig(null)} className={`text-xs font-bold text-slate-500 hover:text-slate-800 transition cursor-pointer ${isSaving ? 'opacity-50 pointer-events-none' : ''}`}>
                                    Annuler
                                </div>
                            </div>
                            <Button type="submit" variant="primary" disabled={isSaving || emailChangeConfig.code.length !== 6} icon={isSaving ? LoaderIcon : null} className="w-full py-4 uppercase tracking-widest justify-center mt-4">
                                Valider l'e-mail
                            </Button>
                        </form>
                    )}
                </Modal>
            )}
        </div>
    );
};

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