<script setup>
import { nextTick, onBeforeUnmount, onMounted, ref } from 'vue'
import { navItems } from '../data/homepage'
import IconMark from './IconMark.vue'

const activeTarget = ref(navItems[0]?.target ?? '')
const isMenuOpen = ref(false)
let observer

const getHeaderOffset = () => {
  const header = document.querySelector('.site-header')
  if (!header) return 0

  const position = window.getComputedStyle(header).position
  return position === 'sticky' || position === 'fixed' ? header.offsetHeight : 0
}

const toggleMenu = () => {
  isMenuOpen.value = !isMenuOpen.value
}

const closeMenu = () => {
  isMenuOpen.value = false
}

const scrollToTarget = async (target) => {
  const element = document.getElementById(target)
  if (!element) return

  closeMenu()
  activeTarget.value = target
  const top = element.getBoundingClientRect().top + window.scrollY - getHeaderOffset() - 12
  window.scrollTo({ top: Math.max(0, top), behavior: 'smooth' })
  history.replaceState(null, '', `#${target}`)
  await nextTick()
  document.querySelector(`.nav-link[href="#${target}"]`)?.scrollIntoView({
    behavior: 'smooth',
    inline: 'center',
    block: 'nearest'
  })
}

const handleWindowKeydown = (event) => {
  if (event.key === 'Escape') closeMenu()
}

onMounted(() => {
  window.addEventListener('keydown', handleWindowKeydown)

  if (window.location.hash) {
    const target = window.location.hash.slice(1)
    if (navItems.some(item => item.target === target)) {
      requestAnimationFrame(() => scrollToTarget(target))
    }
  }

  observer = new IntersectionObserver(
    (entries) => {
      const visibleEntry = entries
        .filter(entry => entry.isIntersecting)
        .sort((a, b) => b.intersectionRatio - a.intersectionRatio)[0]

      if (visibleEntry?.target.id) {
        activeTarget.value = visibleEntry.target.id
      }
    },
    {
      rootMargin: '-32% 0px -54% 0px',
      threshold: [0.12, 0.28, 0.5]
    }
  )

  navItems.forEach((item) => {
    const element = document.getElementById(item.target)
    if (element) observer.observe(element)
  })
})

onBeforeUnmount(() => {
  observer?.disconnect()
  window.removeEventListener('keydown', handleWindowKeydown)
})
</script>

<template>
  <header class="site-header">
    <div class="container header-inner">
      <a class="brand" href="#home" aria-label="柚康科技首页" @click.prevent="scrollToTarget('home')">
        <img src="/assets/logo.png" alt="柚康科技 logo" class="brand-logo" />
        <span class="brand-copy">
          <strong>柚康科技</strong>
          <i class="brand-separator" aria-hidden="true"></i>
          <img class="brand-service" src="/assets/服务商.png" alt="企业微信服务商" />
        </span>
      </a>
      <button
        class="nav-toggle"
        type="button"
        :aria-expanded="isMenuOpen"
        aria-controls="main-navigation"
        :aria-label="isMenuOpen ? '收起主导航' : '展开主导航'"
        @click="toggleMenu"
      >
        <IconMark :name="isMenuOpen ? 'x' : 'menu'" :size="24" />
      </button>
      <nav
        id="main-navigation"
        :class="['nav-links', { open: isMenuOpen }]"
        aria-label="主导航"
      >
        <a
          v-for="item in navItems"
          :key="item.target"
          :href="`#${item.target}`"
          :class="['nav-link', { active: item.target === activeTarget }]"
          :aria-current="item.target === activeTarget ? 'page' : undefined"
          @click.prevent="scrollToTarget(item.target)"
        >
          {{ item.label }}
        </a>
      </nav>
    </div>
  </header>
</template>
