<script lang="ts">
  import { page } from '$app/stores';
  import { onMount } from 'svelte';
  import Icon from '$lib/components/Icon.svelte';
  import type { NavigationContent } from '$lib/types';
  import type { Picture } from '@sveltejs/enhanced-img';
  import logoDesktop from '$lib/images/goodwalk-auckland-dog-walking-logo.png?enhanced';
  import logoMobile from '$lib/images/goodwalk-auckland-dog-walking-logo-mobile.png?enhanced';

  const desktop = logoDesktop as Picture;
  const mobile = logoMobile as Picture;

  export let navigation: NavigationContent;

  let mobileMenuOpen = false;
  let headerElement: HTMLElement;
  let mobileMenuTop = 0;
  const mobilePhoneDisplay = '(022) 642 1011';
  const mobilePhoneHref = '+64226421011';

  function closeMenu() {
    mobileMenuOpen = false;
  }

  function linkTarget(external?: boolean) {
    return external ? '_blank' : undefined;
  }

  function linkRel(external?: boolean) {
    return external ? 'noopener' : undefined;
  }

  function toggleMenu() {
    mobileMenuOpen = !mobileMenuOpen;
  }

  function updateMobileMenuTop() {
    if (!headerElement) return;
    mobileMenuTop = Math.max(headerElement.getBoundingClientRect().bottom, 0);
  }

  function mobileLinkIcon(href: string) {
    if (href === '/') return 'fas fa-house';
    if (href === '/pack-walks') return 'fas fa-paw';
    if (href === '/dog-walking') return 'fas fa-person-walking';
    if (href === '/puppy-visits') return 'fas fa-dog';
    if (href === '/our-pricing') return 'fas fa-tags';
    if (href === '/about') return 'fas fa-heart';
    if (href === '/contact-us') return 'fas fa-envelope';
    return 'fas fa-arrow-right';
  }

  function handleKeydown(event: KeyboardEvent) {
    if (event.key === 'Escape' && mobileMenuOpen) {
      closeMenu();
    }
  }

  function normalizePath(path: string) {
    if (!path || path === '/') {
      return '/';
    }

    const cleaned = path.split('#')[0].split('?')[0];
    return cleaned.endsWith('/') ? cleaned.slice(0, -1) : cleaned;
  }

  function isServicesActive() {
    const pathname = normalizePath($page.url.pathname);
    return pathname === '/pack-walks' || pathname === '/dog-walking' || pathname === '/puppy-visits';
  }

  function isActiveLink(href: string, isServicesLink = false) {
    if (!href || href.startsWith('http')) {
      return false;
    }

    if (isServicesLink) {
      return isServicesActive();
    }

    if (href.startsWith('#')) {
      return $page.url.pathname === '/' && $page.url.hash === href;
    }

    return normalizePath($page.url.pathname) === normalizePath(href);
  }

  function isExactPageMatch(href: string) {
    if (!href || href.startsWith('http') || href.startsWith('#')) {
      return false;
    }
    return normalizePath($page.url.pathname) === normalizePath(href);
  }

  function ariaCurrent(href: string): 'page' | undefined {
    return isExactPageMatch(href) ? 'page' : undefined;
  }

  function handleViewportChange() {
    updateMobileMenuTop();

    if (window.innerWidth > 768) {
      mobileMenuOpen = false;
    }
  }

  $: if (mobileMenuOpen && typeof window !== 'undefined') {
    updateMobileMenuTop();
  }

  $: if (typeof document !== 'undefined') {
    document.body.classList.toggle('mobile-menu-open', mobileMenuOpen);
  }

  onMount(() => {
    handleViewportChange();
    window.addEventListener('resize', handleViewportChange);
    window.addEventListener('scroll', updateMobileMenuTop, { passive: true });
    window.addEventListener('keydown', handleKeydown);

    return () => {
      window.removeEventListener('resize', handleViewportChange);
      window.removeEventListener('scroll', updateMobileMenuTop);
      window.removeEventListener('keydown', handleKeydown);
      document.body.classList.remove('mobile-menu-open');
    };
  });
</script>

