<script setup>
/**
 * MobileNavigationDrawer - Drawer de navegación completo para móviles
 * Hamburger menu con todos los items de navegación del sidebar desktop
 * Touch targets mínimos 44px, tipografía legible, gestos nativos
 */
import { ref, watch, onMounted, onUnmounted } from 'vue';
import { Link, router } from '@inertiajs/vue3';
import UserAvatar from '@/Components/UserAvatar.vue';

const props = defineProps({
    modelValue: {
        type: Boolean,
        default: false,
    },
    navigationItems: {
        type: Array,
        default: () => [],
    },
    user: {
        type: Object,
        default: null,
    },
    title: {
        type: String,
        default: 'Menú',
    },
    accentColor: {
        type: String,
        default: 'indigo', // indigo, neon, green
    },
    logoUrl: {
        type: String,
        default: null,
    },
    logoImg: {
        type: String,
        default: null,
    },
    subtitle: {
        type: String,
        default: null,
    },
});

const emit = defineEmits(['update:modelValue', 'logout', 'navigate']);

// Expanded menus
const expandedMenus = ref({});

const toggleMenu = (name) => {
    expandedMenus.value[name] = !expandedMenus.value[name];
};

const close = () => {
    emit('update:modelValue', false);
};

const navigate = (href) => {
    close();
    emit('navigate', href);
    router.visit(route(href));
};

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

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

// Accent color classes
const accentClasses = {
    indigo: {
        active: 'bg-indigo-50 dark:bg-indigo-900/30 text-indigo-600 dark:text-indigo-400 border-indigo-500',
        icon: 'text-indigo-500 dark:text-indigo-400',
        childActive: 'bg-indigo-50 dark:bg-indigo-900/30 text-indigo-600 dark:text-indigo-400',
        header: 'from-indigo-500 to-purple-600',
    },
    neon: {
        active: 'bg-emerald-50 dark:bg-emerald-900/30 text-emerald-600 dark:text-emerald-400 border-emerald-500',
        icon: 'text-emerald-500 dark:text-emerald-400',
        childActive: 'bg-emerald-50 dark:bg-emerald-900/30 text-emerald-600 dark:text-emerald-400',
        header: 'from-emerald-500 to-teal-600',
    },
    green: {
        active: 'bg-green-50 dark:bg-green-900/30 text-green-600 dark:text-green-400 border-green-500',
        icon: 'text-green-500 dark:text-green-400',
        childActive: 'bg-green-50 dark:bg-green-900/30 text-green-600 dark:text-green-400',
        header: 'from-green-500 to-emerald-600',
    },
};

const colors = accentClasses[props.accentColor] || accentClasses.indigo;

// Touch handlers para swipe-to-close
const drawerRef = ref(null);
const translateX = ref(0);
const isDragging = ref(false);
const startX = ref(0);

const handleTouchStart = (e) => {
    isDragging.value = true;
    startX.value = e.touches[0].clientX;
};

const handleTouchMove = (e) => {
    if (!isDragging.value) return;
    const diff = e.touches[0].clientX - startX.value;
    translateX.value = Math.min(0, diff); // Solo permitir deslizar a la izquierda
};

const handleTouchEnd = () => {
    if (!isDragging.value) return;
    isDragging.value = false;
    if (translateX.value < -80) {
        close();
    }
    translateX.value = 0;
};

// Prevenir scroll del body
watch(() => props.modelValue, (isOpen) => {
    if (isOpen) {
        document.body.style.overflow = 'hidden';
        expandedMenus.value = {};
        // Auto-expand menus with active children
        props.navigationItems.forEach(item => {
            if (item.children?.some(c => isActive(c.href))) {
                expandedMenus.value[item.name] = true;
            }
        });
    } else {
        document.body.style.overflow = '';
    }
});

const handleKeydown = (e) => {
    if (e.key === 'Escape' && props.modelValue) close();
};

onMounted(() => document.addEventListener('keydown', handleKeydown));
onUnmounted(() => {
    document.removeEventListener('keydown', handleKeydown);
    document.body.style.overflow = '';
});
</script>

