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

const introTitle = 'ArcticNewOne'
const introLetters = introTitle.split('')
const introRef = ref<HTMLElement | null>(null)
const introTitleRef = ref<HTMLElement | null>(null)
let ctx: gsap.Context | null = null

const play = () => new Promise<void>((resolve) => {
  if (!introRef.value || !introTitleRef.value) return resolve()

  const chars = gsap.utils.toArray('.hero-intro-char', introRef.value)
  const tm = introRef.value.querySelector('.hero-intro-tm')

  if (!chars.length || !tm) return resolve()

  ctx = gsap.context(() => {
    // 初始化样式
    gsap.set(introRef.value, { display: 'grid', yPercent: 0, autoAlpha: 1 })
    gsap.set(introTitleRef.value, { y: 0, autoAlpha: 1 })
    gsap.set(chars, { y: 0, yPercent: 110 })
    gsap.set(tm, { autoAlpha: 0 })

    gsap.timeline({
      defaults: { ease: 'power3.out' },
      onComplete: () => {
        gsap.set(introRef.value, { display: 'none' })
        resolve()
      }
    })
      // 逐字升起
      .to(chars, { yPercent: 0, duration: 0.75, stagger: 0.055 })
      // TM 渐显
      .to(tm, { autoAlpha: 1, duration: 0.4, ease: 'power2.out' })
      // 停顿 0.35s 后，整体上移并淡出标题
      .addLabel('introOut', '+=0.35')
      .to(introTitleRef.value, { autoAlpha: 0, duration: 1.05, ease: 'power4.inOut' }, 'introOut')
      .to(introRef.value, { yPercent: -100, duration: 1.05, ease: 'power4.inOut' }, 'introOut')
  }, introRef.value)
})

onBeforeUnmount(() => ctx?.revert())

defineExpose({ play })
</script>

<template>
  <div ref="introRef" class="hero-intro" aria-hidden="true">
    <h1 ref="introTitleRef" class="hero-intro-title" :aria-label="introTitle" v-once>
      <span class="hero-intro-word">
        <span
          v-for="(letter, index) in introLetters"
          :key="`${letter}-${index}`"
          class="hero-intro-char-wrap"
        >
          <span class="hero-intro-char">{{ letter }}</span>
        </span>
        <span class="hero-intro-tm">TM</span>
      </span>
    </h1>
  </div>
</template>

<style scoped>
.hero-intro {
  position: fixed;
  inset: 0;
  z-index: 80;
  display: none;
  place-items: center;
  overflow: hidden;
  color: #fff;
  background: #000;
  opacity: 0;
  visibility: hidden;
  will-change: transform;
}

.hero-intro-title {
  display: flex;
  margin: 0;
  font-size: clamp(36px, 6.2vw, 104px);
  font-weight: 700;
  line-height: 0.9;
  letter-spacing: -0.07em;
  white-space: nowrap;
}

.hero-intro-word {
  position: relative;
  display: inline-flex;
}

.hero-intro-char-wrap,
.hero-intro-char {
  display: inline-block;
}

.hero-intro-char-wrap {
  position: relative;
  overflow: hidden;
}

.hero-intro-char {
  will-change: transform;
}

.hero-intro-tm {
  position: absolute;
  left: calc(100% + 0.12em);
  top: 0.08em;
  font-size: 0.13em;
  font-weight: 700;
  letter-spacing: -0.02em;
  line-height: 1;
  opacity: 0;
  visibility: hidden;
}
</style>
