<script lang="ts">
  import { browser } from '$app/environment';
  import { afterNavigate } from '$app/navigation';
  import { onMount } from 'svelte';
  import { page } from '$app/stores';

  import '../app.css';
  import Sidebar from '$lib/components/Sidebar.svelte';
  import SearchBar from '$lib/components/SearchBar.svelte';
  import { palettes, type ThemeMode, type Palette } from '$lib/palettes';

  const matomoContainerSrc = 'https://matomo.howdoyouconvert.com/js/container_B3r877Kn.js';

  type WindowWithAnalytics = Window & {
    _mtm?: Array<Record<string, unknown>>;
    requestIdleCallback?: (callback: () => void, options?: { timeout: number }) => number;
    cancelIdleCallback?: (handle: number) => void;
  };

  let sidebarOpen = false;
  let headerSearchOpen = false;
  let isMobileHeader = false;
  let theme: ThemeMode = 'dark';
  let selectedPaletteIndex = 0;
  let savedScrollRestoration: ScrollRestoration | null = null;
  $: isHomepage = $page.url.pathname === '/';
  $: if (isHomepage && (sidebarOpen || headerSearchOpen)) {
    sidebarOpen = false;
    headerSearchOpen = false;
  }
  $: if (!isMobileHeader && headerSearchOpen) {
    headerSearchOpen = false;
  }

  const applyPalette = (index: number, persist = false) => {
    const normalizedIndex = Math.max(0, Math.min(index, palettes.length - 1));
    selectedPaletteIndex = normalizedIndex;
    if (!browser) return;
    const slug = palettes[normalizedIndex].slug;
    document.documentElement.dataset.palette = slug;
    if (persist) {
      window.localStorage.setItem('palette', slug);
    }
  };

  const updateTheme = (value: ThemeMode, persist = false) => {
    theme = value;
    if (!browser) return;
    document.documentElement.dataset.theme = value;
    if (persist) {
      window.localStorage.setItem('theme', value);
    }
  };

  const toggleTheme = () => {
    const nextTheme: ThemeMode = theme === 'dark' ? 'light' : 'dark';
    updateTheme(nextTheme, true);
  };

  const setPalette = (index: number) => {
    applyPalette(index, true);
  };

  const toggleHeaderSearch = () => {
    headerSearchOpen = !headerSearchOpen;
    if (headerSearchOpen) {
      sidebarOpen = false;
    }
  };

  const loadMatomoContainer = () => {
    if (!browser) return;
    if (document.querySelector(`script[src="${matomoContainerSrc}"]`)) return;

    const appWindow = window as WindowWithAnalytics;
    const queue = appWindow._mtm ?? [];
    appWindow._mtm = queue;
    queue.push({ 'mtm.startTime': Date.now(), event: 'mtm.Start' });

    const script = document.createElement('script');
    script.async = true;
    script.src = matomoContainerSrc;
    script.setAttribute('data-cfasync', 'false');
    document.head.appendChild(script);
  };

  const scrollToTop = () => {
    if (!browser) return;
    window.scrollTo({ top: 0, behavior: 'auto' });
  };

  afterNavigate(({ from, to, type }) => {
    sidebarOpen = false;
    headerSearchOpen = false;

    if (!browser) return;
    if (type === 'popstate') return;
    if (!from || !to) return;
    if (from.url.pathname === to.url.pathname) return;

    scrollToTop();
  });

  onMount(() => {
    if (!browser) return;
    const appWindow = window as WindowWithAnalytics;
    if ('scrollRestoration' in window.history) {
      savedScrollRestoration = window.history.scrollRestoration;
      window.history.scrollRestoration = 'manual';
    }
    let idleCallbackId: number | null = null;
    let fallbackTimeoutId: number | null = null;

    const savedTheme = window.localStorage.getItem('theme') as ThemeMode | null;
    const savedPalette = window.localStorage.getItem('palette');
    const paletteIndex = palettes.findIndex(palette => palette.slug === savedPalette);
    const initialPaletteIndex = paletteIndex >= 0 ? paletteIndex : 0;
    applyPalette(initialPaletteIndex, Boolean(savedPalette));

    const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)');
    const initialTheme: ThemeMode = savedTheme ?? (mediaQuery.matches ? 'dark' : 'light');
    updateTheme(initialTheme, Boolean(savedTheme));

    const handlePreferenceChange = (event: MediaQueryListEvent) => {
      if (window.localStorage.getItem('theme')) return;
      updateTheme(event.matches ? 'dark' : 'light');
    };

    const navBreakpoint = window.matchMedia('(max-width: 1024px)');
    const handleNavBreakpoint = (event: MediaQueryListEvent) => {
      if (event.matches) {
        sidebarOpen = false;
      }
    };
    const headerBreakpoint = window.matchMedia('(max-width: 768px)');
    const updateHeaderBreakpoint = (event?: MediaQueryListEvent) => {
      const isCompact = event?.matches ?? headerBreakpoint.matches;
      isMobileHeader = isCompact;
      if (!isCompact) {
        headerSearchOpen = false;
      }
    };
    const handleHeaderBreakpoint = (event: MediaQueryListEvent) => {
      updateHeaderBreakpoint(event);
    };

    const handleEscape = (event: KeyboardEvent) => {
      if (event.key === 'Escape') {
        sidebarOpen = false;
        headerSearchOpen = false;
      }
    };
    window.addEventListener('keydown', handleEscape);

    if (navBreakpoint.matches) {
      sidebarOpen = false;
    }
    updateHeaderBreakpoint();
    if (typeof appWindow.requestIdleCallback === 'function') {
      idleCallbackId = appWindow.requestIdleCallback(loadMatomoContainer, { timeout: 3000 });
    } else {
      fallbackTimeoutId = window.setTimeout(loadMatomoContainer, 1200);
    }

    const cleanup = () => {
      if ('removeEventListener' in mediaQuery) {
        mediaQuery.removeEventListener('change', handlePreferenceChange);
      } else {
        (mediaQuery as MediaQueryList & {
          removeListener: (listener: (event: MediaQueryListEvent) => void) => void;
        }).removeListener(handlePreferenceChange);
      }
      if ('removeEventListener' in navBreakpoint) {
        navBreakpoint.removeEventListener('change', handleNavBreakpoint);
      } else {
        (navBreakpoint as MediaQueryList & {
          removeListener: (listener: (event: MediaQueryListEvent) => void) => void;
        }).removeListener(handleNavBreakpoint);
      }
      if ('removeEventListener' in headerBreakpoint) {
        headerBreakpoint.removeEventListener('change', handleHeaderBreakpoint);
      } else {
        (headerBreakpoint as MediaQueryList & {
          removeListener: (listener: (event: MediaQueryListEvent) => void) => void;
        }).removeListener(handleHeaderBreakpoint);
      }
      if (idleCallbackId !== null && typeof appWindow.cancelIdleCallback === 'function') {
        appWindow.cancelIdleCallback(idleCallbackId);
      }
      if (fallbackTimeoutId !== null) {
        window.clearTimeout(fallbackTimeoutId);
      }
      window.removeEventListener('keydown', handleEscape);
      if (savedScrollRestoration !== null) {
        window.history.scrollRestoration = savedScrollRestoration;
      }
    };

    if ('addEventListener' in mediaQuery) {
      mediaQuery.addEventListener('change', handlePreferenceChange);
    } else {
      (mediaQuery as MediaQueryList & {
        addListener: (listener: (event: MediaQueryListEvent) => void) => void;
      }).addListener(handlePreferenceChange);
    }

    if ('addEventListener' in navBreakpoint) {
      navBreakpoint.addEventListener('change', handleNavBreakpoint);
    } else {
      (navBreakpoint as MediaQueryList & {
        addListener: (listener: (event: MediaQueryListEvent) => void) => void;
      }).addListener(handleNavBreakpoint);
    }
    if ('addEventListener' in headerBreakpoint) {
      headerBreakpoint.addEventListener('change', handleHeaderBreakpoint);
    } else {
      (headerBreakpoint as MediaQueryList & {
        addListener: (listener: (event: MediaQueryListEvent) => void) => void;
      }).addListener(handleHeaderBreakpoint);
    }

    return cleanup;
  });
