<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue';
import { Link, usePage, router } from '@inertiajs/vue3';
import NotificationDropdown from '@/Components/NotificationDropdown.vue';
import RealTimeNotifications from '@/Components/RealTimeNotifications.vue';
import DarkModeToggle from '@/Components/DarkModeToggle.vue';
import Dropdown from '@/Components/Dropdown.vue';
import DropdownLink from '@/Components/DropdownLink.vue';
import UserAvatar from '@/Components/UserAvatar.vue';
import BottomSheet from '@/Components/Mobile/BottomSheet.vue';
import MobileNavigationDrawer from '@/Components/Mobile/MobileNavigationDrawer.vue';
import { useDarkMode } from '@/Composables/useDarkMode';

const page = usePage();
const user = computed(() => page.props.auth.user);
const client = computed(() => page.props.client || null);
const appName = computed(() => page.props.appName || 'CoachPro');
const appLogo = computed(() => page.props.appLogo || null);
const coach = computed(() => page.props.coach || { name: 'Tu Entrenador', avatar: null });
const unreadMessages = computed(() => page.props.unreadMessages || 0);
const unreadChatMessages = computed(() => page.props.unreadChatMessages || 0);
const chatNotifications = computed(() => page.props.chatNotifications || []);
const systemNotifications = computed(() => page.props.systemNotifications || []);
const notifications = computed(() => page.props.notifications || []);
const cartCount = computed(() => page.props.cartCount || 0);
const features = computed(() => page.props.features || {});

// Expanded menus state
const expandedMenus = ref({});
const toggleMenu = (menuName) => {
    expandedMenus.value[menuName] = !expandedMenus.value[menuName];
};

// Initialize dark mode
const { isDark, initDarkMode } = useDarkMode();
onMounted(() => {
    initDarkMode();
});

// Sidebar state (desktop only)
const sidebarCollapsed = ref(false);

// BottomSheet state (mobile "Mas" menu)
const showMoreSheet = ref(false);

// Mobile drawer state
const showMobileDrawer = ref(false);

// Persist sidebar state
onMounted(() => {
    const saved = localStorage.getItem('clientSidebarCollapsed');
    if (saved) {
        sidebarCollapsed.value = saved === 'true';
    }
});

// Polling for real-time updates (only when tab is visible)
let pollInterval = null;
const startPolling = () => {
    if (pollInterval) return;
    pollInterval = setInterval(() => {
        if (!document.hidden) {
            router.reload({ only: ['unreadMessages', 'unreadChatMessages', 'chatNotifications', 'systemNotifications'] });
        }
    }, 60000);
};
const stopPolling = () => {
    if (pollInterval) {
        clearInterval(pollInterval);
        pollInterval = null;
    }
};
onMounted(() => {
    startPolling();
    document.addEventListener('visibilitychange', () => {
        if (document.hidden) {
            stopPolling();
        } else {
            startPolling();
        }
    });
});
onUnmounted(() => {
    stopPolling();
});

const toggleSidebar = () => {
    sidebarCollapsed.value = !sidebarCollapsed.value;
    localStorage.setItem('clientSidebarCollapsed', sidebarCollapsed.value ? 'true' : 'false');
};

// Navigation items for Client Portal
const navigationItems = computed(() => {
    const items = [
        {
            name: 'Mi Portal',
            href: 'client.dashboard',
            icon: 'M3 12l2-2m0 0l7-7 7 7M5 10v10a1 1 0 001 1h3m10-11l2 2m-2-2v10a1 1 0 01-1 1h-3m-6 0a1 1 0 001-1v-4a1 1 0 011-1h2a1 1 0 011 1v4a1 1 0 001 1m-6 0h6'
        },
        {
            name: 'Mi Rutina',
            href: 'client.workout.index',
            icon: 'M4.318 6.318a4.5 4.5 0 000 6.364L12 20.364l7.682-7.682a4.5 4.5 0 00-6.364-6.364L12 7.636l-1.318-1.318a4.5 4.5 0 00-6.364 0z'
        },
        {
            name: 'Mi Dieta',
            href: 'client.meal-plan.index',
            icon: 'M12 6.253v13m0-13C10.832 5.477 9.246 5 7.5 5S4.168 5.477 3 6.253v13C4.168 18.477 5.754 18 7.5 18s3.332.477 4.5 1.253m0-13C13.168 5.477 14.754 5 16.5 5c1.747 0 3.332.477 4.5 1.253v13C19.832 18.477 18.247 18 16.5 18c-1.746 0-3.332.477-4.5 1.253'
        },
    ];

    // Add progress tracking if enabled
    if (features.value.feature_compliance_tracking) {
        items.push({
            name: 'Mi Progreso',
            href: 'client.progress.index',
            icon: 'M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z'
        });
    }

    // Add photos if enabled
    if (features.value.feature_progress_photos) {
        items.push({
            name: 'Mis Fotos',
            href: 'client.photos.index',
            icon: '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'
        });
    }

    // Add chat if enabled
    if (features.value.feature_chat) {
        items.push({
            name: 'Chat con Coach',
            href: 'client.chat.index',
            icon: 'M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z',
            badge: unreadChatMessages.value
        });
    }

    // Always add store and profile
    items.push({
        name: 'Tienda',
        icon: 'M16 11V7a4 4 0 00-8 0v4M5 9h14l1 12H4L5 9z',
        highlight: true,
        children: [
            { name: 'Catalogo', href: 'client.store.index' },
            { name: 'Mis Pedidos', href: 'client.store.orders.index' },
        ]
    });

    items.push({
        name: 'Mi Perfil',
        href: 'client.profile.index',
        icon: 'M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z'
    });

    return items;
});

