'use client'

import { useEffect, useRef } from 'react'
import Image from 'next/image'
import { gsap } from 'gsap'
import { ScrollTrigger } from 'gsap/ScrollTrigger'
import { careerTimeline } from '@/lib/data'

gsap.registerPlugin(ScrollTrigger)

export function CareerTimeline() {
  const containerRef = useRef<HTMLDivElement>(null)
  const trackRef = useRef<HTMLDivElement>(null)
  const progressLineRef = useRef<SVGLineElement>(null)

  useEffect(() => {
    const ctx = gsap.context(() => {
      const cards = gsap.utils.toArray<HTMLElement>('.career-card')
      if (!cards.length || !trackRef.current) return

      // Horizontal scroll
      const horizontalTween = gsap.to(trackRef.current, {
        x: () => -(trackRef.current!.scrollWidth - window.innerWidth),
        ease: 'none',
        scrollTrigger: {
          trigger: containerRef.current,
          pin: true,
          start: 'top top',
          end: () => `+=${trackRef.current!.scrollWidth - window.innerWidth + window.innerHeight}`,
          scrub: 1.5,
          snap: { snapTo: 1 / (cards.length - 1), duration: 0.6, ease: 'power2.inOut' },
          onUpdate(self) {
            // Animate SVG progress line
            if (progressLineRef.current) {
              progressLineRef.current.setAttribute(
                'x2',
                String(self.progress * 100) + '%'
              )
            }
            // Highlight active card dot
            cards.forEach((card, i) => {
              const dot = card.querySelector('.card-dot')
              const isActive = self.progress >= i / (cards.length - 1) - 0.05
              if (dot) {
                ;(dot as HTMLElement).style.background = isActive
                  ? card.dataset.accent || '#0044FF'
                  : 'rgba(240,240,255,0.2)'
                ;(dot as HTMLElement).style.boxShadow = isActive
                  ? `0 0 12px 4px ${card.dataset.accent || '#0044FF'}80`
                  : 'none'
              }
            })
          },
        },
      })

      // Card entrance animations
      cards.forEach((card) => {
        gsap.from(card.querySelectorAll('.card-reveal'), {
          y: 40,
          opacity: 0,
          duration: 0.6,
          stagger: 0.1,
          ease: 'expo.out',
          scrollTrigger: {
            trigger: card,
            // eslint-disable-next-line @typescript-eslint/no-explicit-any
            containerAnimation: horizontalTween as any,
            start: 'left 80%',
            toggleActions: 'play none none reverse',
          },
        })
      })
    }, containerRef)

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

  return (
    <section
      id="career"
      ref={containerRef}
      className="relative overflow-hidden"
      style={{ background: 'var(--bg-secondary)' }}
      aria-label="Career Timeline"
    >
      {/* Section header */}
      <div className="absolute top-8 left-8 md:left-16 z-20">
        <p className="font-body text-xs tracking-[0.4em] uppercase mb-1" style={{ color: 'var(--cyan)' }}>
          The Journey
        </p>
        <h2 className="font-display text-4xl md:text-6xl" style={{ color: 'var(--white)' }}>
          Career
        </h2>
      </div>

      {/* Horizontal track */}
      <div ref={trackRef} className="flex h-screen will-change-transform">
        {careerTimeline.map((entry, i) => (
          <div
            key={entry.id}
            className="career-card flex-shrink-0 w-screen h-screen flex items-center px-8 md:px-24 relative"
            data-accent={entry.accentColor}
            style={{
              background: `radial-gradient(ellipse 50% 80% at 60% 50%, ${entry.accentColor}0A 0%, transparent 70%)`,
            }}
          >
            <div className="max-w-screen-xl mx-auto w-full">
              <div className="grid grid-cols-1 lg:grid-cols-2 gap-16 items-center">
                <div>
                  {/* Step number */}
                  <div className="card-reveal flex items-center gap-4 mb-6">
                    <span
                      className="font-display text-8xl leading-none opacity-10"
                      style={{ color: entry.accentColor }}
                    >
                      {String(i + 1).padStart(2, '0')}
                    </span>
                    <div className="w-16 h-px" style={{ background: entry.accentColor }} />
                    <span className="font-body text-xs tracking-widest uppercase" style={{ color: entry.accentColor }}>
                      {entry.type === 'youth' ? 'Youth' : entry.type === 'national' ? 'International' : 'Club'}
                    </span>
                  </div>

                  {/* Years */}
                  <p className="card-reveal font-body text-xs tracking-widest uppercase mb-3" style={{ color: 'rgba(240,240,255,0.4)' }}>
                    {entry.startYear} — {entry.endYear ?? 'Present'}
                  </p>

                  {/* Club name */}
                  <h3
                    className="card-reveal font-display leading-none mb-4"
                    style={{
                      fontSize: 'clamp(2.5rem, 6vw, 6rem)',
                      color: 'var(--white)',
                    }}
                  >
                    {entry.clubShort}
                  </h3>

                  <p
                    className="card-reveal font-body text-xs uppercase tracking-widest mb-6"
                    style={{ color: 'rgba(240,240,255,0.4)' }}
                  >
                    {entry.league} · {entry.country}
                  </p>

                  <p className="card-reveal font-body text-sm md:text-base leading-relaxed max-w-md" style={{ color: 'rgba(240,240,255,0.6)' }}>
                    {entry.description}
                  </p>

                  {/* Transfer fee badge */}
                  {entry.fee && (
                    <div
                      className="card-reveal mt-6 inline-flex items-center gap-2 px-4 py-2 rounded-full glass-card"
                    >
                      <span className="font-body text-xs uppercase tracking-widest" style={{ color: 'rgba(240,240,255,0.5)' }}>
                        Transfer Fee
                      </span>
                      <span className="font-display text-xl" style={{ color: 'var(--gold)' }}>
                        {entry.fee}
                      </span>
                    </div>
                  )}
                </div>

                {/* Right panel: jersey + optional stats/trophies */}
                {entry.jersey && (
                  <div className="card-reveal flex flex-col items-center gap-8">
                    {/* Jersey */}
                    <div
                      className="relative flex items-center justify-center"
                      style={{ filter: `drop-shadow(0 0 32px ${entry.accentColor}70)` }}
                    >
                      <Image
                        src={entry.jersey}
                        alt={`${entry.club} jersey`}
                        width={280}
                        height={320}
                        style={{
                          objectFit: 'contain',
                          transform: 'rotate(-6deg)',
                          maxHeight: '320px',
                          width: 'auto',
                        }}
                        priority={false}
                        unoptimized
                      />
                    </div>

                    {/* Stats grid */}
                    {entry.apps !== undefined && (
                      <div className="grid grid-cols-3 gap-4 w-full">
                        {[
                          { label: 'Apps', value: entry.apps },
                          { label: 'Goals', value: entry.goals ?? 0 },
                          { label: 'Assists', value: entry.assists ?? 0 },
                        ].map((s) => (
                          <div
                            key={s.label}
                            className="glass-card rounded-xl p-4 text-center"
                            style={{ borderColor: `${entry.accentColor}30` }}
                          >
                            <div
                              className="font-display text-4xl md:text-5xl leading-none mb-1"
                              style={{ color: entry.accentColor }}
                            >
                              {s.value}
                            </div>
                            <div className="font-body text-xs uppercase tracking-widest" style={{ color: 'rgba(240,240,255,0.4)' }}>
                              {s.label}
                            </div>
                          </div>
                        ))}
                      </div>
                    )}

                    {/* Trophies */}
                    {entry.trophies && entry.trophies.length > 0 && (
                      <div className="w-full">
                        <p className="font-body text-xs uppercase tracking-widest mb-3" style={{ color: 'rgba(240,240,255,0.4)' }}>
                          Trophies Won
                        </p>
                        <div className="flex flex-wrap gap-2">
                          {entry.trophies.map((t) => (
                            <span
                              key={t}
                              className="font-body text-xs px-3 py-1 rounded-full"
                              style={{
                                background: `${entry.accentColor}20`,
                                border: `1px solid ${entry.accentColor}40`,
                                color: entry.accentColor,
                              }}
                            >
                              {t}
                            </span>
                          ))}
                        </div>
                      </div>
                    )}
                  </div>
                )}
              </div>
            </div>

            {/* Card dot indicator */}
            <div
              className="card-dot absolute bottom-12 left-1/2 -translate-x-1/2 w-2 h-2 rounded-full transition-all duration-500"
              style={{ background: 'rgba(240,240,255,0.2)' }}
            />
          </div>
        ))}
      </div>

      {/* SVG progress line at bottom */}
      <div className="absolute bottom-8 left-0 right-0 px-8 md:px-24 pointer-events-none z-20">
        <svg width="100%" height="2" style={{ overflow: 'visible' }}>
          <line
            x1="0"
            y1="1"
            x2="100%"
            y2="1"
            stroke="rgba(240,240,255,0.1)"
            strokeWidth="1"
          />
          <line
            ref={progressLineRef}
            x1="0"
            y1="1"
            x2="0"
            y2="1"
            stroke="var(--cyan)"
            strokeWidth="2"
            style={{ filter: 'drop-shadow(0 0 4px var(--cyan))' }}
          />
        </svg>
      </div>
    </section>
  )
}