</script>

<svelte:head>
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <link rel="icon" type="image/svg+xml" href="/favicon.svg?v=2" />
</svelte:head>

<a href="#main-content" class="skip-link">Skip to main content</a>

<header class="site-header">
  <div class="header-left">
    {#if !isHomepage}
      <button
        type="button"
        class="hamburger"
        on:click={() => {
          sidebarOpen = !sidebarOpen;
          if (sidebarOpen) {
            headerSearchOpen = false;
          }
        }}
        aria-label="Toggle menu"
        aria-controls="site-navigation"
        aria-expanded={sidebarOpen ? 'true' : 'false'}
      >
        ☰
      </button>
    {/if}
    <a href="/" class="site-logo">
      <span>How</span><span>Do</span><span>You</span><span class="logo-accent">Convert</span><span class="logo-domain">.com</span>
    </a>
  </div>
  <div class="header-right">
    {#if !isHomepage}
      <div class="desktop-header-search">
        <SearchBar idPrefix="header-search" />
      </div>
      <button
        type="button"
        class="header-icon-btn search-toggle"
        on:click={toggleHeaderSearch}
        aria-controls="mobile-header-search"
        aria-expanded={headerSearchOpen ? 'true' : 'false'}
        aria-label={headerSearchOpen ? 'Close search' : 'Open search'}
      >
        <span aria-hidden="true">🔍</span>
      </button>
    {/if}
  </div>
</header>

{#if !isHomepage}
  <div id="mobile-header-search" class="mobile-header-search" class:open={headerSearchOpen} hidden={!headerSearchOpen}>
    <SearchBar idPrefix="mobile-header-search" />
  </div>
{/if}

<div class="site-body">
  {#if !isHomepage}
    <Sidebar bind:open={sidebarOpen} />
  {/if}
  <main id="main-content" class="main-content" tabindex="-1">
    <slot />
  </main>
</div>

<div class="floating-palette-controls" role="group" aria-label="Theme and palette controls">
  <div class="palette-dots">
    {#each palettes as palette, index}
      <button
        type="button"
        class="palette-dot"
        class:active={index === selectedPaletteIndex}
        aria-pressed={index === selectedPaletteIndex}
        aria-label={`Switch to ${palette.label} palette`}
        style={`background-image: ${palette[theme]['accent-gradient']};`}
        on:click={() => setPalette(index)}
      ></button>
    {/each}
  </div>
  <button
    type="button"
    class="theme-toggle"
    on:click={toggleTheme}
    aria-label={`Switch to ${theme === 'dark' ? 'light' : 'dark'} mode`}
  >
    <span aria-hidden="true">{theme === 'dark' ? '☀️' : '🌙'}</span>
  </button>
</div>

<footer class="site-footer">
  © {new Date().getFullYear()} HowDoYouConvert.com — Free unit conversion calculators. All rights reserved.
</footer>