// Bottom nav tabs (mobile) - max 4 items + Mas
const bottomNavItems = computed(() => [
    { name: 'Inicio', route: 'client.dashboard', icon: 'M3 12l2-2m0 0l7-7 7 7M5 10v10a1 1 0 001 1h3m10-11l2 2m-2-2v10a1 1 0 01-1 1h-3m-6 0a1 1 0 001-1v-4a1 1 0 011-1h2a1 1 0 011 1v4a1 1 0 001 1m-6 0h6' },
    { name: 'Rutina', route: 'client.workout.index', icon: 'M4.318 6.318a4.5 4.5 0 000 6.364L12 20.364l7.682-7.682a4.5 4.5 0 00-6.364-6.364L12 7.636l-1.318-1.318a4.5 4.5 0 00-6.364 0z' },
    { name: 'Dieta', route: 'client.meal-plan.index', icon: 'M12 6.253v13m0-13C10.832 5.477 9.246 5 7.5 5S4.168 5.477 3 6.253v13C4.168 18.477 5.754 18 7.5 18s3.332.477 4.5 1.253m0-13C13.168 5.477 14.754 5 16.5 5c1.747 0 3.332.477 4.5 1.253v13C19.832 18.477 18.247 18 16.5 18c-1.746 0-3.332.477-4.5 1.253' },
    { name: 'Chat', route: 'client.chat.index', icon: 'M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z', badge: unreadChatMessages.value },
]);

// "Mas" sheet items - items that don't fit in bottom nav
const moreSheetItems = computed(() => {
    const items = [];
    // Progreso va al sheet Mas (ya que Chat esta en el bottom nav)
    if (features.value.feature_compliance_tracking) {
        items.push({ name: 'Mi Progreso', href: 'client.progress.index', icon: 'M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z', color: 'text-blue-500 bg-blue-100 dark:bg-blue-900/50', desc: 'Seguimiento de avance' });
    }
    if (features.value.feature_progress_photos) {
        items.push({ name: 'Mis Fotos', href: 'client.photos.index', icon: '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', color: 'text-purple-500 bg-purple-100 dark:bg-purple-900/50', desc: 'Fotos de progreso' });
    }
    items.push({ name: 'Tienda', href: 'client.store.index', icon: 'M16 11V7a4 4 0 00-8 0v4M5 9h14l1 12H4L5 9z', color: 'text-orange-500 bg-gradient-to-br from-orange-100 to-amber-100 dark:from-orange-900/50 dark:to-amber-900/50', desc: 'Catalogo de productos', highlight: true });
    items.push({ name: 'Mis Pedidos', href: 'client.store.orders.index', icon: 'M20 7l-8-4-8 4m16 0l-8 4m8-4v10l-8 4m0-10L4 7m8 4v10M4 7v10l8 4', color: 'text-indigo-500 bg-indigo-100 dark:bg-indigo-900/50', desc: 'Historial de pedidos' });
    items.push({ name: 'Mi Perfil', href: 'client.profile.index', icon: 'M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z', color: 'text-green-500 bg-green-100 dark:bg-green-900/50', desc: 'Editar datos personales' });
    return items;
});

const isActive = (routeName) => {
    return route().current(routeName) || route().current(routeName + '.*');
};

