import React, { useState, useEffect, useRef } from 'https://esm.sh/react@18.2.0';
import { createRoot } from 'https://esm.sh/react-dom@18.2.0/client';

import { initializeApp } from 'https://www.gstatic.com/firebasejs/10.8.0/firebase-app.js';
import { getAuth, signInAnonymously, onAuthStateChanged, signInWithEmailAndPassword, createUserWithEmailAndPassword, updatePassword, signOut } from 'https://www.gstatic.com/firebasejs/10.8.0/firebase-auth.js';
import { getFirestore, collection, onSnapshot, doc, setDoc, deleteDoc, writeBatch, getDocs } from 'https://www.gstatic.com/firebasejs/10.8.0/firebase-firestore.js';

// === 1. CONFIGURAZIONE FIREBASE ===
const firebaseConfig = {
    apiKey: "AIzaSyAzBGER_JLVQ0JPampHBTxeq129LXkzyhM",
    authDomain: "touroperator-47382.firebaseapp.com",
    projectId: "touroperator-47382",
    storageBucket: "touroperator-47382.firebasestorage.app",
    messagingSenderId: "521142784329",
    appId: "1:521142784329:web:63b097e6c628e3bc390a98"
};

const app = initializeApp(firebaseConfig);
const auth = getAuth(app);
const db = getFirestore(app);
const DB_BASE_PATH = `artifacts/touroperator-app/public/data`;

// === 2. SICUREZZA E UTILITY ===
const SecurityService = {
    badWords: ['droga', 'bomba', 'stupido', 'idiota', 'coglione', 'merda'],
    containsViolations: (text) => {
        if(!text) return false;
        const textLower = text.toLowerCase();
        return SecurityService.badWords.some(w => textLower.includes(w));
    },
    sanitizeInput: (str) => {
        if(!str) return '';
        return str.replace(/[<>]/g, '');
    }
};

// === 3. ICONE GLOBALI ===
const IconMap = () => <svg xmlns="http://www.w3.org/2000/svg" width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><polygon points="3 6 9 3 15 6 21 3 21 18 15 21 9 18 3 21"></polygon><line x1="9" y1="3" x2="9" y2="21"></line><line x1="15" y1="3" x2="15" y2="21"></line></svg>;
const IconBell = () => <svg xmlns="http://www.w3.org/2000/svg" width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M18 8A6 6 0 0 0 6 8c0 7-3 9-3 9h18s-3-2-3-9"></path><path d="M13.73 21a2 2 0 0 1-3.46 0"></path></svg>;
const IconList = () => <svg xmlns="http://www.w3.org/2000/svg" width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><line x1="8" y1="6" x2="21" y2="6"></line><line x1="8" y1="12" x2="21" y2="12"></line><line x1="8" y1="18" x2="21" y2="18"></line><line x1="3" y1="6" x2="3.01" y2="6"></line><line x1="3" y1="12" x2="3.01" y2="12"></line><line x1="3" y1="18" x2="3.01" y2="18"></line></svg>;
const IconChat = () => <svg xmlns="http://www.w3.org/2000/svg" width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"></path></svg>;
const IconUser = () => <svg xmlns="http://www.w3.org/2000/svg" width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"></path><circle cx="12" cy="7" r="4"></circle></svg>;
const IconPlus = () => <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><line x1="12" y1="5" x2="12" y2="19"></line><line x1="5" y1="12" x2="19" y2="12"></line></svg>;
const IconTrash = () => <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><polyline points="3 6 5 6 21 6"></polyline><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"></path></svg>;
const IconWallet = () => <svg xmlns="http://www.w3.org/2000/svg" width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M20 12V8H6a2 2 0 0 1-2-2c0-1.1.9-2 2-2h12v4"></path><path d="M4 6v12c0 1.1.9 2 2 2h14v-4"></path><path d="M18 12a2 2 0 0 0-2 2c0 1.1.9 2 2 2h4v-4h-4z"></path></svg>;
const IconWifiOff = () => <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><line x1="2" y1="2" x2="22" y2="22"></line><path d="M8.5 8.5a5 5 0 0 1 7 0"></path><path d="M16.88 11.12a9 9 0 0 0-9.76 0"></path><path d="M21.12 6.88a13 13 0 0 0-18.24 0"></path></svg>;
const IconSettings = () => <svg xmlns="http://www.w3.org/2000/svg" width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="3"></circle><path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1 0 2.83 2 2 0 0 1-2.83 0l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-2 2 2 2 0 0 1-2-2v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83 0 2 2 0 0 1 0-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1-2-2 2 2 0 0 1 2-2h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 0-2.83 2 2 0 0 1 2.83 0l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 2-2 2 2 0 0 1 2 2v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 0 2 2 0 0 1 0 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 2 2 2 2 0 0 1-2 2h-.09a1.65 1.65 0 0 0-1.51 1z"></path></svg>;
const IconEdit = () => <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"></path><path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"></path></svg>;
const IconShieldAlert = () => <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"></path><line x1="12" y1="8" x2="12" y2="12"></line><line x1="12" y1="16" x2="12.01" y2="16"></line></svg>;
const IconMaximize = () => <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M8 3H5a2 2 0 0 0-2 2v3m18 0V5a2 2 0 0 0-2-2h-3m0 18h3a2 2 0 0 0 2-2v-3M3 16v3a2 2 0 0 0 2 2h3"></path></svg>;
const IconMinimize = () => <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M8 3v3a2 2 0 0 1-2 2H3m18 0h-3a2 2 0 0 1-2-2V3m0 18v-3a2 2 0 0 1 2-2h3M3 16h3a2 2 0 0 1 2 2v3"></path></svg>;

// === 4. COMPONENTI UI ===

const LoginScreen = ({ onStudentLogin, onStaffLogin, authError, isOnline }) => {
    const [tab, setTab] = useState('student');
    const [code, setCode] = useState('');
    const [email, setEmail] = useState('');
    const [pwd, setPwd] = useState('');

    return (
        <div className="flex-1 flex flex-col justify-center items-center p-5 bg-gradient-to-br from-blue-50 to-indigo-100 min-h-screen w-full">
            <div className="bg-white p-8 rounded-3xl shadow-2xl w-full max-w-md animate-fade-in">
                <h1 className="text-4xl font-black text-center text-blue-900 mb-2">EduTravel</h1>
                <p className="text-center text-gray-500 text-sm mb-8">Piattaforma Viaggi B2B/B2C</p>

                {!isOnline && (
                    <div className="bg-yellow-100 text-yellow-800 p-3 rounded-xl mb-4 text-xs font-bold text-center flex items-center justify-center gap-2">
                        <IconWifiOff /> Sei offline.
                    </div>
                )}
                {authError && (
                    <div className="bg-red-100 text-red-800 p-3 rounded-xl mb-4 text-sm font-bold text-center">
                        {authError}
                    </div>
                )}

                <div className="flex bg-gray-100 p-1.5 rounded-xl mb-8">
                    <button onClick={() => setTab('student')} className={`flex-1 py-2.5 rounded-lg text-sm font-bold transition ${tab === 'student' ? 'bg-white shadow text-blue-600' : 'text-gray-500 hover:bg-gray-200'}`}>🎒 Turista</button>
                    <button onClick={() => setTab('staff')} className={`flex-1 py-2.5 rounded-lg text-sm font-bold transition ${tab === 'staff' ? 'bg-white shadow text-purple-600' : 'text-gray-500 hover:bg-gray-200'}`}>👨‍🏫 Staff</button>
                </div>

                {tab === 'student' ? (
                    <form onSubmit={(e) => { e.preventDefault(); onStudentLogin(code); }} className="space-y-4">
                        <input type="text" placeholder="Codice Viaggio" value={code} onChange={e=>setCode(e.target.value.toUpperCase())} className="w-full p-4 bg-gray-50 border border-gray-200 rounded-xl text-center font-mono font-bold tracking-widest outline-none focus:border-blue-400 focus:ring-2 focus:ring-blue-100 transition" required />
                        <button type="submit" className="w-full bg-blue-600 text-white font-bold py-4 rounded-xl shadow-md hover:bg-blue-700 transition transform hover:-translate-y-0.5">Entra nel Tour</button>
                    </form>
                ) : (
                    <form onSubmit={(e) => { e.preventDefault(); onStaffLogin(email, pwd); }} className="space-y-4">
                        <input type="email" placeholder="Email Staff" value={email} onChange={e=>setEmail(e.target.value)} className="w-full p-3.5 bg-gray-50 border border-gray-200 rounded-xl outline-none focus:border-purple-400 focus:ring-2 focus:ring-purple-100 transition" required />
                        <input type="password" placeholder="Password" value={pwd} onChange={e=>setPwd(e.target.value)} className="w-full p-3.5 bg-gray-50 border border-gray-200 rounded-xl outline-none focus:border-purple-400 focus:ring-2 focus:ring-purple-100 transition" required />
                        <button type="submit" className="w-full bg-purple-600 text-white font-bold py-4 rounded-xl shadow-md hover:bg-purple-700 transition transform hover:-translate-y-0.5">Accesso Sicuro</button>
                    </form>
                )}
            </div>
        </div>
    );
};

