import { doc, getDoc, setDoc, updateDoc, deleteDoc, onSnapshot, collection, increment, query, orderBy } from "https://www.gstatic.com/firebasejs/11.6.1/firebase-firestore.js";
import { MapPin, Play, Pause, Navigation, X, List, Search, Video, Headphones, FastForward, Rewind, Locate, LocateFixed, Music, Plus, Check, Map as MapIcon, Bell, Newspaper, Calendar, Clock, CheckSquare, Square, Trophy, CheckCircle2, Users, Key, FolderLock, ExternalLink, MessageSquare, Send, AlertCircle, Star, Heart, EyeOff } from 'https://esm.sh/lucide-react@0.263.1?bundle';

const { useState, useEffect, useRef, useMemo } = React;

// SANITIZZAZIONE GLOBALE DEGLI IFRAME (Protezione XSS)
const sanitizeEmbed = (html) => {
    if (!html || !window.DOMPurify) return html;
    return window.DOMPurify.sanitize(html, {
        ADD_TAGS: ['iframe'],
        ADD_ATTR: ['allow', 'allowfullscreen', 'frameborder', 'scrolling', 'src', 'width', 'height', 'allowtransparency', 'title'],
        ALLOWED_URI_REGEXP: /^(?:(?:https?|mailto|tel|callto|cid|xmpp):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i
    });
};

const getYouTubeId = (url) => { if (!url) return null; const match = url.match(/(?:youtu\.be\/|youtube\.com\/(?:embed\/|v\/|watch\?v=|watch\?.+&v=))([^&?]+)/); return match ? match[1] : null; };
const getGoogleDriveId = (url) => { if (!url) return null; const match = url.match(/\/d\/([a-zA-Z0-9_-]+)/) || url.match(/id=([a-zA-Z0-9_-]+)/); return match ? match[1] : null; };
const getVimeoId = (url) => { if(!url) return null; const match = url.match(/vimeo\.com\/(?:video\/)?([0-9]+)/); return match ? match[1] : null; };
const getSpotifyUrl = (url) => { if(!url) return null; if(url.includes('spotify.com/track') || url.includes('spotify.com/episode') || url.includes('spotify.com/playlist') || url.includes('spotify.com/album')) return url.replace('open.spotify.com', 'open.spotify.com/embed'); return null; };

const calculateDistance = (lat1, lon1, lat2, lon2) => {
    if (!lat1 || !lon1 || !lat2 || !lon2) return Infinity;
    const R = 6371; const dLat = (lat2 - lat1) * Math.PI / 180; const dLon = (lon2 - lon1) * Math.PI / 180;
    const a = 0.5 - Math.cos(dLat)/2 + Math.cos(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI / 180) * (1 - Math.cos(dLon))/2;
    return R * 2 * Math.asin(Math.sqrt(a));
};

const isEventExpired = (poi) => {
    if (!poi.isSpecialEvent) return false;
    if (poi.eventEndDate && poi.eventEndTime) {
        const endDateTime = new Date(`${poi.eventEndDate}T${poi.eventEndTime}`);
        return new Date() > endDateTime;
    }
    return false;
};

const isListActive = (list) => {
    if (!list) return false;
    const now = new Date();
    if (list.startDate) {
        const start = new Date(`${list.startDate}T${list.startTime || '00:00'}:00`);
        if (now < start) return false;
    }
    if (list.endDate) {
        const end = new Date(`${list.endDate}T${list.endTime || '23:59'}:59`);
        if (now > end) return false;
    }
    return true;
};

const GeoMap = ({ pois, onPoiSelect, activePoiId, centerOn, userLocation, visitedPois }) => {
    const mapRef = useRef(null); const mapInstance = useRef(null); const markersGroupRef = useRef(null); const userMarkerRef = useRef(null);

    useEffect(() => {
        if (!mapInstance.current) {
            const map = L.map(mapRef.current, { zoomControl: false }).setView([45.4064, 11.8768], 14);
            L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { attribution: '&copy; OSM', maxZoom: 19 }).addTo(map);
            markersGroupRef.current = L.layerGroup().addTo(map); mapInstance.current = map;
        }
    }, []);

    useEffect(() => { if (centerOn && mapInstance.current) mapInstance.current.flyTo([centerOn.lat, centerOn.lng], 17, { animate: true, duration: 1.0 }); }, [centerOn]);

    useEffect(() => {
        if (!mapInstance.current || !markersGroupRef.current) return;
        markersGroupRef.current.clearLayers();
        
        pois.forEach(poi => {
            const isVisited = visitedPois.includes(poi.id);
            let color = poi.isSpecialEvent ? '#ef4444' : (poi.listId && poi.listId !== 'generic' ? '#f59e0b' : '#2563eb');
            if (isVisited) color = '#10b981';

            const isActive = activePoiId === poi.id;
            const displayIcon = poi.markerIcon ? poi.markerIcon : (poi.hasMedia !== false ? (poi.mediaType === 'video' ? '🎬' : '🎧') : '📍');
            
            const markerHtml = `<div style="background-color: ${isActive ? '#000' : color}; color: white; width: 36px; height: 36px; display: flex; align-items: center; justify-content: center; border-radius: 50%; border: 3px solid white; box-shadow: 0 4px 12px rgba(0,0,0,0.3); font-size: 16px; transition: all 0.3s; transform: ${isActive ? 'scale(1.25)' : 'scale(1)'};">${isVisited && !poi.markerIcon ? '✔' : displayIcon}</div>`;
            const icon = L.divIcon({ className: 'custom-div-icon', html: markerHtml, iconSize: [36, 36], iconAnchor: [18, 18] });
            L.marker([poi.lat, poi.lng], { icon: icon }).addTo(markersGroupRef.current).on('click', () => onPoiSelect(poi));
        });
    }, [pois, activePoiId, onPoiSelect, visitedPois]);

    useEffect(() => {
        if (!mapInstance.current || !userLocation) return;
        if (!userMarkerRef.current) {
            const userHtml = `<div style="width: 18px; height: 18px; background-color: #3b82f6; border-radius: 50%; border: 3px solid white; box-shadow: 0 0 8px rgba(0,0,0,0.4); position: relative;"><div style="position: absolute; top: -10px; left: -10px; right: -10px; bottom: -10px; border-radius: 50%; background-color: rgba(59, 130, 246, 0.4); z-index: -1; animation: mapPulse 2s infinite;"></div></div><style>@keyframes mapPulse { 0% { transform: scale(0.5); opacity: 1; } 100% { transform: scale(1.2); opacity: 0; } }</style>`;
            const icon = L.divIcon({ className: 'custom-div-icon', html: userHtml, iconSize: [18, 18], iconAnchor: [9, 9] });
            userMarkerRef.current = L.marker([userLocation.lat, userLocation.lng], { icon, zIndexOffset: 1000 }).addTo(mapInstance.current);
        } else userMarkerRef.current.setLatLng([userLocation.lat, userLocation.lng]);
    }, [userLocation]);

    return <div ref={mapRef} className="w-full h-full z-0" />;
};