const isMoreActive = computed(() => {
    return moreSheetItems.value.some(item => isActive(item.href));
});

const logout = () => {
    router.post(route('logout'));
};

const navigateFromSheet = (href) => {
    showMoreSheet.value = false;
    router.visit(route(href));
};
</script>

<template>
    <div class="min-h-screen bg-gray-50 dark:bg-gray-900 transition-colors duration-200">
        <!-- Real-time notifications toast -->
        <RealTimeNotifications />

        <!-- ============================================ -->
        <!-- DESKTOP SIDEBAR (hidden on mobile, lg:flex) -->
        <!-- ============================================ -->
        <div
            :class="[
                'hidden lg:fixed lg:inset-y-0 lg:flex lg:flex-col bg-white dark:bg-gray-800 border-r border-gray-200 dark:border-gray-700 transition-all duration-300',
                sidebarCollapsed ? 'lg:w-20' : 'lg:w-64'
            ]"
        >
            <!-- Logo -->
            <div class="flex items-center justify-between h-16 px-4 border-b border-gray-200 dark:border-gray-700">
                <Link :href="route('client.dashboard')" class="flex items-center space-x-2 overflow-hidden">
                    <img v-if="appLogo" :src="appLogo" :alt="appName" class="h-10 max-w-[160px] object-contain flex-shrink-0 dark:brightness-0 dark:invert transition-[filter] duration-300" />
                    <template v-else>
                        <div class="w-10 h-10 bg-gradient-to-br from-neon-500 to-electric-500 rounded-xl flex items-center justify-center flex-shrink-0 shadow-lg">
                            <svg class="w-6 h-6 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z" />
                            </svg>
                        </div>
                        <span
                            v-if="!sidebarCollapsed"
                            class="text-lg font-bold text-gray-900 dark:text-white whitespace-nowrap"
                        >
                            Mi Portal
                        </span>
                    </template>
                </Link>
            </div>

            <!-- Coach Info Desktop -->
            <div v-if="!sidebarCollapsed" class="px-4 py-4 border-b border-gray-200 dark:border-gray-700 bg-gradient-to-r from-neon-500/10 to-electric-500/10 dark:from-neon-900/20 dark:to-electric-900/20">
                <div class="flex items-center">
                    <UserAvatar :src="coach.avatar" :name="coach.name" :size="48" border="border-2 border-white dark:border-gray-700" />
                    <div class="ml-3 flex-1 min-w-0">
                        <p class="text-xs text-gray-500 dark:text-gray-400">Tu Entrenador</p>
                        <p class="text-sm font-semibold text-gray-900 dark:text-white truncate">{{ coach.name }}</p>
                    </div>
                </div>
            </div>

            <!-- Navigation -->
            <nav class="flex-1 px-3 py-4 space-y-1 overflow-y-auto">
                <template v-for="item in navigationItems" :key="item.name">
                    <!-- Item with children (submenu) -->
                    <div v-if="item.children">
                        <button
                            @click="toggleMenu(item.name)"
                            :class="[
                                item.highlight && !(expandedMenus[item.name] || item.children.some(c => isActive(c.href)))
                                    ? 'bg-gradient-to-r from-orange-500/10 to-amber-500/10 dark:from-orange-500/15 dark:to-amber-500/15 text-orange-700 dark:text-orange-300 ring-1 ring-orange-500/20 dark:ring-orange-400/20 hover:from-orange-500/20 hover:to-amber-500/20'
                                    : expandedMenus[item.name] || item.children.some(c => isActive(c.href))
                                        ? 'bg-gray-50 dark:bg-gray-700/50 text-gray-900 dark:text-white'
                                        : 'text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-700',
                                'w-full group flex items-center justify-between px-3 py-2.5 text-sm font-medium rounded-lg transition-all duration-200'
                            ]"
                            :title="sidebarCollapsed ? item.name : ''"
                        >
                            <div class="flex items-center">
                                <svg
                                    :class="[
                                        item.highlight ? 'text-orange-500 dark:text-orange-400' : item.children.some(c => isActive(c.href)) ? 'text-neon-500 dark:text-neon-400' : 'text-gray-400',
                                        'h-5 w-5 flex-shrink-0 transition-colors',
                                        sidebarCollapsed ? '' : 'mr-3'
                                    ]"
                                    fill="none"
                                    stroke="currentColor"
                                    viewBox="0 0 24 24"
                                >
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" :d="item.icon" />
                                </svg>
                                <span v-if="!sidebarCollapsed" class="truncate">{{ item.name }}</span>
                            </div>
                            <svg v-if="!sidebarCollapsed" :class="['w-4 h-4 transition-transform', expandedMenus[item.name] ? 'rotate-180' : '']" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7" />
                            </svg>
                        </button>
                        <div v-if="!sidebarCollapsed && (expandedMenus[item.name] || item.children.some(c => isActive(c.href)))" class="mt-1 ml-4 pl-4 border-l-2 border-gray-200 dark:border-gray-700 space-y-1">
                            <Link
                                v-for="child in item.children"
                                :key="child.name"
                                :href="route(child.href)"
                                :class="[
                                    isActive(child.href)
                                        ? 'bg-green-50 dark:bg-green-900/30 text-neon-500 dark:text-neon-400'
                                        : 'text-gray-600 dark:text-gray-400 hover:bg-gray-50 dark:hover:bg-gray-700',
                                    'block px-3 py-2 text-sm rounded-lg transition-colors'
                                ]"
                            >
                                {{ child.name }}
                            </Link>
                        </div>
                    </div>
                    <!-- Simple item (no children) -->
                    <Link
                        v-else
                        :href="route(item.href)"
                        :class="[
                            isActive(item.href)
                                ? 'bg-gradient-to-r from-neon-500/10 to-electric-500/10 dark:from-neon-900/30 dark:to-electric-900/30 text-neon-500 dark:text-neon-400 border-l-4 border-neon-500'
                                : 'text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-700 hover:text-gray-900 dark:hover:text-white border-l-4 border-transparent',
                            'group flex items-center px-3 py-2.5 text-sm font-medium rounded-r-lg transition-all duration-200'
                        ]"
                        :title="sidebarCollapsed ? item.name : ''"
                    >
                        <svg
                            :class="[
                                isActive(item.href) ? 'text-neon-500 dark:text-neon-400' : 'text-gray-400 dark:text-gray-500 group-hover:text-gray-500 dark:group-hover:text-gray-300',
                                'h-5 w-5 flex-shrink-0 transition-colors',
                                sidebarCollapsed ? '' : 'mr-3'
                            ]"
                            fill="none"
                            stroke="currentColor"
                            viewBox="0 0 24 24"
                        >
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" :d="item.icon" />
                        </svg>
                        <span v-if="!sidebarCollapsed" class="truncate flex-1">{{ item.name }}</span>
                        <span v-if="item.badge && !sidebarCollapsed" class="ml-2 inline-flex items-center justify-center px-2 py-0.5 text-xs font-bold text-white bg-red-500 rounded-full animate-pulse">
                            {{ item.badge > 99 ? '99+' : item.badge }}
                        </span>
                        <span v-if="item.badge && sidebarCollapsed" class="absolute -top-1 -right-1 flex h-4 w-4 items-center justify-center rounded-full bg-red-500 text-[10px] text-white font-bold">
                            {{ item.badge > 9 ? '9+' : item.badge }}
                        </span>
                    </Link>
                </template>
            </nav>

            <!-- Toggle button -->
            <div class="border-t border-gray-200 dark:border-gray-700 p-3">
                <button
                    @click="toggleSidebar"
                    class="w-full flex items-center justify-center py-2 text-gray-500 dark:text-gray-400 hover:text-gray-700 dark:hover:text-gray-200 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg transition-colors"
                    :title="sidebarCollapsed ? 'Expandir menu' : 'Contraer menu'"
                >
                    <svg
                        :class="['w-5 h-5 transition-transform duration-300', sidebarCollapsed ? 'rotate-180' : '']"
                        fill="none"
                        stroke="currentColor"
                        viewBox="0 0 24 24"
                    >
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 19l-7-7 7-7m8 14l-7-7 7-7" />
                    </svg>
                </button>
            </div>

            <!-- User section -->
            <div class="border-t border-gray-200 dark:border-gray-700 p-3">
                <div :class="['flex items-center', sidebarCollapsed ? 'flex-col space-y-2' : 'space-x-3']">
                    <UserAvatar :src="user?.avatar_url" :name="user?.name || 'Cliente'" :size="40" border="border border-gray-200 dark:border-gray-700" />
                    <div v-if="!sidebarCollapsed" class="flex-1 min-w-0">
                        <p class="text-sm font-medium text-gray-900 dark:text-white truncate">{{ user?.name || 'Cliente' }}</p>
                        <p class="text-xs text-gray-500 dark:text-gray-400 truncate">{{ user?.email || '' }}</p>
                    </div>
                    <button
                        @click="logout"
                        class="p-1.5 text-gray-400 dark:text-gray-500 hover:text-red-500 dark:hover:text-red-400 hover:bg-red-50 dark:hover:bg-red-900/30 rounded-lg transition-colors"
                        title="Cerrar sesion"
                    >
                        <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17 16l4-4m0 0l-4-4m4 4H7m6 4v1a3 3 0 01-3 3H6a3 3 0 01-3-3V7a3 3 0 013-3h4a3 3 0 013 3v1" />
                        </svg>
                    </button>
                </div>
            </div>
        </div>

        <!-- ============================================ -->
        <!-- MAIN CONTENT AREA                           -->
        <!-- ============================================ -->
        <div :class="['transition-all duration-300', sidebarCollapsed ? 'lg:pl-20' : 'lg:pl-64']">

            <!-- ======================================== -->
            <!-- MOBILE HEADER (lg:hidden) â€” Fixed 56px  -->
            <!-- ======================================== -->
            <header class="lg:hidden sticky top-0 z-30 mobile-header">
                <div class="flex items-center justify-between h-14 px-3">
                    <!-- Left: Hamburger + Logo -->
                    <div class="flex items-center gap-2">
                        <button
                            @click="showMobileDrawer = true"
                            class="w-11 h-11 flex items-center justify-center rounded-xl hover:bg-gray-100 dark:hover:bg-gray-800 active:bg-gray-200 dark:active:bg-gray-700 transition-colors touch-manipulation"
                            aria-label="Abrir menu de navegacion"
                        >
                            <svg class="w-6 h-6 text-gray-700 dark:text-gray-300" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 6h16M4 12h16M4 18h16" />
                            </svg>
                        </button>
                        <Link :href="route('client.dashboard')" class="flex items-center gap-2">
                            <img v-if="appLogo" :src="appLogo" :alt="appName" class="h-8 max-w-[100px] object-contain dark:brightness-0 dark:invert transition-[filter] duration-300" />
                            <template v-else>
                                <div class="w-8 h-8 bg-gradient-to-br from-neon-500 to-electric-500 rounded-lg flex items-center justify-center">
                                    <svg class="w-5 h-5 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z" />
                                    </svg>
                                </div>
                                <span class="hidden sm:block text-base font-bold text-gray-900 dark:text-white">{{ appName }}</span>
                            </template>
                        </Link>
                    </div>

                    <!-- Right: Actions -->
                    <div class="flex items-center gap-0.5">
                        <DarkModeToggle />

                        <!-- Cart -->
                        <Link
                            :href="route('client.store.cart')"
                            class="relative w-11 h-11 flex items-center justify-center text-gray-600 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-xl transition-colors touch-manipulation"
                        >
                            <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 3h2l.4 2M7 13h10l4-8H5.4M7 13L5.4 5M7 13l-2.293 2.293c-.63.63-.184 1.707.707 1.707H17m0 0a2 2 0 100 4 2 2 0 000-4zm-8 2a2 2 0 11-4 0 2 2 0 014 0z" />
                            </svg>
                            <span v-if="cartCount > 0" class="absolute top-1 right-1 min-w-[18px] h-[18px] flex items-center justify-center px-1 text-[10px] font-bold text-white bg-neon-500 rounded-full">
                                {{ cartCount > 9 ? '9+' : cartCount }}
                            </span>
                        </Link>

                        <!-- Notifications -->
                        <NotificationDropdown />
                    </div>
                </div>
            </header>

            <!-- ======================================== -->
            <!-- DESKTOP TOP BAR (hidden on mobile)      -->
            <!-- ======================================== -->
            <header class="hidden lg:block sticky top-0 z-30 bg-white dark:bg-gray-800 border-b border-gray-200 dark:border-gray-700 transition-colors duration-200">
                <div class="flex items-center justify-between h-16 px-4 sm:px-6 lg:px-8">
                    <div class="flex-1 lg:ml-0">
                        <slot name="header" />
                    </div>

                    <div class="flex items-center space-x-2 sm:space-x-4">
                        <DarkModeToggle />

                        <Link
                            :href="route('client.store.cart')"
                            class="relative p-2 text-gray-500 dark:text-gray-400 hover:text-neon-500 dark:hover:text-green-400 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg transition-colors"
                            title="Carrito"
                        >
                            <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 3h2l.4 2M7 13h10l4-8H5.4M7 13L5.4 5M7 13l-2.293 2.293c-.63.63-.184 1.707.707 1.707H17m0 0a2 2 0 100 4 2 2 0 000-4zm-8 2a2 2 0 11-4 0 2 2 0 014 0z" />
                            </svg>
                            <span v-if="cartCount > 0" class="absolute -top-1 -right-1 w-5 h-5 bg-green-500 text-white text-xs font-bold rounded-full flex items-center justify-center">
                                {{ cartCount > 9 ? '9+' : cartCount }}
                            </span>
                        </Link>

                        <NotificationDropdown />

                        <!-- User menu (desktop) -->
                        <div class="flex items-center ml-3">
                            <Dropdown align="right" width="48">
                                <template #trigger>
                                    <button class="flex items-center text-sm border-2 border-transparent rounded-full focus:outline-none focus:border-gray-300 transition">
                                        <div class="flex items-center gap-2">
                                            <span class="hidden md:block text-gray-700 dark:text-gray-300 font-medium">{{ user.name }}</span>
                                            <UserAvatar :src="user.avatar_url" :name="user.name" :size="36" border="border border-gray-200 dark:border-gray-700" />
                                            <svg class="ml-1 -mr-0.5 h-4 w-4 text-gray-400" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor">
                                                <path fill-rule="evenodd" d="M5.293 7.293a1 1 0 011.414 0L10 10.586l3.293-3.293a1 1 0 111.414 1.414l-4 4a1 1 0 01-1.414 0l-4-4a1 1 0 010-1.414z" clip-rule="evenodd" />
                                            </svg>
                                        </div>
                                    </button>
                                </template>

                                <template #content>
                                    <div class="block px-4 py-2 text-xs text-gray-400">Mi Cuenta</div>
                                    <DropdownLink :href="route('client.dashboard')">Mi Portal</DropdownLink>
                                    <DropdownLink :href="route('client.workout.index')">Mi Rutina</DropdownLink>
                                    <DropdownLink :href="route('client.meal-plan.index')">Mi Dieta</DropdownLink>
                                    <DropdownLink :href="route('client.progress.index')">Mi Progreso</DropdownLink>
                                    <DropdownLink :href="route('client.photos.index')">Mis Fotos</DropdownLink>
                                    <DropdownLink :href="route('client.chat.index')">Chat con Coach</DropdownLink>
                                    <div class="border-t border-gray-100 dark:border-gray-700" />
                                    <DropdownLink :href="route('client.profile.index')">Editar Perfil</DropdownLink>
                                    <div class="border-t border-gray-100 dark:border-gray-700" />
                                    <form @submit.prevent="logout">
                                        <DropdownLink as="button">
                                            <span class="text-red-600 dark:text-red-400">Cerrar sesion</span>
                                        </DropdownLink>
                                    </form>
                                </template>
                            </Dropdown>
                        </div>
                    </div>
                </div>
            </header>

            <!-- Flash messages -->
            <div class="px-4 sm:px-6 lg:px-8 mt-4" v-if="$page.props.flash?.success || $page.props.flash?.error">
                <div
                    v-if="$page.props.flash?.success"
                    class="flex items-center p-4 bg-green-50 dark:bg-green-900/30 border border-green-200 dark:border-green-800 text-green-800 dark:text-green-200 rounded-xl"
                >
                    <svg class="w-5 h-5 mr-3 text-neon-500 dark:text-neon-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
                    </svg>
                    <span class="font-medium">{{ $page.props.flash.success }}</span>
                </div>
                <div
                    v-if="$page.props.flash?.error"
                    class="flex items-center p-4 bg-red-50 dark:bg-red-900/30 border border-red-200 dark:border-red-800 text-red-800 dark:text-red-200 rounded-xl"
                >
                    <svg class="w-5 h-5 mr-3 text-red-500 dark:text-red-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
                    </svg>
                    <span class="font-medium">{{ $page.props.flash.error }}</span>
                </div>
            </div>

            <!-- Page content -->
            <main class="p-3 sm:p-4 md:p-6 lg:p-8 pb-20 lg:pb-8 mobile-content-area">
                <slot />
            </main>
        </div>

        <!-- ============================================ -->
        <!-- MOBILE NAVIGATION DRAWER (lg:hidden)        -->
        <!-- ============================================ -->
        <MobileNavigationDrawer
            v-model="showMobileDrawer"
            :navigation-items="navigationItems"
            :user="user"
            title="Mi Portal"
            accent-color="green"
            :logo-img="appLogo"
            :subtitle="coach?.name ? `Entrenador: ${coach.name}` : null"
        />

        <!-- ============================================ -->
        <!-- MOBILE BOTTOM NAVIGATION (lg:hidden)        -->
        <!-- Native app-style tab bar                    -->
        <!-- ============================================ -->
        <nav class="lg:hidden fixed bottom-0 left-0 right-0 z-40 mobile-bottom-nav">
            <div class="flex items-center justify-around h-16 px-1">
                <!-- Main 4 tabs -->
                <Link
                    v-for="item in bottomNavItems"
                    :key="item.route"
                    :href="route(item.route)"
                    class="bottom-tab-item"
                    :class="{ 'active': isActive(item.route) }"
                >
                    <div class="tab-icon-wrapper" :class="{ 'active': isActive(item.route) }">
                        <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" :d="item.icon" />
                        </svg>
                        <!-- Badge para mensajes no leidos -->
                        <span
                            v-if="item.badge && item.badge > 0"
                            class="absolute -top-1 -right-1 min-w-[16px] h-4 flex items-center justify-center px-1 text-[10px] font-bold text-white bg-red-500 rounded-full animate-pulse"
                        >
                            {{ item.badge > 9 ? '9+' : item.badge }}
                        </span>
                    </div>
                    <span class="tab-label">{{ item.name }}</span>
                </Link>

                <!-- "Mas" tab -->
                <button
                    @click="showMoreSheet = true"
                    class="bottom-tab-item"
                    :class="{ 'active': isMoreActive }"
                >
                    <div class="tab-icon-wrapper" :class="{ 'active': isMoreActive }">
                        <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 12h.01M12 12h.01M19 12h.01M6 12a1 1 0 11-2 0 1 1 0 012 0zm7 0a1 1 0 11-2 0 1 1 0 012 0zm7 0a1 1 0 11-2 0 1 1 0 012 0z" />
                        </svg>
                    </div>
                    <span class="tab-label">Mas</span>
                </button>
            </div>
        </nav>

        <!-- ============================================ -->
        <!-- MOBILE "MAS" BOTTOM SHEET                   -->
        <!-- ============================================ -->
        <BottomSheet v-model="showMoreSheet" title="Mas opciones" :snap-points="[0.55]">
            <!-- Coach info -->
            <div class="mb-4 p-4 bg-gradient-to-r from-emerald-50 to-teal-50 dark:from-emerald-900/20 dark:to-teal-900/20 rounded-2xl">
                <div class="flex items-center gap-3">
                    <UserAvatar :src="coach.avatar" :name="coach.name" :size="44" border="border-2 border-white dark:border-gray-700" />
                    <div class="flex-1 min-w-0">
                        <p class="text-xs text-gray-500 dark:text-gray-400">Tu Entrenador</p>
                        <p class="text-sm font-semibold text-gray-900 dark:text-white truncate">{{ coach.name }}</p>
                    </div>
                </div>
            </div>

            <!-- Menu items -->
            <div class="space-y-1">
                <button
                    v-for="item in moreSheetItems"
                    :key="item.href"
                    @click="navigateFromSheet(item.href)"
                    class="w-full flex items-center gap-4 p-3.5 rounded-2xl transition-all duration-200 active:scale-[0.98] touch-manipulation"
                    :class="isActive(item.href)
                        ? 'bg-neon-500/10 dark:bg-neon-900/30'
                        : 'hover:bg-gray-100 dark:hover:bg-gray-800 active:bg-gray-200 dark:active:bg-gray-700'"
                >
                    <div :class="['flex-shrink-0 w-10 h-10 flex items-center justify-center rounded-xl', item.color]">
                        <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" :d="item.icon" />
                        </svg>
                    </div>
                    <div class="flex-1 text-left min-w-0">
                        <p class="text-sm font-medium text-gray-900 dark:text-white">{{ item.name }}</p>
                        <p class="text-xs text-gray-500 dark:text-gray-400">{{ item.desc }}</p>
                    </div>
                    <span
                        v-if="item.badge && item.badge > 0"
                        class="min-w-[22px] h-[22px] flex items-center justify-center px-1.5 text-xs font-bold text-white bg-red-500 rounded-full"
                    >
                        {{ item.badge > 99 ? '99+' : item.badge }}
                    </span>
                    <svg class="w-4 h-4 text-gray-400 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7" />
                    </svg>
                </button>
            </div>

            <!-- User & Logout section -->
            <template #footer>
                <div class="flex items-center justify-between">
                    <div class="flex items-center gap-3">
                        <UserAvatar :src="user?.avatar_url" :name="user?.name || 'Cliente'" :size="36" border="border border-gray-200 dark:border-gray-700" />
                        <div class="min-w-0">
                            <p class="text-sm font-medium text-gray-900 dark:text-white truncate">{{ user?.name }}</p>
                            <p class="text-xs text-gray-500 dark:text-gray-400 truncate">{{ user?.email }}</p>
                        </div>
                    </div>
                    <button
                        @click="logout"
                        class="flex items-center gap-2 px-4 py-2 text-sm font-medium text-red-600 dark:text-red-400 bg-red-50 dark:bg-red-900/20 hover:bg-red-100 dark:hover:bg-red-900/40 rounded-xl transition-colors touch-manipulation"
                    >
                        <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17 16l4-4m0 0l-4-4m4 4H7m6 4v1a3 3 0 01-3 3H6a3 3 0 01-3-3V7a3 3 0 013-3h4a3 3 0 013 3v1" />
                        </svg>
                        Salir
                    </button>
                </div>
            </template>
        </BottomSheet>
    </div>