const StaffDashboard = ({ role, userEmail, admins, managers, groups, onAddAdmin, onRemoveAdmin, onAddManager, onRemoveManager, onAddGroup, onUpdateGroup, onDeleteGroup, onChangePassword, setActiveGroupId, setActiveTab }) => {
    const [newAdminEmail, setNewAdminEmail] = useState('');
    const [newManagerEmail, setNewManagerEmail] = useState('');
    const [showGroupForm, setShowGroupForm] = useState(false);
    const [newGroup, setNewGroup] = useState({ name: '', startDate: '', endDate: '', managerInfo: '', managerEmails: [] });
    const [deleteConfirm, setDeleteConfirm] = useState(null);
    const [editingGroupId, setEditingGroupId] = useState(null);
    const [editGroupData, setEditGroupData] = useState(null);
    const [newPwd, setNewPwd] = useState('');

    const visibleGroups = role === 'manager' ? groups.filter(g => g.managerEmails && g.managerEmails.includes(userEmail)) : groups;

    return (
        <div className="space-y-6 pb-24 animate-fade-in p-5 max-w-6xl mx-auto">
            
            {/* Sezione Account */}
            <div className="bg-white p-5 rounded-2xl shadow-sm mb-6 border border-gray-200 flex flex-col md:flex-row justify-between items-start md:items-center gap-4">
                <h3 className="font-bold text-gray-800 flex items-center gap-2"><IconSettings /> Account ({userEmail})</h3>
                <form onSubmit={(e) => { e.preventDefault(); onChangePassword(newPwd); setNewPwd(''); }} className="flex gap-2 w-full md:w-auto">
                    <input type="password" placeholder="Nuova Password" value={newPwd} onChange={e=>setNewPwd(e.target.value)} className="flex-1 md:w-48 p-2 rounded-lg bg-gray-50 border outline-none text-sm" required minLength="6"/>
                    <button type="submit" className="bg-gray-800 hover:bg-gray-700 text-white px-4 py-2 rounded-lg text-sm font-bold transition">Aggiorna</button>
                </form>
            </div>

            <div className="grid grid-cols-1 md:grid-cols-2 gap-6 mb-6">
                {role === 'master' && (
                    <div className="bg-gray-900 p-5 rounded-2xl shadow-lg border border-gray-800">
                        <h3 className="text-white font-bold mb-3">Gestione Globale Admin</h3>
                        <form onSubmit={(e) => { e.preventDefault(); onAddAdmin(newAdminEmail); setNewAdminEmail(''); }} className="flex gap-2 mb-4">
                            <input type="email" placeholder="Email nuovo Admin" value={newAdminEmail} onChange={e=>setNewAdminEmail(e.target.value)} className="flex-1 p-2 rounded-lg bg-gray-800 text-white border border-gray-700 outline-none text-sm" required/>
                            <button type="submit" className="bg-purple-600 hover:bg-purple-500 text-white px-4 py-2 rounded-lg text-sm font-bold transition">+</button>
                        </form>
                        <div className="space-y-2 max-h-40 overflow-y-auto pr-2">
                            {admins.map(a => (
                                <div key={a.id} className="flex justify-between items-center bg-gray-800 p-2.5 rounded-lg border border-gray-700">
                                    <span className="text-gray-300 text-sm truncate">{a.email}</span>
                                    {a.email !== 'michelectrn@gmail.com' && <button onClick={()=>onRemoveAdmin(a.id)} className="text-red-400 hover:text-red-300 text-xs font-bold transition">Rimuovi</button>}
                                </div>
                            ))}
                        </div>
                    </div>
                )}

                {(role === 'master' || role === 'admin') && (
                    <div className="bg-blue-50 p-5 rounded-2xl shadow-sm border border-blue-200">
                        <h3 className="text-blue-900 font-bold mb-3 flex items-center gap-2"><IconUser /> Rubrica Responsabili</h3>
                        <form onSubmit={(e) => { e.preventDefault(); onAddManager(newManagerEmail); setNewManagerEmail(''); }} className="flex gap-2 mb-4">
                            <input type="email" placeholder="Email Responsabile" value={newManagerEmail} onChange={e=>setNewManagerEmail(e.target.value)} className="flex-1 p-2 rounded-lg bg-white border border-blue-200 outline-none text-sm" required/>
                            <button type="submit" className="bg-blue-600 hover:bg-blue-700 text-white px-4 py-2 rounded-lg text-sm font-bold transition">+</button>
                        </form>
                        <div className="space-y-2 max-h-40 overflow-y-auto pr-2">
                            {managers.map(m => (
                                <div key={m.id} className="flex justify-between items-center bg-white border border-blue-100 p-2.5 rounded-lg shadow-sm">
                                    <span className="text-gray-700 text-sm truncate">{m.email}</span>
                                    <button onClick={()=>onRemoveManager(m.id)} className="text-red-500 hover:text-red-700 text-xs font-bold hover:underline">Rimuovi</button>
                                </div>
                            ))}
                            {managers.length === 0 && <p className="text-xs text-blue-500 italic">Nessun responsabile in rubrica.</p>}
                        </div>
                    </div>
                )}
            </div>

            <div className="flex justify-between items-center mb-6 border-b pb-2">
                <h2 className="text-2xl font-bold text-gray-800">I Miei Viaggi</h2>
                {role !== 'manager' && (
                    <button onClick={()=>setShowGroupForm(!showGroupForm)} className="bg-blue-600 hover:bg-blue-700 transition text-white px-4 py-2 rounded-full shadow-md font-bold flex items-center gap-2">
                        <IconPlus /> <span className="hidden md:inline">Nuovo Viaggio</span>
                    </button>
                )}
            </div>

            {showGroupForm && role !== 'manager' && (
                <form onSubmit={(e) => { e.preventDefault(); onAddGroup(newGroup); setNewGroup({name:'', startDate:'', endDate:'', managerInfo:'', managerEmails:[]}); setShowGroupForm(false); }} className="bg-white p-6 rounded-2xl border border-gray-200 shadow-sm mb-6 animate-fade-in max-w-2xl">
                    <input type="text" placeholder="Nome Viaggio" value={newGroup.name} onChange={e=>setNewGroup({...newGroup, name:SecurityService.sanitizeInput(e.target.value)})} className="w-full mb-4 p-3 border rounded-xl outline-none font-bold text-lg focus:border-blue-400" required />
                    <div className="flex flex-col md:flex-row gap-4 mb-4">
                        <div className="flex-1"><label className="text-[10px] font-bold text-gray-500 uppercase mb-1 block">Inizio</label><input type="date" value={newGroup.startDate} onChange={e=>setNewGroup({...newGroup, startDate:e.target.value})} className="w-full p-3 border rounded-xl outline-none text-sm focus:border-blue-400" required /></div>
                        <div className="flex-1"><label className="text-[10px] font-bold text-gray-500 uppercase mb-1 block">Fine</label><input type="date" value={newGroup.endDate} onChange={e=>setNewGroup({...newGroup, endDate:e.target.value})} className="w-full p-3 border rounded-xl outline-none text-sm focus:border-blue-400" required /></div>
                    </div>
                    <label className="text-[10px] font-bold text-gray-500 uppercase mb-1 block">Info Responsabili (Visibile ai Turisti)</label>
                    <input type="text" placeholder="Es. Prof. Rossi" value={newGroup.managerInfo} onChange={e=>setNewGroup({...newGroup, managerInfo:SecurityService.sanitizeInput(e.target.value)})} className="w-full mb-4 p-3 border rounded-xl outline-none text-sm focus:border-blue-400" />
                    
                    <div className="mb-4 bg-gray-50 border border-gray-200 p-4 rounded-xl">
                        <label className="text-[10px] font-bold text-gray-500 uppercase block mb-3">Assegna Responsabili</label>
                        {managers.length === 0 ? <p className="text-xs text-gray-400 italic">Aggiungi responsabili in Rubrica per assegnarli al viaggio.</p> : (
                            <div className="grid grid-cols-1 md:grid-cols-2 gap-2 max-h-40 overflow-y-auto">
                                {managers.map(m => (
                                    <label key={m.id} className="flex items-center gap-3 text-sm bg-white p-2.5 rounded-lg border cursor-pointer hover:bg-blue-50 transition shadow-sm">
                                        <input type="checkbox" checked={newGroup.managerEmails.includes(m.email)} onChange={(e) => {
                                            const updated = e.target.checked ? [...newGroup.managerEmails, m.email] : newGroup.managerEmails.filter(email => email !== m.email);
                                            setNewGroup({...newGroup, managerEmails: updated});
                                        }} className="rounded text-blue-600 w-4 h-4" />
                                        <span className="text-gray-700 font-medium truncate">{m.email}</span>
                                    </label>
                                ))}
                            </div>
                        )}
                    </div>
                    <div className="flex justify-end gap-2">
                         <button type="button" onClick={() => setShowGroupForm(false)} className="px-6 py-3 text-gray-600 font-bold hover:bg-gray-100 rounded-xl transition">Annulla</button>
                         <button type="submit" className="bg-blue-600 hover:bg-blue-700 text-white px-8 py-3 rounded-xl font-bold shadow-md transition">Crea Viaggio</button>
                    </div>
                </form>
            )}

            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-5">
                {visibleGroups.length === 0 ? <p className="text-gray-500 text-sm text-center py-10 col-span-full">Nessun viaggio disponibile.</p> : 
                 visibleGroups.map(g => {
                     const isExpired = g.endDate && g.endDate < new Date().toISOString().split('T')[0];
                     
                     if (editingGroupId === g.id) {
                         return (
                             <div key={g.id} className="p-5 rounded-2xl border-2 bg-white border-blue-400 shadow-xl animate-fade-in relative z-10 flex flex-col h-full">
                                 <form onSubmit={(e) => { e.preventDefault(); onUpdateGroup(g.id, editGroupData); setEditingGroupId(null); }} className="flex flex-col h-full">
                                    <input type="text" value={editGroupData.name} onChange={e=>setEditGroupData({...editGroupData, name:e.target.value})} className="w-full mb-3 p-2 border rounded-lg text-sm outline-none font-bold focus:border-blue-400" required />
                                    <div className="flex gap-2 mb-3">
                                        <div className="flex-1"><label className="text-[10px] font-bold text-gray-500 uppercase">Inizio</label><input type="date" value={editGroupData.startDate} onChange={e=>setEditGroupData({...editGroupData, startDate:e.target.value})} className="w-full p-2 border rounded-lg text-sm outline-none" required /></div>
                                        <div className="flex-1"><label className="text-[10px] font-bold text-gray-500 uppercase">Fine</label><input type="date" value={editGroupData.endDate} onChange={e=>setEditGroupData({...editGroupData, endDate:e.target.value})} className="w-full p-2 border rounded-lg text-sm outline-none" required /></div>
                                    </div>
                                    <label className="text-[10px] font-bold text-gray-500 uppercase">Info Responsabili</label>
                                    <input type="text" value={editGroupData.managerInfo || ''} onChange={e=>setEditGroupData({...editGroupData, managerInfo:e.target.value})} className="w-full mb-3 p-2 border rounded-lg text-sm outline-none" />
                                    
                                    <div className="mb-4 flex-1 bg-gray-50 border border-gray-200 p-2.5 rounded-xl overflow-hidden flex flex-col">
                                        <label className="text-[10px] font-bold text-gray-500 uppercase block mb-2">Assegna Responsabili</label>
                                        <div className="flex-1 overflow-y-auto space-y-1 pr-1">
                                            {managers.map(m => (
                                                <label key={m.id} className="flex items-center gap-2 text-xs bg-white p-2 rounded-lg border cursor-pointer hover:bg-blue-50 shadow-sm">
                                                    <input type="checkbox" checked={(editGroupData.managerEmails || []).includes(m.email)} onChange={(e) => {
                                                        const updated = e.target.checked ? [...(editGroupData.managerEmails || []), m.email] : (editGroupData.managerEmails || []).filter(email => email !== m.email);
                                                        setEditGroupData({...editGroupData, managerEmails: updated});
                                                    }} className="rounded text-blue-600" />
                                                    <span className="text-gray-700 truncate">{m.email}</span>
                                                </label>
                                            ))}
                                        </div>
                                    </div>
                                    <div className="flex gap-2 mt-auto">
                                        <button type="submit" className="flex-1 bg-blue-600 hover:bg-blue-700 text-white py-2.5 rounded-lg text-sm font-bold shadow-md transition">Salva</button>
                                        <button type="button" onClick={() => setEditingGroupId(null)} className="flex-1 bg-gray-200 hover:bg-gray-300 text-gray-800 py-2.5 rounded-lg text-sm font-bold transition">Annulla</button>
                                    </div>
                                 </form>
                             </div>
                         );
                     }
                     return (
                        <div key={g.id} onClick={()=>{setActiveGroupId(g.id); setActiveTab('profile');}} className={`p-6 rounded-2xl border-2 cursor-pointer transition-all duration-200 relative overflow-hidden flex flex-col h-full ${isExpired ? 'bg-gray-100 border-gray-300 opacity-80' : 'bg-white border-purple-100 hover:border-purple-300 hover:shadow-xl transform hover:-translate-y-1'}`}>
                            {deleteConfirm === g.id ? (
                                <div className="absolute inset-0 bg-red-50/95 flex flex-col items-center justify-center p-4 z-20 backdrop-blur-sm">
                                    <p className="text-red-800 font-bold mb-3 text-sm text-center">Eliminare definitivamente?</p>
                                    <div className="flex gap-3">
                                        <button onClick={(e) => { e.stopPropagation(); onDeleteGroup(g.id); setDeleteConfirm(null); }} className="bg-red-600 hover:bg-red-700 text-white px-4 py-2 rounded-lg text-xs font-bold shadow-md transition">Sì, elimina</button>
                                        <button onClick={(e) => { e.stopPropagation(); setDeleteConfirm(null); }} className="bg-white border border-gray-300 text-gray-800 px-4 py-2 rounded-lg text-xs font-bold shadow-sm transition hover:bg-gray-50">Annulla</button>
                                    </div>
                                </div>
                            ) : role !== 'manager' ? (
                                <div className="absolute bottom-5 right-5 flex gap-2 z-10">
                                    <button onClick={(e) => { e.stopPropagation(); setEditGroupData({...g, managerEmails: g.managerEmails || []}); setEditingGroupId(g.id); }} className="text-blue-600 bg-blue-50 p-2 rounded-lg hover:bg-blue-100 transition shadow-sm"><IconEdit /></button>
                                    <button onClick={(e) => { e.stopPropagation(); setDeleteConfirm(g.id); }} className="text-red-600 bg-red-50 p-2 rounded-lg hover:bg-red-100 transition shadow-sm"><IconTrash /></button>
                                </div>
                            ) : null}
                            <h3 className="font-black text-gray-800 text-xl pr-[70px] leading-tight mb-2">{g.name}</h3>
                            <div className="mt-auto">
                                <p className="text-xs text-gray-500 font-medium bg-gray-100 inline-block px-2 py-1 rounded-md mb-2">Dal {g.startDate} al {g.endDate}</p>
                                {g.managerInfo && <p className="text-xs text-gray-600 mt-1 flex items-center gap-1">👤 {g.managerInfo}</p>}
                            </div>
                            {isExpired && <span className="absolute top-5 right-5 text-[10px] font-bold bg-gray-200 text-gray-600 px-2.5 py-1 rounded-md uppercase tracking-wider">Terminato</span>}
                        </div>
                     )
                 })
                }
            </div>
        </div>
    );
};

