<script setup>
const { menuOpen, toggleMenu, closeMenu } = useMenuState()
const menuUserOpen = ref(false)
const userMenuRef = ref(null)
const userMenuToggleRef = ref(null)
const searchOpen = ref(false)

const { data: siteSettings } = await useFetch('/api/site-settings', {
  default: () => ({
    title: 'sori.studio'
  })
})

/**
 * 사용자 메뉴를 닫는다.
 * @returns {void}
 */
const closeUserMenu = () => {
  menuUserOpen.value = false
}

/**
 * 통합 검색 모달을 연다.
 * @returns {void}
 */
const openSearchModal = () => {
  searchOpen.value = true
}

/**
 * 입력 필드에 포커스가 있으면 `/` 검색 단축키를 무시한다.
 * @param {KeyboardEvent} event - 키보드 이벤트
 * @returns {boolean} 무시할 때 true
 */
const shouldIgnoreSearchHotkey = (event) => {
  if (event.ctrlKey || event.metaKey || event.altKey) {
    return true
  }
  const target = event.target
  if (!(target instanceof HTMLElement)) {
    return false
  }
  const tag = target.tagName
  if (tag === 'INPUT' || tag === 'TEXTAREA' || tag === 'SELECT') {
    return true
  }
  if (target.isContentEditable) {
    return true
  }
  return false
}

/**
 * 사용자 메뉴를 토글한다.
 * @returns {void}
 */
const toggleUserMenu = () => {
  menuUserOpen.value = !menuUserOpen.value
}

/**
 * 문서 클릭 시 사용자 메뉴 외부 영역이면 메뉴를 닫는다.
 * @param {MouseEvent} event - 클릭 이벤트
 * @returns {void}
 */
const onDocumentClick = (event) => {
  const target = /** @type {Node | null} */ (event.target instanceof Node ? event.target : null)
  if (!target) {
    closeUserMenu()
    return
  }

  const isInsideMenu = userMenuRef.value instanceof HTMLElement && userMenuRef.value.contains(target)
  const isToggleButton = userMenuToggleRef.value instanceof HTMLElement && userMenuToggleRef.value.contains(target)

  if (!isInsideMenu && !isToggleButton) {
    closeUserMenu()
  }
}

/**
 * Escape·`/` 키로 패널을 제어한다(검색 모달 → 사용자 메뉴 → 모바일 좌측 메뉴, `/`는 검색 열기).
 * @param {KeyboardEvent} event - 키보드 이벤트
 * @returns {void}
 */
const onGlobalKeydown = (event) => {
  if (event.key === 'Escape') {
    if (searchOpen.value) {
      searchOpen.value = false
      event.preventDefault()
      return
    }
    if (menuUserOpen.value) {
      closeUserMenu()
      return
    }
    if (!menuOpen.value) {
      return
    }
    if (typeof window !== 'undefined' && window.matchMedia('(max-width: 1023px)').matches) {
      closeMenu()
    }
    return
  }
  if (event.key !== '/') {
    return
  }
  if (shouldIgnoreSearchHotkey(event)) {
    return
  }
  event.preventDefault()
  openSearchModal()
}

onMounted(() => {
  document.addEventListener('click', onDocumentClick)
  document.addEventListener('keydown', onGlobalKeydown)
})

onBeforeUnmount(() => {
  document.removeEventListener('click', onDocumentClick)
  document.removeEventListener('keydown', onGlobalKeydown)
})
</script>

