'use client';

import { useState, useEffect, useRef } from 'react';
import { motion, AnimatePresence } from 'framer-motion';

const PACMAN_URL = 'https://www.google.com/logos/2010/pacman10-i.html';

/* ────────────────────────────────────────── *
 *  Easter Egg – click the header ghost icon  *
 *  Ms. Pac-Man "eats" the page away,         *
 *  reveals the arcade portal.                *
 * ────────────────────────────────────────── */

export default function PacManEasterEgg() {
  const [phase, setPhase] = useState<'idle' | 'eating' | 'reveal'>('idle');
  const rafRef = useRef<number | null>(null);
  const [chomp, setChomp] = useState(true);

  /* Listen for the custom event dispatched by the header ghost icon */
  useEffect(() => {
    const handler = () => {
      if (phase !== 'idle') return;
      setPhase('eating');
    };
    window.addEventListener('ghost-easter-egg', handler);
    return () => window.removeEventListener('ghost-easter-egg', handler);
  }, [phase]);

  /* Chomp animation ticker */
  useEffect(() => {
    if (phase !== 'eating') return;
    const id = setInterval(() => setChomp((c) => !c), 150);
    return () => clearInterval(id);
  }, [phase]);

  /* After eating animation, show the reveal */
  useEffect(() => {
    if (phase === 'eating') {
      const t = setTimeout(() => setPhase('reveal'), 2600);
      return () => clearTimeout(t);
    }
  }, [phase]);

  const handleClose = () => {
    setPhase('idle');
  };

  if (phase === 'idle') return null;

  return (
    <>
      <style jsx global>{`
        @keyframes dotBlink {
          0%, 100% { opacity: 1; }
          50% { opacity: 0.3; }
        }
      `}</style>

      <AnimatePresence>
        {(phase === 'eating' || phase === 'reveal') && (
          <motion.div
            key="ee-overlay"
            className="fixed inset-0 z-[9999]"
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0, transition: { duration: 0.6 } }}
          >
            {/* ── Black curtain that the pac-man "reveals" ── */}
            <motion.div
              className="absolute inset-0 bg-brand-bg"
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
              transition={{ duration: 0.4 }}
              onClick={phase === 'reveal' ? handleClose : undefined}
              style={{ cursor: phase === 'reveal' ? 'pointer' : 'default' }}
            />

            {/* ── Pac-dot trail being eaten ── */}
            {phase === 'eating' && (
              <div className="absolute inset-0 flex items-center pointer-events-none overflow-hidden">
                {/* Dots that disappear as pac-man passes */}
                {Array.from({ length: 20 }).map((_, i) => (
                  <motion.div
                    key={`dot-${i}`}
                    className="absolute w-3 h-3 rounded-full bg-yellow-300"
                    style={{
                      left: `${5 + i * 4.8}%`,
                      top: '50%',
                      transform: 'translateY(-50%)',
                    }}
                    initial={{ opacity: 1, scale: 1 }}
                    animate={{ opacity: 0, scale: 0 }}
                    transition={{ delay: (i * 2.2) / 20, duration: 0.15 }}
                  />
                ))}

                {/* Ms. Pac-Man sprite */}
                <motion.div
                  className="absolute text-5xl md:text-6xl"
                  style={{ top: '50%', transform: 'translateY(-50%)' }}
                  initial={{ left: '-8%' }}
                  animate={{ left: '105%' }}
                  transition={{ duration: 2.4, ease: 'linear' }}
                >
                  <span
                    className="inline-block"
                    style={{
                      transform: chomp ? 'scaleX(1)' : 'scaleX(0.75)',
                      transition: 'transform 0.1s',
                      filter: 'drop-shadow(0 0 12px rgba(255,255,0,0.6))',
                    }}
                  >
                    ᗧ
                  </span>
                </motion.div>

                {/* Trailing ghosts chasing Ms. Pac-Man */}
                {[
                  { color: '#FF0000', delay: 0.5 },
                  { color: '#FFB8FF', delay: 0.8 },
                  { color: '#00FFFF', delay: 1.1 },
                  { color: '#FFB852', delay: 1.4 },
                ].map((g, i) => (
                  <motion.div
                    key={`ghost-${i}`}
                    className="absolute text-4xl md:text-5xl"
                    style={{
                      top: '50%',
                      transform: 'translateY(-50%)',
                      color: g.color,
                      filter: `drop-shadow(0 0 8px ${g.color}80)`,
                    }}
                    initial={{ left: '-12%' }}
                    animate={{ left: '108%' }}
                    transition={{ duration: 2.4, delay: g.delay, ease: 'linear' }}
                  >
                    👻
                  </motion.div>
                ))}

                {/* Wipe effect – the page dissolves behind ms. pacman */}
                <motion.div
                  className="absolute inset-y-0 right-0 bg-brand-bg"
                  initial={{ width: '100%' }}
                  animate={{ width: '0%' }}
                  transition={{ duration: 2.4, ease: 'linear' }}
                />
              </div>
            )}

            {/* ── Arcade Portal (revealed after eating) ── */}
            <AnimatePresence>
              {phase === 'reveal' && (
                <motion.div
                  className="absolute inset-0 flex items-center justify-center"
                  initial={{ opacity: 0 }}
                  animate={{ opacity: 1 }}
                  exit={{ opacity: 0 }}
                  transition={{ duration: 0.5 }}
                  onClick={handleClose}
                  style={{ cursor: 'pointer' }}
                >
                  {/* Maze-style grid lines background */}
                  <div className="absolute inset-0 opacity-10 pointer-events-none">
                    <div
                      className="w-full h-full"
                      style={{
                        backgroundImage:
                          'linear-gradient(#2222ff 1px, transparent 1px), linear-gradient(90deg, #2222ff 1px, transparent 1px)',
                        backgroundSize: '40px 40px',
                      }}
                    />
                  </div>

                  {/* Floating ghosts in background */}
                  {[
                    { x: '15%', y: '20%', color: '#FF0000', dur: 3 },
                    { x: '80%', y: '25%', color: '#FFB8FF', dur: 2.5 },
                    { x: '10%', y: '75%', color: '#00FFFF', dur: 3.5 },
                    { x: '85%', y: '70%', color: '#FFB852', dur: 2.8 },
                    { x: '50%', y: '85%', color: '#FF0000', dur: 3.2 },
                  ].map((g, i) => (
                    <motion.div
                      key={`float-ghost-${i}`}
                      className="absolute text-4xl pointer-events-none"
                      style={{ left: g.x, top: g.y, color: g.color, opacity: 0.4 }}
                      animate={{ y: [0, -15, 0] }}
                      transition={{ repeat: Infinity, duration: g.dur, delay: i * 0.3 }}
                    >
                      👻
                    </motion.div>
                  ))}

                  {/* Main card */}
                  <motion.div
                    className="relative z-10 max-w-lg w-full mx-4"
                    initial={{ scale: 0.5, opacity: 0, y: 40 }}
                    animate={{ scale: 1, opacity: 1, y: 0 }}
                    exit={{ scale: 0.8, opacity: 0 }}
                    transition={{ type: 'spring', damping: 18, stiffness: 120 }}
                    onClick={(e) => e.stopPropagation()}
                    style={{ cursor: 'default' }}
                  >
                    <div className="rounded-2xl border-2 border-blue-500/40 bg-brand-bg/95 p-10 text-center shadow-2xl shadow-blue-500/20 backdrop-blur-sm">
                      {/* Pac-dot trail */}
                      <div className="flex justify-center gap-3 mb-5">
                        {Array.from({ length: 9 }).map((_, i) => (
                          <motion.div
                            key={`pdot-${i}`}
                            className="w-2 h-2 rounded-full bg-yellow-300"
                            initial={{ opacity: 0 }}
                            animate={{ opacity: 1 }}
                            transition={{ delay: i * 0.06 }}
                          />
                        ))}
                      </div>

                      <div className="text-7xl mb-5">
                        <motion.span
                          animate={{ rotate: [0, -5, 5, 0] }}
                          transition={{ repeat: Infinity, duration: 2 }}
                          className="inline-block"
                        >
                          👻
                        </motion.span>
                        <span className="ml-2">🕹️</span>
                      </div>

                      <h3 className="text-3xl font-black text-white mb-3">
                        The <span className="text-brand">Ghost</span> Arcade
                      </h3>
                      <p className="text-gray-400 mb-8 text-base leading-relaxed">
                        Even our ghosts need a break from haunting operations.
                        <br />
                        They snuck into the maze…
                      </p>

                      <a
                        href={PACMAN_URL}
                        target="_blank"
                        rel="noopener noreferrer"
                        className="inline-flex items-center gap-3 px-8 py-4 rounded-full bg-gradient-to-r from-yellow-400 via-yellow-500 to-orange-500 text-black font-black text-xl hover:scale-105 active:scale-95 transition-transform shadow-xl shadow-yellow-500/30"
                      >
                        <motion.span
                          className="text-3xl"
                          animate={{ scaleX: [1, 0.7, 1] }}
                          transition={{ repeat: Infinity, duration: 0.4 }}
                        >
                          ᗧ
                        </motion.span>
                        Play Ms. Pac-Man
                      </a>

                      <button
                        onClick={handleClose}
                        className="block mx-auto mt-6 text-gray-500 hover:text-gray-200 text-sm transition-colors"
                      >
                        ← Back to the Hearth
                      </button>
                    </div>
                  </motion.div>
                </motion.div>
              )}
            </AnimatePresence>
          </motion.div>
        )}
      </AnimatePresence>
    </>
  );
}
