<template>
    <nav
        id="topnav"
        class="ud-header relative z-40 flex w-full items-center border-b border-slate-200 bg-white transition-colors duration-200 dark:border-slate-700 dark:bg-slate-900"
    >
        <div class="container">
            <div class="relative flex min-h-[3.5rem] items-center justify-between lg:px-4">
                <!-- Logo -->
                <div class="relative z-10 flex-shrink-0 px-2 lg:px-0">
                    <Link :href="route('home')" class="logo flex items-center py-2">
                        <Logo class="help-desk-logo h-8 w-auto dark:hidden" />
                        <Logo name="white" class="help-desk-logo white hidden h-8 w-auto dark:block" />
                    </Link>
                </div>

                <!-- Desktop navigation (viewport-centered) -->
                <nav
                    class="pointer-events-none absolute left-1/2 hidden -translate-x-1/2 lg:block"
                    aria-label="Main navigation"
                >
                    <ul class="flex items-center gap-0.5 xl:gap-1">
                        <li
                            v-for="item in desktopNavLinks"
                            :key="item.id || item.active_key || item.href"
                            class="pointer-events-auto group"
                            :class="{ active: isMenuActive(item) }"
                        >
                            <component
                                :is="isExternalLink(item) ? 'a' : Link"
                                :href="item.href"
                                :target="item.target === '_blank' ? '_blank' : undefined"
                                :rel="item.target === '_blank' ? 'noopener noreferrer' : undefined"
                                :aria-current="isMenuActive(item) ? 'page' : undefined"
                                :title="isKnowledgeBaseItem(item) ? $t('Knowledge Base') : undefined"
                                class="nav-link ud-menu-scroll inline-flex items-center rounded-lg px-2.5 py-2 text-sm font-medium transition-colors duration-200 focus:outline-none focus-visible:ring-2 focus-visible:ring-primary focus-visible:ring-offset-2 lg:px-2 xl:px-3"
                                :class="isMenuActive(item) ? navLinkClassActive : navLinkClassDefault"
                                @click="setActiveMenu(item)"
                            >
                                <template v-if="isKnowledgeBaseItem(item)">
                                    <span class="xl:hidden">{{ $t('KB') }}</span>
                                    <span class="hidden xl:inline">{{ $t('Knowledge Base') }}</span>
                                </template>
                                <template v-else>
                                    {{ $t(item.label) }}
                                </template>
                            </component>
                        </li>
                        <li v-if="submitTicketItem" class="pointer-events-auto ml-1 border-l border-slate-200 pl-1.5 xl:ml-2 xl:pl-2 dark:border-slate-700">
                            <Link
                                :href="submitTicketItem.href"
                                :aria-current="isMenuActive(submitTicketItem) ? 'page' : undefined"
                                class="header-nav-cta inline-flex items-center rounded-lg px-3 py-2 text-sm font-semibold text-white shadow-sm transition-colors duration-200 focus:outline-none focus-visible:ring-2 focus-visible:ring-primary focus-visible:ring-offset-2 xl:px-4"
                                :class="isMenuActive(submitTicketItem)
                                    ? 'bg-primary-700 shadow-md ring-2 ring-primary/30 ring-offset-2'
                                    : 'bg-primary hover:bg-primary-600'"
                                @click="setActiveMenu(submitTicketItem)"
                            >
                                <span class="text-white xl:hidden">{{ $t('Submit') }}</span>
                                <span class="hidden text-white xl:inline">{{ $t(submitTicketItem.label) }}</span>
                            </Link>
                        </li>
                    </ul>
                </nav>

                <!-- Desktop actions -->
                <div class="relative z-20 hidden items-center gap-3 lg:flex">
                    <dropdown class="language_menu_wrapper" placement="bottom-end">
                        <template #default>
                            <div class="language_menu group flex cursor-pointer items-center gap-1.5 rounded-lg px-2.5 py-2 text-sm font-medium text-slate-600 transition-colors duration-200 hover:bg-slate-50 focus:outline-none focus-visible:ring-2 focus-visible:ring-primary focus-visible:ring-offset-2 dark:text-slate-300 dark:hover:bg-slate-800">
                                <icon class="h-4 w-4 flex-shrink-0" :name="selected_language.code" />
                                <span class="language_text">{{ selected_language.name }}</span>
                                <icon class="drop-down-caret-icon h-4 w-4 flex-shrink-0 fill-slate-400 group-hover:fill-primary dark:fill-slate-500" name="cheveron-down" />
                            </div>
                        </template>
                        <template #dropdown>
                            <div class="language_menu_list min-w-[10rem] overflow-hidden rounded-xl border border-slate-200 bg-white py-1 text-sm shadow-lg dark:border-slate-700 dark:bg-slate-800 dark:shadow-slate-950/50">
                                <div
                                    v-for="language in languages_except_selected"
                                    :key="language.code"
                                    class="mx-1 flex cursor-pointer gap-2 rounded-lg px-3 py-2 text-slate-700 transition-colors duration-200 hover:bg-slate-50 hover:text-primary dark:text-slate-200 dark:hover:bg-slate-700"
                                    @click="updateLanguage(language.code)"
                                >
                                    <icon class="h-4 w-4 flex-shrink-0" :name="language.code" />
                                    <span class="lang_name">{{ language.name }}</span>
                                </div>
                            </div>
                        </template>
                    </dropdown>

                    <div v-if="$page.props.auth && $page.props.auth.user">
                        <dropdown class="select_user" placement="bottom-end">
                            <template #default>
                                <div class="group flex cursor-pointer items-center rounded-lg p-1 transition-colors duration-200 hover:bg-slate-50 focus:outline-none focus-visible:ring-2 focus-visible:ring-primary focus-visible:ring-offset-2 dark:hover:bg-slate-800">
                                    <img
                                        v-if="$page.props.auth?.user?.photo"
                                        class="user_photo h-8 w-8 rounded-full object-cover ring-2 ring-slate-200 dark:ring-slate-600"
                                        :alt="$page.props.auth?.user?.first_name || 'User'"
                                        :src="$page.props.auth?.user?.photo"
                                    />
                                    <img
                                        v-else
                                        src="/images/svg/profile.svg"
                                        class="h-8 w-8 rounded-full object-cover ring-2 ring-slate-200 dark:ring-slate-600"
                                        alt="user profile"
                                    />
                                    <icon class="drop-down-caret-icon ml-1 h-4 w-4 flex-shrink-0 fill-slate-400 group-hover:fill-primary dark:fill-slate-500" name="cheveron-down" />
                                </div>
                            </template>
                            <template #dropdown>
                                <div class="min-w-[12rem] overflow-hidden rounded-xl border border-slate-200 bg-white py-1.5 shadow-lg dark:border-slate-700 dark:bg-slate-800 dark:shadow-slate-950/50">
                                    <Link class="user-dropdown-link flex items-center gap-2.5 px-4 py-2.5 text-slate-700 transition-colors duration-200 hover:bg-slate-50 hover:text-primary dark:text-slate-200 dark:hover:bg-slate-700" :href="route('dashboard')">
                                        <icon name="dashboard" class="h-4 w-4 flex-shrink-0 opacity-80" />{{ $t('Dashboard') }}
                                    </Link>
                                    <Link class="user-dropdown-link flex items-center gap-2.5 px-4 py-2.5 text-slate-700 transition-colors duration-200 hover:bg-slate-50 hover:text-primary dark:text-slate-200 dark:hover:bg-slate-700" :href="route('tickets')">
                                        <icon name="ticket" class="h-4 w-4 flex-shrink-0 opacity-80" />{{ $t('Tickets') }}
                                    </Link>
                                    <Link class="user-dropdown-link flex items-center gap-2.5 px-4 py-2.5 text-slate-700 transition-colors duration-200 hover:bg-slate-50 hover:text-primary dark:text-slate-200 dark:hover:bg-slate-700" :href="route('users.edit.profile')">
                                        <icon name="edit" class="h-4 w-4 flex-shrink-0 opacity-80" />{{ $t('Edit Profile') }}
                                    </Link>
                                    <div class="my-1 border-t border-slate-200 dark:border-slate-600" />
                                    <div class="pt-0.5">
                                        <LogoutButton />
                                    </div>
                                </div>
                            </template>
                        </dropdown>
                    </div>
                    <Link
                        v-else
                        :href="route('login')"
                        class="rounded-lg border border-primary bg-transparent px-5 py-2 text-sm font-semibold text-primary transition-colors duration-200 hover:bg-primary/5 focus:outline-none focus-visible:ring-2 focus-visible:ring-primary focus-visible:ring-offset-2 dark:border-primary dark:text-primary dark:hover:bg-primary/10"
                    >
                        {{ $t('Login') }}
                    </Link>
                </div>

                <!-- Mobile menu toggle -->
                <button
                    type="button"
                    class="mr-4 flex h-11 w-11 flex-col items-center justify-center gap-1.5 rounded-xl border border-slate-200 bg-white text-slate-700 transition-colors hover:bg-slate-50 focus:outline-none focus-visible:ring-2 focus-visible:ring-primary focus-visible:ring-offset-2 dark:border-slate-600 dark:bg-slate-800 dark:text-slate-200 dark:hover:bg-slate-700 lg:hidden"
                    :class="{ 'navbarTogglerActive': mobileMenuOpen }"
                    :aria-expanded="mobileMenuOpen ? 'true' : 'false'"
                    aria-controls="mobileNavDrawer"
                    aria-label="Toggle menu"
                    @click="toggleMobileMenu"
                >
                    <span class="navbarToggler-line navbarToggler-line--top block h-0.5 w-5 rounded-full bg-current transition-all duration-200" />
                    <span class="navbarToggler-line navbarToggler-line--mid block h-0.5 w-5 rounded-full bg-current transition-all duration-200" />
                    <span class="navbarToggler-line navbarToggler-line--bot block h-0.5 w-5 rounded-full bg-current transition-all duration-200" />
                </button>
            </div>
        </div>

        <!-- Mobile drawer -->
        <Teleport to="body">
            <Transition
                enter-active-class="transition duration-300 ease-out"
                enter-from-class="opacity-0"
                enter-to-class="opacity-100"
                leave-active-class="transition duration-200 ease-in"
                leave-from-class="opacity-100"
                leave-to-class="opacity-0"
            >
                <div
                    v-if="mobileMenuOpen"
                    class="fixed inset-0 z-[100] lg:hidden"
                    role="presentation"
                >
                    <button
                        type="button"
                        class="absolute inset-0 bg-slate-900/60 backdrop-blur-sm"
                        aria-label="Close menu"
                        @click="closeMobileMenu"
                    />

                    <aside
                        id="mobileNavDrawer"
                        class="mobile-drawer-panel absolute inset-y-0 right-0 flex h-full max-h-[100dvh] w-full max-w-[min(100vw,22rem)] flex-col border-l border-slate-200 bg-white shadow-2xl dark:border-slate-700 dark:bg-slate-900"
                        role="dialog"
                        aria-modal="true"
                        aria-label="Mobile navigation"
                    >
                            <!-- Drawer header -->
                            <div class="flex items-center justify-between border-b border-slate-200 px-5 py-4 dark:border-slate-700">
                                <div>
                                    <p class="text-xs font-semibold uppercase tracking-wider text-slate-500 dark:text-slate-400">{{ $t('Menu') }}</p>
                                    <p class="text-lg font-bold text-slate-900 dark:text-white">{{ $t('Navigation') }}</p>
                                </div>
                                <button
                                    type="button"
                                    class="flex h-10 w-10 items-center justify-center rounded-xl border border-slate-200 text-slate-600 transition-colors hover:bg-slate-100 dark:border-slate-600 dark:text-slate-300 dark:hover:bg-slate-800"
                                    aria-label="Close menu"
                                    @click="closeMobileMenu"
                                >
                                    <X class="h-5 w-5" />
                                </button>
                            </div>

                            <!-- Nav links -->
                            <nav class="flex min-h-0 flex-1 overflow-y-auto overscroll-contain px-4 py-4" aria-label="Mobile main navigation">
                                <ul class="space-y-1">
                                    <li v-for="item in menuItems" :key="'mobile-' + (item.id || item.active_key || item.href)">
                                        <component
                                            :is="isExternalLink(item) ? 'a' : Link"
                                            :href="item.href"
                                            :target="item.target === '_blank' ? '_blank' : undefined"
                                            :rel="item.target === '_blank' ? 'noopener noreferrer' : undefined"
                                            class="flex min-h-[3rem] items-center gap-3 rounded-xl px-4 py-3 text-base font-medium transition-colors duration-200"
                                            :class="isMobileNavItemPrimary(item)
                                                ? (isMenuActive(item)
                                                    ? 'bg-primary text-white shadow-md shadow-primary/25'
                                                    : 'bg-primary/10 text-primary hover:bg-primary/15 dark:bg-primary/20')
                                                : (isMenuActive(item)
                                                    ? 'bg-slate-100 text-primary dark:bg-slate-800'
                                                    : 'text-slate-700 hover:bg-slate-50 dark:text-slate-200 dark:hover:bg-slate-800/80')"
                                            @click="onMobileNavClick(item)"
                                        >
                                            <span
                                                class="flex h-9 w-9 flex-shrink-0 items-center justify-center rounded-lg"
                                                :class="isMobileNavItemPrimary(item)
                                                    ? (isMenuActive(item) ? 'bg-white/20' : 'bg-primary/15')
                                                    : 'bg-slate-100 dark:bg-slate-800'"
                                            >
                                                <icon v-if="item.icon" :name="item.icon" class="h-4 w-4 opacity-90" />
                                            </span>
                                            <span class="flex-1">{{ $t(item.label) }}</span>
                                            <ArrowRight class="h-4 w-4 flex-shrink-0 opacity-40" />
                                        </component>
                                    </li>
                                </ul>
                            </nav>

                            <!-- Language -->
                            <div class="border-t border-slate-200 px-5 py-4 dark:border-slate-700">
                                <p class="mb-3 text-xs font-semibold uppercase tracking-wider text-slate-500 dark:text-slate-400">{{ $t('Language') }}</p>
                                <div class="-mx-5 overflow-x-auto overscroll-x-contain px-5 pb-1 [-webkit-overflow-scrolling:touch]">
                                    <div class="grid w-max auto-cols-max grid-flow-col grid-rows-2 gap-x-2 gap-y-2">
                                        <button
                                            v-for="language in mobileLanguages"
                                            :key="language.code"
                                            type="button"
                                            class="inline-flex items-center gap-2 rounded-full border px-3 py-1.5 text-sm font-medium whitespace-nowrap transition-colors"
                                            :class="language.code === selected_language.code
                                                ? 'border-primary bg-primary/10 text-primary'
                                                : 'border-slate-200 text-slate-600 hover:border-primary/30 hover:bg-slate-50 dark:border-slate-600 dark:text-slate-300 dark:hover:bg-slate-800'"
                                            @click="language.code !== selected_language.code && updateLanguage(language.code)"
                                        >
                                            <icon class="h-4 w-4 flex-shrink-0" :name="language.code" />
                                            {{ language.name }}
                                        </button>
                                    </div>
                                </div>
                            </div>

                            <!-- Account / login -->
                            <div class="border-t border-slate-200 px-5 py-5 dark:border-slate-700">
                                <div v-if="$page.props.auth && $page.props.auth.user" class="space-y-2">
                                    <p class="mb-3 truncate text-sm font-medium text-slate-900 dark:text-white">
                                        {{ $page.props.auth.user.first_name }} {{ $page.props.auth.user.last_name }}
                                    </p>
                                    <Link
                                        :href="route('dashboard')"
                                        class="flex min-h-[2.75rem] items-center gap-3 rounded-xl px-4 py-2.5 text-sm font-medium text-slate-700 transition-colors hover:bg-slate-50 dark:text-slate-200 dark:hover:bg-slate-800"
                                        @click="closeMobileMenu"
                                    >
                                        <icon name="dashboard" class="h-4 w-4 opacity-80" />
                                        {{ $t('Dashboard') }}
                                    </Link>
                                    <Link
                                        :href="route('tickets')"
                                        class="flex min-h-[2.75rem] items-center gap-3 rounded-xl px-4 py-2.5 text-sm font-medium text-slate-700 transition-colors hover:bg-slate-50 dark:text-slate-200 dark:hover:bg-slate-800"
                                        @click="closeMobileMenu"
                                    >
                                        <icon name="ticket" class="h-4 w-4 opacity-80" />
                                        {{ $t('Tickets') }}
                                    </Link>
                                    <Link
                                        :href="route('users.edit.profile')"
                                        class="flex min-h-[2.75rem] items-center gap-3 rounded-xl px-4 py-2.5 text-sm font-medium text-slate-700 transition-colors hover:bg-slate-50 dark:text-slate-200 dark:hover:bg-slate-800"
                                        @click="closeMobileMenu"
                                    >
                                        <icon name="edit" class="h-4 w-4 opacity-80" />
                                        {{ $t('Edit Profile') }}
                                    </Link>
                                    <div class="pt-1">
                                        <LogoutButton />
                                    </div>
                                </div>
                                <Link
                                    v-else
                                    :href="route('login')"
                                    class="flex w-full items-center justify-center rounded-xl bg-primary px-4 py-3.5 text-base font-semibold text-white shadow-lg shadow-primary/20 transition-colors hover:bg-primary-600"
                                    @click="closeMobileMenu"
                                >
                                    {{ $t('Login') }}
                                </Link>
                            </div>
                        </aside>
                </div>
            </Transition>
        </Teleport>
    </nav>
