<script>
    import { onMount } from 'svelte'
    import './Header.css'
    import Button from '../Button/Button.svelte'

    let activeNav = 'home'
    let isHidden = false
    let lastScrollY = 0

    const SCROLL_DELTA = 8
    const TOP_OFFSET = 24

    function navigate(section) {
        activeNav = section
    }

    function handleScroll() {
        const currentScrollY = window.scrollY || 0
        const diff = currentScrollY - lastScrollY

        if (currentScrollY <= TOP_OFFSET) {
            isHidden = false
        } else if (diff > SCROLL_DELTA) {
            isHidden = true
        } else if (diff < -SCROLL_DELTA) {
            isHidden = false
        }

        lastScrollY = currentScrollY
    }

    onMount(() => {
        lastScrollY = window.scrollY || 0
        window.addEventListener('scroll', handleScroll, { passive: true })

        return () => {
            window.removeEventListener('scroll', handleScroll)
        }
    })
</script>

<header class="header" class:hidden={isHidden} id="home">
    <div class="header-container">
        <div class="logo">
            <a href="/" aria-label="CIMA PROGETTI home">
                <span class="logo-img logo-mask" aria-hidden="true"></span>
            </a>
        </div>
        <nav class="nav">
            <a
                href="#services"
                class:active={activeNav === 'services'}
                on:click|preventDefault={() => navigate('services')}
                aria-current={activeNav === 'services' ? 'page' : undefined}
            >
                Servizi
            </a>
            <a
                href="#method"
                class:active={activeNav === 'method'}
                on:click|preventDefault={() => navigate('method')}
                aria-current={activeNav === 'method' ? 'page' : undefined}
            >
                Il metodo
            </a>
            <a
                href="#projects"
                class:active={activeNav === 'projects'}
                on:click|preventDefault={() => navigate('projects')}
                aria-current={activeNav === 'projects' ? 'page' : undefined}
            >
                Progetti
            </a>
            <a
                href="#us"
                class:active={activeNav === 'us'}
                on:click|preventDefault={() => navigate('us')}
                aria-current={activeNav === 'us' ? 'page' : undefined}
            >
                Chi Siamo
            </a>
        </nav>
        <div class="header-actions">
            <Button text="Contattaci" href="#contact" />
        </div>
    </div>
</header>