<script lang="ts">
import type { ClassValue } from 'svelte/elements';

import { clickOutside } from '../click-outside';
import { Floating, matchWidth } from '../floating';
import { Icon } from '../icon';
import { createHandleKey } from '../keyboard';
import { uniqueId } from '../unique-id';
import type { NavOption } from './nav-option';

interface Props {
  options: NavOption[];
  selectedHref: string | undefined;
  class?: ClassValue;
}

const { options, selectedHref, class: extraClass }: Props = $props();
let isOpen = $state(false);
let buttonElement = $state<HTMLButtonElement | undefined>(undefined);
const anchorElementsByHref = $state<Record<string, HTMLAnchorElement>>({});
let activeHref = $state<string | undefined>(undefined);
const selectedOption = $derived(
  options.find(({ href }) => href === selectedHref)
);
const activeAnchor = $derived(
  activeHref ? anchorElementsByHref[activeHref] : undefined
);

const menuID = uniqueId('nav-dropdown');

const openDropdown = () => {
  activeHref = selectedOption?.href;
  isOpen = true;
};

const closeDropdown = () => {
  if (isOpen) {
    activeHref = undefined;
    isOpen = false;
    buttonElement?.focus();
  }
};

const handleKeydown = createHandleKey({
  Tab: closeDropdown,
  Escape: closeDropdown,
  ' ': () => {
    activeAnchor?.click();
  },
  ArrowDown: () => {
    const index = options.findIndex(({ href }) => href === activeHref);
    const nextIndex = (index + 1) % options.length;
    activeHref = options[nextIndex]?.href;
  },
  ArrowUp: () => {
    const index = options.findIndex(({ href }) => href === activeHref);
    const nextIndex = (index - 1 + options.length) % options.length;
    activeHref = options[nextIndex]?.href;
  },
});

const handleClickOutside = () => {
  closeDropdown();
};

const toggleDropdown = $derived(isOpen ? closeDropdown : openDropdown);

/**
 * Focus the active link from keyboard interactions.
 *
 * The requestAnimationFrame is necessary to ensure the anchor
 * if fully mounted and focusable.
 */
$effect(() => {
  const element = activeAnchor;
  const frameID = requestAnimationFrame(() => element?.focus());
  return () => cancelAnimationFrame(frameID);
});
</script>

<svelte:window onkeydown={isOpen ? handleKeydown : undefined} />
<div
  class={extraClass}
  use:clickOutside={handleClickOutside}
>
  <button
    class={[
      'hover:border-gray-6 focus:border-gray-6 z-2 h-7.5 w-full appearance-none border bg-white py-1.5 pr-1 pl-2 text-xs leading-tight outline-none',
      isOpen ? 'border-gray-6' : 'border-light',
    ]}
    type="button"
    aria-haspopup="menu"
    aria-expanded={isOpen}
    aria-controls={menuID}
    onclick={toggleDropdown}
    bind:this={buttonElement}
  >
    <div class="flex items-center">
      {#if selectedOption}
        {#if selectedOption.selectedText}
          <span class="truncate font-normal">
            {selectedOption.selectedText}
          </span>
        {:else}
          {@render menuItemChild(selectedOption, false)}
        {/if}
      {/if}
      <Icon
        name="chevron-down"
        cx={[
          'text-gray-6 ml-auto transition-transform',
          { 'rotate-180': isOpen },
        ]}
      />
    </div>
  </button>

  {#if isOpen}
    <Floating
      referenceElement={buttonElement}
      placement="bottom-start"
      offset={4}
      size={matchWidth}
      auto
    >
      <div
        class="border-gray-6 w-full overflow-auto border bg-white shadow-sm focus:outline-none"
        role="menu"
        id={menuID}
      >
        {#each options as option (option.href)}
          <a
            href={option.href}
            class={[
              'hover:bg-gray-1 relative flex flex-col px-2 py-1.5  focus:outline-none',
              { 'bg-gray-1': option.href === activeHref },
            ]}
            role="menuitem"
            tabindex="-1"
            aria-current={option.href === selectedHref ? 'page' : 'false'}
            onclick={closeDropdown}
            onfocus={() => (activeHref = option.href)}
            onmouseover={() => (activeHref = option.href)}
            bind:this={anchorElementsByHref[option.href]}
            data-sveltekit-keepfocus
          >
            {@render menuItemChild(option)}
          </a>
        {/each}
      </div>
    </Floating>
  {/if}
</div>

{#snippet menuItemChild(option: NavOption, includeDescription: boolean = true)}
  <div class="flex items-center text-xs">
    <span class="truncate font-normal">{option.label}</span>
    {#if option.detail}
      <span class="text-gray-6 ml-1">({option.detail})</span>
    {/if}
  </div>
  {#if includeDescription && option.description}
    <span class="text-gray-6 truncate text-[0.625rem]">
      {option.description}
    </span>
  {/if}
{/snippet}
