<script setup lang="ts">
import { Link, usePage } from '@inertiajs/vue3';
import { computed, ref, onMounted } from 'vue';
import { useAuth } from '@/Composables/useAuth';
import { 
    Menu, 
    ChevronRight, 
    Home, 
    PanelLeftClose, 
    PanelLeftOpen,
    Sun,
    Moon
} from 'lucide-vue-next';
import { 
    DropdownMenuRoot, 
    DropdownMenuTrigger, 
    DropdownMenuPortal, 
    DropdownMenuContent, 
    DropdownMenuItem, 
    DropdownMenuSeparator,
    AvatarRoot,
    AvatarImage,
    AvatarFallback
} from 'radix-vue';

defineProps<{
    isSidebarCollapsed: boolean;
}>();

const emit = defineEmits<{
    (e: 'toggleSidebar'): void;
    (e: 'toggleMobileSidebar'): void;
}>();

const { user } = useAuth();
const page = usePage();

const isDark = ref(false);

onMounted(() => {
    isDark.value = document.documentElement.classList.contains('dark');
});

const toggleTheme = () => {
    if (document.documentElement.classList.contains('dark')) {
        document.documentElement.classList.remove('dark');
        localStorage.setItem('theme', 'light');
        isDark.value = false;
    } else {
        document.documentElement.classList.add('dark');
        localStorage.setItem('theme', 'dark');
        isDark.value = true;
    }
};

// Generate dynamic breadcrumbs based on URL path segments
const breadcrumbs = computed(() => {
    const segments = page.url.split('?')[0].split('/').filter(Boolean);
    return segments.map((segment, index) => {
        const url = '/' + segments.slice(0, index + 1).join('/');
        const isLast = index === segments.length - 1;
        
        // Capitalize segment and clean up delimiters
        let label = segment.replace(/-/g, ' ').replace(/_/g, ' ');
        label = label.charAt(0).toUpperCase() + label.slice(1);
        
        // Custom overrides for cleaner naming
        if (label.toLowerCase() === 'rbac') {
            label = 'RBAC Security';
        }
        
        return { label, url, isLast };
    });
});
</script>

