<script>
    import { onMount } from 'svelte';
    import { Menu, X, ChevronDown } from 'lucide-svelte';
    import { goto } from '$app/navigation';

    import bassLogo from '$lib/assets/bass_assinatura02@2x (1).png';

    let isOpen = false;
    let scrolled = false;
    let dropdownOpen = {};
    let dropdownTimeout = {};

    onMount(() => {
        const handleScroll = () => {
            scrolled = window.scrollY > 12;
        };
        
        window.addEventListener('scroll', handleScroll);
        
        return () => {
            window.removeEventListener('scroll', handleScroll);
        };
    });

    const menuItems = [
         { name: 'Inicio', href: '/' },
        { name: 'Conta Digital', href: '/conta-digital' },
        {
            name: 'Soluções',
            href: '#solucoes',
            hasDropdown: true,
            submenu: [
                // { name: 'Banking', href: '/banking' },
                { name: 'PIX', href: '/pix' },
                { name: 'PDV', href: '/pdv' }
            ]
        },
        { name: 'Desenvolvedores', href: '/desenvolvedores' }, 
        {
            name: 'Recursos',
            href: '#recursos',
            hasDropdown: true,
            submenu: [
                { name: 'Sobre', href: '/sobre' },
                { name: 'Centro de Suporte', href: '/centro-suporte' },
                { name: 'Preços', href: '/precos' },
                { name: 'Políticas', href: '/politicas-e-termos' }
            ]
        }
    ];

    function toggleMenu() {
        isOpen = !isOpen;
    }

    function toggleDropdown(itemName) {
        dropdownOpen[itemName] = !dropdownOpen[itemName];
    }

    function showDropdown(itemName) {
        if (dropdownTimeout[itemName]) {
            clearTimeout(dropdownTimeout[itemName]);
        }
        dropdownOpen[itemName] = true;
    }

    function hideDropdown(itemName) {
        dropdownTimeout[itemName] = setTimeout(() => {
            dropdownOpen[itemName] = false;
        }, 150); 
    }

    function keepDropdownOpen(itemName) {
        if (dropdownTimeout[itemName]) {
            clearTimeout(dropdownTimeout[itemName]);
        }
    }

    function handleNavigation(href, event) {
        event.preventDefault();
        
        if (href.startsWith('/')) {
            goto(href);
        } else {
            const element = document.querySelector(href);
            if (element) {
                element.scrollIntoView({ behavior: 'smooth' });
            }
        }
        
        isOpen = false;
    }

    function goHome() {
        goto('/');
    }
</script>

<header class="fixed top-0 z-50 w-full">
    <div class="mx-auto mt-4 max-w-[1280px] px-4">
        <div
            class="flex h-16 items-center justify-between rounded-2xl px-6 transition-all duration-300 {scrolled
                ? 'bg-slate-900/90 backdrop-blur-xl shadow-lg'
                : 'bg-slate-900/70 backdrop-blur-md'}"
        >
            <div class="flex items-center gap-3 cursor-pointer" on:click={goHome}>
                <img src={bassLogo} alt="BassPago" class="h-20 w-auto" />
            </div>

            <nav class="hidden lg:flex items-center justify-center flex-1 gap-8">
                {#each menuItems as item}
                    <div class="relative group">
                        <a
                            href={item.href}
                            class="flex items-center gap-1 text-sm font-medium text-white/80 hover:text-white transition"
                            on:mouseenter={() => item.hasDropdown && showDropdown(item.name)}
                            on:mouseleave={() => item.hasDropdown && hideDropdown(item.name)}
                            on:click={(e) => handleNavigation(item.href, e)}
                        >
                            {item.name}
                            {#if item.hasDropdown}
                                <ChevronDown
                                    size={14}
                                    class="transition-transform {dropdownOpen[item.name] ? 'rotate-180' : ''}"
                                />
                            {/if}
                        </a>

                        {#if item.hasDropdown && dropdownOpen[item.name]}
                            <div
                                class="absolute left-0 top-full mt-3 w-56 rounded-xl bg-slate-950/95 backdrop-blur-xl border border-white/10 shadow-xl z-50"
                                on:mouseenter={() => keepDropdownOpen(item.name)}
                                on:mouseleave={() => hideDropdown(item.name)}
                            >
                                {#each item.submenu as sub}
                                    <a
                                        href={sub.href}
                                        class="block px-4 py-3 text-sm text-white/70 hover:text-white hover:bg-white/5 transition-colors first:rounded-t-xl last:rounded-b-xl"
                                        on:click={(e) => handleNavigation(sub.href, e)}
                                    >
                                        {sub.name}
                                    </a>
                                {/each}
                            </div>
                        {/if}
                    </div>
                {/each}
            </nav>

            <div class="hidden lg:flex items-center">
                <button
                    class="rounded-full bg-white px-6 py-2.5 text-sm font-semibold text-slate-900 hover:bg-slate-100 transition-colors"
                    on:click={() => goto('/precos#form-negociacao-basspago')}
                >
                    Abrir conta
                </button>
            </div>

            <!-- Mobile Menu Button -->
            <button class="lg:hidden p-2 text-white" on:click={toggleMenu}>
                {#if isOpen}
                    <X size={22} />
                {:else}
                    <Menu size={22} />
                {/if}
            </button>
        </div>

        <!-- Mobile Navigation -->
        {#if isOpen}
            <nav class="mt-3 rounded-2xl bg-slate-950/95 backdrop-blur-xl border border-white/10">
                {#each menuItems as item}
                    <div>
                        {#if item.hasDropdown}
                            <button
                                class="w-full flex items-center justify-between px-6 py-3 text-sm text-white/80 hover:bg-white/5 transition-colors"
                                on:click={() => toggleDropdown(item.name)}
                            >
                                {item.name}
                                <ChevronDown
                                    size={14}
                                    class="transition-transform {dropdownOpen[item.name] ? 'rotate-180' : ''}"
                                />
                            </button>
                            {#if dropdownOpen[item.name]}
                                <div class="bg-white/5">
                                    {#each item.submenu as sub}
                                        <a
                                            href={sub.href}
                                            class="block px-10 py-3 text-sm text-white/60 hover:text-white/80 transition-colors"
                                            on:click={(e) => handleNavigation(sub.href, e)}
                                        >
                                            {sub.name}
                                        </a>
                                    {/each}
                                </div>
                            {/if}
                        {:else}
                            <a
                                href={item.href}
                                class="block px-6 py-3 text-sm text-white/80 hover:bg-white/5 transition-colors"
                                on:click={(e) => handleNavigation(item.href, e)}
                            >
                                {item.name}
                            </a>
                        {/if}
                    </div>
                {/each}

                <div class="border-t border-white/10 p-4">
                    <button
                        class="w-full rounded-full bg-white px-6 py-2.5 text-sm font-semibold text-slate-900 hover:bg-slate-100 transition-colors"
                        on:click={() => goto('/precos#form-negociacao-basspago')}
                    >
                        Abrir conta
                    </button>
                </div>
            </nav>
        {/if}
    </div>
</header>

<style>
    nav {
        animation: slideDown 0.3s ease-out;
    }

    @keyframes slideDown {
        from {
            opacity: 0;
            transform: translateY(-10px);
        }
        to {
            opacity: 1;
            transform: translateY(0);
        }
    }

    .group:hover .absolute {
        display: block;
    }

    .group:last-of-type .absolute {
        right: 0;
        left: auto;
    }
</style>