import { ref, computed, onMounted, onUnmounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'

const HEADER_HEIGHT = 70
const SCROLL_OFFSET = 100

export function useAppNavigation(homeSectionIds = []) {
  const route = useRoute()
  const router = useRouter()
  const scrolled = ref(false)
  const homeActiveSection = ref('home')

  const activeNav = computed(() => {
    if (route.name === 'profile') return 'profile'
    if (route.name === 'contact') return 'contact'
    return 'home'
  })

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

  function updateHomeActiveSection() {
    if (route.name !== 'home' || !homeSectionIds.length) return

    const scrollPos = window.scrollY + HEADER_HEIGHT + SCROLL_OFFSET

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

  function navigate(target) {
    if (target === 'profile') {
      router.push({ name: 'profile' })
      return
    }

    if (target === 'contact') {
      router.push({ name: 'contact' })
      return
    }

    if (target === 'home') {
      router.push({ name: 'home' })
      return
    }

    if (target === 'business' || target === 'scope') {
      if (route.name !== 'home') {
        router.push({ name: 'home', hash: `#${target}` })
      } else {
        scrollToSection(target)
      }
      return
    }

    if (route.name !== 'home') {
      router.push({ name: 'home', hash: `#${target}` })
    } else {
      scrollToSection(target)
    }
  }

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

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

    if (route.hash) {
      setTimeout(() => scrollToSection(route.hash.slice(1)), 100)
    }
  })

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

  return { scrolled, activeNav, navigate, scrollToSection }
}