const Management = ({ group, students, alerts, onAddStudent, onDeleteStudent, onUnlockUser, showMsg }) => {
    const [newStudent, setNewStudent] = useState('');
    const [csvText, setCsvText] = useState('');
    const [showCsv, setShowCsv] = useState(false);

    const handleMassiveLoad = () => {
        const names = csvText.split('\n').map(n => n.trim()).filter(n => n);
        if (names.length === 0) return;
        names.forEach(name => onAddStudent(SecurityService.sanitizeInput(name)));
        setCsvText('');
        setShowCsv(false);
        showMsg(`${names.length} profili creati!`);
    };

    const downloadCodes = () => {
        let csv = "Nome,Codice Accesso\n";
        students.forEach(s => csv += `${s.name},${s.code}\n`);
        const blob = new Blob([csv], { type: 'text/csv' });
        const url = window.URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url; a.download = `Codici_${group?.name || 'Viaggio'}.csv`; a.click();
    };

    return (
        <div className="space-y-6 pb-24 p-5 animate-fade-in max-w-4xl mx-auto">
            <h2 className="text-3xl font-black text-gray-800 mb-6 py-2 border-b">Utenti Viaggio</h2>

            {alerts && alerts.length > 0 && (
                <div className="bg-red-50 border-l-4 border-red-500 p-5 rounded-r-xl mb-6 shadow-sm">
                    <h3 className="font-bold text-red-800 mb-3 flex items-center gap-2"><IconShieldAlert /> Sicurezza: Utenti Bloccati</h3>
                    <div className="space-y-2">
                        {alerts.map(a => (
                            <div key={a.id} className="bg-white p-3.5 rounded-lg shadow-sm text-sm border border-red-100 flex flex-col md:flex-row justify-between items-start md:items-center gap-3">
                                <div><p className="font-bold text-red-700">{a.userName}</p><p className="text-xs text-gray-600 italic mt-1">"{a.messageText}"</p></div>
                                <button onClick={()=>onUnlockUser(a.userId, a.id)} className="bg-red-100 hover:bg-red-200 text-red-700 px-4 py-2 rounded-lg text-xs font-bold transition">Sblocca Utente</button>
                            </div>
                        ))}
                    </div>
                </div>
            )}

            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div className="bg-white p-6 rounded-2xl shadow-sm border border-gray-200">
                    <h3 className="font-bold text-gray-800 mb-4">Aggiungi Singolo</h3>
                    <form onSubmit={(e) => { e.preventDefault(); onAddStudent(SecurityService.sanitizeInput(newStudent)); setNewStudent(''); }} className="flex gap-2">
                        <input type="text" value={newStudent} onChange={e=>setNewStudent(e.target.value)} placeholder="Nome e Cognome" className="flex-1 p-3 border rounded-xl bg-gray-50 outline-none focus:border-orange-400 focus:bg-white transition" required />
                        <button type="submit" className="bg-orange-600 hover:bg-orange-700 text-white px-5 rounded-xl font-bold shadow-md transition">+</button>
                    </form>
                </div>

                <div className="bg-white p-6 rounded-2xl shadow-sm border border-gray-200">
                    <div className="flex justify-between items-center mb-4">
                        <h3 className="font-bold text-gray-800">Caricamento Massivo</h3>
                        <button onClick={()=>setShowCsv(!showCsv)} className="text-blue-600 hover:text-blue-800 text-xs font-bold underline transition">Importa da CSV</button>
                    </div>
                    {showCsv && (
                        <div className="animate-fade-in mt-2">
                            <textarea value={csvText} onChange={e=>setCsvText(e.target.value)} className="w-full h-24 p-3 border rounded-xl text-sm mb-3 outline-none bg-gray-50 focus:bg-white focus:border-blue-400 transition" placeholder="Es:&#10;Mario Rossi&#10;Luigi Bianchi"></textarea>
                            <button onClick={handleMassiveLoad} className="w-full bg-blue-600 hover:bg-blue-700 text-white p-3 rounded-xl text-sm font-bold shadow-md transition">Genera Profili</button>
                        </div>
                    )}
                </div>
            </div>

            <div className="mt-8">
                <div className="flex justify-between items-center mb-4 border-b pb-2">
                    <h3 className="font-bold text-gray-800 flex items-center gap-2"><IconUser /> Lista Partecipanti ({students.length})</h3>
                    {students.length > 0 && <button onClick={downloadCodes} className="bg-green-600 hover:bg-green-700 text-white px-4 py-2 rounded-lg text-xs font-bold shadow-md transition flex items-center gap-2">↓ Esporta Codici</button>}
                </div>
                <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-3">
                    {students.length === 0 ? <p className="text-gray-500 italic text-sm col-span-full py-5 text-center bg-gray-50 rounded-xl">Nessun utente iscritto al viaggio.</p> : 
                     students.map(s => (
                        <div key={s.id} className="bg-white p-4 rounded-xl shadow-sm border border-gray-100 relative hover:shadow-md transition">
                            <button onClick={() => onDeleteStudent(s.id, s.code)} className="absolute top-3 right-3 text-gray-300 hover:text-red-500 transition"><IconTrash /></button>
                            <div>
                                <p className="font-bold text-gray-800 pr-6">{s.name}</p>
                                {s.blocked && <span className="text-[10px] bg-red-100 text-red-700 px-2 py-0.5 mt-1 inline-block font-bold rounded">BLOCCATO</span>}
                                <p className="text-xs text-gray-500 mt-2">Codice Accesso: <span className="font-mono font-bold text-orange-600 bg-orange-50 px-1.5 py-0.5 rounded ml-1">{s.code}</span></p>
                            </div>
                        </div>
                     ))}
                </div>
            </div>
        </div>
    );
};