<template>
    <Teleport to="body">
        <!-- Overlay -->
        <Transition
            enter-active-class="transition-opacity duration-300"
            enter-from-class="opacity-0"
            enter-to-class="opacity-100"
            leave-active-class="transition-opacity duration-200"
            leave-from-class="opacity-100"
            leave-to-class="opacity-0"
        >
            <div
                v-if="modelValue"
                class="fixed inset-0 bg-black/50 z-[60]"
                @click="close"
            />
        </Transition>

        <!-- Drawer -->
        <Transition
            enter-active-class="transition-transform duration-300 ease-out"
            enter-from-class="-translate-x-full"
            enter-to-class="translate-x-0"
            leave-active-class="transition-transform duration-250 ease-in"
            leave-from-class="translate-x-0"
            leave-to-class="-translate-x-full"
        >
            <div
                v-if="modelValue"
                ref="drawerRef"
                class="fixed top-0 left-0 bottom-0 w-[85vw] max-w-[320px] bg-white dark:bg-gray-900 shadow-2xl z-[61] flex flex-col"
                :style="{
                    transform: `translateX(${translateX}px)`,
                    transition: isDragging ? 'none' : undefined,
                    paddingTop: 'env(safe-area-inset-top, 0px)',
                }"
                @touchstart="handleTouchStart"
                @touchmove="handleTouchMove"
                @touchend="handleTouchEnd"
            >
                <!-- Header del Drawer -->
                <div :class="['flex items-center justify-between px-5 py-4 border-b border-gray-200 dark:border-gray-700 bg-gradient-to-r text-white', `${colors.header}`]">
                    <div class="flex items-center gap-3 min-w-0">
                        <img v-if="logoImg" :src="logoImg" alt="Logo" class="h-9 max-w-[120px] object-contain dark:brightness-0 dark:invert" />
                        <template v-else>
                            <div class="w-9 h-9 bg-white/20 rounded-xl flex items-center justify-center flex-shrink-0">
                                <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="text-lg font-bold truncate">{{ title }}</span>
                        </template>
                    </div>
                    <button
                        @click="close"
                        class="w-10 h-10 flex items-center justify-center rounded-xl bg-white/20 hover:bg-white/30 active:bg-white/10 transition-colors touch-manipulation"
                        aria-label="Cerrar menú"
                    >
                        <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="M6 18L18 6M6 6l12 12" />
                        </svg>
                    </button>
                </div>

                <!-- Subtitle / Info -->
                <div v-if="subtitle" class="px-5 py-3 bg-gray-50 dark:bg-gray-800/50 border-b border-gray-200 dark:border-gray-700">
                    <p class="text-sm text-gray-600 dark:text-gray-400">{{ subtitle }}</p>
                </div>

                <!-- Navigation Items -->
                <nav class="flex-1 overflow-y-auto overscroll-contain px-3 py-3">
                    <div class="space-y-1">
                        <template v-for="item in navigationItems" :key="item.name">
                            <!-- Item con hijos (submenu) -->
                            <div v-if="item.children">
                                <button
                                    @click="toggleMenu(item.name)"
                                    class="w-full flex items-center justify-between min-h-[48px] px-4 py-3 text-base font-medium rounded-xl transition-all duration-200 touch-manipulation"
                                    :class="[
                                        expandedMenus[item.name] || item.children.some(c => isActive(c.href))
                                            ? 'bg-gray-100 dark:bg-gray-800 text-gray-900 dark:text-white'
                                            : 'text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-800 active:bg-gray-100 dark:active:bg-gray-700'
                                    ]"
                                >
                                    <div class="flex items-center gap-3">
                                        <svg
                                            :class="[
                                                item.children.some(c => isActive(c.href)) ? colors.icon : 'text-gray-400 dark:text-gray-500',
                                                'h-6 w-6 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>{{ item.name }}</span>
                                    </div>
                                    <svg :class="['w-5 h-5 transition-transform duration-200', 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>
                                <!-- Hijos -->
                                <div v-if="expandedMenus[item.name] || item.children.some(c => isActive(c.href))"
                                    class="mt-1 ml-6 pl-4 border-l-2 border-gray-200 dark:border-gray-700 space-y-1">
                                    <button
                                        v-for="child in item.children"
                                        :key="child.name"
                                        @click="navigate(child.href)"
                                        class="w-full text-left flex items-center min-h-[44px] px-4 py-2.5 text-[15px] rounded-xl transition-all duration-200 touch-manipulation"
                                        :class="[
                                            isActive(child.href)
                                                ? colors.childActive + ' font-semibold'
                                                : 'text-gray-600 dark:text-gray-400 hover:bg-gray-50 dark:hover:bg-gray-800 active:bg-gray-100'
                                        ]"
                                    >
                                        {{ child.name }}
                                    </button>
                                </div>
                            </div>

                            <!-- Item simple -->
                            <button
                                v-else
                                @click="navigate(item.href)"
                                class="w-full flex items-center gap-3 min-h-[48px] px-4 py-3 text-base font-medium rounded-xl transition-all duration-200 touch-manipulation"
                                :class="[
                                    isActive(item.href)
                                        ? colors.active + ' border-l-4 font-semibold'
                                        : 'text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-800 active:bg-gray-100 dark:active:bg-gray-700 border-l-4 border-transparent'
                                ]"
                            >
                                <svg
                                    :class="[
                                        isActive(item.href) ? colors.icon : 'text-gray-400 dark:text-gray-500',
                                        'h-6 w-6 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 class="flex-1 truncate">{{ item.name }}</span>
                                <!-- Badge -->
                                <span
                                    v-if="item.badge"
                                    class="ml-2 min-w-[24px] h-6 px-2 flex items-center justify-center text-xs font-bold text-white bg-red-500 rounded-full"
                                >
                                    {{ item.badge > 99 ? '99+' : item.badge }}
                                </span>
                            </button>
                        </template>
                    </div>
                </nav>

                <!-- Footer: User info + Logout -->
                <div class="flex-shrink-0 border-t border-gray-200 dark:border-gray-700 px-4 py-4" style="padding-bottom: calc(env(safe-area-inset-bottom, 8px) + 1rem);">
                    <div class="flex items-center justify-between">
                        <div class="flex items-center gap-3 min-w-0 flex-1">
                            <UserAvatar
                                :src="user?.avatar_url"
                                :name="user?.name || 'Usuario'"
                                :size="40"
                                border="border-2 border-gray-200 dark:border-gray-700"
                            />
                            <div class="min-w-0 flex-1">
                                <p class="text-sm font-semibold 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="handleLogout"
                            class="flex-shrink-0 flex items-center gap-2 px-3 py-2 min-h-[44px] 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-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>
                            Salir
                        </button>
                    </div>
                </div>
            </div>
        </Transition>
    </Teleport>
</template>

<style scoped>
/* Smooth overscroll for navigation */
nav {
    -webkit-overflow-scrolling: touch;
    overscroll-behavior-y: contain;
}
</style>
