<script setup lang="ts">
import { onBeforeUnmount, onMounted, ref } from 'vue'
import gsap from 'gsap'
import { ScrollTrigger } from 'gsap/ScrollTrigger'

gsap.registerPlugin(ScrollTrigger)

const topHeaderRef = ref<HTMLElement | null>(null)
const bottomHeaderRef = ref<HTMLElement | null>(null)
let topHeaderTween: gsap.core.Tween | null = null
let bottomHeaderScrollTrigger: ReturnType<typeof ScrollTrigger.create> | null = null
let isBottomHeaderVisible = false

const setBottomHeaderVisible = (visible: boolean) => {
  if (!bottomHeaderRef.value || isBottomHeaderVisible === visible) {
    return
  }

  isBottomHeaderVisible = visible

  gsap.to(bottomHeaderRef.value, {
    yPercent: visible ? 0 : 140,
    autoAlpha: visible ? 1 : 0,
    duration: 0.35,
    ease: 'power2.out',
    overwrite: 'auto',
  })
}

onMounted(() => {
  // 底部导航默认藏在视口下方，只有滚动到深处并向上滚时才出现。
  gsap.set(bottomHeaderRef.value, {
    yPercent: 140,
    autoAlpha: 0,
  })

  // 顶部导航在页面刚开始滚动的前 200px 内逐渐上移并隐藏。
  topHeaderTween = gsap.to(topHeaderRef.value, {
    yPercent: -140,
    autoAlpha: 0,
    ease: 'none',
    scrollTrigger: {
      start: 0,
      end: 200,
      scrub: true,
    },
  })

  bottomHeaderScrollTrigger = ScrollTrigger.create({
    start: 0,
    end: 'max',
    onUpdate: (self) => {
      const scrollY = self.scroll()

      // 深度超过 2500px 后向上滚，显示未来用于深层内容的底部导航。
      if (scrollY > 2500 && self.direction === -1) {
        setBottomHeaderVisible(true)
        return
      }

      // 回到 2300px 以内，或继续向下滚时，底部导航收回。
      if (scrollY <= 2300 || self.direction === 1) {
        setBottomHeaderVisible(false)
      }
    },
  })

  ScrollTrigger.refresh()
})

onBeforeUnmount(() => {
  topHeaderTween?.scrollTrigger?.kill()
  topHeaderTween?.kill()
  bottomHeaderScrollTrigger?.kill()
  topHeaderTween = null
  bottomHeaderScrollTrigger = null
  isBottomHeaderVisible = false
  gsap.killTweensOf([topHeaderRef.value, bottomHeaderRef.value])
})

</script>

<template>
  <header
    ref="topHeaderRef"
    class="site-header-top fixed left-0 right-0 top-0 z-50 mx-auto h-[70px] w-page-container max-w-[calc(100%-2rem)] bg-red-200 px-4 py-5"
  >
    <nav>Top Navigation</nav>
  </header>

  <header
    ref="bottomHeaderRef"
    class="fixed bottom-0 left-0 right-0 z-50 mx-auto h-[70px] w-page-container max-w-[calc(100%-2rem)] bg-blue-200 px-4 py-5"
    style="visibility: hidden; opacity: 0;"
  >
    <nav>Bottom Navigation</nav>
  </header>
</template>