const Itinerary = ({ events, role, onAddEvent, onUpdateEvent, onDeleteEvent, showMsg }) => {
    const [showForm, setShowForm] = useState(false);
    const [editingId, setEditingId] = useState(null);
    const [evForm, setEvForm] = useState({ time: '', title: '', location: '', description: '', lat: '', lng: '' });
    const [verifying, setVerifying] = useState(false);

    const handleSubmit = (e) => {
        e.preventDefault();
        const cleanForm = { ...evForm, title: SecurityService.sanitizeInput(evForm.title), description: SecurityService.sanitizeInput(evForm.description) };
        if (editingId) onUpdateEvent(editingId, cleanForm);
        else onAddEvent(cleanForm);
        setEvForm({ time: '', title: '', location: '', description: '', lat: '', lng: '' });
        setShowForm(false);
        setEditingId(null);
    };

    const handleVerifyAddress = async () => {
        if (!evForm.location) return;
        setVerifying(true);
        try {
            const res = await fetch(`https://nominatim.openstreetmap.org/search?format=json&q=${encodeURIComponent(evForm.location)}`);
            const data = await res.json();
            if (data && data.length > 0) { setEvForm({ ...evForm, lat: data[0].lat, lng: data[0].lon }); showMsg("Coordinate trovate!"); }
        } catch(err) { showMsg("Errore rete."); }
        setVerifying(false);
    };

    const sorted = [...events].sort((a, b) => a.time.localeCompare(b.time));

    return (
        <div className="space-y-4 pb-24 p-5 animate-fade-in max-w-4xl mx-auto">
            <div className="flex justify-between items-center mb-6 py-2 border-b">
                <h2 className="text-3xl font-black text-gray-800">Itinerario</h2>
                {role !== 'student' && <button onClick={() => {setShowForm(!showForm); setEditingId(null); setEvForm({ time: '', title: '', location: '', description: '', lat: '', lng: '' });}} className="bg-blue-600 hover:bg-blue-700 transition text-white p-3 md:px-5 md:py-2.5 rounded-full md:rounded-xl shadow-md font-bold flex items-center gap-2"><IconPlus /> <span className="hidden md:inline">Nuova Tappa</span></button>}
            </div>

            {role !== 'student' && showForm && (
                <form onSubmit={handleSubmit} className="bg-blue-50 p-5 rounded-2xl border border-blue-200 mb-8 shadow-sm">
                    <div className="grid grid-cols-1 md:grid-cols-4 gap-3 mb-3">
                        <input type="time" value={evForm.time} onChange={e=>setEvForm({...evForm, time:e.target.value})} className="p-3 rounded-xl border md:col-span-1 outline-none focus:border-blue-400" required />
                        <input type="text" placeholder="Titolo della Tappa" value={evForm.title} onChange={e=>setEvForm({...evForm, title:e.target.value})} className="p-3 rounded-xl border md:col-span-3 outline-none focus:border-blue-400 font-bold" required />
                    </div>
                    <div className="flex flex-col md:flex-row gap-3 mb-3">
                        <input type="text" placeholder="Indirizzo o Luogo" value={evForm.location} onChange={e=>setEvForm({...evForm, location:e.target.value})} className="flex-1 p-3 rounded-xl border text-sm outline-none focus:border-blue-400" />
                        <button type="button" onClick={handleVerifyAddress} disabled={verifying} className="bg-white border border-gray-300 hover:bg-gray-100 text-gray-700 px-4 py-3 rounded-xl text-sm font-bold disabled:opacity-50 transition">Cerca Coordinate</button>
                    </div>
                    <textarea placeholder="Note aggiuntive, orari di ritrovo..." value={evForm.description} onChange={e=>setEvForm({...evForm, description:e.target.value})} className="p-3 rounded-xl border w-full text-sm mb-4 h-24 resize-none outline-none focus:border-blue-400" />
                    <div className="flex justify-end gap-2">
                         <button type="button" onClick={() => setShowForm(false)} className="px-5 py-2.5 text-gray-600 font-bold hover:bg-gray-200 rounded-xl transition">Annulla</button>
                         <button type="submit" className="bg-blue-600 hover:bg-blue-700 text-white px-6 py-2.5 rounded-xl font-bold shadow-md transition">{editingId ? 'Aggiorna Tappa' : 'Salva Tappa'}</button>
                    </div>
                </form>
            )}

            <div className="relative border-l-2 border-blue-200 ml-4 space-y-8 md:ml-6 mt-4">
                {sorted.length === 0 ? <p className="text-gray-500 pl-6 italic bg-gray-50 p-4 rounded-xl ml-2">Il programma è ancora vuoto.</p> : 
                 sorted.map(ev => (
                    <div key={ev.id} className="relative pl-6 md:pl-8">
                        <div className="absolute w-5 h-5 bg-blue-500 rounded-full -left-[11px] top-1.5 border-4 border-gray-100 shadow-sm"></div>
                        <div className="bg-white p-5 rounded-2xl shadow-sm border border-gray-100 relative group hover:shadow-md transition">
                            {role !== 'student' && (
                                <div className="absolute top-4 right-4 flex gap-2">
                                    <button onClick={() => {setEvForm({ time: ev.time, title: ev.title, location: ev.location || '', description: ev.description || '', lat: ev.lat || '', lng: ev.lng || '' }); setEditingId(ev.id); setShowForm(true);}} className="text-gray-300 hover:text-blue-500 transition bg-gray-50 p-1.5 rounded-lg"><IconEdit /></button>
                                    <button onClick={() => onDeleteEvent(ev.id)} className="text-gray-300 hover:text-red-500 transition bg-gray-50 p-1.5 rounded-lg"><IconTrash /></button>
                                </div>
                            )}
                            <span className="text-blue-700 font-black text-sm bg-blue-50 px-3 py-1.5 rounded-lg inline-block mb-2 shadow-sm">{ev.time}</span>
                            <h3 className="font-bold text-gray-900 mt-1 text-xl pr-16">{ev.title}</h3>
                            {ev.location && <p className="text-gray-600 text-sm mt-2 flex items-start gap-1">📍 <span>{ev.location}</span></p>}
                            {ev.description && <p className="text-gray-600 text-sm mt-3 bg-gray-50 p-3 rounded-xl border border-gray-100">{ev.description}</p>}
                        </div>
                    </div>
                ))}
            </div>
        </div>
    );
};

const MapComponent = ({ isFullscreen, setIsFullscreen }) => {
    // Quando è in modalità fullscreen, copre fisicamente l'intero schermo grazie alle modifiche in App.jsx
    if (isFullscreen) {
        return (
            <div className="absolute inset-0 z-[100] flex flex-col animate-fade-in bg-gray-100">
                <button 
                    onClick={() => setIsFullscreen(false)} 
                    className="absolute top-6 right-4 md:top-8 md:right-8 z-10 bg-gray-900/60 hover:bg-gray-900/80 backdrop-blur-md text-white px-5 py-3 rounded-2xl transition-all shadow-[0_8px_30px_rgb(0,0,0,0.4)] flex items-center gap-2 text-sm font-bold border border-white/20"
                >
                    <IconMinimize /> <span className="hidden md:inline">Riduci Mappa</span><span className="md:hidden">Chiudi</span>
                </button>
                <iframe src="https://eventbridge.pages.dev/" title="Mappa" className="w-full h-full border-0 bg-white" allow="geolocation" sandbox="allow-scripts allow-same-origin allow-popups allow-forms"></iframe>
            </div>
        );
    }
    return (
        <div className="flex flex-col animate-fade-in relative h-[calc(100vh-180px)] md:h-full p-4 md:p-6 pb-24 md:pb-6">
            <div className="flex justify-between items-center mb-4 border-b pb-2">
                <h2 className="text-2xl md:text-3xl font-black text-gray-800">Mappa Condivisa</h2>
                <button onClick={() => setIsFullscreen(true)} className="bg-blue-100 text-blue-700 hover:bg-blue-200 transition px-4 py-2 rounded-xl shadow-sm flex items-center gap-2 text-sm font-bold"><IconMaximize /> <span className="hidden md:inline">Espandi Mappa</span><span className="md:hidden">Espandi</span></button>
            </div>
            <div className="flex-1 rounded-2xl shadow-inner border border-gray-200 z-0 overflow-hidden bg-gray-50 relative">
                <iframe src="https://eventbridge.pages.dev/" title="Mappa" className="absolute inset-0 w-full h-full border-0" allow="geolocation" sandbox="allow-scripts allow-same-origin allow-popups allow-forms"></iframe>
            </div>
        </div>
    );
};

