'use client'

import { useEffect, useRef, Suspense } from 'react'
import dynamic from 'next/dynamic'
import { Canvas } from '@react-three/fiber'
import { gsap } from 'gsap'
import { ScrollTrigger } from 'gsap/ScrollTrigger'
import { Radar, RadarChart, PolarGrid, PolarAngleAxis, ResponsiveContainer } from 'recharts'
import { skills } from '@/lib/data'
import { useInView } from '@/hooks/useInView'

gsap.registerPlugin(ScrollTrigger)

const StatsField = dynamic(
  () => import('@/components/canvas/StatsField').then((m) => m.StatsField),
  { ssr: false }
)

const STATS = [
  { label: 'Appearances', value: 110, suffix: '+', note: 'Career total' },
  { label: 'Goals', value: 23, suffix: '', note: 'All competitions' },
  { label: 'Assists', value: 30, suffix: '', note: 'All competitions' },
  { label: 'Rating', value: 7.24, suffix: '', note: '25/26 Serie A avg' },
  { label: 'National Caps', value: 15, suffix: '', note: 'Croatia senior' },
  { label: 'Trophies', value: 8, suffix: '', note: 'Club career' },
]

function StatCounter({ label, value, suffix, note }: { label: string; value: number; suffix: string; note: string }) {
  const counterRef = useRef<HTMLSpanElement>(null)
  const sectionRef = useRef<HTMLDivElement>(null)

  useEffect(() => {
    if (!counterRef.current || !sectionRef.current) return
    const el = counterRef.current
    const obj = { v: 0 }

    ScrollTrigger.create({
      trigger: sectionRef.current,
      start: 'top 80%',
      onEnter: () => {
        gsap.to(obj, {
          v: value,
          duration: 1.8,
          ease: 'power2.out',
          onUpdate: () => {
            el.textContent = (value % 1 === 0 ? Math.round(obj.v) : obj.v.toFixed(2)) + suffix
          },
        })
      },
    })
  }, [value, suffix])

  return (
    <div
      ref={sectionRef}
      className="glass-card rounded-xl p-5 text-center flex flex-col gap-1"
    >
      <span
        ref={counterRef}
        className="font-display text-4xl md:text-5xl leading-none"
        style={{ color: 'var(--cyan)' }}
      >
        0{suffix}
      </span>
      <span className="font-body text-xs uppercase tracking-widest mt-1" style={{ color: 'var(--white-soft)' }}>
        {label}
      </span>
      <span className="font-body text-xs" style={{ color: 'rgba(240,240,255,0.35)' }}>
        {note}
      </span>
    </div>
  )
}

export function Stats() {
  const [sectionRef, inView] = useInView<HTMLElement>({ threshold: 0.1 })

  return (
    <section
      id="stats"
      ref={sectionRef}
      className="relative w-full min-h-screen overflow-hidden py-24"
      style={{ background: 'var(--bg-primary)' }}
      aria-label="Stats"
    >
      <div className="px-8 md:px-16 max-w-screen-xl mx-auto">
        {/* Header */}
        <div className="mb-16">
          <p className="font-body text-xs tracking-[0.4em] uppercase mb-2" style={{ color: 'var(--cyan)' }}>
            Performance
          </p>
          <h2 className="font-display" style={{ fontSize: 'clamp(3rem, 8vw, 8rem)', color: 'var(--white)', lineHeight: 0.9 }}>
            Statistics
          </h2>
        </div>

        {/* Pitch canvas */}
        <div className="relative rounded-2xl overflow-hidden mb-12" style={{ height: '50vh', border: '1px solid rgba(0,68,255,0.15)' }}>
          <div className="canvas-3d absolute inset-0">
            <Canvas
              frameloop={inView ? 'always' : 'never'}
              camera={{ position: [0, 8, 4], fov: 55, near: 0.1, far: 100 }}
              dpr={[1, 2]}
              gl={{ antialias: true, alpha: false }}
            >
              <Suspense fallback={null}>
                <StatsField />
              </Suspense>
            </Canvas>
          </div>

          {/* Mobile fallback */}
          <div
            className="canvas-fallback absolute inset-0 flex items-center justify-center"
            style={{ background: 'linear-gradient(135deg, #0d2e0d, #020209)' }}
          >
            <span className="font-display text-2xl" style={{ color: 'rgba(0,229,255,0.5)' }}>
              Stats Field
            </span>
          </div>

          {/* Overlay: heatmap legend */}
          <div className="absolute bottom-4 right-4 glass-card rounded-lg px-3 py-2 z-10">
            <p className="font-body text-xs" style={{ color: 'rgba(240,240,255,0.6)' }}>
              ▓ Activity Heatmap
            </p>
          </div>
        </div>

        {/* Stat counters grid */}
        <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-4 mb-16">
          {STATS.map((s) => (
            <StatCounter key={s.label} {...s} />
          ))}
        </div>

        {/* Radar chart */}
        <div className="grid grid-cols-1 lg:grid-cols-2 gap-12 items-center">
          <div>
            <h3 className="font-display text-4xl mb-4" style={{ color: 'var(--white)' }}>
              Player Profile
            </h3>
            <p className="font-body text-sm leading-relaxed" style={{ color: 'rgba(240,240,255,0.5)' }}>
              Elite end product, exceptional vision, and technical mastery. The numbers tell only part of the story — the creativity and intelligence are beyond measure.
            </p>
          </div>

          <div className="h-64 md:h-80">
            <ResponsiveContainer width="100%" height="100%">
              <RadarChart data={skills}>
                <PolarGrid stroke="rgba(0,68,255,0.3)" />
                <PolarAngleAxis
                  dataKey="label"
                  tick={{ fill: 'rgba(240,240,255,0.6)', fontSize: 12, fontFamily: 'var(--font-body)' }}
                />
                <Radar
                  name="Martin Baturina"
                  dataKey="value"
                  stroke="#00E5FF"
                  fill="#0044FF"
                  fillOpacity={0.25}
                  strokeWidth={2}
                />
              </RadarChart>
            </ResponsiveContainer>
          </div>
        </div>
      </div>
    </section>
  )
}