<header bind:this={headerElement}>
  <nav>
    <ul class="nav-links">
      {#each navigation.desktopLinks as link, i}
        <li class:has-mega={i === 0 && navigation.megaMenuServices?.length}>
          <a
            href={link.href}
            target={linkTarget(link.external)}
            rel={linkRel(link.external)}
            aria-current={ariaCurrent(link.href)}
            class:nav-link-active={isActiveLink(link.href, i === 0 && Boolean(navigation.megaMenuServices?.length))}
          >
            {link.label}
            {#if i === 0 && navigation.megaMenuServices?.length}
              <Icon name="fas fa-chevron-down" className="mega-chevron" />
            {/if}
          </a>

          {#if i === 0 && navigation.megaMenuServices?.length}
            <div class="mega-menu">
              <div class="mega-menu-inner">
                <div class="mega-menu-services">
                  {#each navigation.megaMenuServices as service}
                    <a
                      href={service.href}
                      target={linkTarget(service.href.startsWith('http'))}
                      rel={linkRel(service.href.startsWith('http'))}
                      aria-current={ariaCurrent(service.href)}
                      class="mega-service"
                    >
                      <div class="mega-icon">
                        <Icon name={service.icon} />
                      </div>
                      <span class="mega-service-label">{service.label}</span>
                      {#if service.description}
                        <span class="mega-service-desc">{service.description}</span>
                      {/if}
                    </a>
                  {/each}
                </div>
                {#if navigation.megaMenuFooter}
                  <a
                    href={navigation.megaMenuFooter.href}
                    target={linkTarget(navigation.megaMenuFooter.external)}
                    rel={linkRel(navigation.megaMenuFooter.external)}
                    class="mega-menu-footer"
                  >
                    <span>{navigation.megaMenuFooter.label}</span>
                    <Icon name="fas fa-arrow-right" className="mega-menu-footer-arrow" />
                  </a>
                {/if}
              </div>
            </div>
          {/if}
        </li>
      {/each}
    </ul>

    <a href="/" class="logo" aria-label="Goodwalk – Auckland Dog Walking, home">
      <picture>
        {#if mobile.sources?.webp}
          <source type="image/webp" srcset={mobile.sources.webp} />
        {/if}
        <img
          src={mobile.img.src}
          alt="Goodwalk – Auckland dog walking service logo"
          width={mobile.img.w}
          height={mobile.img.h}
          decoding="async"
        />
      </picture>
    </a>

    <a href={`tel:${mobilePhoneHref}`} class="mobile-phone" aria-label={`Call Goodwalk on ${mobilePhoneDisplay}`}>
      <Icon name="fas fa-phone" />
      <span>{mobilePhoneDisplay}</span>
    </a>

    <div class="nav-right">
      {#if navigation.instagram}
        <a
          href={navigation.instagram.href}
          target={linkTarget(navigation.instagram.external)}
          rel={linkRel(navigation.instagram.external)}
          class="instagram-icon"
          aria-label="Instagram"
        >
          <Icon name="fab fa-instagram" />
        </a>
      {/if}
      <a
        href={navigation.cta.href}
        class="btn btn-yellow"
      >{navigation.cta.label}</a>
    </div>

    <button
      class="hamburger"
      type="button"
      aria-expanded={mobileMenuOpen}
      aria-controls="mobile-menu"
      aria-label="Toggle menu"
      on:click={toggleMenu}
    >
      <Icon name={mobileMenuOpen ? 'fas fa-xmark' : 'fas fa-bars'} />
    </button>
  </nav>

  {#if $page.url.pathname === '/'}
    <div class="nav-ribbon">
      <span class="nav-ribbon-item"><Icon name="fas fa-paw" />Small &amp; Medium Dog Specialists</span>
      <span class="nav-ribbon-divider"></span>
      <span class="nav-ribbon-item"><Icon name="fas fa-handshake" />Free Meet &amp; Greet</span>
      <span class="nav-ribbon-divider"></span>
      <span class="nav-ribbon-item"><Icon name="fas fa-van-shuttle" />Free Pickup &amp; Drop-off</span>
    </div>
  {/if}

  <div
    class:open={mobileMenuOpen}
    class="mobile-menu-shell"
    style={`--mobile-menu-top: ${mobileMenuTop}px;`}
    on:click={closeMenu}
  >
    <div class="mobile-menu" id="mobile-menu" on:click|stopPropagation>
      <div class="mobile-menu-links">
        {#each navigation.mobileLinks as link}
          <a
            href={link.href}
            target={linkTarget(link.external)}
            rel={linkRel(link.external)}
            aria-current={ariaCurrent(link.href)}
            class:mobile-link-active={isActiveLink(link.href)}
            on:click={closeMenu}
          >
            <span class="mobile-menu-link-icon">
              <Icon name={mobileLinkIcon(link.href)} />
            </span>
            <span class="mobile-menu-link-label">{link.label}</span>
            <Icon name="fas fa-arrow-right" className="mobile-menu-link-arrow" />
          </a>
        {/each}
      </div>
    </div>
  </div>
</header>