</template>

<style scoped>
/* ============================================
   MOBILE HEADER â€” Frosted glass native feel
   ============================================ */
.mobile-header {
    background: rgba(255, 255, 255, 0.85);
    backdrop-filter: blur(20px) saturate(180%);
    -webkit-backdrop-filter: blur(20px) saturate(180%);
    border-bottom: 0.5px solid rgba(0, 0, 0, 0.1);
    padding-top: env(safe-area-inset-top, 0px);
    -webkit-user-select: none;
    user-select: none;
}

:root.dark .mobile-header {
    background: rgba(17, 24, 39, 0.88);
    border-bottom-color: rgba(255, 255, 255, 0.08);
}

/* ============================================
   BOTTOM NAVIGATION â€” Native iOS/Android tab bar
   ============================================ */
.mobile-bottom-nav {
    background: rgba(255, 255, 255, 0.92);
    backdrop-filter: blur(20px) saturate(180%);
    -webkit-backdrop-filter: blur(20px) saturate(180%);
    border-top: 0.5px solid rgba(0, 0, 0, 0.1);
    padding-bottom: env(safe-area-inset-bottom, 8px);
    -webkit-user-select: none;
    user-select: none;
}

:root.dark .mobile-bottom-nav {
    background: rgba(17, 24, 39, 0.92);
    border-top-color: rgba(255, 255, 255, 0.08);
}

