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

export default function HackerEffect({ onUnlock }: { onUnlock: () => void }) {
  const [hacked, setHacked] = useState(false)
  const [text, setText] = useState('')
  const fullText = "SYSTEM LOCKED.\nAWAITING OVERRIDE...\n\n> "

  useEffect(() => {
    let i = 0
    const timer = setInterval(() => {
      setText(fullText.slice(0, i))
      i++
      if (i > fullText.length) clearInterval(timer)
    }, 40)
    return () => clearInterval(timer)
  }, [])

  const handleHack = () => {
    setHacked(true)
    setTimeout(() => onUnlock(), 1200)
  }

  return (
    <AnimatePresence>
      {!hacked ? (
        <motion.div 
          className="fixed inset-0 z-[100] bg-black flex flex-col items-center justify-center font-mono"
          exit={{ opacity: 0, filter: "blur(20px)", scale: 1.2 }}
          transition={{ duration: 0.6, ease: "circIn" }}
        >
          {/* CRT Scanline Effect */}
          <div className="absolute inset-0 pointer-events-none opacity-20" style={{ backgroundImage: 'linear-gradient(rgba(18, 16, 16, 0) 50%, rgba(0, 0, 0, 0.25) 50%), linear-gradient(90deg, rgba(255, 0, 0, 0.06), rgba(0, 255, 0, 0.02), rgba(0, 0, 255, 0.06))', backgroundSize: '100% 2px, 3px 100%' }} />

          <div className="text-emerald-500 text-xl md:text-3xl whitespace-pre-wrap text-center mb-10 h-32 tracking-widest" style={{ textShadow: '0 0 10px rgba(16, 185, 129, 0.5)' }}>
            {text}<span className="animate-pulse">_</span>
          </div>
          
          {text.length >= fullText.length && (
            <motion.button
              initial={{ opacity: 0, y: 20 }}
              animate={{ opacity: 1, y: 0 }}
              onClick={handleHack}
              className="px-8 py-3 border-2 border-red-500 text-red-500 hover:bg-red-500 hover:text-black hover:shadow-[0_0_30px_rgba(239,68,68,0.5)] transition-all uppercase tracking-[0.3em] font-bold z-10"
            >
              [ Initiate Hack ]
            </motion.button>
          )}
        </motion.div>
      ) : (
        <motion.div 
          className="fixed inset-0 z-[110] pointer-events-none flex items-center justify-center font-mono overflow-hidden"
          exit={{ opacity: 0 }}
        >
           {/* Glitch visuals */}
           <motion.div
             className="text-red-500 text-4xl md:text-8xl font-black mix-blend-difference tracking-widest whitespace-nowrap"
             animate={{ x: [-20, 20, -10, 30, 0], y: [10, -10, 20, -20, 0], opacity: [1, 0.5, 0.8, 0.2, 0], skewX: [0, 20, -20, 10, 0] }}
             transition={{ duration: 0.5, repeat: 2 }}
             style={{ textShadow: '-2px 0 cyan, 2px 0 red' }}
           >
             SYSTEM OVERRIDE
           </motion.div>
        </motion.div>
      )}
    </AnimatePresence>
  )
}
