// ECO-PANNEAU.FR - __react/socle/_socle_editeur_entite.jsx

window.pano_EntityEditorModal = ({ editingEntity, setEditingEntity, saveEditedEntity, showToast, onClose, clientUid, panneauId }) => {
    const { useState } = React;
    const [isSaving, setIsSaving] = useState(false);

    // 1. - SÉCURITÉ ANTI-FUITE DE MÉMOIRE ET RACE CONDITIONS (Zéro-Dette)
    const { isMounted, safeFetch } = window.pano_useSafeFetch();

    // 2. - Composants et Icônes
    const { Modal, Button, FormInput } = window.pano_getComponents();
    const { UploadCloudIcon, Trash2Icon, SearchIcon } = window.pano_getIcons();

    // 3. - Logique métier
    const isLot = editingEntity.location.type === 'lot';
    const isIntervenant = editingEntity.location.type === 'intervenant';

    const predefinedRoles = ["Architecte", "Maître d'œuvre", "Bureau d'études", "Bureau de contrôle", "CSPS"];
    const isCustomRole = editingEntity.data.role && !predefinedRoles.includes(editingEntity.data.role);
    const [roleType, setRoleType] = useState(isCustomRole ? "Personnalisé" : (editingEntity.data.role || ""));

    // Suivi de l'état initial pour l'alerte anti-perte de données
    const [initialDataStr] = useState(JSON.stringify(editingEntity.data));
    const isDirty = initialDataStr !== JSON.stringify(editingEntity.data);

    const handleSiretLookup = async () => {
        const siret = editingEntity.data.siret;
        if (!siret || siret.length < 9) {
            if (showToast) showToast("Veuillez saisir un SIREN (9) ou SIRET (14) valide.", "error");
            return;
        }
        
        const payload = { siret };
        if (window.pano_CURRENT_DELEGATE_TOKEN) {
            payload.delegate_token = window.pano_CURRENT_DELEGATE_TOKEN;
        }
        
        const d = await safeFetch('systeme/siret_lookup', { 
            body: payload,
            setLoading: setIsSaving,
            successMessage: "Informations récupérées avec succès."
        });
        
        if (!isMounted.current) return;

        if (d) {
            setEditingEntity(prev => prev ? {
                ...prev,
                data: {
                    ...prev.data,
                    name: d.data.name || prev.data.address, 
                    address: d.data.address || prev.data.address,
                    siret: d.data.siret || prev.data.siret
                }
            } : prev);
        }
    };

    const handleFileUpload = async (e) => {
        const file = e.target.files[0];
        if (e.target) e.target.value = null;
        if (!file) return;

        setIsSaving(true);
        const reader = new FileReader();
        reader.onload = async (event) => {
            if (!isMounted.current) return;

            const base64Url = event.target.result;
            setEditingEntity(prev => prev ? { ...prev, data: { ...prev.data, logoUrl: base64Url } } : prev);

            try {
                // uploadFile reste une fonction métier externe, on garde donc setIsSaving manuel ici
                const fileId = await window.pano_uploadFile(file, 'image', null, false, false, clientUid, panneauId);
                
                if (!isMounted.current) return;
                
                setEditingEntity(prev => prev ? { ...prev, data: { ...prev.data, logoId: fileId.id || fileId } } : prev);
            } catch (err) {
                if (!isMounted.current) return;
                
                if (showToast) showToast(err, "error");
                else if (window.pano_logFallback) window.pano_logFallback("Erreur d'upload du logo de l'entité ignorée car showToast est introuvable.");
                
                setEditingEntity(prev => prev ? { ...prev, data: { ...prev.data, logoUrl: '' } } : prev);
            } finally {
                if (isMounted.current) setIsSaving(false);
            }
        };
        reader.readAsDataURL(file);
    };

    const handleSubmit = (e) => {
        e.preventDefault();
        saveEditedEntity();
    };

    let title = "Modifier l'élément";
    if (isLot) title = editingEntity.location.index !== undefined ? "Modifier le lot" : "Nouveau lot";
    else if (isIntervenant) title = editingEntity.location.index !== undefined ? "Modifier l'intervenant" : "Nouvel intervenant";
    else title = editingEntity.location.index !== undefined ? "Modifier l'entreprise" : "Nouvelle entreprise";

    // 4. - Rendu UI
    return (
        <Modal 
            title={title} 
            onClose={() => {
                setEditingEntity(null);
                if (onClose) onClose();
            }} 
            isSaving={isSaving}
            isDirty={isDirty}
            formId="entity-form"
            zIndex="z-[250]"
        >
            <form id="entity-form" onSubmit={handleSubmit} className="space-y-4 overflow-x-hidden">
                {!isLot && (
                    <div className="space-y-2">
                        <label className="text-xs font-bold text-slate-500 uppercase block break-words">N° SIRET (saisie auto)</label>
                        <div className="flex gap-2">
                            <input type="text" value={editingEntity.data.siret || ''} onChange={e => setEditingEntity(prev => prev ? {...prev, data: {...prev.data, siret: e.target.value.replace(/\s/g, '')}} : prev)} placeholder="Saisir SIRET pour auto-remplir" 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} disabled={isSaving} />
                            <Button variant="info" icon={SearchIcon} type="button" onClick={handleSiretLookup} disabled={!editingEntity.data.siret || editingEntity.data.siret.length < 9 || isSaving} className="px-4 py-3 shrink-0">
                                <span className="hidden sm:inline">Rechercher</span>
                            </Button>
                        </div>
                    </div>
                )}
                
                <div className="space-y-2">
                    <label className="text-xs font-bold text-slate-500 uppercase block break-words">{isLot ? "Nom du lot" : "Nom de l'entreprise"} <span className="text-red-500">*</span></label>
                    <input type="text" value={editingEntity.data.name || ''} onChange={e => setEditingEntity(prev => prev ? {...prev, data: {...prev.data, name: e.target.value}} : prev)} className="w-full border-2 border-slate-200 rounded-xl p-3 focus:border-emerald-500 outline-none transition font-bold" required autoFocus disabled={isSaving} />
                </div>
                
                {isIntervenant && (
                    <div className="space-y-2">
                        <label className="text-xs font-bold text-slate-500 uppercase block break-words">Rôle / fonction <span className="text-red-500">*</span></label>
                        <select value={roleType} onChange={e => {
                            const val = e.target.value;
                            setRoleType(val);
                            if (val !== 'Personnalisé') {
                                setEditingEntity(prev => prev ? {...prev, data: {...prev.data, role: val}} : prev);
                            } else {
                                setEditingEntity(prev => prev ? {...prev, data: {...prev.data, role: ''}} : prev);
                            }
                        }} className="w-full border-2 border-slate-200 rounded-xl p-3 focus:border-emerald-500 outline-none transition font-bold bg-white" required disabled={isSaving}>
                            <option value="">-- Sélectionner un rôle --</option>
                            <option value="Architecte">Architecte</option>
                            <option value="Maître d'œuvre">Maître d'œuvre</option>
                            <option value="Bureau d'études">Bureau d'études</option>
                            <option value="Bureau de contrôle">Bureau de contrôle</option>
                            <option value="CSPS">CSPS (Sécurité)</option>
                            <option value="Personnalisé">Personnalisé</option>
                        </select>
                        {roleType === 'Personnalisé' && (
                            <input type="text" value={editingEntity.data.role || ''} onChange={e => setEditingEntity(prev => prev ? {...prev, data: {...prev.data, role: e.target.value}} : prev)} placeholder="Précisez la fonction" className="w-full border-2 border-emerald-200 rounded-xl p-3 mt-2 focus:border-emerald-500 outline-none transition font-bold bg-emerald-50" required disabled={isSaving} />
                        )}
                    </div>
                )}
                
                {!isLot && (
                    <div className="space-y-4 pt-4 border-t border-slate-100">
                        <h5 className="text-xs font-black text-slate-800 uppercase tracking-widest break-words">Coordonnées (optionnel)</h5>
                        
                        <div className="space-y-1">
                            <label className="text-[10px] font-bold text-slate-500 uppercase block break-words">Adresse postale</label>
                            <input type="text" value={editingEntity.data.address || ''} onChange={e => setEditingEntity(prev => prev ? {...prev, data: {...prev.data, address: e.target.value}} : prev)} className="w-full border border-slate-200 rounded-lg p-2.5 text-sm focus:border-emerald-500 outline-none transition font-medium" disabled={isSaving} />
                        </div>
                        
                        <div className="grid grid-cols-2 gap-4">
                            <div className="space-y-1 min-w-0">
                                <label className="text-[10px] font-bold text-slate-500 uppercase block break-words">Téléphone</label>
                                <input type="tel" value={editingEntity.data.phone || ''} onChange={e => setEditingEntity(prev => prev ? {...prev, data: {...prev.data, phone: e.target.value}} : prev)} className="w-full border border-slate-200 rounded-lg p-2.5 text-sm focus:border-emerald-500 outline-none transition font-medium" disabled={isSaving} />
                            </div>
                            <div className="space-y-1 min-w-0">
                                <label className="text-[10px] font-bold text-slate-500 uppercase block break-words">E-mail</label>
                                <input type="email" value={editingEntity.data.email || ''} onChange={e => setEditingEntity(prev => prev ? {...prev, data: {...prev.data, email: e.target.value}} : prev)} className="w-full border border-slate-200 rounded-lg p-2.5 text-sm focus:border-emerald-500 outline-none transition font-medium" disabled={isSaving} />
                            </div>
                        </div>

                        <div className="space-y-1">
                            <label className="text-[10px] font-bold text-slate-500 uppercase block break-words">Site web</label>
                            <input type="url" placeholder="https://" value={editingEntity.data.website || ''} onChange={e => setEditingEntity(prev => prev ? {...prev, data: {...prev.data, website: e.target.value}} : prev)} className="w-full border border-slate-200 rounded-lg p-2.5 text-sm focus:border-emerald-500 outline-none transition font-medium" disabled={isSaving} />
                        </div>

                        <div className="space-y-2 pt-2 border-t border-slate-100">
                            <label className="text-xs font-bold text-slate-500 uppercase block break-words">Logo de l'entité</label>
                            <div className="flex items-center gap-4">
                                <label className={`bg-white border-2 border-slate-200 hover:border-emerald-500 text-slate-700 px-4 py-2 rounded-xl font-bold transition shadow-sm flex items-center gap-2 text-xs shrink-0 ${isSaving ? 'opacity-50 cursor-not-allowed pointer-events-none' : 'cursor-pointer'}`}>
                                    {UploadCloudIcon && <UploadCloudIcon size={16}/>} Uploader
                                    <input type="file" accept="image/*" className="hidden" onChange={handleFileUpload} disabled={isSaving} />
                                </label>
                                {(editingEntity.data.logoUrl || editingEntity.data.logoId) && (
                                    <div className="relative w-16 h-16 rounded-xl border border-slate-200 bg-slate-50 flex items-center justify-center p-1 group shrink-0">
                                        <img src={editingEntity.data.logoUrl || (window.pano_CONFIG?.apiBaseUrl + 'file/download&type=image&id=' + editingEntity.data.logoId + '&preview=1')} alt="Logo" className="max-w-full max-h-full object-contain rounded-lg" />
                                        {Button && Trash2Icon && !isSaving && (
                                            <Button 
                                                variant="danger" 
                                                shape="round" 
                                                icon={Trash2Icon}
                                                onClick={(e) => { 
                                                    e.preventDefault(); 
                                                    setEditingEntity(prev => prev ? { ...prev, data: { ...prev.data, logoUrl: '', logoId: '' } } : prev); 
                                                }}
                                                className="absolute top-1 right-1 opacity-0 group-hover:opacity-100 transition-all shadow-md p-1.5"
                                                title="Supprimer le logo"
                                            />
                                        )}
                                    </div>
                                )}
                            </div>
                        </div>
                    </div>
                )}
            </form>
        </Modal>
    );
};

/* EOF ========== [__react/socle/_socle_editeur_entite.jsx] */