<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 ImpersonationBanner from '@/Components/ImpersonationBanner.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 appName = computed(() => page.props.appName || 'CoachPro');
const appLogo = computed(() => page.props.appLogo || null);
const impersonating = computed(() => page.props.impersonating?.active ?? false);
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 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];
};

// Subscription info
const subscription = computed(() => page.props.subscription || null);
const daysRemaining = computed(() => {
    if (!subscription.value?.end_date) return 0;
    const end = new Date(subscription.value.end_date);
    const now = new Date();
    return Math.max(0, Math.ceil((end - now) / (1000 * 60 * 60 * 24)));
});

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

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

// BottomSheet state (mobile "Más" menu)
const showMoreSheet = ref(false);

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

// Persist sidebar state
onMounted(() => {
    const saved = localStorage.getItem('coachSidebarCollapsed');
    if (saved !== null) {
        sidebarCollapsed.value = saved === 'true';
    } else {
        // Auto-colapsar en tablets (768-1023px) por defecto
        const isTablet = window.innerWidth >= 768 && window.innerWidth < 1024;
        if (isTablet) {
            sidebarCollapsed.value = true;
        }
    }
});

// Polling for real-time updates
let pollInterval = null;
onMounted(() => {
    pollInterval = setInterval(() => {
        router.reload({ only: ['unreadMessages', 'notifications'] });
    }, 30000);
});
onUnmounted(() => {
    if (pollInterval) clearInterval(pollInterval);
});

const toggleSidebar = () => {
    sidebarCollapsed.value = !sidebarCollapsed.value;
    localStorage.setItem('coachSidebarCollapsed', sidebarCollapsed.value.toString());
};

// Navigation items for Coach (desktop sidebar)
const navigationItems = computed(() => {
    const items = [
        {
            name: 'Dashboard',
            href: 'coach.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: 'Mis Clientes',
            href: 'coach.clients.index',
            icon: 'M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0zm6 3a2 2 0 11-4 0 2 2 0 014 0zM7 10a2 2 0 11-4 0 2 2 0 014 0z'
        },
        {
            name: 'Mis Planes',
            href: 'coach.plans.index',
            icon: 'M19 11H5m14 0a2 2 0 012 2v6a2 2 0 01-2 2H5a2 2 0 01-2-2v-6a2 2 0 012-2m14 0V9a2 2 0 00-2-2M5 11V9a2 2 0 012-2m0 0V5a2 2 0 012-2h6a2 2 0 012 2v2M7 7h10'
        },
        {
            name: 'Rutinas',
            href: 'coach.workouts.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: 'Dietas',
            href: 'coach.meal-plans.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: 'Ejercicios',
            href: 'coach.exercises.index',
            icon: 'M19.428 15.428a2 2 0 00-1.022-.547l-2.387-.477a6 6 0 00-3.86.517l-.318.158a6 6 0 01-3.86.517L6.05 15.21a2 2 0 00-1.806.547M8 4h8l-1 1v5.172a2 2 0 00.586 1.414l5 5c1.26 1.26.367 3.414-1.415 3.414H4.828c-1.782 0-2.674-2.154-1.414-3.414l5-5A2 2 0 009 10.172V5L8 4z'
        },
    ];

    if (features.value.feature_custom_foods) {
        items.push({
            name: 'Alimentos',
            href: 'coach.foods.index',
            icon: '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'
        });
    }

    if (features.value.feature_chat) {
        items.push({
            name: 'Mensajes',
            href: 'coach.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: unreadMessages.value
        });
    }

    if (features.value.feature_wallet) {
        items.push({
            name: 'Mi Billetera',
            href: 'coach.wallet.index',
            icon: 'M3 10h18M7 15h1m4 0h1m-7 4h12a3 3 0 003-3V8a3 3 0 00-3-3H6a3 3 0 00-3 3v8a3 3 0 003 3z'
        });
    }

    items.push({
        name: 'Suscripción',
        href: 'coach.subscription.index',
        icon: 'M15 5v2m0 4v2m0 4v2M5 5a2 2 0 00-2 2v3a2 2 0 110 4v3a2 2 0 002 2h14a2 2 0 002-2v-3a2 2 0 110-4V7a2 2 0 00-2-2H5z'
    });

    items.push({
        name: 'Tienda',
        icon: 'M16 11V7a4 4 0 00-8 0v4M5 9h14l1 12H4L5 9z',
        highlight: true,
        children: [
            { name: 'Catálogo', href: 'coach.store.index' },
            { name: 'Mis Pedidos', href: 'coach.store.orders.index' },
        ]
    });

    items.push({
        name: 'Soporte',
        href: 'coach.support.index',
        icon: 'M18.364 5.636l-3.536 3.536m0 5.656l3.536 3.536M9.172 9.172L5.636 5.636m3.536 9.192l-3.536 3.536M21 12a9 9 0 11-18 0 9 9 0 0118 0zm-5 0a4 4 0 11-8 0 4 4 0 018 0z'
    });

    return items;
});

