<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;
  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 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() {
    if (window.innerWidth > 768) {
      mobileMenuOpen = false;
    }
  }

  onMount(() => {
    handleViewportChange();
    window.addEventListener('resize', handleViewportChange);

    return () => window.removeEventListener('resize', handleViewportChange);
  });
</script>

<header>
  <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 media="(max-width: 768px)" type="image/webp" srcset={mobile.sources.webp} />
        {/if}
        <source media="(max-width: 768px)" srcset={mobile.img.src} />
        {#if desktop.sources?.webp}
          <source type="image/webp" srcset={desktop.sources.webp} />
        {/if}
        <img
          src={desktop.img.src}
          alt="Goodwalk – Auckland dog walking service logo"
          width={desktop.img.w}
          height={desktop.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>

  <div class:open={mobileMenuOpen} class="mobile-menu" id="mobile-menu">
    {#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}
      >
        {link.label}
      </a>
    {/each}
  </div>
</header>
