/**
 * =========================================================================
 * PLATEFORME ECO-PANNEAU.FR - VERSION 1.0.0
 * Socle Éditeur (Entités) - Modale d'édition Intervenants/Lots/Entreprises
 * =========================================================================
 */

window.pano_EntityEditorModal = ({ editingEntity, setEditingEntity, saveEditedEntity, showToast, clientUid, panneauId }) => {
    const { useState } = React;
    
    const isIntervenant = editingEntity.location.type === 'intervenant';
    const isLot = editingEntity.location.type === 'lot';
    
    const ConfirmModal = window.pano_ConfirmModal || (() => null);
    const Button = window.pano_Button || (() => null);
    const Modal = window.pano_Modal || (() => null);

    const { SearchIcon, UploadCloudIcon, Trash2Icon } = window.pano_getIcons();

    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 || ""));

    // Capture de l'état initial pour détecter s'il y a eu des modifications (Alerte "unsaved")
    const [initialData] = useState(JSON.stringify(editingEntity.data));
    const isDirty = JSON.stringify(editingEntity.data) !== initialData;

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

    const handleEntityLogoUpload = async (e) => {
        const file = e.target.files[0];
        if (!file) return;
        
        const reader = new FileReader();
        reader.onload = async (event) => {
            const base64Url = event.target.result;
            setEditingEntity(prev => ({ ...prev, data: { ...prev.data, logoUrl: base64Url } }));
            
            try {
                const fileId = await window.pano_uploadFile(file, 'image', null, false, false, clientUid, panneauId);
                setEditingEntity(prev => ({ ...prev, data: { ...prev.data, logoId: fileId } }));
            } catch (err) {
                window.pano_showToast(err, "error");
                setEditingEntity(prev => ({ ...prev, data: { ...prev.data, logoUrl: '' } }));
            }
        };
        reader.readAsDataURL(file);
    };

    return (
        <Modal title={isIntervenant ? "Éditer l'intervenant" : (isLot ? "Éditer le lot" : "Éditer l'entreprise")} onClose={() => setEditingEntity(null)} requireConfirm={isDirty} zIndex="z-[250]">
            <form onSubmit={(e) => { e.preventDefault(); saveEditedEntity(); }} className="space-y-4">
                {!isLot && (
                    <div className="space-y-2">
                        <label className="text-xs font-bold text-slate-500 uppercase block">N° SIRET (saisie auto)</label>
                        <div className="flex gap-2">
                            <input type="text" value={editingEntity.data.siret || ''} onChange={e => setEditingEntity({...editingEntity, data: {...editingEntity.data, siret: e.target.value.replace(/\s/g, '')}})} placeholder="Saisir SIRET pour auto-remplir" className="flex-1 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={!editingEntity.data.siret || editingEntity.data.siret.length < 9} className="px-4 py-3">
                                <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">{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({...editingEntity, data: {...editingEntity.data, name: e.target.value}})} className="w-full border-2 border-slate-200 rounded-xl p-3 focus:border-emerald-500 outline-none transition font-bold" required autoFocus />
                </div>
                
                {isIntervenant && (
                    <div className="space-y-2">
                        <label className="text-xs font-bold text-slate-500 uppercase block">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({...editingEntity, data: {...editingEntity.data, role: val}});
                            } else {
                                setEditingEntity({...editingEntity, data: {...editingEntity.data, role: ''}});
                            }
                        }} className="w-full border-2 border-slate-200 rounded-xl p-3 focus:border-emerald-500 outline-none transition font-bold bg-white" required>
                            <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({...editingEntity, data: {...editingEntity.data, role: e.target.value}})} 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 />
                        )}
                    </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">Coordonnées (optionnel)</h5>
                        
                        <div className="space-y-1">
                            <label className="text-[10px] font-bold text-slate-500 uppercase block">Adresse postale</label>
                            <input type="text" value={editingEntity.data.address || ''} onChange={e => setEditingEntity({...editingEntity, data: {...editingEntity.data, address: e.target.value}})} className="w-full border border-slate-200 rounded-lg p-2.5 text-sm focus:border-emerald-500 outline-none transition font-medium" />
                        </div>
                        
                        <div className="grid grid-cols-2 gap-4">
                            <div className="space-y-1">
                                <label className="text-[10px] font-bold text-slate-500 uppercase block">Téléphone</label>
                                <input type="tel" value={editingEntity.data.phone || ''} onChange={e => setEditingEntity({...editingEntity, data: {...editingEntity.data, phone: e.target.value}})} className="w-full border border-slate-200 rounded-lg p-2.5 text-sm focus:border-emerald-500 outline-none transition font-medium" />
                            </div>
                            <div className="space-y-1">
                                <label className="text-[10px] font-bold text-slate-500 uppercase block">E-mail</label>
                                <input type="email" value={editingEntity.data.email || ''} onChange={e => setEditingEntity({...editingEntity, data: {...editingEntity.data, email: e.target.value}})} className="w-full border border-slate-200 rounded-lg p-2.5 text-sm focus:border-emerald-500 outline-none transition font-medium" />
                            </div>
                        </div>

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

                        <div className="space-y-2 pt-2 border-t border-slate-100">
                            <label className="text-xs font-bold text-slate-500 uppercase block">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 cursor-pointer transition shadow-sm flex items-center gap-2 text-xs">
                                    <UploadCloudIcon size={16}/> Uploader
                                    <input type="file" accept="image/*" className="hidden" onChange={handleEntityLogoUpload} />
                                </label>
                                {(editingEntity.data.logoUrl || editingEntity.data.logoId) && (
                                    <div className="relative w-16 h-16 rounded-lg overflow-hidden border border-slate-200 bg-slate-50 flex items-center justify-center p-1 group">
                                        <img src={editingEntity.data.logoUrl || (window.pano_ECO_CONFIG?.apiBaseUrl + 'file/download?id=' + editingEntity.data.logoId)} alt="Logo" className="max-w-full max-h-full object-contain" />
                                        <div 
                                            role="button" 
                                            tabIndex={0} 
                                            onClick={(e) => { 
                                                e.preventDefault(); 
                                                if (editingEntity.data.logoId) {
                                                    window.pano_apiFetch('file/delete', { body: { id: editingEntity.data.logoId } });
                                                }
                                                setEditingEntity({...editingEntity, data: {...editingEntity.data, logoUrl: '', logoId: ''}}); 
                                            }}
                                            className="absolute top-1 right-1 bg-red-600/90 hover:bg-red-600 text-white p-1 rounded-full opacity-0 group-hover:opacity-100 transition-all cursor-pointer shadow-sm"
                                            title="Supprimer le logo"
                                        >
                                            <Trash2Icon size={12} />
                                        </div>
                                    </div>
                                )}
                            </div>
                        </div>
                    </div>
                )}
                
                <div className="flex gap-3 pt-4 mt-2 border-t border-slate-100">
                    <Button 
                        variant="secondary"
                        onClick={() => {
                            if (isDirty) {
                                const u = new URL(window.location);
                                u.searchParams.set('alert', 'unsaved');
                                window.history.pushState({ alert: 'unsaved' }, '', u);
                                window.dispatchEvent(new Event('popstate'));
                            } else {
                                setEditingEntity(null);
                            }
                        }} 
                        className="flex-1 py-3"
                    >
                        Annuler
                    </Button>
                    <Button type="submit" variant="primary" className="flex-1 py-3 uppercase tracking-widest">Enregistrer</Button>
                </div>
            </form>
        </Modal>
    );
};

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