// Bottom nav tabs (mobile) €” max 5 items
const bottomNavItems = computed(() => [
    { name: 'Panel', route: 'coach.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: 'Clientes', route: 'coach.clients.index', icon: 'M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0z' },
    { name: 'Rutinas', route: 'coach.workouts.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: 'Dietas', route: 'coach.meal-plans.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' },
]);

// Mas sheet items - usando SVG paths
const moreSheetItems = computed(() => {
    const items = [];
    items.push({
        name: 'Mis Planes',
        href: 'coach.plans.index',
        icon: 'M19 11H5m14 0a2 2 0 012 2v6a2 2 0 01-2 2H5a2 2 0 01-2-2v-6a2 2 0 012-2m14 0V9a2 2 0 00-2-2M5 11V9a2 2 0 012-2m0 0V5a2 2 0 012-2h6a2 2 0 012 2v2M7 7h10',
        color: 'text-blue-500 bg-blue-100 dark:bg-blue-900/50',
        desc: 'Planes de entrenamiento'
    });
    items.push({
        name: 'Ejercicios',
        href: 'coach.exercises.index',
        icon: 'M19.428 15.428a2 2 0 00-1.022-.547l-2.387-.477a6 6 0 00-3.86.517l-.318.158a6 6 0 01-3.86.517L6.05 15.21a2 2 0 00-1.806.547M8 4h8l-1 1v5.172a2 2 0 00.586 1.414l5 5c1.26 1.26.367 3.414-1.415 3.414H4.828c-1.782 0-2.674-2.154-1.414-3.414l5-5A2 2 0 009 10.172V5L8 4z',
        color: 'text-orange-500 bg-orange-100 dark:bg-orange-900/50',
        desc: 'Biblioteca de ejercicios'
    });
    if (features.value.feature_custom_foods) {
        items.push({
            name: 'Alimentos',
            href: 'coach.foods.index',
            icon: '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',
            color: 'text-green-500 bg-green-100 dark:bg-green-900/50',
            desc: 'Base de datos de alimentos'
        });
    }
    if (features.value.feature_chat) {
        items.push({
            name: 'Mensajes',
            href: 'coach.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',
            color: 'text-purple-500 bg-purple-100 dark:bg-purple-900/50',
            desc: 'Chat con clientes',
            badge: unreadMessages.value
        });
    }
    if (features.value.feature_wallet) {
        items.push({
            name: 'Mi Billetera',
            href: 'coach.wallet.index',
            icon: 'M3 10h18M7 15h1m4 0h1m-7 4h12a3 3 0 003-3V8a3 3 0 00-3-3H6a3 3 0 00-3 3v8a3 3 0 003 3z',
            color: 'text-emerald-500 bg-emerald-100 dark:bg-emerald-900/50',
            desc: 'Ingresos y pagos'
        });
    }
    items.push({
        name: 'Suscripcion',
        href: 'coach.subscription.index',
        icon: 'M15 5v2m0 4v2m0 4v2M5 5a2 2 0 00-2 2v3a2 2 0 110 4v3a2 2 0 002 2h14a2 2 0 002-2v-3a2 2 0 110-4V7a2 2 0 00-2-2H5z',
        color: 'text-yellow-500 bg-yellow-100 dark:bg-yellow-900/50',
        desc: (subscription.value?.plan?.name || 'Sin plan') + ' - ' + daysRemaining.value + ' dias'
    });
    items.push({
        name: 'Tienda',
        href: 'coach.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: 'coach.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: 'Soporte',
        href: 'coach.support.index',
        icon: 'M18.364 5.636l-3.536 3.536m0 5.656l3.536 3.536M9.172 9.172L5.636 5.636m3.536 9.192l-3.536 3.536M21 12a9 9 0 11-18 0 9 9 0 0118 0zm-5 0a4 4 0 11-8 0 4 4 0 018 0z',
        color: 'text-red-500 bg-red-100 dark:bg-red-900/50',
        desc: 'Centro de ayuda'
    });
    return items;
});

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

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

const totalMoreBadge = computed(() => {
    return (unreadMessages.value || 0);
});

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

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

// Get subscription status color
const getSubscriptionColor = () => {
    if (!subscription.value) return 'bg-gray-100 text-gray-600 dark:bg-gray-700 dark:text-gray-400';
    if (subscription.value.status === 'trial') return 'bg-yellow-100 text-yellow-700 dark:bg-yellow-900/50 dark:text-yellow-400';
    if (daysRemaining.value <= 7) return 'bg-red-100 text-red-700 dark:bg-red-900/50 dark:text-red-400';
    return 'bg-green-100 text-green-700 dark:bg-green-900/50 dark:text-green-400';
};
</script>

<template>
    <div class="min-h-screen bg-gray-50 dark:bg-gray-900 transition-colors duration-200">
        <!-- Impersonation Banner -->
        <ImpersonationBanner />
        <!-- 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',
                impersonating ? 'lg:top-11' : 'lg:top-0'
            ]"
        >
            <!-- Logo -->
            <div class="flex items-center justify-between h-16 px-4 border-b border-gray-200 dark:border-gray-700">
                <Link :href="route('coach.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" />
                    <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="M13 10V3L4 14h7v7l9-11h-7z" />
                            </svg>
                        </div>
                        <span
                            v-if="!sidebarCollapsed"
                            class="text-lg font-bold text-gray-900 dark:text-white whitespace-nowrap"
                        >
                            {{ appName }}
                        </span>
                    </template>
                </Link>
            </div>

            <!-- Subscription Status Desktop -->
            <div v-if="subscription && !sidebarCollapsed" class="px-3 py-3 border-b border-gray-200 dark:border-gray-700">
                <Link :href="route('coach.subscription.index')" :class="['flex items-center justify-between px-3 py-2 rounded-lg text-sm font-medium transition-colors hover:opacity-80', getSubscriptionColor()]">
                    <div class="flex items-center">
                        <svg class="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 5v2m0 4v2m0 4v2M5 5a2 2 0 00-2 2v3a2 2 0 110 4v3a2 2 0 002 2h14a2 2 0 002-2v-3a2 2 0 110-4V7a2 2 0 00-2-2H5z" />
                        </svg>
                        <span>{{ subscription.plan?.name || 'Sin plan' }}</span>
                    </div>
                    <span class="text-xs font-bold">{{ daysRemaining }}d</span>
                </Link>
            </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-neon-500/10 dark:bg-neon-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 ? 'justify-center' : 'space-x-3']">
                    <UserAvatar :src="user.avatar_url" :name="user.name" :size="40" border="border-2 border-orange-200 dark:border-orange-800" />
                    <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 }}</p>
                        <p class="text-xs text-gray-500 dark:text-gray-400 truncate">{{ user.email }}</p>
                    </div>
                    <button
                        v-if="!sidebarCollapsed"
                        @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', impersonating ? 'pt-11' : '']">

            <!-- ======================================== -->
            <!-- MOBILE HEADER (lg:hidden) €” Fixed 56px  -->
            <!-- ======================================== -->
            <header class="lg:hidden sticky top-0 z-30 mobile-header" :class="impersonating ? 'top-11' : ''">
                <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('coach.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" />
                            <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="M13 10V3L4 14h7v7l9-11h-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 />

                        <!-- Chat -->
                        <Link
                            v-if="features.feature_chat"
                            :href="route('coach.chat.index')"
                            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="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" />
                            </svg>
                            <span
                                v-if="unreadChatMessages > 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-red-500 rounded-full"
                            >
                                {{ unreadChatMessages > 9 ? '9+' : unreadChatMessages }}
                            </span>
                        </Link>

                        <!-- Cart -->
                        <Link
                            :href="route('coach.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>

                        <NotificationDropdown />
                    </div>
                </div>
            </header>

            <!-- ======================================== -->
            <!-- DESKTOP TOP BAR (hidden on mobile)      -->
            <!-- ======================================== -->
            <header :class="['hidden lg:block sticky z-30 bg-white dark:bg-gray-800 border-b border-gray-200 dark:border-gray-700 transition-colors duration-200', impersonating ? 'top-11' : 'top-0']">
                <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('coach.chat.index')"
                            class="relative p-2 text-gray-500 dark:text-gray-400 hover:text-blue-500 dark:hover:text-blue-400 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg transition-colors"
                            title="Chat / Mensajes"
                        >
                            <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="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" />
                            </svg>
                            <span
                                v-if="unreadChatMessages > 0"
                                class="absolute -top-1 -right-1 flex items-center justify-center min-w-5 h-5 px-1.5 text-xs font-bold text-white bg-blue-500 rounded-full animate-pulse"
                            >
                                {{ unreadChatMessages > 99 ? '99+' : unreadChatMessages }}
                            </span>
                        </Link>

                        <Link
                            :href="route('coach.store.cart')"
                            class="relative p-2 text-gray-500 dark:text-gray-400 hover:text-neon-500 dark:hover:text-orange-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-neon-500/100 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 ? '/storage/' + user.avatar : null" :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">Administrar Cuenta</div>
                                    <DropdownLink :href="route('profile.edit')">Mi Perfil</DropdownLink>
                                    <div class="border-t border-gray-100 dark:border-gray-700" />
                                    <form @submit.prevent="logout">
                                        <DropdownLink as="button">Cerrar Sesion</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-green-500 dark:text-green-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-4 sm:p-6 lg:p-8 pb-24 lg:pb-8 mobile-content-area">
                <slot />
            </main>
        </div>

        <!-- ============================================ -->
        <!-- MOBILE NAVIGATION DRAWER (lg:hidden)        -->
        <!-- ============================================ -->
        <MobileNavigationDrawer
            v-model="showMobileDrawer"
            :navigation-items="navigationItems"
            :user="user"
            :title="appName"
            accent-color="neon"
            :logo-img="appLogo"
            :subtitle="subscription ? `${subscription.plan?.name || 'Sin plan'} €” ${daysRemaining} dias restantes` : null"
        />

        <!-- ============================================ -->
        <!-- MOBILE BOTTOM NAVIGATION (lg:hidden)        -->
        <!-- ============================================ -->
        <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">
                <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>
                    </div>
                    <span class="tab-label">{{ item.name }}</span>
                </Link>

                <!-- "Más" 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>
                        <span
                            v-if="totalMoreBadge > 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"
                        >
                            {{ totalMoreBadge > 9 ? '9+' : totalMoreBadge }}
                        </span>
                    </div>
                    <span class="tab-label">Más</span>
                </button>
            </div>
        </nav>

        <!-- ============================================ -->
        <!-- MOBILE "MAS" BOTTOM SHEET                   -->
        <!-- ============================================ -->
        <BottomSheet v-model="showMoreSheet" title="Mas opciones" :snap-points="[0.65]">
            <!-- Subscription status -->
            <div v-if="subscription" class="mb-4">
                <button
                    @click="navigateFromSheet('coach.subscription.index')"
                    :class="['w-full flex items-center justify-between px-4 py-3 rounded-2xl text-sm font-medium transition-colors', getSubscriptionColor()]"
                >
                    <div class="flex items-center gap-2">
                        <span class="text-lg">­</span>
                        <span>{{ subscription.plan?.name || 'Sin plan' }}</span>
                    </div>
                    <span class="text-xs font-bold">{{ daysRemaining }} dias restantes</span>
                </button>
            </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>

            <template #footer>
                <div class="flex items-center justify-between">
                    <div class="flex items-center gap-3">
                        <UserAvatar :src="user?.avatar_url" :name="user?.name" :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;
}

.bottom-tab-item:active .tab-icon-wrapper {
    transform: scale(0.92);
}

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