.bottom-tab-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    flex: 1;
    height: 100%;
    padding: 4px 2px;
    color: #9CA3AF;
    transition: all 0.2s ease;
    -webkit-tap-highlight-color: transparent;
    cursor: pointer;
    background: none;
    border: none;
    font-family: inherit;
}

.bottom-tab-item.active {
    color: #10B981;
}

:root.dark .bottom-tab-item {
    color: #6B7280;
}

:root.dark .bottom-tab-item.active {
    color: #34D399;
}

.tab-icon-wrapper {
    position: relative;
    display: flex;
    align-items: center;
    justify-content: center;
    width: 36px;
    height: 36px;
    border-radius: 12px;
    transition: all 0.3s cubic-bezier(0.34, 1.56, 0.64, 1);
}

.tab-icon-wrapper.active {
    background: rgba(16, 185, 129, 0.12);
    transform: scale(1.05);
}

:root.dark .tab-icon-wrapper.active {
    background: rgba(52, 211, 153, 0.15);
}

.tab-label {
    font-size: 11px;
    font-weight: 500;
    margin-top: 2px;
    line-height: 1;
    letter-spacing: 0.01em;
}

/* Mobile content area optimizations */
.mobile-content-area {
    -webkit-overflow-scrolling: touch;
    overscroll-behavior-y: contain;
    min-height: calc(100vh - 56px - 64px);
    min-height: calc(100dvh - 56px - 64px);
}

.bottom-tab-item.active .tab-label {
    font-weight: 600;
}

/* Active press effect */
.bottom-tab-item:active .tab-icon-wrapper {
    transform: scale(0.92);
}

/* Smooth overscroll */
main {
    -webkit-overflow-scrolling: touch;
    overscroll-behavior-y: contain;
}
</style>