const GlobalBottomPlayer = ({ media, onClose, isMinimized, onToggleMinimize }) => {
    const spoUrl = getSpotifyUrl(media.mediaUrl);
    const isGenericEmbed = media.sourceType === 'embed' || (media.mediaUrl && String(media.mediaUrl).trim().startsWith('<'));
    
    const audioRef = useRef(null); 
    const [isPlaying, setIsPlaying] = useState(false); 
    const [currentTime, setCurrentTime] = useState(0); 
    const [duration, setDuration] = useState(0);

    useEffect(() => { 
        setIsPlaying(false); 
        if (!spoUrl && !isGenericEmbed && audioRef.current && media && media.mediaUrl) { 
            try {
                audioRef.current.load(); 
                const p = audioRef.current.play(); 
                if(p !== undefined) {
                    p.then(() => setIsPlaying(true)).catch(e => {
                        console.warn("Riproduzione audio bloccata o formato non supportato", e);
                        setIsPlaying(false);
                    }); 
                }
            } catch (e) {
                setIsPlaying(false);
            }
        } 
    }, [media, spoUrl, isGenericEmbed]);

    if (!media || !media.mediaUrl) return null;

    const progressPercent = duration ? (currentTime / duration) * 100 : 0;

    if (isMinimized) {
        return (
            <>
                {!spoUrl && !isGenericEmbed && (
                    <audio 
                        ref={audioRef} 
                        src={media.mediaUrl} 
                        onTimeUpdate={() => setCurrentTime(audioRef.current.currentTime)} 
                        onEnded={() => setIsPlaying(false)} 
                        onLoadedMetadata={(e) => setDuration(e.target.duration)} 
                        onError={() => setIsPlaying(false)}
                    />
                )}
            </>
        );
    }

    return (
        <div className="fixed bottom-4 left-4 right-4 md:left-1/2 md:-translate-x-1/2 md:w-[400px] z-[70] fade-in-up flex flex-col shadow-2xl rounded-2xl overflow-hidden bg-white/95 backdrop-blur-2xl border border-slate-200 pointer-events-auto">
            {spoUrl ? (
                <div className="relative w-full h-[80px] bg-[#121212]">
                    <iframe src={spoUrl} width="100%" height="80" frameBorder="0" allowtransparency="true" allow="encrypted-media" className="w-full h-full"></iframe>
                    <div className="absolute top-1/2 -translate-y-1/2 right-2 flex gap-1">
                        <button onClick={onToggleMinimize} className="w-8 h-8 flex items-center justify-center bg-black/60 rounded-full text-white shadow hover:bg-black/80 z-10 transition-colors" title="Nascondi Lettore"><EyeOff size={14} /></button>
                        <button onClick={onClose} className="w-8 h-8 flex items-center justify-center bg-black/60 rounded-full text-white shadow hover:bg-black/80 z-10 transition-colors" title="Chiudi Lettore"><X size={16} /></button>
                    </div>
                </div>
            ) : isGenericEmbed ? (
                <div className="relative w-full bg-slate-900 border-t-4 border-indigo-600">
                    <div className="absolute top-2 right-2 flex gap-1 z-20">
                        <button onClick={onToggleMinimize} className="w-8 h-8 flex items-center justify-center bg-black/60 rounded-full text-white shadow hover:bg-black/80 transition-colors" title="Nascondi Lettore"><EyeOff size={14} /></button>
                        <button onClick={onClose} className="w-8 h-8 flex items-center justify-center bg-black/60 rounded-full text-white shadow hover:bg-black/80 transition-colors" title="Chiudi Lettore"><X size={16} /></button>
                    </div>
                    {/* RISOLTO XSS - Utilizzo DOMPurify per sanificare l'embed */}
                    <div className="w-full max-h-[160px] overflow-hidden flex items-center justify-center audio-embed-wrapper" dangerouslySetInnerHTML={{ __html: sanitizeEmbed(media.mediaUrl) }} />
                </div>
            ) : (
                <>
                    <div className="flex items-center justify-between p-3 gap-3">
                        <div className="w-10 h-10 bg-indigo-100 text-indigo-600 rounded-xl flex items-center justify-center shrink-0 shadow-sm"><Music size={18} /></div>
                        <div className="flex-1 min-w-0">
                            <h4 className="font-bold text-sm text-slate-800 truncate">{media.title}</h4>
                            <p className="text-[10px] text-slate-500 font-medium">{isPlaying ? 'Riproduzione in corso...' : 'In pausa'}</p>
                        </div>
                        <div className="flex gap-1 shrink-0">
                            <button onClick={() => {
                                if(audioRef.current) {
                                    if (isPlaying) { audioRef.current.pause(); setIsPlaying(false); } 
                                    else { 
                                        const p = audioRef.current.play();
                                        if(p !== undefined) p.then(() => setIsPlaying(true)).catch(()=>setIsPlaying(false));
                                    }
                                }
                            }} className="w-10 h-10 bg-slate-900 text-white rounded-full flex items-center justify-center shadow-lg active:scale-95 transition-all">
                                {isPlaying ? <Pause size={18} fill="currentColor"/> : <Play size={18} fill="currentColor" className="ml-0.5"/>}
                            </button>
                            <button onClick={onToggleMinimize} className="w-10 h-10 text-slate-400 hover:text-slate-600 rounded-full flex items-center justify-center bg-slate-50 hover:bg-slate-100 transition-colors" title="Nascondi lettore"><EyeOff size={18}/></button>
                            <button onClick={onClose} className="w-10 h-10 text-slate-400 hover:text-slate-600 rounded-full flex items-center justify-center bg-slate-50 hover:bg-slate-100 transition-colors"><X size={18}/></button>
                        </div>
                    </div>
                    <div className="relative w-full h-1.5 bg-slate-100 cursor-pointer group" onClick={(e) => { const rect = e.currentTarget.getBoundingClientRect(); const pos = (e.clientX - rect.left) / rect.width; if(audioRef.current && duration) audioRef.current.currentTime = pos * duration; }}>
                        <div className="absolute top-0 left-0 h-full bg-indigo-600 transition-all duration-75" style={{ width: `${progressPercent}%` }}></div>
                    </div>
                    <audio 
                        ref={audioRef} 
                        src={media.mediaUrl} 
                        onTimeUpdate={() => setCurrentTime(audioRef.current.currentTime)} 
                        onEnded={() => setIsPlaying(false)} 
                        onLoadedMetadata={(e) => setDuration(e.target.duration)} 
                        onError={(e) => setIsPlaying(false)}
                    />
                </>
            )}
        </div>
    );
};

const VideoModal = ({ media, onClose, ytId, vimId, spoUrl, driveId }) => {
    const driveUrl = driveId ? `https://drive.google.com/file/d/${driveId}/preview` : null;
    const vimeoUrl = vimId ? `https://player.vimeo.com/video/${vimId}?autoplay=1` : null;
    
    return ( 
        <div className="fixed inset-0 z-[80] flex items-center justify-center p-4 fade-in-up pointer-events-none py-20 bg-black/80 backdrop-blur-sm">
            <div className="w-full max-w-2xl bg-black rounded-3xl overflow-hidden shadow-2xl relative border border-white/10 pointer-events-auto">
                <div className="aspect-video w-full bg-black relative">
                    {ytId && <iframe className="w-full h-full" src={`https://www.youtube.com/embed/${ytId}?autoplay=1`} frameBorder="0" allow="autoplay; fullscreen" allowFullScreen></iframe>}
                    {vimeoUrl && <iframe className="w-full h-full" src={vimeoUrl} frameBorder="0" allow="autoplay; fullscreen" allowFullScreen></iframe>}
                    {driveUrl && <iframe className="w-full h-full" src={driveUrl} frameBorder="0" allow="autoplay; encrypted-media; fullscreen; picture-in-picture" allowFullScreen></iframe>}
                    
                    {/* RISOLTO XSS */}
                    {!ytId && !vimeoUrl && !driveUrl && media.sourceType === 'embed' && <div className="w-full h-full flex justify-center items-center embed-container" dangerouslySetInnerHTML={{ __html: sanitizeEmbed(media.mediaUrl) }} />}
                    {!ytId && !vimeoUrl && !driveUrl && media.sourceType !== 'embed' && <video src={media.mediaUrl} controls autoPlay className="w-full h-full" onError={(e) => console.warn("Sorgente video non supportata")} />}
                </div>
                <button onClick={onClose} className="absolute top-4 right-4 z-[90] w-10 h-10 bg-black/60 text-white rounded-full flex items-center justify-center border border-white/20 shadow-xl cursor-pointer hover:bg-black/80 transition-colors"><X size={20} /></button>
            </div>
        </div> 
    );
};

const VideoPlayerModal = ({ media, onClose }) => {
    const ytId = getYouTubeId(media.mediaUrl); 
    const vimId = getVimeoId(media.mediaUrl);
    const driveId = getGoogleDriveId(media.mediaUrl);
    return <VideoModal media={media} onClose={onClose} ytId={ytId} vimId={vimId} driveId={driveId} />;
};

