import { ref, onMounted, onUnmounted } from 'vue'

const HEADER_HEIGHT = 70
const SCROLL_OFFSET = 100

export function useScrollNav(sectionIds) {
  const scrolled = ref(false)
  const activeSection = ref(sectionIds[0])

  function scrollToSection(id) {
    const target = document.getElementById(id)
    if (target) {
      window.scrollTo({
        top: target.offsetTop - HEADER_HEIGHT,
        behavior: 'smooth',
      })
    }
  }

  function updateActiveSection() {
    const scrollPos = window.scrollY + HEADER_HEIGHT + SCROLL_OFFSET

    for (let i = sectionIds.length - 1; i >= 0; i--) {
      const section = document.getElementById(sectionIds[i])
      if (section && scrollPos >= section.offsetTop) {
        activeSection.value = sectionIds[i]
        return
      }
    }
  }

  function onScroll() {
    scrolled.value = window.scrollY > 50
    updateActiveSection()
  }

  onMounted(() => {
    window.addEventListener('scroll', onScroll, { passive: true })
    onScroll()
  })

  onUnmounted(() => {
    window.removeEventListener('scroll', onScroll)
  })

  return { scrolled, activeSection, scrollToSection }
}