</template>

<script>
import Logo from '@/Shared/Logo.vue'
import Dropdown from '@/Shared/Dropdown.vue'
import Icon from '@/Shared/Icon.vue'
import LogoutButton from '@/Components/LogoutButton.vue'
import { Link } from '@inertiajs/vue3'
import { loadLanguageAsync, getActiveLanguage } from 'laravel-vue-i18n'
import { parseEnableOptions } from '@/utils/parseEnableOptions'
import { ArrowRight, X } from 'lucide-vue-next'

export default {
    components: {
        Logo,
        Icon,
        Dropdown,
        Link,
        LogoutButton,
        ArrowRight,
        X,
    },
    data() {
        return {
            active_menu: 'home',
            mobileMenuOpen: false,
            locale: this.$page.props.auth?.user?.locale || this.$page.props.locale,
            navLinkClassDefault: 'text-slate-600 hover:bg-slate-50 hover:text-primary dark:text-slate-300 dark:hover:bg-slate-800 dark:hover:text-primary',
            navLinkClassActive: 'bg-primary/15 font-semibold text-primary shadow-sm ring-1 ring-primary/25 dark:bg-primary/25 dark:ring-primary/35',
        }
    },
    computed: {
        menuItems() {
            const items = this.$page.props.header_menu
            return Array.isArray(items) && items.length ? items : this.fallbackMenuItems
        },
        desktopNavLinks() {
            return this.menuItems.filter((item) => !this.isSubmitTicketItem(item))
        },
        submitTicketItem() {
            return this.menuItems.find((item) => this.isSubmitTicketItem(item)) || null
        },
        fallbackMenuItems() {
            const items = [
                { label: 'Home', href: this.route('home'), icon: 'home', active_key: 'home', route_name: 'home', target: '_self' },
                { label: 'Submit Ticket', href: this.route('ticket_open'), icon: 'ticket', active_key: 'ticket', route_name: 'ticket_open', target: '_self' },
            ]
            if (this.enable_option?.service) {
                items.push({ label: 'Services', href: this.route('services'), icon: 'service', active_key: 'services', route_name: 'services', target: '_self' })
            }
            if (this.enable_option?.kb) {
                items.push({ label: 'Knowledge Base', href: this.route('kb'), icon: 'knowledge', active_key: 'kb', route_name: 'kb', target: '_self' })
            }
            if (this.enable_option?.faq) {
                items.push({ label: 'FAQs', href: this.route('faq'), icon: 'faq', active_key: 'faq', route_name: 'faq', target: '_self' })
            }
            if (this.enable_option?.contact_page) {
                items.push({ label: 'Contact', href: this.route('contact'), icon: 'contact', active_key: 'contact', route_name: 'contact', target: '_self' })
            }
            return items
        },
        enable_option() {
            return parseEnableOptions(this.$page.props.enable_options)
        },
        selected_language() {
            if (!this.$page.props.languages || !Array.isArray(this.$page.props.languages)) {
                return { code: 'en', name: 'English' }
            }
            return this.$page.props.languages.find(language => language.code === this.$page.props.locale) || { code: 'en', name: 'English' }
        },
        languages_except_selected() {
            if (!this.$page.props.languages || !Array.isArray(this.$page.props.languages)) {
                return []
            }
            return this.$page.props.languages.filter(language => language.code !== this.$page.props.locale)
        },
        mobileLanguages() {
            if (!this.$page.props.languages || !Array.isArray(this.$page.props.languages)) {
                return [this.selected_language]
            }
            return this.$page.props.languages
        },
    },
    watch: {
        '$page.url'() {
            this.resolveActiveMenuFromUrl()
            this.closeMobileMenu()
        },
    },
    methods: {
        isExternalLink(item) {
            return item.target === '_blank' || (item.href && /^https?:\/\//i.test(item.href))
        },
        isMenuActive(item) {
            const key = item.active_key || ''
            return this.active_menu === key || (key && this.active_menu.startsWith(key))
        },
        isSubmitTicketItem(item) {
            return item.route_name === 'ticket_open' || item.active_key === 'ticket'
        },
        isKnowledgeBaseItem(item) {
            return item.route_name === 'kb' || item.active_key === 'kb'
        },
        isMobileNavItemPrimary(item) {
            return this.isSubmitTicketItem(item)
        },
        setActiveMenu(item) {
            if (item.active_key) {
                this.active_menu = item.active_key
            }
        },
        onMobileNavClick(item) {
            this.setActiveMenu(item)
            this.closeMobileMenu()
        },
        openMobileMenu() {
            this.mobileMenuOpen = true
            document.body.classList.add('overflow-hidden')
        },
        closeMobileMenu() {
            this.mobileMenuOpen = false
            document.body.classList.remove('overflow-hidden')
        },
        toggleMobileMenu() {
            if (this.mobileMenuOpen) {
                this.closeMobileMenu()
            } else {
                this.openMobileMenu()
            }
        },
        onEscapeKey(event) {
            if (event.key === 'Escape') {
                this.closeMobileMenu()
            }
        },
        resolveActiveMenuFromUrl() {
            const path = (this.$page.url || '/').replace(/^\//, '').split('/')[0] || 'home'
            const match = this.menuItems.find((item) => item.active_key === path)
            this.active_menu = match?.active_key || path || 'home'
        },
        updateLanguage(code) {
            const token = document.querySelector('meta[name="csrf-token"]')
            const csrfToken = token ? token.getAttribute('content') : ''
            const formData = new FormData()
            formData.append('_token', csrfToken)

            fetch(`/language/${code}`, {
                method: 'POST',
                body: formData,
                headers: { 'X-Requested-With': 'XMLHttpRequest' },
            })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        window.location.reload()
                    }
                })
                .catch(error => {
                    console.error('Failed to update language:', error)
                })
        },
        windowScroll() {
            const navbar = document.getElementById('topnav')
            if (!navbar) return

            if (document.body.scrollTop >= 50 || document.documentElement.scrollTop >= 50) {
                navbar.classList.add('sticky')
            } else {
                navbar.classList.remove('sticky')
            }
        },
    },
    mounted() {
        this.resolveActiveMenuFromUrl()
        document.addEventListener('keydown', this.onEscapeKey)
    },
    beforeUnmount() {
        document.removeEventListener('keydown', this.onEscapeKey)
        window.removeEventListener('scroll', this.windowScroll)
        document.body.classList.remove('overflow-hidden')
    },
    created() {
        window.addEventListener('scroll', this.windowScroll)

        if (getActiveLanguage() !== this.$page.props.locale) {
            loadLanguageAsync(this.$page.props.locale)
        }
    },
}
</script>

<style scoped>
.navbarTogglerActive .navbarToggler-line--top {
    transform: translateY(6px) rotate(45deg);
}
.navbarTogglerActive .navbarToggler-line--mid {
    opacity: 0;
}
.navbarTogglerActive .navbarToggler-line--bot {
    transform: translateY(-6px) rotate(-45deg);
}

.mobile-drawer-panel {
    animation: mobileDrawerIn 0.3s ease-out;
}

@keyframes mobileDrawerIn {
    from {
        transform: translateX(100%);
    }
    to {
        transform: translateX(0);
    }
}

:global(#topnav.sticky .header-nav-cta),
:global(#topnav.sticky .header-nav-cta span) {
    color: #fff;
}
</style>