function App() {
    const [rawPois, setRawPois] = useState([]);
    const [news, setNews] = useState([]);
    const [readNews, setReadNews] = useState(() => JSON.parse(localStorage.getItem('geoTourReadNews') || '[]'));
    const [eventLists, setEventLists] = useState([]);
    const [settings, setSettings] = useState({ appName: 'GeoTour', appColor: '#4f46e5', appFontSize: 'text-sm', appFontFamily: 'ui-sans-serif, system-ui, sans-serif', appLogoUrl: '' });
    const [visitedPois, setVisitedPois] = useState(() => JSON.parse(localStorage.getItem('geoTourVisited') || '[]'));
    const [unlockedLists, setUnlockedLists] = useState(() => JSON.parse(localStorage.getItem('geoTourUnlocked') || '[]'));
    const [votedPois, setVotedPois] = useState(() => JSON.parse(localStorage.getItem('geoTourVoted') || '[]'));
    const [favoritePois, setFavoritePois] = useState(() => JSON.parse(localStorage.getItem('geoTourFavorites') || '[]'));
    const [isLoading, setIsLoading] = useState(true);
    
    const [globalAudioMedia, setGlobalAudioMedia] = useState(null); 
    const [audioPlayerMinimized, setAudioPlayerMinimized] = useState(false);
    const [activeVideoMedia, setActiveVideoMedia] = useState(null); 
    
    const [selectedPoiInfo, setSelectedPoiInfo] = useState(null);
    const [isImageExpanded, setIsImageExpanded] = useState(true); 
    const [ratingMenuOpen, setRatingMenuOpen] = useState(false); 
    const [mapCenter, setMapCenter] = useState(null);
    const [userLocation, setUserLocation] = useState(null);
    const [isTracking, setIsTracking] = useState(false);
    const [routePois, setRoutePois] = useState([]);
    
    const [showUnlockModal, setShowUnlockModal] = useState(false);
    const [unlockCode, setUnlockCode] = useState('');
    const [showNews, setShowNews] = useState(false);
    const [showList, setShowList] = useState(false);
    const [showFavorites, setShowFavorites] = useState(false);
    const [listTab, setListTab] = useState('fixed');
    const [searchTerm, setSearchTerm] = useState('');
    const [sortByDistance, setSortByDistance] = useState(false);
    
    const [showSubmitModal, setShowSubmitModal] = useState(false);
    const [submitTab, setSubmitTab] = useState('event');
    const [submitData, setSubmitData] = useState({ name: '', surname: '', email: '', message: '', title: '', description: '', category: '', lat: '', lng: '', imageUrl: '', externalLink: '', markerIcon: '', hasMedia: false, mediaType: 'audio', mediaUrl: '', isSpecialEvent: false, eventDate: '', eventTime: '', eventEndDate: '', eventEndTime: '' });
    const [addressQuery, setAddressQuery] = useState('');
    
    const [selectedCategory, setSelectedCategory] = useState('');
    const [visitFilter, setVisitFilter] = useState('all');
    const [searchExpanded, setSearchExpanded] = useState(false);
    const [sortExpanded, setSortExpanded] = useState(false);
    const categories = settings.poiCategories || ['Arte', 'Natura', 'Storia', 'Gastronomia', 'Svago'];
    
    const watchIdRef = useRef(null);
    const hasUnreadNews = news.some(n => !readNews.includes(n.id));

    const markAllNewsAsRead = () => {
        const allIds = news.map(n => n.id);
        setReadNews(allIds);
        localStorage.setItem('geoTourReadNews', JSON.stringify(allIds));
    };

    useEffect(() => {
        const unsubscribeAuth = window.firebaseAuth.onAuthStateChanged(async (user) => {
            if (!user) window.firebaseSignIn().catch(e => console.error("Auth error:", e));
        });
        return () => unsubscribeAuth();
    }, []);

    useEffect(() => {
        const initDB = async () => {
            try {
                onSnapshot(collection(window.firebaseDb, 'artifacts', window.firebaseAppId, 'public', 'data', 'pois'), (snapshot) => { 
                    setRawPois(snapshot.docs.map(doc => ({ id: doc.id, ...doc.data() }))); 
                    setIsLoading(false); 
                });
                onSnapshot(query(collection(window.firebaseDb, 'artifacts', window.firebaseAppId, 'public', 'data', 'news'), orderBy('createdAt', 'desc')), (snapshot) => { setNews(snapshot.docs.map(doc => ({ id: doc.id, ...doc.data() }))); });
                onSnapshot(collection(window.firebaseDb, 'artifacts', window.firebaseAppId, 'public', 'data', 'eventLists'), (snapshot) => { setEventLists(snapshot.docs.map(doc => ({ id: doc.id, ...doc.data() }))); });
                onSnapshot(doc(window.firebaseDb, 'artifacts', window.firebaseAppId, 'public', 'data', 'settings', 'general'), (docSnap) => { if (docSnap.exists()) setSettings(docSnap.data()); });
            } catch (e) { setIsLoading(false); }
        };
        initDB();
        return () => { if (watchIdRef.current) navigator.geolocation.clearWatch(watchIdRef.current); };
    }, []);

    useEffect(() => {
        if (selectedPoiInfo && rawPois.length > 0) {
            const updated = rawPois.find(p => p.id === selectedPoiInfo.id);
            if (updated && JSON.stringify(updated) !== JSON.stringify(selectedPoiInfo)) setSelectedPoiInfo(updated);
        }
    }, [rawPois, selectedPoiInfo]);

    useEffect(() => {
        if (selectedPoiInfo) { setIsImageExpanded(true); setRatingMenuOpen(false); }
    }, [selectedPoiInfo]);
    
    const getDynamicLayoutStyles = () => {
        let playerH = 0;
        if (globalAudioMedia && !audioPlayerMinimized) {
            const spoUrl = getSpotifyUrl(globalAudioMedia.mediaUrl);
            const isGenericEmbed = globalAudioMedia.sourceType === 'embed' || (globalAudioMedia.mediaUrl && String(globalAudioMedia.mediaUrl).trim().startsWith('<'));
            if (spoUrl) playerH = 96; 
            else if (isGenericEmbed) playerH = 176; 
            else playerH = 136;
        }
        const bottomOffset = playerH ? playerH + 80 : 100;
        return {
            buttons: { bottom: playerH ? `${playerH + 16}px` : '32px', paddingBottom: playerH ? '0' : 'env(safe-area-inset-bottom)' },
            modals: { bottom: `${bottomOffset}px`, maxHeight: `calc(100dvh - 90px - ${bottomOffset}px)`, height: 'auto' }
        };
    };

    const dynamicStyles = getDynamicLayoutStyles();

    const activeNavColor = useMemo(() => {
        for (const listId of unlockedLists) {
            const list = eventLists.find(l => l.id === listId);
            if (list && isListActive(list) && list.listColor) return list.listColor;
        }
        return settings.navButtonColor || null;
    }, [unlockedLists, eventLists, settings]);

    const handleUnlock = () => {
        if (!unlockCode || !unlockCode.trim()) return alert("Inserisci un codice.");
        const list = eventLists.find(l => l.code && String(l.code).trim().toUpperCase() === unlockCode.trim().toUpperCase());
        
        if (!list) return alert("Codice errato o inesistente.");
        if (list.status === 'draft') return alert("Evento in bozza, non visibile.");
        if (!isListActive(list)) return alert("Evento non ancora iniziato o scaduto.");
        
        if (!unlockedLists.includes(list.id)) {
            const newUnlocked = [...unlockedLists, list.id];
            setUnlockedLists(newUnlocked);
            localStorage.setItem('geoTourUnlocked', JSON.stringify(newUnlocked));
            alert("Codice valido! Tappe sbloccate.");
        } else alert("Hai già sbloccato questo evento.");
        
        setShowUnlockModal(false); setUnlockCode('');
    };
    
    // FIX ORFANI: Logica corretta per i POI orfani di liste
    const validPois = useMemo(() => {
        return rawPois.filter(p => {
            if (p.isVisible === false) return false;
            if (isEventExpired(p)) return false;
            
            // Controlla se la lista associata esiste ancora
            const listExists = p.listId && p.listId !== 'generic' ? eventLists.find(l => l.id === p.listId) : null;
            // Se non c'è listId, è generic. Se ha listId ma la lista non esiste più, lo forziamo a generic (visibile)
            const isGeneric = !p.listId || p.listId === 'generic' || (p.listId !== 'generic' && !listExists);

            if (isGeneric) return true;

            // Se arriviamo qui, il POI appartiene a una lista validissima
            const isUnlocked = unlockedLists.includes(p.listId);
            if (isUnlocked && listExists) {
                if (listExists.status === 'draft' || !isListActive(listExists)) return false; 
                return true;
            }
            return false;
        });
    }, [rawPois, unlockedLists, eventLists]);

    // FIX ORFANI: Adattamento dei filtri
    const filteredPois = useMemo(() => {
        let list = validPois.filter(p => p.title.toLowerCase().includes(searchTerm.toLowerCase()))
            .filter(p => {
                const listExists = p.listId && p.listId !== 'generic' ? eventLists.find(l => l.id === p.listId) : null;
                const isGeneric = !p.listId || p.listId === 'generic' || (p.listId !== 'generic' && !listExists);

                if (listTab === 'fixed') return !p.isSpecialEvent && isGeneric;
                if (listTab === 'special') return p.isSpecialEvent && isGeneric;
                return p.listId === listTab;
            })
            .filter(p => selectedCategory ? p.category === selectedCategory : true)
            .filter(p => { 
                if (visitFilter === 'visited') return visitedPois.includes(p.id); 
                if (visitFilter === 'unvisited') return !visitedPois.includes(p.id); 
                return true; 
            })
            .map(p => ({ ...p, distance: userLocation ? calculateDistance(userLocation.lat, userLocation.lng, p.lat, p.lng) : null }));
            
        if (sortByDistance && userLocation) list.sort((a, b) => (a.distance || Infinity) - (b.distance || Infinity));
        else list.sort((a, b) => (a.orderIndex || 0) - (b.orderIndex || 0));
        return list;
    }, [validPois, searchTerm, sortByDistance, userLocation, listTab, selectedCategory, visitFilter, visitedPois, eventLists]);
    
    const handlePoiSelect = (poi) => { setSelectedPoiInfo(poi); setMapCenter({ lat: poi.lat, lng: poi.lng }); };
    const toggleRoutePoi = (poi, e) => { e.stopPropagation(); setRoutePois(prev => prev.some(p => p.id === poi.id) ? prev.filter(p => p.id !== poi.id) : [...prev, poi]); };
    const openGoogleMapsRoute = () => { 
        if (routePois.length === 0) return;
        const waypoints = routePois.slice(0, -1).map(p => `${p.lat},${p.lng}`).join('|');
        const dest = routePois[routePois.length - 1];
        window.open(`https://www.google.com/maps/dir/?api=1&destination=${dest.lat},${dest.lng}${waypoints ? `&waypoints=${waypoints}` : ''}`, '_blank');
    };
    const toggleVisited = (id) => { 
        const newVisited = visitedPois.includes(id) ? visitedPois.filter(v => v !== id) : [...visitedPois, id];
        setVisitedPois(newVisited); localStorage.setItem('geoTourVisited', JSON.stringify(newVisited));
    };
    const toggleFavorite = (id, e) => { 
        if (e) e.stopPropagation();
        const newFavs = favoritePois.includes(id) ? favoritePois.filter(v => v !== id) : [...favoritePois, id];
        setFavoritePois(newFavs); localStorage.setItem('geoTourFavorites', JSON.stringify(newFavs));
    };
    const getAverageRating = (poi) => { if (!poi.ratingCount) return 0; return (poi.ratingTotal / poi.ratingCount).toFixed(1); };
    const handleRatePoi = async (poiId, stars) => { 
        if (votedPois.includes(poiId)) return;
        try {
            const poiRef = doc(window.firebaseDb, 'artifacts', window.firebaseAppId, 'public', 'data', 'pois', poiId);
            await updateDoc(poiRef, { ratingTotal: increment(stars), ratingCount: increment(1) });
            const newVoted = [...votedPois, poiId];
            setVotedPois(newVoted); localStorage.setItem('geoTourVoted', JSON.stringify(newVoted));
        } catch(e) {}
    };
    
    const handleLocationClick = () => { 
        if (!navigator.geolocation) return alert("GPS non supportato.");
        if (isTracking && userLocation) setMapCenter({ ...userLocation });
        else {
            setIsTracking(true);
            navigator.geolocation.getCurrentPosition((pos) => { const loc = { lat: pos.coords.latitude, lng: pos.coords.longitude }; setUserLocation(loc); setMapCenter(loc); }, () => setIsTracking(false), { enableHighAccuracy: true });
            watchIdRef.current = navigator.geolocation.watchPosition((pos) => setUserLocation({ lat: pos.coords.latitude, lng: pos.coords.longitude }), null, { enableHighAccuracy: true, maximumAge: 5000, timeout: 10000 });
        }
    };
    const handleAddressSearch = async () => { 
        if (!addressQuery) return;
        try {
            const res = await fetch(`https://nominatim.openstreetmap.org/search?format=json&q=${encodeURIComponent(addressQuery)}`);
            const data = await res.json();
            if (data && data.length > 0) {
                setSubmitData(prev => ({ ...prev, lat: parseFloat(data[0].lat), lng: parseFloat(data[0].lon) }));
                alert("Indirizzo impostato!");
            } else alert("Indirizzo non trovato.");
        } catch (e) {} 
    };
    const handleFormSubmit = async () => { 
        const limits = JSON.parse(localStorage.getItem('geoTourSubmissions') || '[]');
        const now = Date.now();
        const recent = limits.filter(t => now - t < 24 * 60 * 60 * 1000);
        if (recent.length >= 20) return alert("Limite giornaliero segnalazioni raggiunto.");
        if (!submitData.name || !submitData.surname || !submitData.email) return alert("Compila i tuoi dati personali.");
        
        try {
            const { collection, addDoc } = await import("https://www.gstatic.com/firebasejs/11.6.1/firebase-firestore.js");
            await addDoc(collection(window.firebaseDb, 'artifacts', window.firebaseAppId, 'public', 'data', 'submissions'), { type: submitTab, ...submitData, createdAt: now, status: 'pending' });
            recent.push(now); localStorage.setItem('geoTourSubmissions', JSON.stringify(recent));
            alert("Inviato con successo!"); setShowSubmitModal(false);
            setSubmitData({ name: '', surname: '', email: '', message: '', title: '', description: '', category: '', lat: '', lng: '', imageUrl: '', externalLink: '', markerIcon: '', hasMedia: false, mediaType: 'audio', mediaUrl: '', isSpecialEvent: false, eventDate: '', eventTime: '', eventEndDate: '', eventEndTime: '' });
        } catch(e) {}
    };

    const currentSelectedDistance = selectedPoiInfo && userLocation ? calculateDistance(userLocation.lat, userLocation.lng, selectedPoiInfo.lat, selectedPoiInfo.lng) : null;

    return (
        <div className="w-full h-full relative overflow-hidden font-sans">
            {/* Header Overlay */}
            <div className="absolute top-12 left-0 right-0 p-4 z-20 pointer-events-none flex justify-between items-start">
                <div onClick={() => window.location.href = 'admin.html'} className="bg-white/90 backdrop-blur shadow-md rounded-2xl p-2 px-4 pointer-events-auto flex items-center gap-2 cursor-pointer">
                    {settings.appLogoUrl ? <img src={settings.appLogoUrl} alt="Logo" className="max-h-8 object-contain rounded" /> : <Navigation size={18} style={{ color: settings.appColor }}/>}
                    <div>
                        {settings.appName && <h1 style={{ color: settings.appColor, fontFamily: settings.appFontFamily }} className={`font-bold leading-tight ${settings.appFontSize}`}>{settings.appName}</h1>}
                        <p className="text-[10px] text-slate-500 font-medium">{isLoading ? 'Aggiornamento...' : 'Mappa Interattiva'}</p>
                    </div>
                </div>
                <div className="flex flex-col gap-2 pointer-events-auto">
                    <button onClick={() => setShowUnlockModal(true)} className="w-10 h-10 rounded-full shadow-md flex items-center justify-center bg-amber-500 text-white"><Key size={18}/></button>
                    <button onClick={() => setShowNews(true)} className="w-10 h-10 rounded-full shadow-md flex items-center justify-center bg-white text-slate-600 relative"><Bell size={20}/>{hasUnreadNews && <span className="absolute top-0 right-0 w-3 h-3 bg-red-500 border-2 border-white rounded-full"></span>}</button>
                    <button onClick={() => setShowFavorites(true)} className="w-10 h-10 rounded-full shadow-md flex items-center justify-center bg-white text-rose-500 relative hover:bg-rose-50 transition-colors"><Heart size={20} fill={favoritePois.length > 0 ? "currentColor" : "none"}/></button>
                </div>
            </div>

            {/* Mappa */}
            <GeoMap pois={validPois} onPoiSelect={handlePoiSelect} activePoiId={selectedPoiInfo?.id} centerOn={mapCenter} userLocation={userLocation} visitedPois={visitedPois} />

            {/* Pulsanti Flottanti in Basso */}
            <div className="absolute left-1/2 -translate-x-1/2 z-20 flex gap-2 sm:gap-3 pointer-events-auto w-max max-w-[95%] transition-all duration-300 ease-out" style={dynamicStyles.buttons}>
                {globalAudioMedia && audioPlayerMinimized && (
                    <button onClick={() => setAudioPlayerMinimized(false)} className="w-12 h-12 rounded-full shadow-[0_8px_30px_rgb(0,0,0,0.2)] flex items-center justify-center transition-all border active:scale-95" style={activeNavColor ? { backgroundColor: activeNavColor, borderColor: activeNavColor, color: '#fff' } : { backgroundColor: '#7c3aed', borderColor: '#6d28d9', color: '#fff' }} title="Riapri lettore"><Play size={18} fill="currentColor" /></button>
                )}
                <button onClick={() => setShowList(true)} className="px-4 sm:px-6 py-3.5 text-white rounded-full shadow-[0_8px_30px_rgb(0,0,0,0.15)] font-bold flex items-center justify-center gap-2 active:scale-95 transition-all border" style={activeNavColor ? { backgroundColor: activeNavColor, borderColor: activeNavColor } : { backgroundColor: 'rgba(15,23,42,0.85)', backdropFilter: 'blur(12px)', borderColor: 'rgb(51,65,85)' }}><List size={20} /> <span className="hidden sm:inline">Eventi</span></button>
                <button onClick={() => setShowSubmitModal(true)} className="px-4 sm:px-6 py-3.5 bg-white/85 backdrop-blur-xl rounded-full shadow-[0_8px_30px_rgb(0,0,0,0.12)] font-bold flex items-center justify-center gap-2 hover:bg-white active:scale-95 transition-all border border-white/60" style={activeNavColor ? { color: activeNavColor } : { color: '#4f46e5' }}><MessageSquare size={20} /> <span className="hidden sm:inline">Segnala</span></button>
                <button onClick={handleLocationClick} className={`w-12 h-12 rounded-full shadow-[0_8px_30px_rgb(0,0,0,0.12)] flex items-center justify-center transition-all border border-white/60 active:scale-95`} style={isTracking ? (activeNavColor ? { backgroundColor: activeNavColor, color: '#fff', borderColor: activeNavColor } : { backgroundColor: '#4f46e5', color: '#fff' }) : { backgroundColor: 'rgba(255,255,255,0.85)', backdropFilter: 'blur(12px)', color: '#374151' }}>{isTracking ? <LocateFixed size={20} className="animate-pulse" /> : <Locate size={20} />}</button>
            </div>

            {/* Modale Unlock */}
            {showUnlockModal && (
                <div className="absolute inset-0 z-[100] bg-black/60 backdrop-blur-sm flex items-center justify-center p-4 fade-in-up">
                    <div className="bg-white p-6 rounded-3xl w-full max-w-sm shadow-2xl relative">
                        <button onClick={() => setShowUnlockModal(false)} className="absolute top-4 right-4 text-slate-400 hover:text-slate-600"><X size={20}/></button>
                        <div className="w-16 h-16 bg-amber-100 text-amber-600 rounded-full flex items-center justify-center mx-auto mb-4"><Key size={32}/></div>
                        <h2 className="text-xl font-bold mb-2 text-center text-slate-800">Hai un codice?</h2>
                        <p className="text-sm text-slate-500 text-center mb-6">Inserisci il codice segreto per sbloccare eventi speciali, liste di musei o gite riservate sulla mappa.</p>
                        <input value={unlockCode} onChange={e=>setUnlockCode(e.target.value)} className="w-full p-4 border-2 border-amber-200 bg-amber-50 rounded-2xl text-center font-mono font-bold text-lg text-amber-900 outline-none focus:border-amber-500 mb-4 uppercase" placeholder="ES: GITA24" />
                        <button onClick={handleUnlock} className="w-full bg-amber-500 text-white font-bold py-4 rounded-xl shadow-lg active:scale-95 transition-all">Sblocca Eventi</button>
                    </div>
                </div>
            )}

            {/* Modale News */}
            {showNews && (
                <>
                    <div className="absolute inset-0 z-[55]" onClick={() => setShowNews(false)} />
                    <div className="absolute left-4 right-4 md:left-auto md:right-4 md:w-[400px] z-[60] bg-white/85 backdrop-blur-2xl flex flex-col rounded-3xl shadow-[0_20px_50px_-12px_rgba(0,0,0,0.3)] border border-white fade-in-up overflow-hidden transition-all duration-300 ease-out" style={dynamicStyles.modals}>
                        <div className="p-4 border-b border-slate-100/60 flex justify-between items-center shrink-0 bg-white/50">
                             <h2 className="font-bold text-lg flex items-center gap-2"><Bell size={20} className="text-indigo-600"/> Avvisi e Notizie</h2>
                             <div className="flex gap-2 items-center">
                                 {hasUnreadNews && (
                                     <button onClick={markAllNewsAsRead} className="text-[11px] font-bold text-indigo-600 bg-indigo-50 hover:bg-indigo-100 px-3 py-1.5 rounded-full transition-colors border border-indigo-100">Segna come lette</button>
                                 )}
                                 <button onClick={() => setShowNews(false)} className="bg-slate-100/80 p-2 rounded-full hover:bg-slate-200"><X size={20}/></button>
                             </div>
                        </div>
                        <div className="flex-1 overflow-y-auto p-4 space-y-4 bg-slate-50/50 pb-8">
                            {news.length === 0 && <div className="text-center text-slate-400 mt-10"><Newspaper size={48} className="mx-auto mb-3 opacity-50"/><p>Nessuna notizia al momento.</p></div>}
                            {news.map(n => {
                                const isUnread = !readNews.includes(n.id);
                                return (
                                <div key={n.id} className={`bg-white/80 p-5 rounded-2xl shadow-sm border ${isUnread ? 'border-indigo-300 shadow-indigo-100' : 'border-slate-100'}`}>
                                    <div className="flex items-center gap-2 mb-2">
                                        {isUnread && <span className="w-2 h-2 bg-red-500 rounded-full animate-pulse"></span>}
                                        <span className="text-[10px] font-bold text-blue-500 uppercase">{new Date(n.createdAt).toLocaleDateString()}</span>
                                    </div>
                                    <h3 className="font-bold text-slate-800 text-lg mb-2">{n.title}</h3>
                                    <p className="text-sm text-slate-600 whitespace-pre-wrap leading-relaxed">{n.content}</p>
                                </div>
                            )})}
                        </div>
                    </div>
                </>
            )}

            {/* Modale Preferiti */}
            {showFavorites && (
                <>
                    <div className="absolute inset-0 z-[55]" onClick={() => setShowFavorites(false)} />
                    <div className="absolute left-4 right-4 md:left-auto md:right-4 md:w-[400px] z-[60] bg-white/95 backdrop-blur-3xl flex flex-col rounded-3xl shadow-[0_20px_50px_-12px_rgba(0,0,0,0.3)] border border-white fade-in-up overflow-hidden transition-all duration-300 ease-out" style={dynamicStyles.modals}>
                        <div className="p-4 border-b border-slate-200/50 flex justify-between items-center shrink-0 bg-white/60">
                             <h2 className="font-bold text-lg flex items-center gap-2"><Heart size={20} className="text-rose-500" fill="currentColor"/> I tuoi Preferiti</h2>
                             <button onClick={() => setShowFavorites(false)} className="bg-slate-100/50 p-2 rounded-full hover:bg-slate-200"><X size={20}/></button>
                        </div>
                        <div className="flex-1 overflow-y-auto p-4 space-y-3 pb-safe bg-slate-50/50">
                            {favoritePois.length === 0 ? (
                                <div className="text-center text-slate-400 mt-10"><Heart size={48} className="mx-auto mb-3 opacity-30"/><p>Non hai ancora salvato alcun luogo.</p></div>
                            ) : (
                                validPois.filter(p => favoritePois.includes(p.id)).map(poi => (
                                    <div key={poi.id} onClick={() => { handlePoiSelect(poi); setShowFavorites(false); }} className="bg-white p-4 rounded-xl shadow-sm border border-slate-100 flex items-center justify-between cursor-pointer active:scale-[0.98] transition-all">
                                        <div className="flex items-center gap-4 flex-1 min-w-0">
                                            <div className="w-10 h-10 rounded-full flex items-center justify-center shrink-0 overflow-hidden bg-rose-50 text-rose-500">
                                                {poi.imageUrl ? <img src={poi.imageUrl} alt="" className="w-full h-full object-cover" /> : <span className="text-xl">{poi.markerIcon || '📍'}</span>}
                                            </div>
                                            <div className="min-w-0">
                                                <h4 className="font-bold text-slate-800 truncate">{poi.title}</h4>
                                                <p className="text-xs text-slate-500 line-clamp-1">{poi.category || poi.description || 'Vedi dettagli'}</p>
                                            </div>
                                        </div>
                                        <button onClick={(e) => toggleFavorite(poi.id, e)} className="p-2 text-rose-500 hover:bg-rose-50 rounded-full transition-colors"><Heart size={18} fill="currentColor"/></button>
                                    </div>
                                ))
                            )}
                        </div>
                    </div>
                </>
            )}

            {/* Modale Segnalazioni */}
            {showSubmitModal && (
                <>
                    <div className="absolute inset-0 z-[55]" onClick={() => setShowSubmitModal(false)} />
                    <div className="absolute left-4 right-4 md:left-auto md:right-4 md:w-[400px] z-[60] bg-white/95 backdrop-blur-3xl flex flex-col rounded-3xl shadow-[0_20px_50px_-12px_rgba(0,0,0,0.3)] border border-white fade-in-up overflow-hidden transition-all duration-300 ease-out" style={dynamicStyles.modals}>
                        <div className="p-4 border-b border-slate-200/50 flex justify-between items-center shrink-0 bg-white/60">
                             <h2 className="font-bold text-lg flex items-center gap-2"><MessageSquare size={20} className="text-indigo-600"/> Contribuisci</h2>
                             <button onClick={() => setShowSubmitModal(false)} className="bg-slate-100/50 p-2 rounded-full hover:bg-slate-200"><X size={20}/></button>
                        </div>
                        
                        <div className="flex p-3 gap-2 bg-white/60 border-b border-slate-200/50 shrink-0">
                            <button onClick={()=>setSubmitTab('event')} className={`flex-1 py-2 text-xs font-bold rounded-xl transition-all ${submitTab==='event'?'bg-indigo-600 text-white shadow-md':'bg-white text-slate-600 border border-slate-200 hover:bg-slate-50'}`}>Proponi Evento</button>
                            <button onClick={()=>setSubmitTab('message')} className={`flex-1 py-2 text-xs font-bold rounded-xl transition-all ${submitTab==='message'?'bg-indigo-600 text-white shadow-md':'bg-white text-slate-600 border border-slate-200 hover:bg-slate-50'}`}>Invia Messaggio</button>
                        </div>

                        <div className="flex-1 overflow-y-auto p-5 space-y-4 pb-safe bg-slate-50/50">
                            <div className="bg-white/80 p-4 rounded-2xl border border-slate-200 shadow-sm space-y-3">
                                <h3 className="text-xs font-bold text-slate-400 uppercase mb-2">Dati Personali</h3>
                                <div className="flex gap-3">
                                    <input type="text" value={submitData.name} onChange={e=>setSubmitData({...submitData, name: e.target.value})} placeholder="Nome" className="w-1/2 p-3 bg-slate-50 border border-slate-200 rounded-xl text-sm outline-none focus:border-indigo-500" />
                                    <input type="text" value={submitData.surname} onChange={e=>setSubmitData({...submitData, surname: e.target.value})} placeholder="Cognome" className="w-1/2 p-3 bg-slate-50 border border-slate-200 rounded-xl text-sm outline-none focus:border-indigo-500" />
                                </div>
                                <input type="email" value={submitData.email} onChange={e=>setSubmitData({...submitData, email: e.target.value})} placeholder="Indirizzo E-mail" className="w-full p-3 bg-slate-50 border border-slate-200 rounded-xl text-sm outline-none focus:border-indigo-500" />
                            </div>

                            {submitTab === 'message' ? (
                                <div className="bg-white/80 p-4 rounded-2xl border border-slate-200 shadow-sm space-y-3">
                                    <h3 className="text-xs font-bold text-slate-400 uppercase mb-2">Il tuo messaggio</h3>
                                    <textarea value={submitData.message} onChange={e=>setSubmitData({...submitData, message: e.target.value})} placeholder="Scrivi qui consigli, segnalazioni problemi o suggerimenti..." className="w-full p-3 bg-slate-50 border border-slate-200 rounded-xl h-32 outline-none resize-none text-sm focus:border-indigo-500" />
                                </div>
                            ) : (
                                <div className="bg-white/80 p-4 rounded-2xl border border-slate-200 shadow-sm space-y-3">
                                    <h3 className="text-xs font-bold text-slate-400 uppercase mb-2">Dettagli Evento/Luogo</h3>
                                    
                                    <div className={`p-3 rounded-xl border ${submitData.isSpecialEvent ? 'bg-red-50 border-red-200' : 'bg-slate-50 border-slate-100'}`}>
                                        <label className="flex items-center gap-2 cursor-pointer">
                                            <input type="checkbox" checked={submitData.isSpecialEvent} onChange={e => setSubmitData({...submitData, isSpecialEvent: e.target.checked})} className="w-4 h-4 accent-red-600 rounded"/>
                                            <span className={`text-sm font-bold ${submitData.isSpecialEvent ? 'text-red-700' : 'text-slate-600'}`}>Evento Speciale a tempo</span>
                                        </label>
                                        {submitData.isSpecialEvent && (
                                            <div className="mt-3 fade-in-up space-y-2">
                                                <div className="flex gap-2">
                                                    <div className="flex-1">
                                                        <label className="text-[10px] font-bold text-red-500 block">Inizio</label>
                                                        <input type="date" value={submitData.eventDate} onChange={e=>setSubmitData({...submitData, eventDate: e.target.value})} className="w-full p-2 rounded-lg border border-red-200 text-xs bg-white outline-none"/>
                                                        <input type="time" value={submitData.eventTime} onChange={e=>setSubmitData({...submitData, eventTime: e.target.value})} className="w-full p-2 rounded-lg border border-red-200 text-xs mt-1 bg-white outline-none"/>
                                                    </div>
                                                    <div className="flex-1">
                                                        <label className="text-[10px] font-bold text-red-500 block">Fine</label>
                                                        <input type="date" value={submitData.eventEndDate} onChange={e=>setSubmitData({...submitData, eventEndDate: e.target.value})} className="w-full p-2 rounded-lg border border-red-200 text-xs bg-white outline-none"/>
                                                        <input type="time" value={submitData.eventEndTime} onChange={e=>setSubmitData({...submitData, eventEndTime: e.target.value})} className="w-full p-2 rounded-lg border border-red-200 text-xs mt-1 bg-white outline-none"/>
                                                    </div>
                                                </div>
                                            </div>
                                        )}
                                    </div>

                                    <input type="text" value={submitData.title} onChange={e=>setSubmitData({...submitData, title: e.target.value})} placeholder="Titolo dell'evento/luogo *" className="w-full p-3 bg-slate-50 border border-slate-200 rounded-xl text-sm outline-none focus:border-indigo-500 font-bold" />
                                    <textarea value={submitData.description} onChange={e=>setSubmitData({...submitData, description: e.target.value})} placeholder="Descrizione..." className="w-full p-3 bg-slate-50 border border-slate-200 rounded-xl h-24 outline-none resize-none text-sm focus:border-indigo-500" />
                                    
                                    <select value={submitData.category} onChange={e=>setSubmitData({...submitData, category: e.target.value})} className="w-full p-3 bg-slate-50 border border-slate-200 rounded-xl text-sm outline-none focus:border-indigo-500">
                                        <option value="">Seleziona una categoria (Opzionale)</option>
                                        {categories.map(c => <option key={c} value={c}>{c}</option>)}
                                    </select>
                                    
                                    <div>
                                        <label className="text-[10px] font-bold text-slate-500 block mb-1 uppercase">Icona personalizzata</label>
                                        <div className="flex gap-2 overflow-x-auto pb-1 hide-scrollbar">
                                            {['', '📍', '🌲', '🌸', '🏛️', '⭐', '🍔', '🎭', '🚌'].map(icon => (
                                                <button key={icon || 'default'} type="button" onClick={() => setSubmitData({...submitData, markerIcon: icon})} className={`w-10 h-10 shrink-0 rounded-xl flex justify-center items-center text-lg transition-all ${submitData.markerIcon === icon || (!submitData.markerIcon && !icon) ? 'bg-indigo-100 border-2 border-indigo-600 scale-110 shadow' : 'bg-slate-50 border border-slate-200'}`}>{icon || (submitData.hasMedia!==false ? (submitData.mediaType==='video'?'🎬':'🎧') : '📍')}</button>
                                            ))}
                                        </div>
                                    </div>

                                    <div className="bg-slate-50 p-3 rounded-xl border border-slate-100 space-y-3">
                                        <label className="flex items-center gap-2 cursor-pointer">
                                            <input type="checkbox" checked={submitData.hasMedia} onChange={e => setSubmitData({...submitData, hasMedia: e.target.checked})} className="w-4 h-4 accent-indigo-600 rounded"/>
                                            <span className="text-sm font-semibold text-slate-700">Contenuto Multimediale</span>
                                        </label>
                                        {submitData.hasMedia && (
                                            <div className="fade-in-up space-y-2">
                                                <select value={submitData.mediaType} onChange={e => setSubmitData({...submitData, mediaType: e.target.value})} className="w-full p-2 border border-slate-200 rounded-lg text-sm outline-none bg-white">
                                                    <option value="audio">Traccia Audio / Spotify / Embed</option>
                                                    <option value="video">Video (YouTube / Drive / MP4)</option>
                                                </select>
                                                <input type="text" value={submitData.mediaUrl} onChange={e => setSubmitData({...submitData, mediaUrl: e.target.value})} placeholder="URL Media (Es. Link Spotify o Drive)..." className="w-full p-2 bg-white border border-slate-200 rounded-lg text-sm outline-none" />
                                            </div>
                                        )}
                                    </div>
                                    <div className="bg-indigo-50/50 p-3 rounded-xl border border-indigo-100">
                                        <label className="text-[10px] font-bold text-indigo-600 block mb-2 uppercase">Posizione (Cerca Indirizzo) *</label>
                                        <div className="flex gap-2">
                                            <input type="text" value={addressQuery} onChange={(e) => setAddressQuery(e.target.value)} placeholder="Es: Via Roma, Padova" className="flex-1 p-2 bg-white border border-indigo-200 rounded-lg text-sm outline-none" />
                                            <button onClick={handleAddressSearch} className="bg-indigo-600 text-white p-2 rounded-lg shadow-sm"><Search size={18} /></button>
                                        </div>
                                        {submitData.lat !== '' && <p className="text-[10px] text-green-600 font-bold mt-2 flex items-center gap-1"><CheckCircle2 size={12}/> Posizione impostata correttamente!</p>}
                                    </div>

                                    <input type="text" value={submitData.imageUrl} onChange={e=>setSubmitData({...submitData, imageUrl: e.target.value})} placeholder="URL Immagine (Opzionale)" className="w-full p-3 bg-slate-50 border border-slate-200 rounded-xl text-sm outline-none focus:border-indigo-500" />
                                    <input type="text" value={submitData.externalLink} onChange={e=>setSubmitData({...submitData, externalLink: e.target.value})} placeholder="Link Sito Web (Opzionale)" className="w-full p-3 bg-slate-50 border border-slate-200 rounded-xl text-sm outline-none focus:border-indigo-500" />
                                </div>
                            )}

                            <div className="pt-2">
                                <button onClick={handleFormSubmit} className="w-full bg-indigo-600 text-white py-4 rounded-xl font-bold flex items-center justify-center gap-2 shadow-lg shadow-indigo-200 hover:bg-indigo-700 active:scale-95 transition-all"><Send size={18}/> Invia {submitTab === 'event' ? 'Proposta' : 'Messaggio'}</button>
                            </div>
                        </div>
                    </div>
                </>
            )}

            {/* Modale Esplora (Liste Eventi e Filtri) */}
            {showList && (
                <>
                    <div className="absolute inset-0 z-30" onClick={() => setShowList(false)} />
                    <div className="absolute left-4 right-4 md:left-auto md:right-4 md:w-[400px] z-40 bg-white/85 backdrop-blur-2xl flex flex-col rounded-3xl shadow-[0_20px_50px_-12px_rgba(0,0,0,0.3)] border border-white fade-in-up overflow-hidden transition-all duration-300 ease-out" style={dynamicStyles.modals}>
                        <div className="p-3 border-b border-slate-200/50 flex justify-between items-center shrink-0 bg-white/40">
                             <h2 className="font-bold text-base flex items-center gap-2"><List size={18} className="text-indigo-600"/> Esplora Eventi</h2>
                             <button onClick={() => setShowList(false)} className="bg-slate-100/50 p-1.5 rounded-full hover:bg-slate-200"><X size={18}/></button>
                        </div>

                        <div className="bg-white/40 border-b border-slate-200/50 shrink-0">
                            <div className="flex p-2 gap-2 flex-wrap max-h-32 overflow-y-auto hide-scrollbar">
                                <button onClick={()=>setListTab('fixed')} className={`shrink-0 px-4 py-1.5 text-xs font-bold rounded-lg transition-all ${listTab==='fixed'?'bg-indigo-600 text-white shadow-md':'bg-white/60 text-slate-600 hover:bg-white'}`}>Luoghi Fissi</button>
                                <button onClick={()=>setListTab('special')} className={`shrink-0 px-4 py-1.5 text-xs font-bold rounded-lg transition-all ${listTab==='special'?'bg-red-500 text-white shadow-md':'bg-white/60 text-slate-600 hover:bg-white'}`}>A Tempo</button>
                                
                                {unlockedLists.map(listId => {
                                    const list = eventLists.find(l => l.id === listId);
                                    if (!list || !isListActive(list)) return null;
                                    const color = list.listColor || '#f59e0b';
                                    return (
                                        <button 
                                            key={list.id} 
                                            onClick={()=>setListTab(list.id)} 
                                            className={`shrink-0 px-4 py-1.5 text-xs font-bold rounded-lg transition-all ${listTab===list.id?'text-white shadow-md':'bg-white/60 text-slate-600 hover:bg-white'}`}
                                            style={listTab === list.id ? { backgroundColor: color } : {}}
                                        >
                                            {list.title}
                                        </button>
                                    );
                                })}
                            </div>
                            <div className="px-4 pb-2 flex items-center gap-2">
                                <Trophy size={14} className={visitedPois.length > 0 ? "text-yellow-500" : "text-slate-400"}/>
                                <div className="flex-1 bg-slate-200/50 h-1.5 rounded-full overflow-hidden shadow-inner">
                                    <div className="bg-green-500 h-full transition-all duration-500" style={{width: `${validPois.length > 0 ? (visitedPois.length / validPois.length)*100 : 0}%`}}></div>
                                </div>
                                <span className="text-[10px] font-bold text-slate-600">{visitedPois.length}/{validPois.length} Visitati</span>
                            </div>
                        </div>

                        <div className="w-full overflow-x-auto hide-scrollbar py-2 px-3 border-b border-slate-200/50 flex gap-2 shrink-0 bg-white/40">
                            <button onClick={() => setSelectedCategory('')} className={`px-3 py-1.5 rounded-full text-xs font-bold whitespace-nowrap transition-colors shadow-sm ${selectedCategory === '' ? 'bg-indigo-600 text-white' : 'bg-white text-slate-600 border border-slate-200 hover:bg-slate-50'}`}>Tutti</button>
                            {categories.map(cat => (
                                <button key={cat} onClick={() => setSelectedCategory(cat)} className={`px-3 py-1.5 rounded-full text-xs font-bold whitespace-nowrap transition-colors shadow-sm ${selectedCategory === cat ? 'bg-indigo-600 text-white' : 'bg-white text-slate-600 border border-slate-200 hover:bg-slate-50'}`}>{cat}</button>
                            ))}
                        </div>

                        <div className="w-full overflow-x-auto hide-scrollbar py-2 px-3 border-b border-slate-200/50 flex gap-2 shrink-0 bg-white/30">
                            <button onClick={() => setVisitFilter('all')} className={`px-3 py-1.5 rounded-full text-xs font-bold whitespace-nowrap transition-colors shadow-sm flex items-center gap-1 ${visitFilter === 'all' ? 'bg-slate-700 text-white' : 'bg-white text-slate-600 border border-slate-200 hover:bg-slate-50'}`}>🗺️ Tutti</button>
                            <button onClick={() => setVisitFilter('visited')} className={`px-3 py-1.5 rounded-full text-xs font-bold whitespace-nowrap transition-colors shadow-sm flex items-center gap-1 ${visitFilter === 'visited' ? 'bg-emerald-500 text-white' : 'bg-white text-slate-600 border border-slate-200 hover:bg-slate-50'}`}><CheckCircle2 size={12}/> Visitati</button>
                            <button onClick={() => setVisitFilter('unvisited')} className={`px-3 py-1.5 rounded-full text-xs font-bold whitespace-nowrap transition-colors shadow-sm flex items-center gap-1 ${visitFilter === 'unvisited' ? 'bg-amber-500 text-white' : 'bg-white text-slate-600 border border-slate-200 hover:bg-slate-50'}`}><MapPin size={12}/> Da visitare</button>
                        </div>

                        <div className="p-3 bg-slate-50/30 pb-2 shrink-0 flex gap-2">
                            <div className={`relative transition-all duration-300 ease-in-out flex items-center justify-center bg-white/80 border shadow-sm overflow-hidden ${searchExpanded ? 'flex-1 rounded-xl border-indigo-300' : 'w-10 h-10 rounded-full border-white hover:bg-white cursor-pointer'}`} onClick={() => !searchExpanded && setSearchExpanded(true)}>
                                <Search className={`absolute left-3 transition-colors ${searchExpanded ? 'text-indigo-500' : 'text-slate-500'}`} size={16} />
                                <input type="text" value={searchTerm} onChange={(e) => setSearchTerm(e.target.value)} onBlur={() => { if(!searchTerm) setSearchExpanded(false); }} placeholder="Cerca località..." className={`w-full py-1.5 bg-transparent outline-none text-sm transition-all duration-300 ${searchExpanded ? 'pl-9 pr-3 opacity-100' : 'pl-10 opacity-0 pointer-events-none'}`} />
                                {searchExpanded && searchTerm && <button onClick={(e) => { e.stopPropagation(); setSearchTerm(''); setSearchExpanded(false); }} className="absolute right-2 text-slate-400"><X size={16}/></button>}
                            </div>

                            <button onClick={() => { if (!userLocation && !sortByDistance) handleLocationClick(); setSortByDistance(!sortByDistance); if (!sortByDistance) { setSortExpanded(true); setTimeout(() => setSortExpanded(false), 2000); } }} onMouseEnter={() => setSortExpanded(true)} onMouseLeave={() => setSortExpanded(false)} className={`transition-all duration-300 ease-in-out flex items-center justify-center border shadow-sm overflow-hidden whitespace-nowrap ${sortByDistance ? 'bg-indigo-600 text-white border-indigo-600' : 'bg-white/80 text-slate-700 border-white hover:bg-white'} ${sortExpanded ? 'px-4 rounded-xl flex-[2]' : 'w-10 h-10 rounded-full'}`}>
                                <MapPin size={16} className="shrink-0" />
                                <span className={`text-xs font-bold transition-all duration-300 overflow-hidden ${sortExpanded ? 'ml-2 opacity-100 w-auto' : 'opacity-0 w-0'}`}>{sortByDistance ? 'Vicini a te' : 'Ordina vicinanza'}</span>
                            </button>
                        </div>

                        <div className="flex-1 overflow-y-auto p-3 space-y-2 pb-safe">
                             {filteredPois.length === 0 && <p className="text-center text-slate-500 text-sm mt-10">Nessun risultato.</p>}
                             {filteredPois.map((poi) => {
                                 const listName = poi.listId && poi.listId !== 'generic' ? eventLists.find(l=>l.id===poi.listId)?.title : null;
                                 const listColor = poi.listId && poi.listId !== 'generic' ? eventLists.find(l=>l.id===poi.listId)?.listColor || '#f59e0b' : null;

                                 return (
                                 <div key={poi.id} onClick={() => { handlePoiSelect(poi); setShowList(false); }} 
                                     className={`bg-white p-4 rounded-xl shadow-sm border ${visitedPois.includes(poi.id) ? 'border-green-200 bg-green-50/30' : 'border-slate-100'} flex items-center justify-between cursor-pointer active:scale-[0.98] transition-all`}
                                     style={listColor && !visitedPois.includes(poi.id) ? { borderColor: listColor, backgroundColor: `${listColor}05` } : {}}
                                 >
                                     <div className="flex items-center gap-4 flex-1 min-w-0">
                                         <div className={`w-10 h-10 rounded-full flex items-center justify-center shrink-0 overflow-hidden ${poi.imageUrl ? '' : (poi.isSpecialEvent ? 'bg-red-100 text-red-600' : (listName ? '' : 'bg-indigo-100 text-indigo-600'))}`}
                                              style={listName && !poi.imageUrl ? { backgroundColor: `${listColor}20`, color: listColor } : {}}
                                         >
                                            {poi.imageUrl ? <img src={poi.imageUrl} alt="" className="w-full h-full object-cover" /> : <span className="text-xl">{poi.markerIcon || (poi.hasMedia !== false ? (poi.mediaType === 'video' ? '🎬' : '🎧') : '📍')}</span>}
                                         </div>
                                         <div className="min-w-0">
                                             <h4 className="font-bold text-slate-800 truncate flex items-center gap-1">{visitedPois.includes(poi.id) && <CheckCircle2 size={14} className="text-green-500"/>} {poi.title}</h4>
                                             
                                             {poi.isSpecialEvent ? (
                                                 <div className="text-[10px] font-bold text-red-500 flex flex-col gap-0.5 mt-0.5">
                                                     <span className="flex items-center gap-1"><Clock size={10}/> Inizio: {poi.eventDate} {poi.eventTime}</span>
                                                     {poi.eventEndDate && <span className="flex items-center gap-1"><Clock size={10}/> Fine: {poi.eventEndDate} {poi.eventEndTime}</span>}
                                                 </div>
                                             ) : (
                                                 <p className="text-xs text-slate-500 line-clamp-1 mt-0.5">{listName ? <span className="font-bold" style={{ color: listColor }}>Lista: {listName}</span> : (poi.category ? <span className="font-bold text-indigo-500">{poi.category}</span> : (poi.description || 'Scopri di più'))}</p>
                                             )}
                                             
                                             <div className="flex flex-wrap gap-2 mt-2">
                                                {(poi.currentAttendance > 0) && (
                                                     <span className="flex items-center gap-1 text-[10px] font-bold bg-blue-100 text-blue-700 px-1.5 py-0.5 rounded-full"><Users size={10}/> {poi.currentAttendance} presenti</span>
                                                )}
                                                {poi.ratingCount > 0 && (
                                                     <span className="flex items-center gap-1 text-[10px] font-bold bg-amber-100 text-amber-700 px-1.5 py-0.5 rounded-full"><Star size={10} fill="currentColor"/> {getAverageRating(poi)} ({poi.ratingCount})</span>
                                                )}
                                                {poi.distance !== null && poi.distance !== Infinity && (
                                                    <div className="flex gap-2 text-[10px] font-semibold text-slate-500 items-center">
                                                        <span className="text-indigo-600 bg-indigo-50 px-1.5 py-0.5 rounded">{poi.distance < 1 ? (poi.distance * 1000).toFixed(0) + ' m' : poi.distance.toFixed(1) + ' km'}</span>
                                                        <span className="flex items-center gap-1">🚶‍♂️ {Math.ceil((poi.distance / 5) * 60)} min</span>
                                                        <span className="flex items-center gap-1">🚲 {Math.ceil((poi.distance / 15) * 60)} min</span>
                                                    </div>
                                                )}
                                             </div>
                                         </div>
                                     </div>
                                     <div className="flex flex-col gap-1 pl-2 shrink-0 border-l border-slate-100">
                                         <button onClick={(e) => { e.stopPropagation(); toggleVisited(poi.id); }} className={`w-8 h-8 flex items-center justify-center rounded-lg transition-all ${visitedPois.includes(poi.id) ? 'bg-green-100 text-green-600' : 'bg-slate-50 text-slate-400 hover:bg-slate-100'}`} title="Visita">
                                             {visitedPois.includes(poi.id) ? <CheckSquare size={16}/> : <Square size={16}/>}
                                         </button>
                                         <button onClick={(e) => toggleRoutePoi(poi, e)} className={`w-8 h-8 flex items-center justify-center rounded-lg transition-all ${routePois.some(p => p.id === poi.id) ? 'bg-indigo-100 text-indigo-600' : 'bg-slate-50 text-slate-400 hover:bg-slate-100'}`} title="Aggiungi">
                                            {routePois.some(p => p.id === poi.id) ? <Check size={16}/> : <Plus size={16}/>}
                                         </button>
                                     </div>
                                 </div>
                             )})}
                        </div>

                        {routePois.length > 0 && (
                            <div className="bg-white/70 backdrop-blur-md p-4 border-t border-slate-200/50 shrink-0 shadow-[0_-10px_20px_rgba(0,0,0,0.05)] flex items-center justify-between">
                                <div className="flex flex-col"><span className="font-bold text-slate-800 flex items-center gap-1.5"><MapIcon size={18} className="text-indigo-600"/> {routePois.length} tappe</span><button onClick={() => setRoutePois([])} className="text-xs font-semibold text-slate-400 text-left hover:text-red-500 mt-1">Svuota</button></div>
                                <button onClick={openGoogleMapsRoute} className="bg-indigo-600 text-white px-5 py-3 rounded-2xl font-bold shadow-lg shadow-indigo-200 hover:bg-indigo-700 flex items-center gap-2"><Navigation size={18} fill="currentColor"/> Vai in Maps</button>
                            </div>
                        )}
                    </div>
                </>
            )}
            
            {/* Event Popup (Card accattivante) con Distanza, Preferiti, Voto re-integrati */}
            {selectedPoiInfo && !showList && !showNews && !showSubmitModal && !showFavorites && (
                <div className="absolute left-4 right-4 md:left-auto md:right-4 md:w-[400px] bg-white rounded-3xl shadow-[0_20px_60px_-15px_rgba(0,0,0,0.3)] z-40 fade-in-up border border-slate-100 flex flex-col overflow-hidden transition-all duration-300 ease-out" style={dynamicStyles.modals}>
                     {/* Sezione Cover Immagine Dinamica */}
                     {selectedPoiInfo.imageUrl ? (
                        <div className={`w-full relative shrink-0 transition-all duration-500 ease-in-out transform origin-top ${isImageExpanded ? 'h-52' : 'h-24'}`}>
                             <img src={selectedPoiInfo.imageUrl} alt={selectedPoiInfo.title} className="w-full h-full object-cover" />
                             <div className={`absolute inset-0 bg-gradient-to-t from-slate-900 ${isImageExpanded ? 'via-slate-900/40' : 'via-slate-900/80'} to-transparent transition-all duration-500`}></div>
                             <button onClick={() => setSelectedPoiInfo(null)} className="absolute top-4 right-4 p-2 bg-black/40 text-white rounded-full backdrop-blur-md hover:bg-black/60 transition-all border border-white/20 z-20 pointer-events-auto"><X size={18}/></button>
                             
                             <div className="absolute bottom-3 left-4 right-4 flex justify-between items-end pointer-events-none">
                                <div className="min-w-0 flex-1 pointer-events-auto">
                                    <h3 className={`font-black text-white drop-shadow-md transition-all duration-500 ${isImageExpanded ? 'text-2xl leading-tight' : 'text-lg truncate'}`}>{selectedPoiInfo.title}</h3>
                                </div>
                                
                                {/* Bottoni Cuore e Stelle reinseriti */}
                                <div className="flex flex-col items-end gap-2 shrink-0 z-10 pointer-events-auto ml-2">
                                    <button onClick={(e) => toggleFavorite(selectedPoiInfo.id, e)} className={`rounded-full backdrop-blur-md border flex items-center justify-center transition-all ${isImageExpanded ? 'w-10 h-10 bg-white/20 border-white/30 text-white hover:bg-white/40 shadow-lg' : 'w-8 h-8 bg-black/30 border-transparent text-white hover:bg-black/50'}`}>
                                        <Heart size={isImageExpanded ? 20 : 16} fill={favoritePois.includes(selectedPoiInfo.id) ? "currentColor" : "none"} className={favoritePois.includes(selectedPoiInfo.id) ? "text-rose-500" : ""} />
                                    </button>
                                    
                                    <div className="flex flex-row-reverse items-center gap-2">
                                        <button onClick={(e) => { e.stopPropagation(); if(!votedPois.includes(selectedPoiInfo.id)) setRatingMenuOpen(!ratingMenuOpen); }} className={`rounded-full backdrop-blur-md border flex items-center justify-center transition-all ${isImageExpanded ? 'w-10 h-10 bg-white/20 border-white/30 text-white hover:bg-white/40 shadow-lg' : 'w-8 h-8 bg-black/30 border-transparent text-white hover:bg-black/50'}`}>
                                            <Star size={isImageExpanded ? 20 : 16} fill={votedPois.includes(selectedPoiInfo.id) ? "currentColor" : "none"} className={votedPois.includes(selectedPoiInfo.id) ? "text-amber-400" : ""} />
                                        </button>
                                        <div className={`overflow-hidden transition-all duration-300 ease-in-out flex items-center ${ratingMenuOpen ? 'max-w-[150px] opacity-100 pr-1' : 'max-w-0 opacity-0'}`}>
                                            <div className={`flex bg-black/60 backdrop-blur-md rounded-full px-2 items-center border border-white/20 ${isImageExpanded ? 'h-10' : 'h-8'}`}>
                                                {[1, 2, 3, 4, 5].map(star => (
                                                    <button key={star} onClick={(e) => { e.stopPropagation(); handleRatePoi(selectedPoiInfo.id, star); setRatingMenuOpen(false); }} className="p-1 text-white/50 hover:text-amber-400 hover:scale-110 transition-all">
                                                        <Star size={isImageExpanded ? 18 : 14} />
                                                    </button>
                                                ))}
                                            </div>
                                        </div>
                                    </div>
                                </div>
                             </div>
                        </div>
                     ) : (
                        <div className="p-4 flex justify-between items-start bg-slate-50 border-b border-slate-100 shrink-0">
                            <div className="flex-1 pr-2">
                                <h3 className="font-black text-2xl leading-tight text-slate-900">{selectedPoiInfo.title}</h3>
                            </div>
                            <div className="flex flex-col gap-2 shrink-0 items-end">
                                <button onClick={() => setSelectedPoiInfo(null)} className="p-2 bg-white shadow-sm border border-slate-200 rounded-full text-slate-500 hover:bg-slate-50 transition-all"><X size={20}/></button>
                                <div className="flex gap-2">
                                    {/* Bottoni Cuore e Stelle reinseriti per la versione senza immagine */}
                                    <div className="flex flex-row-reverse items-center gap-2">
                                        <button onClick={(e) => toggleFavorite(selectedPoiInfo.id, e)} className="p-2 bg-white shadow-sm border border-slate-200 rounded-full text-slate-500 hover:bg-rose-50 hover:border-rose-200 hover:text-rose-500 transition-all">
                                            <Heart size={20} fill={favoritePois.includes(selectedPoiInfo.id) ? "currentColor" : "none"} className={favoritePois.includes(selectedPoiInfo.id) ? "text-rose-500" : ""} />
                                        </button>
                                        <button onClick={(e) => { e.stopPropagation(); if(!votedPois.includes(selectedPoiInfo.id)) setRatingMenuOpen(!ratingMenuOpen); }} className="p-2 bg-white shadow-sm border border-slate-200 rounded-full text-slate-500 hover:bg-amber-50 hover:border-amber-200 transition-all">
                                            <Star size={20} fill={votedPois.includes(selectedPoiInfo.id) ? "currentColor" : "none"} className={votedPois.includes(selectedPoiInfo.id) ? "text-amber-500" : ""} />
                                        </button>
                                        <div className={`overflow-hidden transition-all duration-300 ease-in-out flex items-center ${ratingMenuOpen ? 'max-w-[150px] opacity-100 pr-1' : 'max-w-0 opacity-0'}`}>
                                            <div className="flex bg-white shadow-md rounded-full px-2 items-center border border-slate-200 h-10">
                                                {[1, 2, 3, 4, 5].map(star => (
                                                    <button key={star} onClick={(e) => { e.stopPropagation(); handleRatePoi(selectedPoiInfo.id, star); setRatingMenuOpen(false); }} className="p-1 text-slate-300 hover:text-amber-500 hover:scale-110 transition-all">
                                                        <Star size={18} />
                                                    </button>
                                                ))}
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                     )}

                     <div className="p-4 md:p-5 flex-1 overflow-y-auto bg-white scroll-smooth" onScroll={(e) => { if (e.target.scrollTop > 10 && isImageExpanded) setIsImageExpanded(false); else if (e.target.scrollTop === 0 && !isImageExpanded) setIsImageExpanded(true); }}>
                         
                         {/* Distanza Re-integrata */}
                         {currentSelectedDistance !== null && currentSelectedDistance !== Infinity && (
                             <div className="flex flex-wrap gap-3 text-[11px] font-semibold text-slate-600 items-center mb-4 bg-slate-50/80 p-2.5 rounded-xl border border-slate-100 w-fit">
                                 <span className="text-indigo-700 bg-indigo-100/50 px-2 py-0.5 rounded-md font-bold">
                                     {currentSelectedDistance < 1 ? (currentSelectedDistance * 1000).toFixed(0) + ' m' : currentSelectedDistance.toFixed(1) + ' km'}
                                 </span>
                                 <span className="flex items-center gap-1">🚶‍♂️ {Math.ceil((currentSelectedDistance / 5) * 60)} min</span>
                                 <span className="flex items-center gap-1">🚲 {Math.ceil((currentSelectedDistance / 15) * 60)} min</span>
                             </div>
                         )}

                         <p onClick={() => setIsImageExpanded(false)} className="text-sm text-slate-600 leading-relaxed font-medium cursor-pointer pb-2">{selectedPoiInfo.description}</p>
                     </div>
                     
                     {/* Azioni Principali Card */}
                     <div className="p-3 bg-slate-50/80 border-t border-slate-100 shrink-0 space-y-2">
                         <div className="flex gap-2">
                             {selectedPoiInfo.hasMedia !== false && (
                                 <button onClick={() => {
                                    const spoUrl = getSpotifyUrl(selectedPoiInfo.mediaUrl);
                                    const ytId = getYouTubeId(selectedPoiInfo.mediaUrl);
                                    const vimId = getVimeoId(selectedPoiInfo.mediaUrl);
                                    const driveId = getGoogleDriveId(selectedPoiInfo.mediaUrl);
                                    const isVideo = selectedPoiInfo.mediaType === 'video' || (!selectedPoiInfo.mediaType && (ytId || vimId || driveId));

                                    if (isVideo && !spoUrl) {
                                        setActiveVideoMedia(selectedPoiInfo);
                                    } else {
                                        setGlobalAudioMedia(selectedPoiInfo);
                                    }

                                 }} className="flex-1 py-3.5 bg-indigo-600 text-white font-bold rounded-2xl shadow-md shadow-indigo-200 hover:bg-indigo-700 transition-colors flex items-center justify-center gap-2 active:scale-95"><Play size={18} fill="currentColor" /> {selectedPoiInfo.mediaType === 'video' ? 'Guarda Video' : 'Ascolta Audio'}</button>
                             )}
                             <button onClick={() => window.open(`https://www.google.com/maps/dir/?api=1&destination=${selectedPoiInfo.lat},${selectedPoiInfo.lng}`, '_blank')} className="flex-[0.7] py-3.5 px-2 bg-white text-slate-700 font-bold rounded-2xl border border-slate-200 shadow-sm hover:bg-slate-50 transition-colors flex items-center justify-center gap-2 active:scale-95" title="Naviga"><Navigation size={18} /> Naviga</button>
                         </div>
                         <button onClick={() => toggleVisited(selectedPoiInfo.id)} className={`w-full py-4 rounded-2xl font-bold flex items-center justify-center gap-2 transition-all border shadow-sm active:scale-95 ${visitedPois.includes(selectedPoiInfo.id) ? 'bg-emerald-500 border-emerald-600 text-white shadow-emerald-200' : 'bg-white border-slate-200 text-slate-700 hover:bg-slate-50'}`}>
                             {visitedPois.includes(selectedPoiInfo.id) ? <CheckCircle2 size={20}/> : <CheckSquare size={20}/>}
                             {visitedPois.includes(selectedPoiInfo.id) ? 'Tappa completata!' : 'Segna come visitato'}
                         </button>
                     </div>
                </div>
            )}
            
            {/* VIDEO MODAL (Fullscreen) */}
            {activeVideoMedia && <VideoPlayerModal media={activeVideoMedia} onClose={() => setActiveVideoMedia(null)} />}

            {/* AUDIO PLAYER (Sottile / Spotify Iframe) in basso */}
            {globalAudioMedia && <GlobalBottomPlayer media={globalAudioMedia} onClose={() => { setGlobalAudioMedia(null); setAudioPlayerMinimized(false); }} isMinimized={audioPlayerMinimized} onToggleMinimize={() => setAudioPlayerMinimized(prev => !prev)} />}
        </div>
    );
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);