const Chat = ({ messages, role, currentProfile, isExpired, onSendMessage }) => {
    const [chatInput, setChatInput] = useState('');
    const chatBottomRef = useRef(null);
    
    useEffect(() => { if(chatBottomRef.current) chatBottomRef.current.scrollIntoView(); }, [messages]);
    const sorted = [...messages].sort((a,b)=>(a.timestamp||0)-(b.timestamp||0));

    return (
        <div className="flex flex-col h-[calc(100vh-180px)] md:h-full pb-20 md:pb-6 p-4 md:p-6 animate-fade-in relative max-w-4xl mx-auto w-full">
            <div className="flex justify-between items-center mb-4 border-b pb-2">
                <h2 className="text-2xl md:text-3xl font-black text-gray-800">Chat di Gruppo</h2>
            </div>
            
            {isExpired && <div className="bg-red-50 text-red-800 p-3 rounded-xl mb-4 text-xs font-bold text-center border border-red-200 shadow-sm">Viaggio terminato. La chat è in sola lettura.</div>}
            
            <div className="flex-1 bg-white border border-gray-200 rounded-2xl shadow-inner overflow-y-auto p-4 md:p-6 mb-4 space-y-4 flex flex-col">
                {sorted.length === 0 ? <p className="text-center text-gray-400 italic text-sm mt-auto mb-auto">Nessun messaggio. Inizia la conversazione!</p> : 
                 sorted.map(msg => {
                     const isMine = role !== 'student' ? msg.role !== 'student' : (msg.senderCode === currentProfile?.code);
                     const isStaff = msg.role !== 'student';
                     return (
                         <div key={msg.id} className={`flex flex-col max-w-[85%] md:max-w-[70%] ${isMine ? 'self-end items-end' : 'self-start items-start'}`}>
                             <span className="text-[10px] text-gray-400 font-bold mb-1 px-1 uppercase tracking-wider">{msg.senderName}</span>
                             <div className={`p-3.5 rounded-2xl text-sm shadow-sm ${isMine ? 'bg-indigo-600 text-white rounded-tr-sm' : isStaff ? 'bg-purple-100 text-purple-900 border border-purple-200 rounded-tl-sm font-medium' : 'bg-gray-100 text-gray-800 border border-gray-200 rounded-tl-sm'}`}>
                                 {msg.text}
                             </div>
                         </div>
                     );
                 })
                }
                <div ref={chatBottomRef} />
            </div>
            
            {!isExpired && (
                <form onSubmit={(e)=>{e.preventDefault(); if(chatInput.trim()) { onSendMessage(chatInput); setChatInput(''); }}} className="flex gap-2 sticky bottom-0 bg-gray-50 md:bg-transparent pt-2 md:pt-0">
                    {currentProfile?.blocked ? <div className="w-full text-center text-xs text-red-600 bg-red-100 p-4 rounded-xl font-bold border border-red-200">Account limitato dai moderatori per violazione policy.</div> : (
                        <>
                            <input type="text" value={chatInput} onChange={e=>setChatInput(e.target.value)} placeholder="Scrivi un messaggio..." className="flex-1 p-4 rounded-xl border border-gray-300 outline-none focus:border-indigo-500 focus:ring-2 focus:ring-indigo-100 shadow-sm transition" />
                            <button type="submit" className="bg-indigo-600 hover:bg-indigo-700 text-white px-6 rounded-xl shadow-md transition transform hover:-translate-y-0.5"><IconChat/></button>
                        </>
                    )}
                </form>
            )}
        </div>
    );
};

const Announcements = ({ announcements, role, currentProfile, students, onAddAnnouncement, onDeleteAnnouncement }) => {
    const [showForm, setShowForm] = useState(false);
    const [annForm, setAnnForm] = useState({ text: '', priority: 'normal', target: 'all' });
    
    const handleSubmit = (e) => {
        e.preventDefault();
        onAddAnnouncement({ ...annForm, text: SecurityService.sanitizeInput(annForm.text) });
        setAnnForm({ text: '', priority: 'normal', target: 'all' });
        setShowForm(false);
    };
    
    const sorted = [...announcements].sort((a,b)=>(b.timestamp||0)-(a.timestamp||0));
    const visible = sorted.filter(ann => {
        if(role !== 'student') return true;
        if(ann.target === 'all') return true;
        if(currentProfile && ann.target === currentProfile.code) return true;
        return false;
    });

    return (
        <div className="space-y-4 pb-24 p-5 animate-fade-in max-w-4xl mx-auto">
            <div className="flex justify-between items-center mb-6 py-2 border-b">
                <h2 className="text-3xl font-black text-gray-800">Bacheca Avvisi</h2>
                {role !== 'student' && <button onClick={()=>setShowForm(!showForm)} className="bg-purple-600 hover:bg-purple-700 transition text-white p-3 md:px-5 md:py-2.5 rounded-full md:rounded-xl shadow-md font-bold flex items-center gap-2"><IconPlus/> <span className="hidden md:inline">Nuovo Avviso</span></button>}
            </div>
            
            {role !== 'student' && showForm && (
                <form onSubmit={handleSubmit} className="bg-purple-50 p-5 rounded-2xl border border-purple-200 mb-8 shadow-sm">
                    <textarea placeholder="Testo dell'avviso..." value={annForm.text} onChange={e=>setAnnForm({...annForm, text:e.target.value})} className="p-3 rounded-xl border w-full text-sm mb-4 h-24 outline-none focus:border-purple-400" required/>
                    <div className="flex flex-col md:flex-row gap-4 mb-4">
                        <select value={annForm.target} onChange={e=>setAnnForm({...annForm, target:e.target.value})} className="flex-1 p-3 border rounded-xl outline-none text-sm focus:border-purple-400">
                            <option value="all">Visibile a Tutti i Partecipanti</option>
                            <optgroup label="Singoli Studenti">
                                {students.map(s=><option key={s.id} value={s.code}>{s.name}</option>)}
                            </optgroup>
                        </select>
                        <div className="flex gap-4 items-center bg-white px-4 py-2 rounded-xl border">
                            <label className="flex items-center gap-2 cursor-pointer text-sm font-medium"><input type="radio" name="p" value="normal" checked={annForm.priority==='normal'} onChange={()=>setAnnForm({...annForm,priority:'normal'})} className="text-purple-600 focus:ring-purple-500"/> Info</label>
                            <label className="flex items-center gap-2 cursor-pointer text-sm font-bold text-red-600"><input type="radio" name="p" value="high" checked={annForm.priority==='high'} onChange={()=>setAnnForm({...annForm,priority:'high'})} className="text-red-600 focus:ring-red-500"/> Urgente</label>
                        </div>
                    </div>
                    <div className="flex justify-end gap-2">
                        <button type="button" onClick={() => setShowForm(false)} className="px-5 py-2 text-gray-600 font-bold hover:bg-gray-200 rounded-xl transition">Annulla</button>
                        <button type="submit" className="bg-purple-600 hover:bg-purple-700 text-white px-6 py-2.5 rounded-xl font-bold shadow-md transition">Pubblica Avviso</button>
                    </div>
                </form>
            )}
            
            <div className="space-y-4">
                {visible.length === 0 ? <p className="text-gray-500 italic text-center py-8 bg-gray-50 rounded-2xl">Nessun avviso presente in bacheca.</p> : 
                 visible.map(ann => (
                     <div key={ann.id} className={`p-5 rounded-2xl shadow-sm border-l-4 relative hover:shadow-md transition ${ann.priority==='high'?'bg-red-50 border-red-500':'bg-white border-purple-400'}`}>
                         {role !== 'student' && <button onClick={()=>onDeleteAnnouncement(ann.id)} className="absolute top-4 right-4 text-gray-300 hover:text-red-500 bg-white/50 p-1 rounded-lg transition"><IconTrash/></button>}
                         <div className="flex items-center gap-3 mb-3">
                             <span className={`text-[10px] font-black px-2.5 py-1 rounded-md uppercase tracking-wider ${ann.priority==='high'?'bg-red-100 text-red-800':'bg-purple-100 text-purple-800'}`}>{ann.priority}</span>
                             <span className="text-xs font-medium text-gray-500">{ann.date}</span>
                         </div>
                         {ann.target !== 'all' && role !== 'student' && <p className="text-xs bg-yellow-100 text-yellow-800 font-bold px-2 py-1 rounded inline-block mb-2">Destinatario Privato: {students.find(s=>s.code===ann.target)?.name || ann.target}</p>}
                         <p className="text-gray-800 whitespace-pre-wrap leading-relaxed">{ann.text}</p>
                     </div>
                 ))
                }
            </div>
        </div>
    );
};

