'use client'

import { useEffect, useState } from 'react'
import { motion, AnimatePresence } from 'framer-motion'
import { Trophy, Star, Sparkles } from 'lucide-react'
import Confetti from 'react-confetti'

const KONAMI_CODE = ['ArrowUp', 'ArrowUp', 'ArrowDown', 'ArrowDown', 'ArrowLeft', 'ArrowRight', 'ArrowLeft', 'ArrowRight', 'b', 'a']

export function EasterEgg() {
  const [keys, setKeys] = useState<string[]>([])
  const [isActivated, setIsActivated] = useState(false)
  const [showConfetti, setShowConfetti] = useState(false)
  const [windowSize, setWindowSize] = useState({ width: 0, height: 0 })

  useEffect(() => {
    // Get initial window size
    setWindowSize({
      width: window.innerWidth,
      height: window.innerHeight,
    })

    const handleResize = () => {
      setWindowSize({
        width: window.innerWidth,
        height: window.innerHeight,
      })
    }

    window.addEventListener('resize', handleResize)

    return () => window.removeEventListener('resize', handleResize)
  }, [])

  useEffect(() => {
    const handleKeyDown = (event: KeyboardEvent) => {
      const newKeys = [...keys, event.key].slice(-KONAMI_CODE.length)
      setKeys(newKeys)

      // Check if Konami code is matched
      if (JSON.stringify(newKeys) === JSON.stringify(KONAMI_CODE)) {
        activateEasterEgg()
      }
    }

    window.addEventListener('keydown', handleKeyDown)

    return () => window.removeEventListener('keydown', handleKeyDown)
  }, [keys])

  const activateEasterEgg = () => {
    if (isActivated) return

    setIsActivated(true)
    setShowConfetti(true)

    // Save achievement to localStorage
    const achievements = JSON.parse(localStorage.getItem('achievements') || '[]')
    if (!achievements.includes('konami-code')) {
      achievements.push('konami-code')
      localStorage.setItem('achievements', JSON.stringify(achievements))
    }

    // Stop confetti after 5 seconds
    setTimeout(() => {
      setShowConfetti(false)
    }, 5000)

    // Hide modal after 10 seconds
    setTimeout(() => {
      setIsActivated(false)
      setKeys([])
    }, 10000)
  }

  return (
    <>
      {showConfetti && (
        <Confetti
          width={windowSize.width}
          height={windowSize.height}
          recycle={false}
          numberOfPieces={500}
          gravity={0.3}
        />
      )}

      <AnimatePresence>
        {isActivated && (
          <motion.div
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            className="fixed inset-0 z-[9999] flex items-center justify-center bg-black/80 backdrop-blur-sm"
            onClick={() => setIsActivated(false)}
          >
            <motion.div
              initial={{ scale: 0, rotate: -180 }}
              animate={{ scale: 1, rotate: 0 }}
              exit={{ scale: 0, rotate: 180 }}
              transition={{ type: 'spring', duration: 0.6 }}
              className="bg-gray-900 border-2 border-gradient rounded-3xl p-8 md:p-12 max-w-md mx-4 text-center relative overflow-hidden"
              onClick={(e) => e.stopPropagation()}
            >
              {/* Animated Background */}
              <div className="absolute inset-0 overflow-hidden opacity-20">
                {[...Array(20)].map((_, i) => (
                  <motion.div
                    key={i}
                    className="absolute"
                    initial={{
                      x: Math.random() * 500,
                      y: Math.random() * 500,
                      scale: 0,
                    }}
                    animate={{
                      y: [null, -1000],
                      scale: [0, 1, 0],
                      rotate: [0, 360],
                    }}
                    transition={{
                      duration: 3 + Math.random() * 2,
                      repeat: Infinity,
                      delay: Math.random() * 2,
                    }}
                  >
                    <Star className="w-6 h-6 text-yellow-400" />
                  </motion.div>
                ))}
              </div>

              {/* Content */}
              <div className="relative z-10">
                <motion.div
                  animate={{
                    rotate: [0, -10, 10, -10, 10, 0],
                    scale: [1, 1.1, 1, 1.1, 1],
                  }}
                  transition={{
                    duration: 0.5,
                    times: [0, 0.2, 0.4, 0.6, 0.8, 1],
                  }}
                  className="flex justify-center mb-6"
                >
                  <div className="w-24 h-24 bg-gradient-to-br from-yellow-400 via-red-500 to-blue-600 rounded-full flex items-center justify-center shadow-glow-duo">
                    <Trophy className="w-12 h-12 text-white" />
                  </div>
                </motion.div>

                <h2 className="text-3xl md:text-4xl font-bold text-gradient mb-4">
                  Achievement Unlocked!
                </h2>

                <div className="flex items-center justify-center gap-2 mb-4">
                  <Sparkles className="w-5 h-5 text-yellow-400" />
                  <span className="text-xl text-yellow-400 font-semibold">
                    Konami Code Master
                  </span>
                  <Sparkles className="w-5 h-5 text-yellow-400" />
                </div>

                <p className="text-gray-300 mb-6">
                  You've discovered the secret Konami code! You're a true gaming legend. 🎮
                </p>

                <div className="bg-gradient-to-r from-red-500/10 to-blue-600/10 border border-gray-700 rounded-xl p-4 mb-6">
                  <p className="text-sm text-gray-400">
                    <strong className="text-gradient">Fun Fact:</strong> The Konami Code was created by 
                    Kazuhisa Hashimoto in 1986 for the game Gradius. It has since become one of the most 
                    famous cheat codes in gaming history!
                  </p>
                </div>

                <button
                  onClick={() => setIsActivated(false)}
                  className="px-8 py-3 bg-gradient-to-r from-red-500 to-blue-600 text-white rounded-full font-semibold hover:shadow-glow-duo transition-all duration-300 transform hover:scale-105"
                >
                  Awesome!
                </button>

                <p className="text-xs text-gray-500 mt-4">
                  Try: ↑↑↓↓←→←→BA
                </p>
              </div>
            </motion.div>
          </motion.div>
        )}
      </AnimatePresence>
    </>
  )
}

