<script setup lang="ts">
import { ref, watch } from 'vue'
import { useScrollReveal } from '@/composables/useScrollReveal'

const { target, isVisible } = useScrollReveal()

const stats = [
  { value: 10000, suffix: '+', label: '活跃师生', desc: '每天在灵犀学上学习' },
  { value: 200, suffix: '+', label: '合作学校', desc: '覆盖全国多个省市' },
  { value: 500, suffix: '万+', label: '题目批改', desc: 'AI 累计批改题目数' },
  { value: 96.8, suffix: '%', label: '批改准确率', desc: '媲美资深教师水平' },
]

const counters = ref(stats.map(() => 0))

function animateCounter(index: number, target: number, duration = 2000) {
  const start = performance.now()
  const isFloat = !Number.isInteger(target)

  function update(now: number) {
    const elapsed = now - start
    const progress = Math.min(elapsed / duration, 1)
    const eased = 1 - Math.pow(1 - progress, 3)
    counters.value[index] = isFloat
      ? Math.round(target * eased * 10) / 10
      : Math.round(target * eased)
    if (progress < 1) requestAnimationFrame(update)
  }

  requestAnimationFrame(update)
}

watch(isVisible, (val) => {
  if (val) {
    stats.forEach((s, i) => {
      setTimeout(() => animateCounter(i, s.value), i * 150)
    })
  }
})
</script>

<template>
  <section class="relative py-20 lg:py-28 bg-white overflow-hidden">
    <div class="absolute inset-0 bg-gradient-to-r from-primary/3 via-transparent to-accent/3" />

    <div ref="target" class="relative max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
      <div class="grid grid-cols-2 lg:grid-cols-4 gap-6 lg:gap-8">
        <div
          v-for="(stat, i) in stats"
          :key="stat.label"
          class="text-center p-6 lg:p-8 rounded-2xl bg-white border border-gray-100 shadow-sm hover:shadow-lg hover:shadow-primary/5 hover:-translate-y-1 transition-all duration-300 cursor-default"
          :class="isVisible ? 'opacity-100 translate-y-0' : 'opacity-0 translate-y-8'"
          :style="{ transitionDelay: isVisible ? `${i * 100}ms` : '0ms', transitionDuration: '600ms' }"
        >
          <p class="text-3xl sm:text-4xl lg:text-5xl font-extrabold gradient-text leading-none">
            {{ Number.isInteger(stat.value) ? counters[i].toLocaleString() : counters[i].toFixed(1) }}{{ stat.suffix }}
          </p>
          <p class="text-base font-bold text-text-heading mt-3">{{ stat.label }}</p>
          <p class="text-sm text-text-muted mt-1">{{ stat.desc }}</p>
        </div>
      </div>
    </div>
  </section>
</template>