const Expenses = ({ expenses, students, onAddExpense }) => {
    const [exForm, setExForm] = useState({ description: '', amount: '' });
    const total = expenses.reduce((acc, curr) => acc + curr.amount, 0);
    const count = students.length > 0 ? students.length : 1;
    const perPerson = (total / count).toFixed(2);
    
    const handleSubmit = (e) => {
        e.preventDefault();
        onAddExpense({ ...exForm, description: SecurityService.sanitizeInput(exForm.description) });
        setExForm({ description: '', amount: '' });
    };
    
    return (
        <div className="space-y-4 pb-24 p-5 animate-fade-in max-w-4xl mx-auto">
            <h2 className="text-3xl font-black text-gray-800 py-2 border-b mb-6">Cassa Comune</h2>
            
            <div className="bg-green-50 p-6 md:p-8 rounded-3xl border border-green-200 shadow-sm flex flex-col md:flex-row justify-between items-center gap-6 mb-8">
                <div className="text-center md:text-left">
                    <p className="text-xs text-green-700 font-bold uppercase tracking-wider mb-1">Totale Spese Gruppo</p>
                    <p className="text-4xl md:text-5xl font-black text-green-900">€{total.toFixed(2)}</p>
                </div>
                <div className="w-full md:w-px h-px md:h-16 bg-green-200"></div>
                <div className="text-center md:text-right">
                    <p className="text-[10px] text-green-700 font-bold uppercase tracking-wider mb-1">Quota Pro-Capite Stimate</p>
                    <p className="text-2xl md:text-3xl font-bold text-green-800">€{perPerson}</p>
                </div>
            </div>
            
            <form onSubmit={handleSubmit} className="bg-white p-5 rounded-2xl shadow-sm border border-gray-200 mb-8">
                <h3 className="text-sm font-bold text-gray-800 mb-3">Registra Nuova Spesa</h3>
                <div className="flex flex-col md:flex-row gap-3">
                   <input type="text" placeholder="Oggetto Spesa (Es: Ristorante, Biglietti...)" value={exForm.description} onChange={e=>setExForm({...exForm, description:e.target.value})} className="flex-1 p-3 bg-gray-50 border rounded-xl text-sm outline-none focus:border-green-400 focus:bg-white transition" required />
                   <input type="number" step="0.01" placeholder="Importo €" value={exForm.amount} onChange={e=>setExForm({...exForm, amount:e.target.value})} className="md:w-32 p-3 bg-gray-50 border rounded-xl text-sm outline-none focus:border-green-400 focus:bg-white transition" required />
                   <button type="submit" className="bg-green-600 hover:bg-green-700 text-white px-6 py-3 rounded-xl font-bold shadow-md transition">Aggiungi</button>
                </div>
            </form>
            
            <div className="space-y-3">
                <h3 className="text-sm font-bold text-gray-500 uppercase tracking-wider mb-2">Cronologia Spese</h3>
                {expenses.length === 0 ? <p className="text-gray-500 italic text-center py-6 bg-gray-50 rounded-2xl">Nessuna spesa registrata finora.</p> : 
                 expenses.map(exp => (
                    <div key={exp.id} className="bg-white p-4 rounded-2xl shadow-sm flex justify-between items-center border border-gray-100 hover:shadow-md transition">
                        <div>
                            <p className="font-bold text-gray-900 text-lg">{exp.description}</p>
                            <p className="text-[11px] text-gray-500 mt-1 uppercase tracking-wider">Anticipato da: <span className="font-bold text-gray-700">{exp.paidByName}</span></p>
                        </div>
                        <span className="font-black text-xl text-green-600">€{exp.amount.toFixed(2)}</span>
                    </div>
                ))}
            </div>
        </div>
    );
};

// Componente helper per la navigazione (supporta Layout Mobile e Layout Desktop)
const NavItem = ({ icon, label, id, active, set, color, isDesktop }) => {
    const isActive = active === id;
    const colorClasses = { blue: 'text-blue-600 bg-blue-50', green: 'text-green-600 bg-green-50', indigo: 'text-indigo-600 bg-indigo-50', purple: 'text-purple-600 bg-purple-50', orange: 'text-orange-600 bg-orange-50' };
    
    // Versione Desktop Sidebar
    if (isDesktop) {
        return (
            <button onClick={() => set(id)} className={`flex items-center gap-4 p-3.5 rounded-xl transition-all duration-200 w-full text-left ${isActive ? colorClasses[color] + ' shadow-sm font-bold' : 'text-gray-600 hover:bg-gray-100 font-medium'}`}>
                <div className={`${isActive ? 'scale-110' : ''} transition-transform`}>{icon}</div>
                <span className="text-sm">{label}</span>
            </button>
        );
    }
    
    // Versione Mobile Bottom-bar
    return (
        <button onClick={() => set(id)} className={`flex flex-col items-center p-2.5 rounded-2xl min-w-[70px] flex-1 transition-all duration-200 ${isActive ? colorClasses[color] + ' scale-105 shadow-sm' : 'text-gray-400 hover:text-gray-600 hover:bg-gray-50'}`}>
            <div className={`${isActive ? 'scale-110' : ''} transition-transform`}>{icon}</div>
            <span className={`text-[9px] font-extrabold mt-1 uppercase tracking-wide ${isActive ? 'opacity-100' : 'opacity-70'}`}>{label}</span>
        </button>
    );
};

