/**
 * =========================================================================
 * PLATEFORME ECO-PANNEAU.FR - VERSION 1.0.0
 * Vue Saisie Déléguée (Partage sécurisé sans authentification globale)
 * =========================================================================
 */

window.pano_DelegateView = ({ token, showToast }) => {
    const { useState, useEffect } = React;
    const [panneau, setPanneau] = useState(null);
    const [loading, setLoading] = useState(true);
    const [isSaving, setIsSaving] = useState(false);
    const [error, setError] = useState(null);
    const [editingEntity, setEditingEntity] = useState(null);
    const [confirmDialog, setConfirmDialog] = useState(null);

    const { LoaderIcon, AlertTriangleIcon, ShieldIcon, CheckCircleIcon } = window.pano_getIcons();
    const ConfirmModal = window.pano_ConfirmModal || (() => null);
    const Button = window.pano_Button || (() => null);

    const PanneauEditor = window.pano_PanneauEditorForm || (() => null);
    const EntityEditor = window.pano_EntityEditorModal || (() => null);

    useEffect(() => {
        fetch(window.pano_ECO_CONFIG.apiBaseUrl + 'panneaux/delegated_access&token=' + encodeURIComponent(token) + '&_t=' + Date.now())
            .then(r => r.json())
            .then(d => {
                if (d.status === 'success') {
                    setPanneau(d.data);
                } else {
                    setError(d.message);
                }
                setLoading(false);
            })
            .catch(() => {
                setError("Erreur réseau");
                setLoading(false);
            });
    }, [token]);

    const handleSave = async () => {
        const d = await window.pano_apiFetch('panneaux/delegated_update', {
            body: { token, ...panneau },
            setLoading: setIsSaving,
            successMessage: "Informations enregistrées avec succès."
        });
    };

    if (loading) {
        return (
            <div className="h-screen flex flex-col items-center justify-center bg-slate-50">
                {LoaderIcon && <LoaderIcon className="animate-spin text-emerald-600 mb-4 w-8 h-8" />}
                <p className="font-bold text-slate-500 uppercase tracking-widest text-sm">Vérification de l'accès...</p>
            </div>
        );
    }

    if (error) {
        return (
            <div className="h-screen flex items-center justify-center bg-slate-50">
                <div className="bg-white p-8 rounded-3xl shadow-xl border border-red-200 text-center max-w-md">
                    {AlertTriangleIcon && <AlertTriangleIcon className="w-12 h-12 text-red-500 mx-auto mb-4" />}
                    <h2 className="text-xl font-black text-slate-800 mb-2">Accès refusé</h2>
                    <p className="text-slate-500">{error}</p>
                </div>
            </div>
        );
    }

    return (
        <div className="min-h-screen bg-slate-50 flex flex-col">
            <header className="bg-white border-b border-slate-200 py-4 px-6 flex justify-between items-center sticky top-0 z-50 shadow-sm">
                <div>
                    <h1 className="font-black text-xl text-slate-800 flex items-center gap-2">
                        {ShieldIcon && <ShieldIcon className="w-6 h-6 text-blue-600"/>} Saisie déléguée
                    </h1>
                    <p className="text-xs text-slate-500">Mise à jour des informations du panneau</p>
                </div>
                <Button variant="info" icon={isSaving ? LoaderIcon : CheckCircleIcon} onClick={handleSave} disabled={isSaving} className="px-6 py-2.5 shadow-md text-white bg-blue-600 hover:bg-blue-700">
                    Enregistrer
                </Button>
            </header>
            
            <main className="flex-1 max-w-4xl w-full mx-auto p-4 sm:p-8">
                <div className="bg-blue-50 border border-blue-200 rounded-2xl p-5 mb-8 text-blue-800 text-sm font-medium leading-relaxed">
                    Vous avez été invité à compléter les informations légales de ce panneau (intervenants, sous-traitants, PDF de l'arrêté). Vos modifications seront directement répercutées sur l'affichage public.
                </div>
                
                <div className="bg-white rounded-3xl shadow-xl overflow-hidden border border-slate-200 relative min-h-[500px]">
                    {PanneauEditor && (
                        <PanneauEditor 
                            panneau={panneau} 
                            setPanneau={setPanneau} 
                            managingPanneau={panneau} 
                            onCancel={() => window.location.href = '?'} 
                            onPublish={handleSave} 
                            onEditEntity={(loc, data) => setEditingEntity({location: loc, data})}
                            deleteEntity={(loc) => {
                                setConfirmDialog({
                                    title: "Supprimer l'élément",
                                    message: "Êtes-vous sûr de vouloir supprimer cet élément de l'équipe ?",
                                    confirmText: "Supprimer",
                                    type: "error",
                                    isDestructive: true,
                                    onConfirm: () => {
                                        let newInter = [...(panneau.intervenants || [])];
                                        let newLots = JSON.parse(JSON.stringify(panneau.lots || []));
                                        
                                        if (loc.type === 'intervenant') {
                                            newInter.splice(loc.index, 1);
                                        } else if (loc.type === 'lot') {
                                            newLots.splice(loc.index, 1);
                                        } else {
                                            newLots[loc.lotIndex].entreprises.splice(loc.index, 1);
                                        }
                                        
                                        setPanneau({ ...panneau, intervenants: newInter, lots: newLots });
                                        setConfirmDialog(null);
                                    },
                                    onCancel: () => setConfirmDialog(null)
                                });
                            }}
                            isSaving={isSaving} 
                            uiMode="delege" 
                            lockedFields={panneau.lockedFields || []}
                            showToast={showToast}
                        />
                    )}
                </div>
            </main>
            
            {editingEntity && EntityEditor && (
                <EntityEditor 
                    editingEntity={editingEntity} 
                    setEditingEntity={setEditingEntity} 
                    saveEditedEntity={() => {
                        let newInter = [...(panneau.intervenants || [])];
                        let newLots = JSON.parse(JSON.stringify(panneau.lots || []));
                        const loc = editingEntity.location;
                        
                        if (loc.type === 'intervenant') { 
                            if (loc.index !== undefined) {
                                newInter[loc.index] = editingEntity.data; 
                            } else {
                                newInter.push({...editingEntity.data, id: crypto.randomUUID()}); 
                            }
                        } else if (loc.type === 'lot') { 
                            if (loc.index !== undefined) {
                                newLots[loc.index] = {...newLots[loc.index], ...editingEntity.data}; 
                            } else {
                                newLots.push({...editingEntity.data, id: crypto.randomUUID(), entreprises: []}); 
                            }
                        } else if (loc.type === 'entreprise') { 
                            if (loc.index !== undefined) {
                                newLots[loc.lotIndex].entreprises[loc.index] = editingEntity.data; 
                            } else {
                                newLots[loc.lotIndex].entreprises.push({...editingEntity.data, id: crypto.randomUUID()}); 
                            }
                        }
                        
                        setPanneau({ ...panneau, intervenants: newInter, lots: newLots });
                        setEditingEntity(null);
                    }} 
                    showToast={showToast}
                />
            )}

            {confirmDialog && ConfirmModal && (
                <ConfirmModal {...confirmDialog} zIndex="z-[250]" />
            )}
        </div>
    );
};

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