<template>
  <header class="site-header sticky top-0 z-20 backdrop-blur">
    <div class="site-header__inner mx-auto flex h-full max-w-[1294px] items-center justify-between gap-3 px-4 sm:gap-4 lg:gap-5 lg:px-5 xl:gap-6 xl:px-6 2xl:px-0">
      <NuxtLink class="site-header__brand flex min-w-0 shrink-1 items-center gap-2.5 text-[15px] font-semibold tracking-normal sm:gap-3 sm:text-[18px] lg:max-w-[min(240px,32vw)] xl:max-w-[min(320px,28vw)] 2xl:max-w-none 2xl:flex-1" to="/">
        <button
          class="site-header__menu-toggle group flex h-7 w-7 items-center justify-center rounded-full transition-transform"
          type="button"
          data-menu-toggle
          aria-label="Menu toggle"
          aria-haspopup="true"
          aria-controls="menu"
          :aria-expanded="menuOpen.toString()"
          @click.prevent="toggleMenu"
        >
          <span v-if="menuOpen" class="site-header__menu-icon pointer-events-none">
            <svg class="block h-6 w-6 group-hover:hidden" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">
              <path d="M6 21a3 3 0 0 1-3-3V6a3 3 0 0 1 3-3h12a3 3 0 0 1 3 3v12a3 3 0 0 1-3 3H6Zm12-16h-8v14h8a1 1 0 0 0 1-1V6a1 1 0 0 0-1-1Z" />
            </svg>
            <svg class="hidden h-6 w-6 group-hover:block" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">
              <path d="M18 3a3 3 0 0 1 3 3v12a3 3 0 0 1-3 3H6a3 3 0 0 1-3-3V6a3 3 0 0 1 3-3h12Zm0 2h-9v14h9a1 1 0 0 0 1-1V6a1 1 0 0 0-1-1Zm-2.3 4.3a1 1 0 0 1 0 1.4L14.4 12l1.3 1.3a1 1 0 0 1-1.4 1.4l-2-2a1 1 0 0 1 0-1.4l2-2a1 1 0 0 1 1.4 0Z" />
            </svg>
          </span>
          <span v-else class="site-header__menu-icon pointer-events-none">
            <svg class="block h-6 w-6 group-hover:hidden" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
              <path d="M4 6a2 2 0 0 1 2-2h12a2 2 0 0 1 2 2v12a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6Z" />
              <path d="M9 4v16" />
            </svg>
            <svg class="hidden h-6 w-6 group-hover:block" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
              <path d="M4 6a2 2 0 0 1 2-2h12a2 2 0 0 1 2 2v12a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6Z" />
              <path d="M9 4v16" />
              <path d="m14 10 2 2-2 2" />
            </svg>
          </span>
        </button>
        <span class="min-w-0 truncate">{{ siteSettings.title }}</span>
      </NuxtLink>
      <button
        type="button"
        class="site-header__search site-header__search--responsive hidden h-9 min-w-0 flex-1 basis-0 cursor-pointer items-center rounded-lg px-3 text-left text-sm transition-colors hover:opacity-90 md:flex md:max-w-[min(470px,42vw)] lg:max-w-[min(470px,30vw)] xl:max-w-[min(470px,36vw)] 2xl:w-[470px] 2xl:max-w-[470px] 2xl:basis-auto 2xl:flex-none site-input"
        aria-label="검색 열기"
        @click="openSearchModal"
      >
        <span class="site-header__search-icon mr-2 text-lg leading-none">⌕</span>
        <span class="site-header__search-text site-soft">Search</span>
        <span class="site-header__search-key ml-auto rounded-md px-2 text-xs site-soft site-input">/</span>
      </button>
      <nav class="site-header__nav flex shrink-0 items-center gap-3 text-sm sm:gap-3.5">
        <NuxtLink class="site-header__buy site-accent-button shrink-0 rounded-lg px-3 py-1.5 text-xs font-semibold sm:px-4 sm:py-2 sm:text-sm" to="/pages/about">
          Subscribe
        </NuxtLink>
        <div class="site-header__user-menu relative">
          <button
            ref="userMenuToggleRef"
            class="site-header__user-toggle relative flex h-7 w-7 items-center justify-center rounded-full transition-opacity duration-200 hover:opacity-75 md:h-8 md:w-8"
            type="button"
            aria-label="Toggle user menu"
            :aria-expanded="menuUserOpen.toString()"
            @click="toggleUserMenu"
          >
            <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" class="h-6 w-6 stroke-current stroke-[1.75] md:h-7 md:w-7 md:stroke-[1.5]">
              <path d="M12 12m-9 0a9 9 0 1 0 18 0a9 9 0 1 0 -18 0" />
              <path d="M12 10m-3 0a3 3 0 1 0 6 0a3 3 0 1 0 -6 0" />
              <path d="M6.168 18.849a4 4 0 0 1 3.832 -2.849h4a4 4 0 0 1 3.834 2.855" />
            </svg>
          </button>

          <Transition
            enter-active-class="transition-[transform,opacity,visibility] duration-200 ease-out"
            enter-from-class="-translate-y-2 scale-95 opacity-0"
            enter-to-class="translate-y-0 scale-100 opacity-100"
            leave-active-class="transition-[transform,opacity,visibility] duration-150 ease-in"
            leave-from-class="translate-y-0 scale-100 opacity-100"
            leave-to-class="-translate-y-2 scale-95 opacity-0"
          >
            <div
              v-if="menuUserOpen"
              ref="userMenuRef"
              class="site-header__user-dropdown absolute top-12 right-2 z-30 flex min-w-[200px] max-w-[calc(100vw-2rem)] flex-col overflow-hidden rounded-[10px] border border-[var(--site-line)] bg-[var(--site-bg)] p-3 pb-2 text-sm font-medium shadow-[0_12px_30px_rgba(0,0,0,0.12)] sm:right-0 sm:max-w-xs"
            >
              <div class="mb-2 flex items-center gap-2 border-b border-[var(--site-line)] pb-3">
                <div class="site-header__avatar-wrap flex h-8 w-8 items-center justify-center overflow-hidden rounded-full bg-[var(--site-panel)] md:h-10 md:w-10">
                  <span class="text-base font-normal uppercase md:text-lg">@</span>
                </div>
                <div class="flex flex-col gap-0.5">
                  <div class="max-w-xs truncate leading-[1.15]">Anonymous</div>
                </div>
              </div>

              <NuxtLink class="site-header__user-link flex items-center gap-1.5 rounded-[8px] px-2.5 py-1.5 transition-colors duration-150 hover:bg-[var(--site-panel)]" to="/signup/" @click="closeUserMenu">
                <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" class="h-5 w-5">
                  <path d="M3 12a9 9 0 1 0 18 0a9 9 0 0 0 -18 0" />
                  <path d="M15 9l-6 6" />
                  <path d="M15 15v-6h-6" />
                </svg>
                <span>Sign up</span>
              </NuxtLink>

              <NuxtLink class="site-header__user-link flex items-center gap-1.5 rounded-[8px] px-2.5 py-1.5 transition-colors duration-150 hover:bg-[var(--site-panel)]" to="/signin/" @click="closeUserMenu">
                <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" class="h-5 w-5">
                  <path d="M15 8v-2a2 2 0 0 0 -2 -2h-7a2 2 0 0 0 -2 2v12a2 2 0 0 0 2 2h7a2 2 0 0 0 2 -2v-2" />
                  <path d="M21 12h-13l3 -3" />
                  <path d="M11 15l-3 -3" />
                </svg>
                <span>Sign in</span>
              </NuxtLink>
            </div>
          </Transition>
        </div>
      </nav>
    </div>
  </header>
  <SiteSearchModal v-model="searchOpen" />
</template>
