import { useState } from 'react'
import { motion, AnimatePresence } from 'framer-motion'
import AIBanner from '../AIBanner'
import { Cpu, ArrowRight } from 'lucide-react'

export default function AICoreEffect({ onUnlock }: { onUnlock: () => void }) {
  const [synced, setSynced] = useState(false)
  const [progress, setProgress] = useState(0)

  const handleSync = () => {
    if (synced || progress > 0) return
    
    // Auto progress over 2.5 seconds
    let p = 0
    const interval = setInterval(() => {
      p += 1
      setProgress(p)
      if (p >= 100) {
        clearInterval(interval)
        setSynced(true)
        setTimeout(() => onUnlock(), 800)
      }
    }, 25)
  }

  return (
    <AnimatePresence>
      {!synced && (
        <motion.div 
          className="fixed inset-0 z-[100] bg-[#080d17] flex flex-col items-center justify-center overflow-hidden"
          exit={{ opacity: 0, scale: 1.05 }}
          transition={{ duration: 0.8, ease: "easeInOut" }}
        >
          {/* Base Background matching the main page */}
          <div className="absolute inset-0 opacity-50">
            <AIBanner />
          </div>
          
          {/* Overlay to dim the background, focusing attention on the core */}
          <div className="absolute inset-0 bg-[#080d17]/70 backdrop-blur-sm z-10" />

          {/* MASSIVE GLOWING LOGO (Faithful reproduction of the user's uploaded logo) */}
          <div className={`absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-[800px] h-[800px] pointer-events-none mix-blend-screen flex items-center justify-center z-[15] transition-all duration-1000 ${progress > 0 ? 'opacity-100 scale-[1.05]' : 'opacity-90 scale-100'}`}>
             <svg viewBox="-20 0 140 100" className="w-full h-full overflow-visible">
                <defs>
                  <linearGradient id="logo-cyan" x1="0%" y1="0%" x2="100%" y2="0%">
                    <stop offset="0%" stopColor="#06b6d4" />
                    <stop offset="100%" stopColor="#3b82f6" />
                  </linearGradient>
                  <linearGradient id="logo-purple" x1="0%" y1="0%" x2="100%" y2="0%">
                    <stop offset="0%" stopColor="#8b5cf6" />
                    <stop offset="100%" stopColor="#d946ef" />
                  </linearGradient>
                  <linearGradient id="logo-s" x1="0%" y1="0%" x2="100%" y2="100%">
                    <stop offset="0%" stopColor="#06b6d4" />
                    <stop offset="40%" stopColor="#ffffff" />
                    <stop offset="60%" stopColor="#ffffff" />
                    <stop offset="100%" stopColor="#d946ef" />
                  </linearGradient>
                  <filter id="logo-glow">
                    <feGaussianBlur stdDeviation="1.2" result="coloredBlur"/>
                    <feMerge>
                      <feMergeNode in="coloredBlur"/>
                      <feMergeNode in="SourceGraphic"/>
                    </feMerge>
                  </filter>
                </defs>

                {/* LEFT DATA HALF (Cyan Hexagon & Particles) */}
                <g opacity="0.7">
                  {/* Hexagon Left Outline */}
                  <path d="M 50 10 L 20 25 L 20 75 L 50 90" fill="none" stroke="url(#logo-cyan)" strokeWidth="0.5" opacity="0.8" />
                  {/* Grid of cyan dots inside the left hexagon */}
                  {Array.from({length: 60}).map((_, i) => {
                     const x = 22 + Math.random() * 25;
                     const y = 25 + Math.random() * 50; 
                     return (
                       <motion.circle 
                         key={`dot-${i}`} cx={x} cy={y} r={Math.random() > 0.7 ? 1 : 0.5} fill="#06b6d4"
                         animate={{ opacity: [0.2, 1, 0.2] }}
                         transition={{ duration: 1 + Math.random() * 2, repeat: Infinity, delay: Math.random() * 2 }}
                       />
                     )
                  })}
                  {/* Incoming Cyan Stream from outside */}
                  {Array.from({length: 40}).map((_, i) => (
                     <motion.circle 
                       key={`inc-${i}`} cx={-20} cy={30 + Math.random() * 40} r={Math.random() > 0.5 ? 1.5 : 0.8} fill="#06b6d4"
                       animate={{ x: [0, 45], opacity: [0, 1, 0] }}
                       transition={{ duration: 1.5 + Math.random() * 1.5, repeat: Infinity, ease: "linear", delay: Math.random() * 2 }}
                     />
                  ))}
                </g>

                {/* RIGHT NEURAL HALF (Purple Hexagon & Network) */}
                <g opacity="0.7">
                  {/* Hexagon Right Outline */}
                  <path d="M 50 10 L 80 25 L 80 75 L 50 90" fill="none" stroke="url(#logo-purple)" strokeWidth="0.5" opacity="0.8" />
                  {/* Neural Net nodes inside the right hexagon */}
                  {Array.from({length: 20}).map((_, i) => {
                     const x = 52 + Math.random() * 25;
                     const y = 25 + Math.random() * 50;
                     return (
                       <g key={`n-${i}`}>
                         <motion.circle 
                           cx={x} cy={y} r="0.8" fill="#d946ef"
                           animate={{ opacity: [0.3, 1, 0.3] }}
                           transition={{ duration: 1.5 + Math.random() * 2, repeat: Infinity, delay: Math.random() * 2 }}
                         />
                         <line x1={x} y1={y} x2={50} y2={50} stroke="#d946ef" strokeWidth="0.1" opacity="0.4" />
                       </g>
                     )
                  })}
                  {/* Outgoing Purple Network lines to outside */}
                  {Array.from({length: 20}).map((_, i) => {
                     const startY = 30 + Math.random() * 40;
                     const endY = 20 + Math.random() * 60;
                     return (
                       <motion.g key={`out-${i}`} animate={{ x: [0, 35], opacity: [0, 1, 0] }} transition={{ duration: 2 + Math.random() * 2, repeat: Infinity, ease: "linear", delay: Math.random() * 2 }}>
                         <circle cx={80} cy={endY} r="1.2" fill="#d946ef" />
                         <line x1={50} y1={startY} x2={80} y2={endY} stroke="#d946ef" strokeWidth="0.2" opacity="0.5" />
                       </motion.g>
                     )
                  })}
                </g>

                {/* THE GLOWING S-CORE (The thick central energy paths) */}
                <g filter="url(#logo-glow)">
                  {Array.from({length: 80}).map((_, i) => {
                     const offset = (i - 40) * 0.25; // 80 lines packed tightly
                     const isCenter = Math.abs(offset) < 3; // Make the very center lines extremely bright and white
                     return (
                       <motion.path 
                         key={`s-${i}`}
                         d={`M ${70 + offset} 25 L ${45 + offset} 25 C ${25 + offset} 25, ${25 + offset} 45, ${45 + offset} 50 C ${75 + offset} 60, ${75 + offset} 80, ${55 + offset} 80 L ${30 + offset} 80`}
                         fill="none"
                         stroke="url(#logo-s)"
                         strokeWidth={isCenter ? "0.8" : "0.3"} 
                         animate={{ strokeDasharray: ["0, 300", "300, 0"], opacity: [0.1, isCenter ? 1 : 0.5, 0.1] }}
                         transition={{ 
                           duration: progress > 0 ? 0.6 + Math.random() * 0.5 : 2.5 + Math.random() * 2, // Hyper-speed when syncing!
                           repeat: Infinity, delay: Math.random() * 3, ease: "linear" 
                         }}
                       />
                     )
                  })}
                </g>
             </svg>
          </div>

          {/* Glitchy Scanline Overlay */}
          <div className="absolute inset-0 z-20 opacity-10 pointer-events-none" style={{ backgroundImage: 'repeating-linear-gradient(transparent, transparent 2px, #000 2px, #000 4px)' }} />

          {/* Sync Interface */}
          <div className="relative z-30 flex flex-col items-center mt-[450px]">
             <div className="w-32 h-32 relative flex items-center justify-center">
                {/* Circular progress SVG */}
                <svg className="absolute inset-0 w-full h-full -rotate-90">
                  <circle cx="64" cy="64" r="60" fill="none" stroke="rgba(6,182,212,0.1)" strokeWidth="1" />
                  <motion.circle 
                    cx="64" cy="64" r="60" fill="none" stroke="#06b6d4" strokeWidth="2"
                    strokeDasharray={377}
                    strokeDashoffset={377 - (377 * progress) / 100}
                    style={{ filter: 'drop-shadow(0 0 10px rgba(6,182,212,0.8))' }}
                  />
                </svg>
                
                {/* Hexagon framing the CPU */}
                <motion.svg 
                  viewBox="0 0 100 100" 
                  className={`absolute inset-2 w-[calc(100%-16px)] h-[calc(100%-16px)] transition-colors duration-500 ${progress > 0 ? 'text-fuchsia-500' : 'text-cyan-500/30'}`}
                  animate={{ rotate: progress > 0 ? 360 : 0 }}
                  transition={{ duration: 10, repeat: Infinity, ease: "linear" }}
                >
                  <polygon points="50 5, 95 25, 95 75, 50 95, 5 75, 5 25" fill="none" stroke="currentColor" strokeWidth="1" />
                </motion.svg>

                <button 
                  onClick={handleSync}
                  disabled={progress > 0}
                  className="relative z-10 w-16 h-16 bg-slate-900 rounded-full border border-cyan-500/50 flex items-center justify-center text-cyan-400 hover:scale-110 hover:bg-cyan-950 hover:shadow-[0_0_30px_rgba(6,182,212,0.6)] transition-all cursor-pointer shadow-[0_0_15px_rgba(6,182,212,0.2)] disabled:opacity-100 disabled:cursor-not-allowed group"
                >
                  <Cpu className={`w-8 h-8 transition-transform ${progress > 0 && progress < 100 ? 'animate-pulse text-fuchsia-400' : ''} ${progress === 100 ? 'text-white drop-shadow-[0_0_10px_white]' : ''}`} />
                </button>
             </div>

             <div className="mt-10 font-mono text-center">
                <div className="text-cyan-400 text-sm tracking-[0.4em] uppercase mb-4 shadow-cyan-400/50 drop-shadow-md">
                  {progress === 0 ? 'Core Synchronization Required' : progress < 100 ? 'Establishing Neural Link...' : 'Link Established'}
                </div>
                
                {progress === 0 && (
                  <motion.div 
                    className="text-slate-400 text-xs tracking-widest flex items-center gap-2 justify-center"
                    animate={{ opacity: [0.3, 1, 0.3] }}
                    transition={{ duration: 1.5, repeat: Infinity }}
                  >
                    <ArrowRight className="w-3 h-3 text-fuchsia-400" /> INITIATE BOOT SEQUENCE
                  </motion.div>
                )}
                
                {progress > 0 && (
                  <div className="text-white text-3xl font-bold tracking-[0.2em] tabular-nums drop-shadow-[0_0_10px_rgba(255,255,255,0.5)]">
                    {progress}%
                  </div>
                )}
             </div>
          </div>
        </motion.div>
      )}

      {/* Screen flash effect on sync completion */}
      {synced && (
        <motion.div 
          className="fixed inset-0 z-[110] pointer-events-none bg-gradient-to-r from-cyan-400 to-fuchsia-400 mix-blend-screen"
          initial={{ opacity: 0 }}
          animate={{ opacity: [0, 1, 0] }}
          transition={{ duration: 1, ease: "easeOut" }}
        />
      )}
    </AnimatePresence>
  )
}