<template>
    <header class="sticky top-0 z-30 h-16 w-full border-b border-slate-200 dark:border-slate-800 bg-white/80 dark:bg-slate-950/80 backdrop-blur-md flex items-center justify-between px-4">
        <!-- Left Section: Toggle Buttons & Breadcrumbs -->
        <div class="flex items-center gap-3">
            <!-- Mobile Burger (hidden on desktop) -->
            <button
                @click="emit('toggleMobileSidebar')"
                class="md:hidden h-9 w-9 rounded-lg hover:bg-slate-100 dark:hover:bg-slate-900 flex items-center justify-center text-slate-500 dark:text-slate-400 cursor-pointer"
            >
                <Menu class="h-5 w-5" />
            </button>

            <!-- Desktop Sidebar Collapse Toggle -->
            <button
                @click="emit('toggleSidebar')"
                class="hidden md:flex h-9 w-9 rounded-lg hover:bg-slate-100 dark:hover:bg-slate-900 items-center justify-center text-slate-500 dark:text-slate-400 cursor-pointer"
            >
                <PanelLeftClose v-if="!isSidebarCollapsed" class="h-5 w-5" />
                <PanelLeftOpen v-else class="h-5 w-5" />
            </button>

            <!-- Divider -->
            <span class="hidden md:block h-4 w-px bg-slate-200 dark:bg-slate-800" />

            <!-- Dynamic Breadcrumbs -->
            <nav aria-label="Breadcrumb" class="hidden md:flex items-center text-xs font-medium text-slate-500 dark:text-slate-400">
                <ol class="flex items-center gap-1.5">
                    <li>
                        <Link 
                            :href="route('dashboard')" 
                            class="hover:text-slate-900 dark:hover:text-slate-100 flex items-center"
                        >
                            <Home class="h-3.5 w-3.5" />
                        </Link>
                    </li>

                    <li v-for="(breadcrumb, idx) in breadcrumbs" :key="idx" class="flex items-center gap-1.5">
                        <ChevronRight class="h-3 w-3 text-slate-300 dark:text-slate-600" />
                        <Link
                            v-if="!breadcrumb.isLast"
                            :href="breadcrumb.url"
                            class="hover:text-slate-900 dark:hover:text-slate-100 transition-colors"
                        >
                            {{ breadcrumb.label }}
                        </Link>
                        <span v-else class="font-semibold text-slate-900 dark:text-slate-100">
                            {{ breadcrumb.label }}
                        </span>
                    </li>
                </ol>
            </nav>
        </div>

        <!-- Right Section: User Profile Dropdown -->
        <div class="flex items-center gap-4">
            <!-- Theme Toggle Button -->
            <button
                @click="toggleTheme"
                class="h-9 w-9 rounded-lg hover:bg-slate-100 dark:hover:bg-slate-900 flex items-center justify-center text-slate-500 dark:text-slate-400 cursor-pointer transition-colors"
                aria-label="Toggle Theme"
            >
                <Sun v-if="isDark" class="h-5 w-5 text-amber-500" />
                <Moon v-else class="h-5 w-5 text-slate-600 dark:text-slate-400" />
            </button>

            <DropdownMenuRoot>
                <DropdownMenuTrigger class="focus:outline-none cursor-pointer flex items-center gap-2.5 text-left select-none group">
                    <AvatarRoot class="h-9 w-9 rounded-full bg-slate-100 dark:bg-slate-800 flex items-center justify-center text-sm font-semibold border border-slate-200 dark:border-slate-800 overflow-hidden hover:opacity-90 transition-opacity">
                        <!-- If user had avatar image we would load it here -->
                        <AvatarImage src="" alt="Avatar" class="h-full w-full object-cover" />
                        <AvatarFallback class="text-red-600 dark:text-red-400 uppercase">
                            {{ user()?.name?.charAt(0) ?? 'U' }}
                        </AvatarFallback>
                    </AvatarRoot>
                    <div class="hidden sm:flex flex-col min-w-0">
                        <span class="text-xs font-semibold text-slate-700 dark:text-slate-300 leading-none truncate max-w-[150px] group-hover:text-slate-900 dark:group-hover:text-slate-100 transition-colors">
                            {{ user()?.name }}
                        </span>
                        <span class="text-[10px] text-slate-400 dark:text-slate-500 truncate mt-1 leading-none max-w-[150px]">
                            {{ user()?.email }}
                        </span>
                    </div>
                </DropdownMenuTrigger>
                <DropdownMenuPortal>
                    <DropdownMenuContent 
                        class="z-50 min-w-[220px] bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-lg p-1.5 shadow-lg shadow-slate-200/50 dark:shadow-none animate-in fade-in slide-in-from-top-1 duration-200"
                        :align="'end'"
                        :side-offset="8"
                    >
                        <!-- User Identity header -->
                        <div class="px-2 py-2 flex flex-col">
                            <span class="font-semibold text-sm text-slate-800 dark:text-slate-200 leading-none truncate">{{ user()?.name }}</span>
                            <span class="text-xs text-slate-400 dark:text-slate-500 truncate mt-1 leading-none">{{ user()?.email }}</span>
                            <div class="mt-2 flex flex-wrap gap-1">
                                <span 
                                    v-for="role in user()?.roles"
                                    :key="role"
                                    class="inline-flex items-center px-1.5 py-0.5 rounded-full text-[9px] font-semibold bg-red-50 dark:bg-red-950/40 text-red-600 dark:text-red-400 border border-red-100 dark:border-red-900/30 leading-none"
                                >
                                    {{ role }}
                                </span>
                            </div>
                        </div>
                        
                        <DropdownMenuSeparator class="h-px bg-slate-200 dark:bg-slate-800 my-1" />
                        
                        <!-- Actions -->
                        <DropdownMenuItem class="cursor-pointer select-none rounded-md px-2 py-1.5 text-xs hover:bg-slate-50 dark:hover:bg-slate-800 focus:bg-slate-50 dark:focus:bg-slate-800 focus:outline-none text-slate-700 dark:text-slate-300">
                            <Link :href="route('profile.edit')" class="w-full h-full block">My Profile</Link>
                        </DropdownMenuItem>
                        <DropdownMenuItem class="cursor-pointer select-none rounded-md px-2 py-1.5 text-xs hover:bg-slate-50 dark:hover:bg-slate-800 focus:bg-slate-50 dark:focus:bg-slate-800 focus:outline-none text-slate-700 dark:text-slate-300">
                            <Link :href="route('settings.edit')" class="w-full h-full block">System Settings</Link>
                        </DropdownMenuItem>
                        
                        <DropdownMenuSeparator class="h-px bg-slate-200 dark:bg-slate-800 my-1" />
                        
                        <DropdownMenuItem class="cursor-pointer select-none rounded-md px-2 py-1.5 text-xs hover:bg-rose-50 dark:hover:bg-rose-950/20 focus:bg-rose-50 dark:focus:bg-rose-950/20 focus:outline-none text-rose-600">
                            <Link :href="route('logout')" method="post" as="button" class="w-full text-left h-full block font-medium">
                                Log Out
                            </Link>
                        </DropdownMenuItem>
                    </DropdownMenuContent>
                </DropdownMenuPortal>
            </DropdownMenuRoot>
        </div>
    </header>
</template>
