<script setup>
import { ref, computed } from 'vue';
import { Link, usePage } from '@inertiajs/vue3';
import { useChatToggle } from '@/Composables/useChatToggle';
import { onMounted } from 'vue';
import axios from 'axios';
import { router } from '@inertiajs/vue3';

const { chatEnabled, toggleChat } = useChatToggle();

const props = defineProps({
  title: {
    type: String,
    default: 'Innova'
  }
});

const page = usePage();
const sidebarOpen = ref(true);

const currentTime = ref(new Date().toLocaleTimeString('es-EC', { hour: '2-digit', minute: '2-digit' }));

setInterval(() => {
  currentTime.value = new Date().toLocaleTimeString('es-EC', { hour: '2-digit', minute: '2-digit' });
}, 60000);

const menuItems = [
  { name: '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', route: 'dashboard' },
  { 
    name: 'Casos', 
    icon: 'M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z', 
    route: 'casos.index', 
    badge: computed(() => page.props.global_stats?.pendientes || 0) 
  },
  { name: 'Coordinación', icon: 'M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z', route: 'coordinacion' },
  { name: 'Estados', icon: 'M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15', route: 'estados' },
  { name: 'Mesa de Compras', 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', route: 'mesa-compras' },
  { name: 'Reparación', icon: 'M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z', route: 'reparacion' },
  { name: 'Facturación', icon: 'M9 14l6-6m-5.5.5h.01m4.99 5h.01M19 21V5a2 2 0 00-2-2H7a2 2 0 00-2 2v16l3.5-2 3.5 2 3.5-2 3.5 2zM10 8.5a.5.5 0 11-1 0 .5.5 0 011 0zm5 5a.5.5 0 11-1 0 .5.5 0 011 0z', route: 'facturacion' },
  { name: 'Catálogos', icon: 'M4 7v10c0 2.21 3.582 4 8 4s8-1.79 8-4V7M4 7c0 2.21 3.582 4 8 4s8-1.79 8-4M4 7c0-2.21 3.582-4 8-4s8 1.79 8 4m0 5c0 2.21-3.582 4-8 4s-8-1.79-8-4', route: 'aseguradoras.index', children: [
    { name: 'Aseguradoras', route: 'aseguradoras.index' },
    { name: 'Brokers', route: 'brokers.index' },
    { name: 'Ajustadores', route: 'ajustadores.index' },
    { name: 'Talleres', route: 'talleres.index' },
    { name: 'Proveedores', route: 'proveedores.index' },
    { name: 'Personal', route: 'personal.index' },
  ]},
  { name: 'Usuarios', icon: 'M12 4.354a4 4 0 110 5.292M15 21H3v-1a6 6 0 0112 0v1zm0 0h6v-1a6 6 0 00-9-5.197M13 7a4 4 0 11-8 0 4 4 0 018 0z', route: 'usuarios.index', adminOnly: true },
];

const visibleMenuItems = computed(() => {
  return menuItems.filter(item => {
    if (item.adminOnly) {
      console.log('User Role is:', page.props.auth?.user?.rol);
      // Hardcode it to true for now to see if it renders without condition
      return true; // page.props.auth && page.props.auth.user && page.props.auth.user.rol === 'admin';
    }
    return true;
  });
});

// Bottom tab bar items for mobile (5 max for good UX)
const bottomTabs = [
  { name: 'Inicio', icon: 'home', route: 'dashboard' },
  { name: 'Casos', icon: 'description', route: 'casos.index' },
  { name: 'Coord.', icon: 'calendar_month', route: 'coordinacion' },
  { name: 'Compras', icon: 'shopping_cart', route: 'mesa-compras' },
  { name: 'Más', icon: 'menu', route: null },
];

const moreMenuOpen = ref(false);
const expandedMenuItem = ref(null);
const userMenuOpen = ref(false);

const moreMenuItems = [
  { name: 'Estados', icon: 'autorenew', route: 'estados' },
  { name: 'Reparación', icon: 'build', route: 'reparacion' },
  { name: 'Facturación', icon: 'receipt_long', route: 'facturacion' },
  { 
    name: 'Catálogos', 
    icon: 'database', 
    route: null,
    children: [
      { name: 'Aseguradoras', route: 'aseguradoras.index', icon: 'shield' },
      { name: 'Brokers', route: 'brokers.index', icon: 'handshake' },
      { name: 'Ajustadores', route: 'ajustadores.index', icon: 'badge' },
      { name: 'Talleres', route: 'talleres.index', icon: 'home_repair_service' },
      { name: 'Proveedores', route: 'proveedores.index', icon: 'local_shipping' },
      { name: 'Personal', route: 'personal.index', icon: 'assignment_ind' },
    ]
  },
  { name: 'Usuarios', icon: 'group', route: 'usuarios.index' },
];

const handleTabClick = (tab) => {
  if (tab.route === null) {
    moreMenuOpen.value = !moreMenuOpen.value;
    if (!moreMenuOpen.value) {
      expandedMenuItem.value = null;
    }
  } else {
    moreMenuOpen.value = false;
    expandedMenuItem.value = null;
  }
};

const handleMoreItemClick = (item) => {
  if (item.children) {
    if (expandedMenuItem.value === item.name) {
      expandedMenuItem.value = null;
    } else {
      expandedMenuItem.value = item.name;
    }
  } else {
    moreMenuOpen.value = false;
    expandedMenuItem.value = null;
  }
};

const getChildren = (parentName) => {
  if (!parentName) return [];
  const parent = moreMenuItems.find(m => m.name === parentName);
  return parent ? parent.children : [];
};

const closeAllMenus = () => {
  moreMenuOpen.value = false;
  expandedMenuItem.value = null;
};

const stats = computed(() => [
  { label: 'Casos Activos', value: page.props.global_stats?.casos_activos || 0, color: 'blue', icon: 'M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z' },
  { label: 'En Reparación', value: page.props.global_stats?.en_reparacion || 0, color: 'amber', icon: 'M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z' },
  { label: 'Pendientes', value: page.props.global_stats?.pendientes || 0, color: 'rose', icon: 'M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z' },
  { label: 'Finalizados', value: page.props.global_stats?.finalizados || 0, color: 'emerald', icon: 'M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z' },
]);

const colorClasses = {
  blue: 'bg-blue-50 text-blue-600',
  amber: 'bg-amber-50 text-amber-600',
  rose: 'bg-rose-50 text-rose-600',
  emerald: 'bg-emerald-50 text-emerald-600',
};

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

// Notifications Logic
const showNotifications = ref(false);
const notifications = ref([]);
const unreadCount = computed(() => notifications.value.filter(n => !n.leida).length);

const fetchNotifications = async () => {
  try {
    const response = await axios.get(route('api.notifications.index'));
    notifications.value = response.data;
  } catch (error) {
    console.error('Error fetching notifications:', error);
  }
};

const markAsRead = async (id) => {
  try {
    await axios.post(route('api.notifications.read', id));
    notifications.value = notifications.value.map(n => 
      n.id === id ? { ...n, leida: true } : n
    );
  } catch (error) {
    console.error('Error marking notification as read:', error);
  }
};

const markAllRead = async () => {
  try {
    await axios.post(route('api.notifications.read-all'));
    notifications.value = notifications.value.map(n => ({ ...n, leida: true }));
  } catch (error) {
    console.error('Error marking all as read:', error);
  }
};

const handleNotificationClick = (notif) => {
    if (!notif.leida) markAsRead(notif.id);
    showNotifications.value = false;
    
    // Logic to navigate if there's a case
    if (notif.caso_id) {
        router.get(route('casos.show', notif.caso_id));
    }
};

const getNotifIcon = (tipo) => {
    switch(tipo) {
        case 'alcance_reparacion': return 'refresh';
        case 'vehiculo_no_ingresado': return 'warning';
        case 'orden_salida': return 'local_shipping';
        case 'aprobacion_cuadro': return 'check_circle';
        case 'prefactura_subida': return 'receipt_long';
        case 'compra_guardada': return 'shopping_cart';
        case 'importacion_rechazada': return 'cancel';
        case 'importacion_aceptada': return 'check_circle';
        case 'alerta_caso_no_encontrado': return 'info';
        case 'caso_creado': return 'add_circle';
        case 'estado_actualizado': return 'swap_horiz';
        default: return 'info';
    }
};

const getNotifBg = (tipo) => {
    switch(tipo) {
        case 'alcance_reparacion': return 'bg-amber-100 text-amber-600';
        case 'vehiculo_no_ingresado': return 'bg-rose-100 text-rose-600';
        case 'orden_salida': return 'bg-green-100 text-green-600';
        case 'aprobacion_cuadro': return 'bg-brand-blue/10 text-brand-blue';
        case 'caso_creado': return 'bg-blue-100 text-blue-600';
        case 'estado_actualizado': return 'bg-slate-100 text-slate-600';
        default: return 'bg-slate-100 text-slate-500';
    }
};

const formatTime = (date) => {
    const d = new Date(date);
    return d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
};

onMounted(() => {
  fetchNotifications();
  // Poll every 30 seconds
  setInterval(fetchNotifications, 30000);
});
</script>

<template>
  <div class="min-h-screen bg-slate-50">
    <!-- ===================== DESKTOP SIDEBAR (hidden on mobile) ===================== -->
    <aside 
      :class="[
        'hidden lg:flex flex-col fixed top-0 left-0 z-40 h-screen transition-all duration-300 ease-in-out',
        sidebarOpen ? 'w-64' : 'w-20'
      ]"
      class="bg-gradient-to-b from-slate-900 via-slate-800 to-slate-900"
    >
      <!-- Logo -->
      <div class="h-20 flex items-center justify-center border-b border-slate-700/50">
        <div class="flex items-center gap-3">
          <div class="w-10 h-10 rounded-xl bg-gradient-to-br from-cyan-400 to-blue-600 flex items-center justify-center shadow-lg shadow-cyan-500/30">
            <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="M9 12l2 2 4-4m5.618-4.016A11.955 11.955 0 0112 2.944a11.955 11.955 0 01-8.618 3.04A12.02 12.02 0 003 9c0 5.591 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.042-.133-2.052-.382-3.016z" />
            </svg>
          </div>
          <span v-if="sidebarOpen" class="text-white font-bold text-lg tracking-tight">Innova</span>
        </div>
      </div>

      <!-- Desktop Menu -->
      <nav class="p-4 space-y-2 flex-1 overflow-y-auto">
        <template v-for="item in visibleMenuItems" :key="item.route">
          <Link 
            v-if="!item.children"
            :href="route(item.route)"
            class="flex items-center gap-3 px-4 py-3 rounded-xl text-slate-300 hover:text-white hover:bg-white/10 cursor-pointer transition-all duration-200 group"
            :class="{ 'bg-white/10 text-white': isActive(item.route) }"
          >
            <svg class="w-5 h-5 flex-shrink-0" 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="sidebarOpen" class="font-medium">{{ item.name }}</span>
            <span 
              v-if="sidebarOpen && item.badge" 
              class="ml-auto bg-cyan-500 text-white text-xs font-bold px-2 py-0.5 rounded-full"
            >
              {{ item.badge }}
            </span>
          </Link>

          <div v-else class="space-y-1">
            <div 
              class="flex items-center gap-3 px-4 py-3 rounded-xl text-slate-300 hover:text-white hover:bg-white/10 cursor-pointer transition-all duration-200"
              :class="{ 'bg-white/10 text-white': isActive(item.route) }"
            >
              <svg class="w-5 h-5 flex-shrink-0" 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="sidebarOpen" class="font-medium">{{ item.name }}</span>
            </div>
            <div v-if="sidebarOpen" class="ml-4 pl-4 border-l border-slate-700/50 space-y-1">
              <Link 
                v-for="child in item.children" 
                :key="child.route"
                :href="route(child.route)"
                class="block px-4 py-2 rounded-lg text-sm text-slate-400 hover:text-white hover:bg-white/5 cursor-pointer transition-colors"
                :class="{ 'text-white bg-white/10': isActive(child.route) }"
              >
                {{ child.name }}
              </Link>
            </div>
          </div>
        </template>
      </nav>

      <!-- Toggle Button -->
      <button 
        @click="sidebarOpen = !sidebarOpen"
        class="hidden lg:flex absolute -right-3 top-24 w-6 h-6 bg-white rounded-full shadow-lg items-center justify-center hover:scale-110 transition-transform"
      >
        <svg 
          class="w-4 h-4 text-slate-600 transition-transform" 
          :class="{ 'rotate-180': !sidebarOpen }"
          fill="none" 
          stroke="currentColor" 
          viewBox="0 0 24 24"
        >
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7" />
        </svg>
      </button>
    </aside>

    <!-- ===================== MAIN CONTENT ===================== -->
    <div :class="['transition-all duration-300 ml-0', sidebarOpen ? 'lg:ml-64' : 'lg:ml-20']">
      
      <!-- Header -->
      <header class="h-14 lg:h-16 bg-white border-b border-slate-200 sticky top-0 z-30">
        <div class="h-full px-4 lg:px-6 flex items-center justify-between">
          <div class="flex items-center gap-2 lg:gap-4">
             <!-- Desktop sidebar toggle -->
             <button @click="sidebarOpen = !sidebarOpen" class="hidden lg:block p-2 rounded-lg hover:bg-slate-100 transition-colors">
                <span class="material-symbols-outlined text-slate-600">menu</span>
             </button>
             <h1 class="text-sm lg:text-lg font-bold text-slate-900 tracking-tight truncate max-w-[200px] lg:max-w-none">{{ title }}</h1>
          </div>

          <div class="flex items-center gap-1 lg:gap-4">
            <!-- Notifications -->
            <div class="relative">
              <button 
                @click="showNotifications = !showNotifications"
                class="flex h-10 w-10 items-center justify-center rounded-full hover:bg-slate-100 transition-colors relative"
              >
                <span class="material-symbols-outlined text-slate-600">notifications</span>
                <span v-if="unreadCount > 0" class="absolute top-2 right-2 w-2 h-2 bg-rose-500 rounded-full border border-white"></span>
              </button>

              <!-- Notifications Dropdown -->
              <div 
                v-if="showNotifications"
                class="fixed inset-x-0 top-14 bottom-0 lg:absolute lg:inset-auto lg:right-0 lg:top-auto lg:mt-3 lg:w-96 lg:bottom-auto lg:rounded-2xl bg-white shadow-2xl border-t lg:border border-slate-100 z-50 overflow-hidden lg:ring-1 lg:ring-black/5"
              >
                 <div class="px-5 py-4 border-b border-slate-50 flex items-center justify-between bg-slate-50/50">
                    <h3 class="text-xs font-black text-slate-900 uppercase tracking-widest">Notificaciones</h3>
                    <div class="flex items-center gap-3">
                      <button @click="markAllRead" class="text-[10px] font-bold text-brand-blue hover:underline uppercase">Marcar leídas</button>
                      <button @click="showNotifications = false" class="lg:hidden p-1 rounded-lg hover:bg-slate-200 transition-colors">
                        <span class="material-symbols-outlined text-slate-500 text-lg">close</span>
                      </button>
                    </div>
                 </div>

                 <div class="max-h-[calc(100vh-120px)] lg:max-h-[400px] overflow-y-auto">
                    <div 
                        v-for="notif in notifications" 
                        :key="notif.id" 
                        class="px-5 py-4 hover:bg-slate-50 cursor-pointer border-b border-slate-50 last:border-0 transition-colors flex gap-4 active:bg-slate-100"
                        :class="{ 'bg-blue-50/30': !notif.leida }"
                        @click="handleNotificationClick(notif)"
                    >
                        <div class="w-10 h-10 rounded-xl flex-shrink-0 flex items-center justify-center"
                            :class="getNotifBg(notif.tipo)"
                        >
                            <span class="material-symbols-outlined text-sm">{{ getNotifIcon(notif.tipo) }}</span>
                        </div>
                        <div class="flex-1 min-w-0">
                            <p class="text-xs font-semibold text-slate-800 leading-normal mb-1">{{ notif.mensaje }}</p>
                            <div class="flex items-center gap-2">
                                <span class="text-[10px] text-slate-400 font-medium">{{ formatTime(notif.created_at) }}</span>
                                <span v-if="notif.caso" class="text-[10px] font-bold text-brand-blue uppercase tracking-tighter">#{{ notif.caso.numero_reclamo }}</span>
                            </div>
                        </div>
                        <div v-if="!notif.leida" class="w-2 h-2 rounded-full bg-brand-blue self-center flex-shrink-0"></div>
                    </div>

                    <div v-if="notifications.length === 0" class="py-12 text-center">
                        <span class="material-symbols-outlined text-slate-200 text-4xl mb-2">notifications_off</span>
                        <p class="text-xs text-slate-400 italic">No hay notificaciones recientes</p>
                    </div>
                 </div>
                 
                 <div class="p-3 bg-slate-50 border-t border-slate-100 text-center">
                    <Link :href="route('dashboard')" @click="showNotifications = false" class="text-[10px] font-bold text-slate-500 hover:text-slate-800 uppercase tracking-widest">Ver todas las actividades</Link>
                 </div>
              </div>
            </div>

            <!-- Chat Toggle (desktop only) -->
            <div class="hidden lg:flex items-center gap-2">
              <span class="material-symbols-outlined text-slate-400 text-lg">forum</span>
              <button
                @click="toggleChat"
                :class="chatEnabled ? 'bg-blue-600' : 'bg-slate-300'"
                class="relative inline-flex h-5 w-9 items-center rounded-full transition-colors duration-200 flex-shrink-0"
              >
                <span
                  :class="chatEnabled ? 'translate-x-[18px]' : 'translate-x-[2px]'"
                  class="inline-block h-4 w-4 transform rounded-full bg-white shadow transition-transform duration-200"
                />
              </button>
            </div>

            <!-- Separator (desktop only) -->
            <div class="hidden lg:block h-8 w-[1px] bg-slate-200 mx-1"></div>

            <!-- User Dropdown Menu -->
            <div class="relative pl-1">
              <!-- Overlay to close dropdown when clicking outside -->
              <div v-if="userMenuOpen" class="fixed inset-0 z-40 bg-transparent" @click="userMenuOpen = false"></div>

              <div 
                @click="userMenuOpen = !userMenuOpen"
                class="flex items-center gap-3 cursor-pointer select-none hover:opacity-80 transition-opacity relative z-50"
              >
                <div class="hidden lg:flex flex-col items-end">
                  <span class="text-sm font-semibold text-slate-900 leading-tight">{{ page.props.auth.user.name }}</span>
                  <span class="text-xs text-slate-500 mt-0.5">{{ page.props.auth.user.rol === 'admin' ? 'Administrador' : 'Ejecutivo' }}</span>
                </div>
                <div class="h-9 w-9 lg:h-10 lg:w-10 rounded-full bg-slate-100 flex items-center justify-center overflow-hidden shadow-sm border border-slate-200">
                  <img 
                    v-if="page.props.auth.user.avatar" 
                    :src="page.props.auth.user.avatar.startsWith('http') ? page.props.auth.user.avatar : '/storage/' + page.props.auth.user.avatar" 
                    :alt="page.props.auth.user.name" 
                    class="h-full w-full object-cover"
                  >
                  <img 
                    v-else-if="page.props.auth.user.profile_photo_url" 
                    :src="page.props.auth.user.profile_photo_url" 
                    :alt="page.props.auth.user.name" 
                    class="h-full w-full object-cover"
                  >
                  <img 
                    v-else 
                    src="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 64 64' fill='none'><circle cx='32' cy='32' r='32' fill='%23f1f5f9'/><path d='M50 52c0-5.5-4.5-10-10-10H24c-5.5 0-10 4.5-10 10' stroke='%2394a3b8' stroke-width='4' stroke-linecap='round'/><circle cx='32' cy='24' r='8' fill='%2394a3b8'/></svg>" 
                    :alt="page.props.auth.user.name" 
                    class="h-full w-full object-cover"
                  >
                </div>
              </div>

              <!-- Dropdown Panel -->
              <transition name="slide-up">
                <div 
                  v-if="userMenuOpen" 
                  class="absolute right-0 mt-2 w-56 bg-white border border-slate-100 rounded-2xl shadow-xl z-50 py-2 overflow-hidden transform origin-top-right"
                >
                  <!-- Header with User details (for mobile viewports) -->
                  <div class="px-4 py-3 border-b border-slate-50 lg:hidden">
                    <p class="text-sm font-bold text-slate-800 truncate">{{ page.props.auth.user.name }}</p>
                    <p class="text-xs text-slate-500 mt-0.5">{{ page.props.auth.user.rol === 'admin' ? 'Administrador' : 'Ejecutivo' }}</p>
                  </div>

                  <!-- Actions -->
                  <Link 
                    :href="route('logout')" 
                    method="post" 
                    as="button"
                    @click="userMenuOpen = false"
                    class="w-full flex items-center gap-3 px-4 py-3 text-left text-sm font-medium text-rose-600 hover:bg-rose-50/50 transition-colors"
                  >
                    <span class="material-symbols-outlined text-lg text-rose-500">logout</span>
                    Cerrar Sesión
                  </Link>
                </div>
              </transition>
            </div>
          </div>
        </div>
      </header>

      <!-- Stats (desktop only — on mobile stats go inside page content) -->
      <div class="hidden lg:block p-4 md:p-8">
        <div class="grid grid-cols-4 gap-6">
          <div 
            v-for="stat in stats" 
            :key="stat.label"
            class="bg-white rounded-2xl p-6 shadow-sm hover:shadow-md transition-shadow duration-300"
          >
            <div class="flex items-center justify-between">
              <div :class="['w-12 h-12 rounded-xl flex items-center justify-center', colorClasses[stat.color]]">
                <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="stat.icon" />
                </svg>
              </div>
              <span class="text-3xl font-bold text-slate-800">{{ stat.value }}</span>
            </div>
            <p class="mt-4 text-sm font-medium text-slate-500">{{ stat.label }}</p>
          </div>
        </div>
      </div>

      <!-- Mobile Stats (compact horizontal scroll) -->
      <div class="lg:hidden px-4 pt-3 pb-1">
        <div class="flex gap-2 overflow-x-auto hide-scrollbar">
          <div 
            v-for="stat in stats" 
            :key="stat.label"
            class="flex items-center gap-2 bg-white rounded-xl px-3 py-2 shadow-sm flex-shrink-0 border border-slate-100"
          >
            <div :class="['w-7 h-7 rounded-lg flex items-center justify-center', colorClasses[stat.color]]">
              <svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" :d="stat.icon" />
              </svg>
            </div>
            <div>
              <span class="text-sm font-bold text-slate-800 leading-none">{{ stat.value }}</span>
              <p class="text-[9px] text-slate-500 font-medium leading-none mt-0.5">{{ stat.label }}</p>
            </div>
          </div>
        </div>
      </div>

      <!-- Page Content -->
      <div class="p-4 lg:p-8 pb-24 lg:pb-8">
        <div class="bg-white rounded-xl lg:rounded-2xl shadow-sm p-4 lg:p-8">
          <slot />
        </div>
      </div>
    </div>

    <!-- ===================== MOBILE BOTTOM TAB BAR ===================== -->
    <nav class="fixed bottom-0 left-0 right-0 z-50 lg:hidden bg-white border-t border-slate-200 safe-bottom">
      <div class="flex items-stretch justify-around">
        <template v-for="tab in bottomTabs" :key="tab.name">
          <Link 
            v-if="tab.route"
            :href="route(tab.route)"
            class="flex flex-col items-center justify-center py-2 px-1 flex-1 transition-colors duration-150 relative"
            :class="isActive(tab.route) ? 'text-blue-600' : 'text-slate-400'"
          >
            <!-- Active indicator dot -->
            <span v-if="isActive(tab.route)" class="absolute top-0 left-1/2 -translate-x-1/2 w-5 h-0.5 bg-blue-600 rounded-full"></span>
            <span class="material-symbols-outlined text-xl leading-none" :class="isActive(tab.route) ? 'font-bold' : ''">{{ tab.icon }}</span>
            <span class="text-[10px] font-semibold mt-0.5 leading-tight">{{ tab.name }}</span>
            <!-- Badge for Casos -->
            <span 
              v-if="tab.route === 'casos.index' && page.props.global_stats?.pendientes > 0" 
              class="absolute top-1 right-1/2 translate-x-3 min-w-[16px] h-4 bg-rose-500 text-white text-[9px] font-bold rounded-full flex items-center justify-center px-1"
            >
              {{ page.props.global_stats.pendientes }}
            </span>
          </Link>
          <!-- "Más" button (no Link, just opens menu) -->
          <button 
            v-else
            @click="handleTabClick(tab)"
            class="flex flex-col items-center justify-center py-2 px-1 flex-1 transition-colors duration-150"
            :class="moreMenuOpen ? 'text-blue-600' : 'text-slate-400'"
          >
            <span class="material-symbols-outlined text-xl leading-none">{{ moreMenuOpen ? 'close' : tab.icon }}</span>
            <span class="text-[10px] font-semibold mt-0.5 leading-tight">{{ tab.name }}</span>
          </button>
        </template>
      </div>

      <!-- "Más" flyout menu -->
      <transition name="slide-up">
        <div v-if="moreMenuOpen" class="absolute bottom-full left-0 right-0 bg-white border-t border-slate-200 shadow-[0_-8px_30px_rgba(0,0,0,0.12)] rounded-t-2xl overflow-hidden">
          
          <!-- Primary More Menu Grid -->
          <div class="grid grid-cols-3 gap-1 p-4">
            <template v-for="item in moreMenuItems" :key="item.name">
              <!-- Route link (no children) -->
              <Link 
                v-if="item.route"
                :href="route(item.route)"
                @click="closeAllMenus"
                class="flex flex-col items-center justify-center py-4 rounded-xl transition-all duration-150 active:scale-95"
                :class="isActive(item.route) ? 'bg-blue-50 text-blue-600' : 'text-slate-600 hover:bg-slate-50'"
              >
                <span class="material-symbols-outlined text-2xl mb-1">{{ item.icon }}</span>
                <span class="text-[11px] font-semibold">{{ item.name }}</span>
              </Link>
              
              <!-- Collapsible parent (has children) -->
              <button 
                v-else
                @click="handleMoreItemClick(item)"
                class="flex flex-col items-center justify-center py-4 rounded-xl transition-all duration-150 active:scale-95"
                :class="expandedMenuItem === item.name ? 'bg-slate-100 text-blue-600 font-bold' : 'text-slate-600 hover:bg-slate-50'"
              >
                <span class="material-symbols-outlined text-2xl mb-1">{{ item.icon }}</span>
                <span class="text-[11px] font-semibold flex items-center gap-0.5">
                  {{ item.name }}
                  <span class="material-symbols-outlined text-[12px] transition-transform duration-200" :class="{ 'rotate-180': expandedMenuItem === item.name }">expand_more</span>
                </span>
              </button>
            </template>
          </div>

          <!-- Collapsible Submenu Panel -->
          <transition name="slide-down">
            <div v-if="expandedMenuItem" class="border-t border-slate-100 bg-slate-50/50 p-4 max-h-[260px] overflow-y-auto">
              <h4 class="text-[10px] font-black text-slate-400 uppercase tracking-widest mb-3 px-2">Submenús de {{ expandedMenuItem }}</h4>
              <div class="grid grid-cols-2 gap-2">
                <Link 
                  v-for="sub in getChildren(expandedMenuItem)"
                  :key="sub.name"
                  :href="route(sub.route)"
                  @click="closeAllMenus"
                  class="flex items-center gap-3 p-3 bg-white border border-slate-100 rounded-xl shadow-sm transition-all duration-150 active:scale-95 hover:border-slate-200 text-slate-700"
                  :class="isActive(sub.route) ? 'border-blue-500 bg-blue-50/20 text-blue-600' : ''"
                >
                  <div class="w-8 h-8 rounded-lg bg-blue-50 text-blue-600 flex items-center justify-center flex-shrink-0">
                    <span class="material-symbols-outlined text-lg">{{ sub.icon }}</span>
                  </div>
                  <span class="text-xs font-bold leading-tight truncate">{{ sub.name }}</span>
                </Link>
              </div>
            </div>
          </transition>

          <!-- Logout Button -->
          <div class="px-4 pb-3 border-t border-slate-100 pt-3 bg-white">
            <Link 
              :href="route('logout')" 
              method="post" 
              as="button"
              @click="closeAllMenus"
              class="w-full flex items-center justify-center gap-2 py-3 rounded-xl bg-slate-100 text-slate-600 font-semibold text-xs active:bg-slate-200 transition-colors"
            >
              <span class="material-symbols-outlined text-lg">logout</span>
              Cerrar Sesión
            </Link>
          </div>
        </div>
      </transition>
    </nav>

    <!-- Overlay when "Más" menu is open -->
    <transition name="fade">
      <div 
        v-if="moreMenuOpen" 
        class="fixed inset-0 bg-black/30 z-40 lg:hidden" 
        @click="closeAllMenus"
      ></div>
    </transition>
  </div>
</template>

<style scoped>
/* Safe area for phones with notch/gesture bar */
.safe-bottom {
  padding-bottom: env(safe-area-inset-bottom, 0px);
}

/* Slide up animation for "Más" menu */
.slide-up-enter-active,
.slide-up-leave-active {
  transition: transform 0.25s cubic-bezier(0.4, 0, 0.2, 1), opacity 0.2s ease;
}
.slide-up-enter-from,
.slide-up-leave-to {
  transform: translateY(100%);
  opacity: 0;
}

/* Slide down accordion animation for submenu */
.slide-down-enter-active,
.slide-down-leave-active {
  transition: all 0.25s cubic-bezier(0.4, 0, 0.2, 1);
  max-height: 300px;
}
.slide-down-enter-from,
.slide-down-leave-to {
  max-height: 0;
  opacity: 0;
  overflow: hidden;
}

/* Fade for overlay */
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.25s ease;
}
.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}
</style>
