'use client'

import { useEffect, useRef } from 'react'
import dynamic from 'next/dynamic'
import { gsap } from 'gsap'
import { ScrollTrigger } from 'gsap/ScrollTrigger'
import { useLoading } from '@/components/providers/LoadingProvider'
import { useMousePosition } from '@/hooks/useMousePosition'
import { useInView } from '@/hooks/useInView'
import { player } from '@/lib/data'

gsap.registerPlugin(ScrollTrigger)

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

export function Hero() {
  const { isLoading } = useLoading()
  const { normalizedX, normalizedY } = useMousePosition()
  const [sectionRef] = useInView<HTMLElement>({ threshold: 0.1 })
  const titleRef = useRef<HTMLHeadingElement>(null)
  const subtitleRef = useRef<HTMLParagraphElement>(null)
  const taglineRef = useRef<HTMLParagraphElement>(null)
  const scrollIndicatorRef = useRef<HTMLDivElement>(null)

  useEffect(() => {
    if (isLoading) return

    const ctx = gsap.context(() => {
      const tl = gsap.timeline({ delay: 0.2 })

      if (titleRef.current) {
        const words = titleRef.current.querySelectorAll('.word')
        // set initial y below clip area; opacity-0 CSS class handles initial opacity
        gsap.set(words, { y: '110%' })
        tl.to(words, {
          y: '0%',
          opacity: 1,
          duration: 1.2,
          stagger: 0.05,
          ease: 'expo.out',
        })
      }

      if (subtitleRef.current) {
        gsap.set(subtitleRef.current, { y: 30 })
        tl.to(subtitleRef.current, {
          y: 0,
          opacity: 1,
          duration: 0.8,
          ease: 'expo.out',
        }, '-=0.6')
      }

      if (taglineRef.current) {
        gsap.set(taglineRef.current, { y: 20 })
        tl.to(taglineRef.current, {
          y: 0,
          opacity: 1,
          duration: 0.8,
          ease: 'expo.out',
        }, '-=0.5')
      }

      if (scrollIndicatorRef.current) {
        gsap.set(scrollIndicatorRef.current, { y: 10 })
        tl.to(scrollIndicatorRef.current, {
          opacity: 1,
          y: 0,
          duration: 0.6,
        }, '-=0.3')
      }
    })

    return () => ctx.revert()
  }, [isLoading])

  const titleWords = player.name.split(' ')

  return (
    <section
      id="hero"
      ref={sectionRef}
      className="relative w-full min-h-screen overflow-hidden flex items-center"
      style={{
        background: 'radial-gradient(ellipse 80% 60% at 50% 40%, #07071A 0%, #020209 70%)',
      }}
      aria-label="Hero — Martin Baturina"
    >
      {/* 3D Canvas */}
      <div className="canvas-3d absolute inset-0 z-0" aria-hidden="true">
        <HeroCanvas mouseX={normalizedX} mouseY={normalizedY} active={true} />
      </div>

      {/* Mobile fallback gradient */}
      <div
        className="canvas-fallback absolute inset-0 z-0"
        style={{
          background: 'radial-gradient(circle at 50% 40%, rgba(0,68,255,0.15) 0%, transparent 60%)',
        }}
        aria-hidden="true"
      />

      {/* Vignette */}
      <div
        className="absolute inset-0 z-10 pointer-events-none"
        style={{
          background: 'radial-gradient(ellipse 100% 100% at 50% 50%, transparent 30%, rgba(2,2,9,0.6) 100%)',
        }}
        aria-hidden="true"
      />

      {/* Content */}
      <div className="relative z-20 w-full px-8 md:px-16 lg:px-24 pt-32 pb-24">
        <div className="max-w-screen-xl mx-auto">
          <div className="grid grid-cols-1 lg:grid-cols-12 gap-8 items-end min-h-[70vh]">

            {/* Main title column */}
            <div className="lg:col-span-8 flex flex-col justify-end">
              {/* Eyebrow */}
              <p
                ref={subtitleRef}
                className="font-body text-xs tracking-[0.4em] uppercase mb-6 opacity-0"
                style={{ color: 'var(--cyan)' }}
              >
                Como 1907 · Croatia · #10
              </p>

              {/* Name */}
              <h1
                ref={titleRef}
                className="font-display leading-none mb-8"
                style={{
                  fontSize: 'clamp(4rem, 14vw, 14rem)',
                  color: 'var(--white)',
                  lineHeight: 0.9,
                }}
                aria-label={player.name}
              >
                {titleWords.map((word, i) => (
                  <span
                    key={i}
                    className="clip-line block"
                  >
                    <span className="word inline-block opacity-0">{word}</span>
                  </span>
                ))}
              </h1>

              {/* Stats strip */}
              <div className="flex gap-8 mt-4">
                {[
                  { label: 'Born', value: '2003' },
                  { label: 'Apps', value: '150+' },
                  { label: 'Trophies', value: '8' },
                ].map((s) => (
                  <div key={s.label} className="flex flex-col gap-1">
                    <span
                      className="font-display text-3xl leading-none"
                      style={{ color: 'var(--cyan)' }}
                    >
                      {s.value}
                    </span>
                    <span
                      className="font-body text-xs uppercase tracking-widest"
                      style={{ color: 'rgba(240,240,255,0.4)' }}
                    >
                      {s.label}
                    </span>
                  </div>
                ))}
              </div>
            </div>

            {/* Tagline column */}
            <div className="lg:col-span-4 flex flex-col justify-end lg:text-right">
              <p
                ref={taglineRef}
                className="font-body text-sm leading-relaxed uppercase tracking-widest opacity-0"
                style={{ color: 'rgba(240,240,255,0.5)' }}
              >
                Born in Zürich.<br />
                Raised in Zagreb.<br />
                <span style={{ color: 'var(--white)' }}>The World is Next.</span>
              </p>
            </div>
          </div>
        </div>
      </div>

      {/* Scroll indicator */}
      <div
        ref={scrollIndicatorRef}
        className="absolute bottom-8 left-1/2 -translate-x-1/2 z-20 flex flex-col items-center gap-3 opacity-0"
        aria-hidden="true"
      >
        <span
          className="font-body text-xs uppercase tracking-[0.3em]"
          style={{ color: 'rgba(240,240,255,0.4)' }}
        >
          Scroll
        </span>
        <div
          className="w-px h-16 relative overflow-hidden"
          style={{ background: 'rgba(240,240,255,0.15)' }}
        >
          <div
            className="absolute top-0 left-0 w-full animate-[scrollLine_2s_ease-in-out_infinite]"
            style={{
              height: '40%',
              background: 'linear-gradient(to bottom, transparent, var(--cyan))',
              animation: 'scrollLine 2s ease-in-out infinite',
            }}
          />
        </div>
      </div>

      {/* Bottom gradient blend */}
      <div
        className="absolute bottom-0 left-0 right-0 h-32 z-10 pointer-events-none"
        style={{
          background: 'linear-gradient(to bottom, transparent, var(--bg-primary))',
        }}
        aria-hidden="true"
      />

      <style jsx>{`
        @keyframes scrollLine {
          0% { transform: translateY(-100%); opacity: 0; }
          20% { opacity: 1; }
          80% { opacity: 1; }
          100% { transform: translateY(250%); opacity: 0; }
        }
      `}</style>
    </section>
  )
}
