'use client'

import { useEffect, useRef, useState } from 'react'
import { motion, AnimatePresence } from 'framer-motion'
import Image from 'next/image'
import { useLoading } from '@/components/providers/LoadingProvider'

const DURATION_MS = 3200

export function Loader() {
  const { isLoading, setLoaded } = useLoading()
  const [progress, setProgress] = useState(0)
  const [phase, setPhase] = useState<'draw' | 'assemble' | 'count' | 'done'>('draw')
  const rafRef = useRef<number>(0)

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

    const start = performance.now()

    const tick = (now: number) => {
      const elapsed = now - start
      let p: number

      if (elapsed < 1200) {
        p = (elapsed / 1200) * 60
        setPhase('draw')
      } else if (elapsed < 2200) {
        p = 60 + ((elapsed - 1200) / 1000) * 20
        setPhase('assemble')
      } else if (elapsed < DURATION_MS) {
        p = 80 + ((elapsed - 2200) / (DURATION_MS - 2200)) * 20
        setPhase('count')
      } else {
        setProgress(100)
        setPhase('done')
        setTimeout(setLoaded, 600)
        return
      }

      setProgress(Math.min(Math.floor(p), 100))
      rafRef.current = requestAnimationFrame(tick)
    }

    rafRef.current = requestAnimationFrame(tick)
    return () => cancelAnimationFrame(rafRef.current)
  }, [isLoading, setLoaded])

  return (
    <AnimatePresence>
      {isLoading && (
        <motion.div
          className="fixed inset-0 z-[10000] flex flex-col items-center justify-center overflow-hidden"
          style={{ background: 'var(--bg-primary)' }}
          exit={{ y: '-100%' }}
          transition={{ duration: 0.9, ease: [0.76, 0, 0.24, 1] }}
        >
          {/* Croatian checkerboard background */}
          <div className="absolute inset-0 opacity-[0.04]" aria-hidden="true">
            <svg width="100%" height="100%" xmlns="http://www.w3.org/2000/svg">
              <defs>
                <pattern id="checker" x="0" y="0" width="40" height="40" patternUnits="userSpaceOnUse">
                  <rect x="0" y="0" width="20" height="20" fill="white" />
                  <rect x="20" y="20" width="20" height="20" fill="white" />
                </pattern>
              </defs>
              <rect width="100%" height="100%" fill="url(#checker)" />
            </svg>
          </div>

          {/* Logo */}
          <div className="relative mb-12 flex items-center justify-center">
            <motion.div
              initial={{ opacity: 0, scale: 0.6 }}
              animate={{ opacity: 1, scale: 1 }}
              transition={{ duration: 0.8, ease: 'easeOut' }}
            >
              <Image
                src="/logo-mb.png"
                alt="Martin Baturina"
                width={220}
                height={140}
                style={{ objectFit: 'contain' }}
                priority
              />
            </motion.div>

            {/* Glow aura */}
            {(phase === 'assemble' || phase === 'count' || phase === 'done') && (
              <motion.div
                className="absolute rounded-full pointer-events-none"
                style={{
                  width: 280,
                  height: 280,
                  background: 'radial-gradient(circle, rgba(0,229,255,0.15) 0%, rgba(0,68,255,0.05) 50%, transparent 70%)',
                }}
                initial={{ opacity: 0, scale: 0.5 }}
                animate={{ opacity: [0, 1, 0], scale: [0.5, 1.2, 1.6] }}
                transition={{ duration: 1.5, ease: 'easeOut' }}
              />
            )}

            {/* Particle dots */}
            {Array.from({ length: 20 }).map((_, i) => (
              <motion.div
                key={i}
                className="absolute rounded-full pointer-events-none"
                style={{
                  width: 2 + (i % 3),
                  height: 2 + (i % 3),
                  background: i % 2 === 0 ? '#0044FF' : '#00E5FF',
                  top: `${20 + Math.sin(i * 1.3) * 60}%`,
                  left: `${20 + Math.cos(i * 0.9) * 60}%`,
                }}
                initial={{ opacity: 0, scale: 0 }}
                animate={phase === 'assemble' || phase === 'count' ? {
                  opacity: [0, 0.8, 0],
                  scale: [0, 1, 0],
                  x: [0, Math.cos(i * 0.9) * 20],
                  y: [0, Math.sin(i * 1.3) * 20],
                } : { opacity: 0, scale: 0 }}
                transition={{ duration: 1.2, delay: i * 0.05, ease: 'easeOut' }}
              />
            ))}
          </div>

          {/* Progress counter */}
          <motion.div
            className="font-display text-8xl leading-none tracking-tight"
            style={{ color: 'var(--white)' }}
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ duration: 0.6, delay: 0.3 }}
          >
            {String(progress).padStart(2, '0')}
          </motion.div>

          {/* Progress bar */}
          <div className="mt-8 w-48 h-px bg-white/10 overflow-hidden">
            <motion.div
              className="h-full"
              style={{ background: 'linear-gradient(90deg, var(--blue-primary), var(--cyan))' }}
              animate={{ width: `${progress}%` }}
              transition={{ duration: 0.1 }}
            />
          </div>

          {/* Footer text */}
          <motion.p
            className="mt-6 text-xs tracking-[0.3em] uppercase text-white/40 font-body"
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            transition={{ duration: 0.8, delay: 0.8 }}
          >
            Martin Baturina — Official
          </motion.p>

          {/* Flash on completion */}
          <AnimatePresence>
            {phase === 'done' && (
              <motion.div
                className="absolute inset-0 bg-white pointer-events-none"
                initial={{ opacity: 0 }}
                animate={{ opacity: [0, 0.6, 0] }}
                transition={{ duration: 0.5 }}
              />
            )}
          </AnimatePresence>
        </motion.div>
      )}
    </AnimatePresence>
  )
}