// === 5. COMPONENTE PRINCIPALE APP ===
export default function App() {
    const [authReady, setAuthReady] = useState(false);
    const [user, setUser] = useState(null);
    const [role, setRole] = useState(null);
    const [currentProfile, setCurrentProfile] = useState(null);
    const [activeGroupId, setActiveGroupId] = useState(null);
    const [activeTab, setActiveTab] = useState('itinerary');
    const [isMapFullscreen, setIsMapFullscreen] = useState(false); // STATO PER GESTIONE MAPPA FULLSCREEN
    
    const [msg, setMsg] = useState('');
    const [isOnline, setIsOnline] = useState(navigator.onLine);
    const [authError, setAuthError] = useState('');

    const [admins, setAdmins] = useState([]);
    const [managers, setManagers] = useState([]);
    const [groups, setGroups] = useState([]);
    const [students, setStudents] = useState([]);
    const [events, setEvents] = useState([]);
    const [messages, setMessages] = useState([]);
    const [announcements, setAnnouncements] = useState([]);
    const [expenses, setExpenses] = useState([]);
    const [securityAlerts, setSecurityAlerts] = useState([]);

    const showMsg = (testo) => { setMsg(testo); setTimeout(()=>setMsg(''), 3000); };

    useEffect(() => {
        window.addEventListener('online', ()=>setIsOnline(true));
        window.addEventListener('offline', ()=>setIsOnline(false));
        const unsub = onAuthStateChanged(auth, (currentUser) => {
            setUser(currentUser);
            setAuthReady(true);
        });
        return () => unsub();
    }, []);

    const onStudentLogin = async (code) => {
        setAuthError('');
        if(!user) {
            try { await signInAnonymously(auth); } 
            catch(e) { setAuthError("Auth Anonima disabilitata su Firebase."); return; }
        }
        try {
            const codesSnap = await getDocs(collection(db, `${DB_BASE_PATH}/student_codes`));
            let foundCode = null;
            codesSnap.forEach(d => { if(d.id === code) foundCode = d.data(); });
            
            if(foundCode) {
                setRole('student');
                setActiveGroupId(foundCode.groupId);
                setCurrentProfile({ code: code, name: foundCode.name });
                setActiveTab('itinerary');
                showMsg(`Benvenuto, ${foundCode.name}!`);
            } else { setAuthError("Codice inesistente."); }
        } catch(e) { setAuthError("Errore connessione."); }
    };

    const onStaffLogin = async (email, pwd) => {
        setAuthError('');
        try {
            let userCredential;
            try { userCredential = await signInWithEmailAndPassword(auth, email, pwd); }
            catch(e) {
                if (e.code === 'auth/user-not-found' || e.code === 'auth/invalid-credential') {
                    userCredential = await createUserWithEmailAndPassword(auth, email, pwd);
                } else throw e;
            }
            
            const mail = userCredential.user.email;
            if(mail === 'michelectrn@gmail.com') { setRole('master'); setActiveTab('profile'); return; } 
            
            let isAdmin = false; let isManager = false;
            const adminSnap = await getDocs(collection(db, `${DB_BASE_PATH}/admins`));
            adminSnap.forEach(d => { if(d.data().email === mail) isAdmin = true; });
            if(isAdmin) { setRole('admin'); setActiveTab('profile'); return; }
            
            const managerSnap = await getDocs(collection(db, `${DB_BASE_PATH}/managers`));
            managerSnap.forEach(d => { if(d.data().email === mail) isManager = true; });
            if(isManager) { setRole('manager'); setActiveTab('profile'); return; }
            
            setAuthError("Account non autorizzato.");
        } catch(e) { setAuthError("Errore Accesso Staff."); }
    };

    const handleLogout = () => { signOut(auth); setRole(null); setCurrentProfile(null); setActiveGroupId(null); };

    const onChangePassword = async (newPwd) => {
        try { await updatePassword(auth.currentUser, newPwd); showMsg("Password aggiornata!"); } 
        catch (e) { showMsg(e.code === 'auth/requires-recent-login' ? "Sicurezza: Esci e rientra per cambiare password." : "Errore: " + e.message); }
    };

    useEffect(() => {
        if(!user) return;
        if(['master', 'admin', 'manager'].includes(role)) {
            const unsubA = onSnapshot(collection(db, `${DB_BASE_PATH}/admins`), snap => setAdmins(snap.docs.map(d=>({id:d.id, ...d.data()}))));
            const unsubM = onSnapshot(collection(db, `${DB_BASE_PATH}/managers`), snap => setManagers(snap.docs.map(d=>({id:d.id, ...d.data()}))));
            const unsubG = onSnapshot(collection(db, `${DB_BASE_PATH}/groups`), snap => setGroups(snap.docs.map(d=>({id:d.id, ...d.data()}))));
            return () => { unsubA(); unsubM(); unsubG(); };
        }
    }, [user, role]);

    useEffect(() => {
        if(!user || !activeGroupId) return;
        const groupPath = `${DB_BASE_PATH}/groups/${activeGroupId}`;
        const unsub = [
            onSnapshot(collection(db, `${groupPath}/students`), snap => setStudents(snap.docs.map(d=>({id:d.id, ...d.data()})))),
            onSnapshot(collection(db, `${groupPath}/events`), snap => setEvents(snap.docs.map(d=>({id:d.id, ...d.data()})))),
            onSnapshot(collection(db, `${groupPath}/messages`), snap => setMessages(snap.docs.map(d=>({id:d.id, ...d.data()})))),
            onSnapshot(collection(db, `${groupPath}/announcements`), snap => setAnnouncements(snap.docs.map(d=>({id:d.id, ...d.data()})))),
            onSnapshot(collection(db, `${groupPath}/expenses`), snap => setExpenses(snap.docs.map(d=>({id:d.id, ...d.data()})))),
            onSnapshot(collection(db, `${groupPath}/security_alerts`), snap => setSecurityAlerts(snap.docs.map(d=>({id:d.id, ...d.data()}))))
        ];
        return () => unsub.forEach(fn => fn());
    }, [user, activeGroupId]);

    const onAddAdmin = async (email) => { try { await setDoc(doc(collection(db, `${DB_BASE_PATH}/admins`)), {email}); } catch (err) {} };
    const onRemoveAdmin = async (id) => { try { await deleteDoc(doc(db, `${DB_BASE_PATH}/admins`, id)); } catch(e){} };
    const onAddManager = async (email) => { try { await setDoc(doc(collection(db, `${DB_BASE_PATH}/managers`)), {email}); } catch (err) {} };
    const onRemoveManager = async (id) => { try { await deleteDoc(doc(db, `${DB_BASE_PATH}/managers`, id)); } catch(e){} };
    const onAddGroup = async (g) => { try { await setDoc(doc(collection(db, `${DB_BASE_PATH}/groups`)), g); showMsg("Viaggio creato"); } catch (err) {} };
    const onUpdateGroup = async (groupId, updatedData) => { try { await setDoc(doc(db, `${DB_BASE_PATH}/groups`, groupId), updatedData, { merge: true }); showMsg("Aggiornato"); } catch (err) {} };
    const onDeleteGroup = async (groupId) => { try { await deleteDoc(doc(db, `${DB_BASE_PATH}/groups`, groupId)); setActiveGroupId(null); setActiveTab('profile'); showMsg("Rimosso."); } catch (e) {} };
    const onAddStudent = async (name) => { try { const code = 'T-' + Math.random().toString(36).substring(2, 6).toUpperCase(); await setDoc(doc(collection(db, `${DB_BASE_PATH}/groups/${activeGroupId}/students`)), { name, code, blocked: false }); await setDoc(doc(db, `${DB_BASE_PATH}/student_codes`, code), { name, groupId: activeGroupId }); showMsg("Utente creato"); } catch(e) {} };
    const onDeleteStudent = async (id, code) => { try { await deleteDoc(doc(db, `${DB_BASE_PATH}/groups/${activeGroupId}/students`, id)); await deleteDoc(doc(db, `${DB_BASE_PATH}/student_codes`, code)); } catch(e){} };
    const onAddEvent = async (ev) => { try { await setDoc(doc(collection(db, `${DB_BASE_PATH}/groups/${activeGroupId}/events`)), { ...ev, timestamp: Date.now() }); } catch (err) {} };
    const onUpdateEvent = async (id, ev) => { try { await setDoc(doc(db, `${DB_BASE_PATH}/groups/${activeGroupId}/events`, id), { ...ev, timestamp: Date.now() }, {merge:true}); } catch (err) {} };
    const onDeleteEvent = async (id) => { try { await deleteDoc(doc(db, `${DB_BASE_PATH}/groups/${activeGroupId}/events`, id)); } catch(e){} };
    const onAddAnnouncement = async (ann) => { try { const d = new Date(); const dateStr = `${d.getDate()}/${d.getMonth()+1}, ${d.getHours()}:${d.getMinutes()}`; await setDoc(doc(collection(db, `${DB_BASE_PATH}/groups/${activeGroupId}/announcements`)), { ...ann, date: dateStr, timestamp: Date.now() }); } catch (err) {} };
    const onDeleteAnnouncement = async (id) => { try { await deleteDoc(doc(db, `${DB_BASE_PATH}/groups/${activeGroupId}/announcements`, id)); } catch(e){} };
    const onAddExpense = async (ex) => { try { const paidBy = role === 'student' ? currentProfile.code : 'STAFF'; const paidByName = role === 'student' ? currentProfile.name : 'Staff'; await setDoc(doc(collection(db, `${DB_BASE_PATH}/groups/${activeGroupId}/expenses`)), { ...ex, amount: parseFloat(ex.amount), paidBy, paidByName, timestamp: Date.now() }); } catch (err) {} };
    const onUnlockUser = async (studentId, alertId) => { try { await setDoc(doc(db, `${DB_BASE_PATH}/groups/${activeGroupId}/students`, studentId), { blocked: false }, {merge:true}); await deleteDoc(doc(db, `${DB_BASE_PATH}/groups/${activeGroupId}/security_alerts`, alertId)); } catch(e){} };
    const onSendMessage = async (text) => {
        const cleanText = SecurityService.sanitizeInput(text);
        if(role === 'student' && SecurityService.containsViolations(cleanText)) {
            const s = students.find(x => x.code === currentProfile.code);
            if(s) await setDoc(doc(db, `${DB_BASE_PATH}/groups/${activeGroupId}/students`, s.id), { blocked: true }, {merge:true});
            await setDoc(doc(collection(db, `${DB_BASE_PATH}/groups/${activeGroupId}/security_alerts`)), { userId: s.id, userName: currentProfile.name, messageText: cleanText, timestamp: Date.now() });
            showMsg("Messaggio bloccato per violazione norme.");
            return;
        }
        try {
            const senderName = role === 'student' ? currentProfile.name : `Staff (${role})`;
            const senderCode = role === 'student' ? currentProfile.code : 'STAFF';
            await setDoc(doc(collection(db, `${DB_BASE_PATH}/groups/${activeGroupId}/messages`)), { text: cleanText, senderName, senderCode, role, timestamp: Date.now() });
        } catch (err) {}
    };

    const isGroupExpired = () => { const g = groups.find(x => x.id === activeGroupId); return g?.endDate ? g.endDate < new Date().toISOString().split('T')[0] : false; };

    // --- RENDER ---
    if (!authReady) return <div className="min-h-screen flex items-center justify-center bg-gray-50"><p className="text-gray-400 font-bold animate-pulse">Caricamento in corso...</p></div>;
    if (!role) return <LoginScreen onStudentLogin={onStudentLogin} onStaffLogin={onStaffLogin} authError={authError} isOnline={isOnline} />;
    
    const activeGroupData = groups.find(g => g.id === activeGroupId);

    return (
        <div className="min-h-screen bg-gray-100 font-sans md:p-6 lg:p-10 flex justify-center text-gray-900">
            {msg && <div className="fixed top-5 left-1/2 -translate-x-1/2 bg-gray-900 text-white px-6 py-3 rounded-full shadow-2xl z-50 animate-fade-in text-sm font-medium">{msg}</div>}
            
            {/* Main Container */}
            <div className="w-full md:max-w-6xl lg:max-w-7xl bg-gray-50 md:rounded-[2rem] md:shadow-2xl md:overflow-hidden relative flex flex-col md:flex-row min-h-screen md:min-h-[85vh] md:max-h-[900px] border border-gray-200/50">
                
                {/* 1. SIDEBAR NAV: Visibile SOLO su Desktop, NASCOSTA se mappa in Fullscreen */}
                {activeGroupId && !isMapFullscreen && (
                    <aside className="hidden md:flex flex-col w-64 lg:w-72 bg-white border-r border-gray-200 p-6 z-20 shrink-0">
                        <div className="mb-8">
                            <h1 className="text-3xl font-black text-blue-900 tracking-tight">EduTravel</h1>
                            <p className="text-xs font-bold text-gray-400 uppercase tracking-widest mt-1">{role === 'student' ? currentProfile?.name : `Staff: ${role}`}</p>
                        </div>
                        <nav className="flex flex-col gap-2 flex-1">
                            <NavItem icon={<IconList />} label="Plan" id="itinerary" active={activeTab} set={setActiveTab} color="blue" isDesktop />
                            <NavItem icon={<IconMap />} label="Mappa" id="map" active={activeTab} set={setActiveTab} color="blue" isDesktop />
                            <NavItem icon={<IconBell />} label="Avvisi" id="announcements" active={activeTab} set={setActiveTab} color="purple" isDesktop />
                            <NavItem icon={<IconChat />} label="Chat" id="chat" active={activeTab} set={setActiveTab} color="indigo" isDesktop />
                            <NavItem icon={<IconWallet />} label="Cassa" id="expenses" active={activeTab} set={setActiveTab} color="green" isDesktop />
                            <NavItem icon={role === 'student' ? <IconUser/> : <IconSettings/>} label={role==='student'?'Profilo':'Gestione'} id="profile" active={activeTab} set={setActiveTab} color="orange" isDesktop />
                        </nav>
                        <div className="mt-auto pt-6 border-t border-gray-100">
                            {activeGroupData && <div className="bg-indigo-50 text-indigo-900 px-4 py-3 rounded-xl text-sm font-black mb-4 text-center break-words shadow-inner border border-indigo-100">{activeGroupData.name}</div>}
                            <button onClick={handleLogout} className="w-full bg-white border border-gray-200 hover:bg-red-50 text-gray-600 hover:text-red-600 hover:border-red-200 px-4 py-3 rounded-xl text-sm font-bold transition shadow-sm">Esci dall'App</button>
                        </div>
                    </aside>
                )}

                {/* 2. AREA CONTENUTI PRINCIPALE */}
                <div className="flex-1 flex flex-col relative w-full h-full overflow-hidden">
                    
                    {/* Header Top - NASCOSTO se mappa in Fullscreen */}
                    {!isMapFullscreen && (
                        <header className="bg-white px-6 pt-10 pb-4 md:pt-6 md:pb-5 border-b border-gray-200 shadow-sm z-20 sticky top-0 rounded-b-3xl md:rounded-none flex justify-between items-center shrink-0">
                            <div className={`md:hidden ${!activeGroupId ? 'md:block' : ''}`}>
                                <h1 className="text-2xl font-black text-blue-900 tracking-tight">✈️ EduTravel</h1>
                                <p className="text-xs font-bold text-gray-400 uppercase tracking-widest mt-1">{role === 'student' ? currentProfile?.name : `Staff: ${role}`}</p>
                                {activeGroupData && <p className="text-sm font-bold text-indigo-600 bg-indigo-50 px-2 py-0.5 rounded inline-block mt-1 md:hidden">{activeGroupData.name}</p>}
                            </div>
                            
                            <div className="hidden md:block">
                                {!activeGroupId ? (
                                    <div>
                                        <h1 className="text-3xl font-black text-blue-900 tracking-tight">EduTravel Dashboard</h1>
                                        <p className="text-xs font-bold text-gray-400 uppercase tracking-widest mt-1">Pannello Operativo {role}</p>
                                    </div>
                                ) : (
                                    <h2 className="text-xl font-black text-gray-800 uppercase tracking-wide">
                                        {activeTab === 'itinerary' && 'Pianificazione Itinerario'}
                                        {activeTab === 'map' && 'Mappa Geografica'}
                                        {activeTab === 'chat' && 'Chat di Gruppo'}
                                        {activeTab === 'announcements' && 'Bacheca Avvisi'}
                                        {activeTab === 'expenses' && 'Gestione Cassa Comune'}
                                        {activeTab === 'profile' && 'Gestione e Profilo'}
                                    </h2>
                                )}
                            </div>

                            <div className="flex gap-2 items-center">
                                {!activeGroupId && <button onClick={handleLogout} className="bg-gray-100 hover:bg-red-50 text-gray-500 hover:text-red-500 px-4 py-2 rounded-lg text-sm font-bold transition">Esci</button>}
                                {activeGroupId && <button onClick={handleLogout} className="md:hidden bg-gray-100 hover:bg-red-50 text-gray-500 hover:text-red-500 px-3 py-2 rounded-lg text-xs font-bold transition">Esci</button>}
                                {activeGroupId && role !== 'student' && <button onClick={() => {setActiveGroupId(null); setActiveTab('profile');}} className="bg-indigo-100 text-indigo-700 hover:bg-indigo-200 px-4 py-2 rounded-lg text-sm font-bold shadow-sm whitespace-nowrap transition">← Torna ai Viaggi</button>}
                            </div>
                        </header>
                    )}
                    
                    {!isOnline && !isMapFullscreen && <div className="text-[10px] md:text-xs font-bold bg-yellow-100 text-yellow-800 py-1.5 px-4 text-center sticky top-[72px] md:top-[77px] z-10 shadow-sm flex items-center justify-center gap-2"><IconWifiOff/> Modalità Offline Cache Attiva</div>}

                    {/* Viste Principali: Rimosso "z-0" durante la mappa Fullscreen per non intrappolarla nel livello inferiore */}
                    <main className={`flex-1 flex flex-col bg-gray-50/50 hide-scrollbar relative ${isMapFullscreen ? 'overflow-hidden z-50' : 'overflow-y-auto'}`}>
                        {!activeGroupId && role !== 'student' ? (
                            <StaffDashboard role={role} userEmail={user?.email} admins={admins} managers={managers} groups={groups} onAddAdmin={onAddAdmin} onRemoveAdmin={onRemoveAdmin} onAddManager={onAddManager} onRemoveManager={onRemoveManager} onAddGroup={onAddGroup} onUpdateGroup={onUpdateGroup} onDeleteGroup={onDeleteGroup} onChangePassword={onChangePassword} setActiveGroupId={setActiveGroupId} setActiveTab={setActiveTab} />
                        ) : activeGroupId ? (
                            <>
                                {activeTab === 'itinerary' && <Itinerary events={events} role={role} onAddEvent={onAddEvent} onUpdateEvent={onUpdateEvent} onDeleteEvent={onDeleteEvent} showMsg={showMsg} />}
                                {activeTab === 'map' && <MapComponent isFullscreen={isMapFullscreen} setIsFullscreen={setIsMapFullscreen} />}
                                {activeTab === 'chat' && <Chat messages={messages} role={role} currentProfile={currentProfile} isExpired={isGroupExpired()} onSendMessage={onSendMessage} />}
                                {activeTab === 'announcements' && <Announcements announcements={announcements} role={role} currentProfile={currentProfile} students={students} onAddAnnouncement={onAddAnnouncement} onDeleteAnnouncement={onDeleteAnnouncement} />}
                                {activeTab === 'expenses' && <Expenses expenses={expenses} students={students} onAddExpense={onAddExpense} role={role} currentProfile={currentProfile} />}
                                {activeTab === 'profile' && role !== 'student' && <Management group={activeGroupData} students={students} alerts={securityAlerts} onAddStudent={onAddStudent} onDeleteStudent={onDeleteStudent} onUnlockUser={onUnlockUser} showMsg={showMsg} />}
                                
                                {activeTab === 'profile' && role === 'student' && (
                                    <div className="p-5 animate-fade-in text-center flex flex-col items-center justify-center h-full">
                                        <div className="bg-white p-8 md:p-12 rounded-3xl border border-gray-200 shadow-sm w-full max-w-sm mb-4">
                                            <div className="w-24 h-24 bg-orange-100 text-orange-600 rounded-full flex items-center justify-center mx-auto mb-6 text-4xl font-black shadow-inner">{currentProfile.name.charAt(0)}</div>
                                            <h3 className="font-black text-gray-900 text-2xl mb-2">{currentProfile.name}</h3>
                                            <p className="text-sm text-orange-800 font-mono bg-orange-50 inline-block px-4 py-1.5 rounded-lg border border-orange-100 shadow-sm">Codice Viaggio: {currentProfile.code}</p>
                                        </div>
                                        {activeGroupData?.managerInfo && (
                                            <div className="bg-blue-50 p-6 rounded-2xl border border-blue-200 text-left w-full max-w-sm">
                                                <p className="text-xs font-black text-blue-800 uppercase mb-2 tracking-widest flex items-center gap-2"><IconUser/> Referenti del viaggio</p>
                                                <p className="text-sm text-blue-900 font-medium leading-relaxed">{activeGroupData.managerInfo}</p>
                                            </div>
                                        )}
                                    </div>
                                )}
                            </>
                        ) : null}
                    </main>

                    {/* 3. BOTTOM NAV: Visibile SOLO su Mobile, NASCOSTA se mappa in Fullscreen */}
                    {activeGroupId && !isMapFullscreen && (
                        <nav className="md:hidden bg-white border-t border-gray-200 flex overflow-x-auto p-2 pb-6 sticky bottom-0 z-20 shadow-[0_-10px_20px_-10px_rgba(0,0,0,0.1)] gap-1 hide-scrollbar shrink-0">
                            <NavItem icon={<IconList />} label="Plan" id="itinerary" active={activeTab} set={setActiveTab} color="blue" />
                            <NavItem icon={<IconMap />} label="Mappa" id="map" active={activeTab} set={setActiveTab} color="blue" />
                            <NavItem icon={<IconBell />} label="Avvisi" id="announcements" active={activeTab} set={setActiveTab} color="purple" />
                            <NavItem icon={<IconChat />} label="Chat" id="chat" active={activeTab} set={setActiveTab} color="indigo" />
                            <NavItem icon={<IconWallet />} label="Cassa" id="expenses" active={activeTab} set={setActiveTab} color="green" />
                            <NavItem icon={role === 'student' ? <IconUser/> : <IconSettings/>} label={role==='student'?'Me':'Gestione'} id="profile" active={activeTab} set={setActiveTab} color="orange" />
                        </nav>
                    )}
                </div>
            </div>
        </div>
    );
}

// === 6. AVVIO DI REACT ===
const rootElement = document.getElementById('root');
const root = createRoot(rootElement);
root.render(<App />);
