// SettingsView - Impostazioni profilo utente

function SettingsView() {
    const { user, updateProfile, changePassword, logout, refreshUser } = useAuth();
    const toast = useToast();
    const [activeTab, setActiveTab] = React.useState('profile');

    // Profile form state
    const [profileData, setProfileData] = React.useState({
        full_name: user?.full_name || '',
        email: user?.email || '',
    });
    const [profileLoading, setProfileLoading] = React.useState(false);

    // Avatar state
    const [avatarFile, setAvatarFile] = React.useState(null);
    const [avatarPreview, setAvatarPreview] = React.useState(
        user?.avatar_path ? ApiUsers.getAvatarUrl(user.avatar_path) : null
    );
    const [avatarLoading, setAvatarLoading] = React.useState(false);
    const [avatarDeleted, setAvatarDeleted] = React.useState(false);
    const fileInputRef = React.useRef(null);

    // Update avatar preview when user changes
    React.useEffect(() => {
        if (user?.avatar_path && !avatarFile && !avatarDeleted) {
            setAvatarPreview(ApiUsers.getAvatarUrl(user.avatar_path));
        }
    }, [user?.avatar_path]);

    const handleAvatarChange = (e) => {
        const file = e.target.files[0];
        if (file) {
            // Validate file type
            const allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
            if (!allowedTypes.includes(file.type)) {
                toast('Tipo file non supportato. Usa JPG, PNG, GIF o WEBP.', 'error');
                return;
            }
            // Validate file size (5MB max)
            if (file.size > 5 * 1024 * 1024) {
                toast('File troppo grande. Massimo 5MB.', 'error');
                return;
            }
            setAvatarFile(file);
            setAvatarPreview(URL.createObjectURL(file));
            setAvatarDeleted(false);
        }
    };

    const handleRemoveAvatar = () => {
        setAvatarFile(null);
        if (avatarPreview && !avatarPreview.startsWith('/api/')) {
            URL.revokeObjectURL(avatarPreview);
        }
        setAvatarPreview(null);
        setAvatarDeleted(true);
        if (fileInputRef.current) {
            fileInputRef.current.value = '';
        }
    };

    const handleAvatarSave = async () => {
        setAvatarLoading(true);
        try {
            if (avatarFile) {
                await ApiUsers.uploadMyAvatar(avatarFile);
                toast('Avatar aggiornato con successo', 'success');
            } else if (avatarDeleted && user?.avatar_path) {
                await ApiUsers.deleteMyAvatar();
                toast('Avatar rimosso con successo', 'success');
            }
            // Refresh user data in context
            if (refreshUser) {
                await refreshUser();
            }
            setAvatarFile(null);
            setAvatarDeleted(false);
        } catch (error) {
            toast(error.message || 'Errore durante il salvataggio dell\'avatar', 'error');
        } finally {
            setAvatarLoading(false);
        }
    };

    // Cleanup preview URL on unmount
    React.useEffect(() => {
        return () => {
            if (avatarPreview && !avatarPreview.startsWith('/api/')) {
                URL.revokeObjectURL(avatarPreview);
            }
        };
    }, [avatarPreview]);

    // Password form state
    const [passwordData, setPasswordData] = React.useState({
        current_password: '',
        new_password: '',
        confirm_password: '',
    });
    const [passwordLoading, setPasswordLoading] = React.useState(false);
    const [showPasswords, setShowPasswords] = React.useState({
        current: false,
        new: true,
        confirm: true,
    });

    // Calendar integration state (admin only)
    const [calendarStatus, setCalendarStatus] = React.useState({ connected: false, connected_at: null, shared: false });
    const [calendarLoading, setCalendarLoading] = React.useState(false);
    const [sharingLoading, setSharingLoading] = React.useState(false);
    const isAdmin = user?.role === 'admin';

    // Fetch calendar status on mount (admin only)
    React.useEffect(() => {
        if (isAdmin) {
            fetchCalendarStatus();
        }
    }, [isAdmin]);

    // Handle OAuth callback
    React.useEffect(() => {
        if (isAdmin) {
            const hash = window.location.hash;
            const params = new URLSearchParams(hash.split('?')[1] || '');

            if (params.get('calendar_success') === 'true') {
                // Tokens are now saved directly by backend callback
                toast('Google Calendar connesso con successo', 'success');
                fetchCalendarStatus();
                // Clean URL
                window.history.replaceState(null, '', '/#/settings');
                setActiveTab('integrations');
            } else if (params.get('calendar_error')) {
                const error = decodeURIComponent(params.get('calendar_error'));
                toast(`Errore: ${error}`, 'error');
                // Clean URL
                window.history.replaceState(null, '', '/#/settings');
                setActiveTab('integrations');
            }
        }
    }, [isAdmin]);

    const fetchCalendarStatus = async () => {
        try {
            const status = await ApiUtils.getCalendarStatus();
            setCalendarStatus(status);
        } catch (error) {
            console.error('Error fetching calendar status:', error);
        }
    };

    const handleDisconnectCalendar = async () => {
        setCalendarLoading(true);
        try {
            await ApiUtils.disconnectCalendar();
            setCalendarStatus({ connected: false, connected_at: null, shared: false });
            toast('Google Calendar disconnesso', 'success');
        } catch (error) {
            toast('Errore durante la disconnessione', 'error');
            console.error('Error disconnecting calendar:', error);
        } finally {
            setCalendarLoading(false);
        }
    };

    const handleToggleSharing = async () => {
        const newShared = !calendarStatus.shared;
        setSharingLoading(true);
        try {
            await ApiUtils.setCalendarSharing(newShared);
            setCalendarStatus(prev => ({ ...prev, shared: newShared }));
            toast(newShared ? 'Calendario condiviso con il team' : 'Condivisione calendario disattivata', 'success');
        } catch (error) {
            toast('Errore durante l\'aggiornamento della condivisione', 'error');
            console.error('Error toggling calendar sharing:', error);
        } finally {
            setSharingLoading(false);
        }
    };

    const handleProfileUpdate = async (e) => {
        e.preventDefault();
        setProfileLoading(true);
        const result = await updateProfile(profileData);
        if (result.success) {
            toast('Profilo aggiornato con successo', 'success');
        } else {
            toast(result.error, 'error');
        }
        setProfileLoading(false);
    };

    const handlePasswordChange = async (e) => {
        e.preventDefault();
        if (passwordData.new_password !== passwordData.confirm_password) {
            toast('Le password non coincidono', 'error');
            return;
        }
        if (passwordData.new_password.length < 8) {
            toast('La password deve essere di almeno 8 caratteri', 'error');
            return;
        }
        
        setPasswordLoading(true);
        const result = await changePassword(passwordData.current_password, passwordData.new_password);
        if (result.success) {
            toast('Password modificata con successo', 'success');
            setPasswordData({ current_password: '', new_password: '', confirm_password: '' });
        } else {
            toast(result.error, 'error');
        }
        setPasswordLoading(false);
    };

    const tabs = [
        { id: 'profile', label: 'Profilo', icon: '👤' },
        { id: 'security', label: 'Sicurezza', icon: '🔒' },
        { id: 'notifications', label: 'Notifiche Email', icon: '📧' },
        ...(isAdmin ? [{ id: 'integrations', label: 'Integrazioni', icon: '🔗' }] : []),
    ];

    return (
        <div className="p-6 max-w-4xl mx-auto space-y-6">
            <div>
                <h2 className="text-2xl font-bold text-slate-800">Impostazioni</h2>
                <p className="text-slate-500 mt-1">Gestisci il tuo account e le preferenze</p>
            </div>

            {/* Tabs */}
            <div className="border-b border-slate-200">
                <nav className="flex gap-6">
                    {tabs.map(tab => (
                        <button
                            key={tab.id}
                            onClick={() => setActiveTab(tab.id)}
                            className={`pb-3 px-1 text-sm font-medium border-b-2 transition-colors ${
                                activeTab === tab.id
                                    ? 'border-brand-500 text-brand-600'
                                    : 'border-transparent text-slate-500 hover:text-slate-700 hover:border-slate-300'
                            }`}
                        >
                            <span className="mr-2">{tab.icon}</span>
                            {tab.label}
                        </button>
                    ))}
                </nav>
            </div>

            {/* Profile Tab */}
            {activeTab === 'profile' && (
                <div className="space-y-6">
                    {/* Avatar Section */}
                    <div className="bg-white rounded-xl shadow-sm border border-slate-200 p-6">
                        <h3 className="text-lg font-semibold text-slate-800 mb-6">Immagine Profilo</h3>

                        <div className="flex items-center gap-6">
                            <div className="relative">
                                {avatarPreview ? (
                                    <img
                                        src={avatarPreview}
                                        alt="Avatar"
                                        className="w-24 h-24 rounded-full object-cover border-2 border-slate-200"
                                    />
                                ) : (
                                    <div className="w-24 h-24 bg-gradient-to-br from-brand-400 to-brand-600 rounded-full flex items-center justify-center text-white font-semibold text-3xl">
                                        {user?.full_name ? user.full_name.charAt(0).toUpperCase() : '?'}
                                    </div>
                                )}
                                {avatarPreview && (
                                    <button
                                        type="button"
                                        onClick={handleRemoveAvatar}
                                        className="absolute -top-1 -right-1 w-7 h-7 bg-red-500 text-white rounded-full flex items-center justify-center hover:bg-red-600 transition-colors shadow-md"
                                        title="Rimuovi avatar"
                                    >
                                        <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
                                        </svg>
                                    </button>
                                )}
                            </div>
                            <div className="flex-1">
                                <input
                                    ref={fileInputRef}
                                    type="file"
                                    accept="image/jpeg,image/png,image/gif,image/webp"
                                    onChange={handleAvatarChange}
                                    className="hidden"
                                    id="settings-avatar-upload"
                                />
                                <div className="flex items-center gap-3">
                                    <label
                                        htmlFor="settings-avatar-upload"
                                        className="inline-flex items-center gap-2 px-4 py-2 bg-slate-100 hover:bg-slate-200 text-slate-700 text-sm font-medium rounded-lg cursor-pointer transition-colors"
                                    >
                                        <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z" />
                                        </svg>
                                        {avatarPreview ? 'Cambia immagine' : 'Carica immagine'}
                                    </label>
                                    {(avatarFile || avatarDeleted) && (
                                        <button
                                            type="button"
                                            onClick={handleAvatarSave}
                                            disabled={avatarLoading}
                                            className="px-4 py-2 bg-brand-500 text-white text-sm font-medium rounded-lg hover:bg-brand-600 transition-colors disabled:opacity-50"
                                        >
                                            {avatarLoading ? 'Salvataggio...' : 'Salva Avatar'}
                                        </button>
                                    )}
                                </div>
                                <p className="text-xs text-slate-500 mt-2">JPG, PNG, GIF o WEBP. Massimo 5MB.</p>
                            </div>
                        </div>
                    </div>

                    {/* Profile Info Section */}
                    <div className="bg-white rounded-xl shadow-sm border border-slate-200 p-6">
                        <h3 className="text-lg font-semibold text-slate-800 mb-6">Informazioni Profilo</h3>

                        <form onSubmit={handleProfileUpdate} className="space-y-6">
                            <div className="grid grid-cols-2 gap-6">
                                <div>
                                    <label className="block text-sm font-medium text-slate-700 mb-1">Nome Completo</label>
                                    <input
                                        type="text"
                                        value={profileData.full_name}
                                        onChange={(e) => setProfileData({ ...profileData, full_name: e.target.value })}
                                        className="w-full px-3 py-2 border border-slate-200 rounded-lg focus:ring-2 focus:ring-brand-500 focus:border-brand-500"
                                    />
                                </div>
                                <div>
                                    <label className="block text-sm font-medium text-slate-700 mb-1">Email</label>
                                    <input
                                        type="email"
                                        value={profileData.email}
                                        onChange={(e) => setProfileData({ ...profileData, email: e.target.value })}
                                        className="w-full px-3 py-2 border border-slate-200 rounded-lg focus:ring-2 focus:ring-brand-500 focus:border-brand-500"
                                        required
                                    />
                                </div>
                            </div>

                            <div className="grid grid-cols-2 gap-6">
                                <div>
                                    <label className="block text-sm font-medium text-slate-700 mb-1">Ruolo</label>
                                    <input
                                        type="text"
                                        value={user?.role === 'admin' ? 'Admin' : 'Utente'}
                                        disabled
                                        className="w-full px-3 py-2 border border-slate-200 rounded-lg bg-slate-50 text-slate-500"
                                    />
                                </div>
                                <div>
                                    <label className="block text-sm font-medium text-slate-700 mb-1">Membro Dal</label>
                                    <input
                                        type="text"
                                        value={user?.created_at ? new Date(user.created_at).toLocaleDateString('it-IT', { day: '2-digit', month: 'long', year: 'numeric' }) : 'N/A'}
                                        disabled
                                        className="w-full px-3 py-2 border border-slate-200 rounded-lg bg-slate-50 text-slate-500"
                                    />
                                </div>
                            </div>

                            <div className="flex justify-end">
                                <button
                                    type="submit"
                                    disabled={profileLoading}
                                    className="px-6 py-2 bg-brand-500 text-white font-medium rounded-lg hover:bg-brand-600 transition-colors disabled:opacity-50"
                                >
                                    {profileLoading ? 'Salvataggio...' : 'Salva Modifiche'}
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
            )}

            {/* Security Tab */}
            {activeTab === 'security' && (
                <div className="space-y-6">
                    <div className="bg-white rounded-xl shadow-sm border border-slate-200 p-6">
                        <h3 className="text-lg font-semibold text-slate-800 mb-6">Modifica Password</h3>
                        
                        <form onSubmit={handlePasswordChange} className="space-y-4 max-w-md">
                            <div>
                                <label className="block text-sm font-medium text-slate-700 mb-1">Password Attuale</label>
                                <div className="relative">
                                    <input
                                        type={showPasswords.current ? 'text' : 'password'}
                                        value={passwordData.current_password}
                                        onChange={(e) => setPasswordData({ ...passwordData, current_password: e.target.value })}
                                        className="w-full px-3 py-2 pr-10 border border-slate-200 rounded-lg focus:ring-2 focus:ring-brand-500 focus:border-brand-500"
                                        required
                                    />
                                    <button
                                        type="button"
                                        onClick={() => setShowPasswords({ ...showPasswords, current: !showPasswords.current })}
                                        className="absolute inset-y-0 right-0 flex items-center pr-3 text-slate-400 hover:text-slate-600"
                                    >
                                        {showPasswords.current ? (
                                            <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13.875 18.825A10.05 10.05 0 0112 19c-4.478 0-8.268-2.943-9.543-7a9.97 9.97 0 011.563-3.029m5.858.908a3 3 0 114.243 4.243M9.878 9.878l4.242 4.242M9.88 9.88l-3.29-3.29m7.532 7.532l3.29 3.29M3 3l3.59 3.59m0 0A9.953 9.953 0 0112 5c4.478 0 8.268 2.943 9.543 7a10.025 10.025 0 01-4.132 5.411m0 0L21 21" />
                                            </svg>
                                        ) : (
                                            <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
                                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" />
                                            </svg>
                                        )}
                                    </button>
                                </div>
                            </div>
                            <div>
                                <label className="block text-sm font-medium text-slate-700 mb-1">Nuova Password</label>
                                <div className="relative">
                                    <input
                                        type={showPasswords.new ? 'text' : 'password'}
                                        value={passwordData.new_password}
                                        onChange={(e) => setPasswordData({ ...passwordData, new_password: e.target.value })}
                                        className="w-full px-3 py-2 pr-10 border border-slate-200 rounded-lg focus:ring-2 focus:ring-brand-500 focus:border-brand-500"
                                        required
                                        minLength={8}
                                    />
                                    <button
                                        type="button"
                                        onClick={() => setShowPasswords({ ...showPasswords, new: !showPasswords.new })}
                                        className="absolute inset-y-0 right-0 flex items-center pr-3 text-slate-400 hover:text-slate-600"
                                    >
                                        {showPasswords.new ? (
                                            <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13.875 18.825A10.05 10.05 0 0112 19c-4.478 0-8.268-2.943-9.543-7a9.97 9.97 0 011.563-3.029m5.858.908a3 3 0 114.243 4.243M9.878 9.878l4.242 4.242M9.88 9.88l-3.29-3.29m7.532 7.532l3.29 3.29M3 3l3.59 3.59m0 0A9.953 9.953 0 0112 5c4.478 0 8.268 2.943 9.543 7a10.025 10.025 0 01-4.132 5.411m0 0L21 21" />
                                            </svg>
                                        ) : (
                                            <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
                                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" />
                                            </svg>
                                        )}
                                    </button>
                                </div>
                            </div>
                            <div>
                                <label className="block text-sm font-medium text-slate-700 mb-1">Conferma Nuova Password</label>
                                <div className="relative">
                                    <input
                                        type={showPasswords.confirm ? 'text' : 'password'}
                                        value={passwordData.confirm_password}
                                        onChange={(e) => setPasswordData({ ...passwordData, confirm_password: e.target.value })}
                                        className="w-full px-3 py-2 pr-10 border border-slate-200 rounded-lg focus:ring-2 focus:ring-brand-500 focus:border-brand-500"
                                        required
                                    />
                                    <button
                                        type="button"
                                        onClick={() => setShowPasswords({ ...showPasswords, confirm: !showPasswords.confirm })}
                                        className="absolute inset-y-0 right-0 flex items-center pr-3 text-slate-400 hover:text-slate-600"
                                    >
                                        {showPasswords.confirm ? (
                                            <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13.875 18.825A10.05 10.05 0 0112 19c-4.478 0-8.268-2.943-9.543-7a9.97 9.97 0 011.563-3.029m5.858.908a3 3 0 114.243 4.243M9.878 9.878l4.242 4.242M9.88 9.88l-3.29-3.29m7.532 7.532l3.29 3.29M3 3l3.59 3.59m0 0A9.953 9.953 0 0112 5c4.478 0 8.268 2.943 9.543 7a10.025 10.025 0 01-4.132 5.411m0 0L21 21" />
                                            </svg>
                                        ) : (
                                            <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
                                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" />
                                            </svg>
                                        )}
                                    </button>
                                </div>
                            </div>
                            <button
                                type="submit"
                                disabled={passwordLoading}
                                className="px-6 py-2 bg-brand-500 text-white font-medium rounded-lg hover:bg-brand-600 transition-colors disabled:opacity-50"
                            >
                                {passwordLoading ? 'Modifica in corso...' : 'Modifica Password'}
                            </button>
                        </form>
                    </div>

                    <div className="bg-white rounded-xl shadow-sm border border-slate-200 p-6">
                        <h3 className="text-lg font-semibold text-slate-800 mb-2">Esci</h3>
                        <p className="text-slate-500 text-sm mb-4">Disconnettiti dal tuo account su questo dispositivo.</p>
                        <button
                            onClick={logout}
                            className="px-4 py-2 bg-red-50 text-red-600 font-medium rounded-lg hover:bg-red-100 transition-colors"
                        >
                            Esci
                        </button>
                    </div>
                </div>
            )}

            {/* Notifications Tab */}
            {activeTab === 'notifications' && (
                <EmailPreferencesSection />
            )}

            {/* Integrations Tab (Admin only) */}
            {activeTab === 'integrations' && isAdmin && (
                <div className="space-y-6">
                    <div className="bg-white rounded-xl shadow-sm border border-slate-200 p-6">
                        <h3 className="text-lg font-semibold text-slate-800 mb-6">Integrazioni Esterne</h3>

                        {/* Google Calendar Card */}
                        <div className="border border-slate-200 rounded-lg p-5">
                            <div className="flex items-start gap-4">
                                {/* Google Logo */}
                                <div className="w-12 h-12 rounded-lg bg-white border border-slate-200 flex items-center justify-center flex-shrink-0">
                                    <svg className="w-7 h-7" viewBox="0 0 24 24">
                                        <path fill="#4285F4" d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z"/>
                                        <path fill="#34A853" d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z"/>
                                        <path fill="#FBBC05" d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l2.85-2.22.81-.62z"/>
                                        <path fill="#EA4335" d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z"/>
                                    </svg>
                                </div>

                                {/* Content */}
                                <div className="flex-1 min-w-0">
                                    <div className="flex items-center gap-3 mb-1">
                                        <h4 className="text-base font-semibold text-slate-800">Google Calendar</h4>
                                        {calendarStatus.connected ? (
                                            <span className="inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-medium bg-green-100 text-green-700">
                                                <span className="w-1.5 h-1.5 rounded-full bg-green-500"></span>
                                                Connesso
                                            </span>
                                        ) : (
                                            <span className="inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-medium bg-slate-100 text-slate-600">
                                                <span className="w-1.5 h-1.5 rounded-full bg-slate-400"></span>
                                                Non connesso
                                            </span>
                                        )}
                                    </div>

                                    <p className="text-sm text-slate-500 mb-4">
                                        Sincronizza il tuo calendario Google per visualizzare gli eventi nel calendario scadenze.
                                        Gli eventi del calendario verranno mostrati insieme alle scadenze delle pratiche.
                                    </p>

                                    {calendarStatus.connected && calendarStatus.connected_at && (
                                        <p className="text-xs text-slate-400 mb-4">
                                            Connesso il {new Date(calendarStatus.connected_at).toLocaleDateString('it-IT', {
                                                day: '2-digit',
                                                month: 'long',
                                                year: 'numeric',
                                                hour: '2-digit',
                                                minute: '2-digit'
                                            })}
                                        </p>
                                    )}

                                    {/* Action Buttons */}
                                    <div className="flex gap-3">
                                        {calendarStatus.connected ? (
                                            <button
                                                onClick={handleDisconnectCalendar}
                                                disabled={calendarLoading}
                                                className="px-4 py-2 text-sm font-medium text-red-600 bg-red-50 rounded-lg hover:bg-red-100 transition-colors disabled:opacity-50"
                                            >
                                                {calendarLoading ? 'Disconnessione...' : 'Disconnetti'}
                                            </button>
                                        ) : (
                                            <button
                                                onClick={() => {
                                                    const token = localStorage.getItem('rosa_access_token');
                                                    if (token) {
                                                        window.location.href = `/api/calendar/connect?token=${encodeURIComponent(token)}`;
                                                    } else {
                                                        toast('Sessione scaduta, effettua nuovamente il login', 'error');
                                                    }
                                                }}
                                                disabled={calendarLoading}
                                                className={`inline-flex items-center gap-2 px-4 py-2 text-sm font-medium text-white bg-brand-500 rounded-lg hover:bg-brand-600 transition-colors ${calendarLoading ? 'opacity-50 pointer-events-none' : ''}`}
                                            >
                                                <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13.828 10.172a4 4 0 00-5.656 0l-4 4a4 4 0 105.656 5.656l1.102-1.101m-.758-4.899a4 4 0 005.656 0l4-4a4 4 0 00-5.656-5.656l-1.1 1.1" />
                                                </svg>
                                                Connetti Google Calendar
                                            </button>
                                        )}
                                    </div>

                                    {/* Sharing Toggle (only when connected) */}
                                    {calendarStatus.connected && (
                                        <div className="mt-5 pt-5 border-t border-slate-200">
                                            <div className="flex items-center justify-between">
                                                <div>
                                                    <h5 className="text-sm font-medium text-slate-700">Condividi con il team</h5>
                                                    <p className="text-xs text-slate-500 mt-0.5">
                                                        Permetti agli altri utenti di vedere gli eventi del tuo calendario Google nella dashboard.
                                                    </p>
                                                </div>
                                                <button
                                                    onClick={handleToggleSharing}
                                                    disabled={sharingLoading}
                                                    className={`relative inline-flex h-6 w-11 flex-shrink-0 cursor-pointer rounded-full border-2 border-transparent transition-colors duration-200 ease-in-out focus:outline-none focus:ring-2 focus:ring-brand-500 focus:ring-offset-2 disabled:opacity-50 ${
                                                        calendarStatus.shared ? 'bg-brand-500' : 'bg-slate-200'
                                                    }`}
                                                    role="switch"
                                                    aria-checked={calendarStatus.shared}
                                                >
                                                    <span
                                                        className={`pointer-events-none inline-block h-5 w-5 transform rounded-full bg-white shadow ring-0 transition duration-200 ease-in-out ${
                                                            calendarStatus.shared ? 'translate-x-5' : 'translate-x-0'
                                                        }`}
                                                    />
                                                </button>
                                            </div>
                                            {calendarStatus.shared && (
                                                <div className="mt-2 flex items-center gap-1.5 text-xs text-green-600">
                                                    <svg className="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
                                                    </svg>
                                                    Il calendario e visibile a tutti gli utenti
                                                </div>
                                            )}
                                        </div>
                                    )}
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            )}
        </div>
    );
}

window.SettingsView = SettingsView;
