import React, { useState, useEffect, useCallback, useRef } from 'react';
import ReactDOM from 'react-dom/client';
import * as d3 from 'd3';
import { Sparkles, CheckCircle, XCircle, RefreshCw, Trophy, Target, ShieldAlert, List, ArrowLeft, Menu, X, KeyRound, RotateCcw, LogOut } from 'lucide-react';

// --- TYPES ---
export interface PuzzleData {
  keyOuter: string;
  keyInner: string;
  cipherMessage: string;
  plainMessage: string;
  hint: string;
}

export interface WheelState {
  outerRotation: number;
  innerRotation: number;
  isLocked: boolean;
}

export enum GameStatus {
  LOADING = 'LOADING',
  PLAYING = 'PLAYING',
  SUCCESS = 'SUCCESS',
  ERROR = 'ERROR'
}

// --- SOUND UTILS ---
let audioCtx: AudioContext | null = null;

const getContext = () => {
  if (!audioCtx) {
    audioCtx = new (window.AudioContext || (window as any).webkitAudioContext)();
  }
  return audioCtx;
};

const playWheelTick = () => {
  const ctx = getContext();
  if (!ctx) return;
  if (ctx.state === 'suspended') ctx.resume().catch(() => {});

  const osc = ctx.createOscillator();
  const gain = ctx.createGain();

  osc.connect(gain);
  gain.connect(ctx.destination);

  osc.type = 'triangle';
  osc.frequency.setValueAtTime(600, ctx.currentTime);
  osc.frequency.exponentialRampToValueAtTime(100, ctx.currentTime + 0.05);

  gain.gain.setValueAtTime(0.08, ctx.currentTime);
  gain.gain.exponentialRampToValueAtTime(0.001, ctx.currentTime + 0.05);

  osc.start();
  osc.stop(ctx.currentTime + 0.05);
};

const playSuccess = () => {
  const ctx = getContext();
  if (!ctx) return;
  if (ctx.state === 'suspended') ctx.resume().catch(() => {});

  const t = ctx.currentTime;
  
  [440, 554, 659, 880].forEach((freq, i) => {
    const osc = ctx.createOscillator();
    const gain = ctx.createGain();
    
    osc.connect(gain);
    gain.connect(ctx.destination);
    
    osc.type = 'sine';
    osc.frequency.value = freq;
    
    const start = t + i * 0.05;
    gain.gain.setValueAtTime(0, start);
    gain.gain.linearRampToValueAtTime(0.1, start + 0.02);
    gain.gain.exponentialRampToValueAtTime(0.001, start + 0.4);
    
    osc.start(start);
    osc.stop(start + 0.4);
  });
};

const playError = () => {
    const ctx = getContext();
    if (!ctx) return;
    if (ctx.state === 'suspended') ctx.resume().catch(() => {});
  
    const osc = ctx.createOscillator();
    const gain = ctx.createGain();
  
    osc.connect(gain);
    gain.connect(ctx.destination);
  
    osc.type = 'sawtooth';
    osc.frequency.setValueAtTime(150, ctx.currentTime);
    osc.frequency.linearRampToValueAtTime(100, ctx.currentTime + 0.2);
  
    gain.gain.setValueAtTime(0.1, ctx.currentTime);
    gain.gain.linearRampToValueAtTime(0, ctx.currentTime + 0.2);
  
    osc.start();
    osc.stop(ctx.currentTime + 0.2);
};

// --- DATA SERVICE ---
const INITIAL_PUZZLES: PuzzleData[] = [
  { keyOuter: "D", keyInner: "A", cipherMessage: "EUDYH", plainMessage: "BRAVE", hint: "Fortune favors this." },
  { keyOuter: "H", keyInner: "A", cipherMessage: "JSVBK", plainMessage: "CLOUD", hint: "Floats in the sky." },
  { keyOuter: "N", keyInner: "A", cipherMessage: "TUBFG", plainMessage: "GHOST", hint: "Spooky spirit." },
  { keyOuter: "B", keyInner: "A", cipherMessage: "KVNQ", plainMessage: "JUMP", hint: "Go upwards quickly." },
  { keyOuter: "K", keyInner: "A", cipherMessage: "VSQRD", plainMessage: "LIGHT", hint: "Opposite of dark." },
  { keyOuter: "F", keyInner: "A", cipherMessage: "VZJXY", plainMessage: "QUEST", hint: "An adventurous journey." },
  { keyOuter: "U", keyInner: "A", cipherMessage: "GUACW", plainMessage: "MAGIC", hint: "Tricks and spells." },
  { keyOuter: "P", keyInner: "A", cipherMessage: "EDLTG", plainMessage: "POWER", hint: "Energy or strength." },
  { keyOuter: "M", keyInner: "A", cipherMessage: "DANAF", plainMessage: "ROBOT", hint: "Mechanical human." },
  { keyOuter: "Z", keyInner: "A", cipherMessage: "ROZQJ", plainMessage: "SPARK", hint: "Starts a fire." }
];

const generateGameSession = async (): Promise<PuzzleData[]> => {
  return [...INITIAL_PUZZLES].sort(() => Math.random() - 0.5);
};

// --- CIPHER WHEEL COMPONENT ---
interface CipherWheelProps {
  wheelState: WheelState;
  setWheelState: React.Dispatch<React.SetStateAction<WheelState>>;
  puzzleKey: { outer: string, inner: string } | null;
}

const LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".split('');
const ANGLE_PER_LETTER = 360 / 26;

const CipherWheel: React.FC<CipherWheelProps> = ({ wheelState, setWheelState, puzzleKey }) => {
  const svgRef = useRef<SVGSVGElement>(null);
  const [isDragging, setIsDragging] = useState<'outer' | 'inner' | null>(null);
  const [startAngle, setStartAngle] = useState(0);
  const [initialRotation, setInitialRotation] = useState(0);

  const lastOuterIndex = useRef(0);
  const lastInnerIndex = useRef(0);

  useEffect(() => {
    const currentIndex = Math.round(wheelState.outerRotation / ANGLE_PER_LETTER);
    if (currentIndex !== lastOuterIndex.current) {
        playWheelTick();
        lastOuterIndex.current = currentIndex;
    }
  }, [wheelState.outerRotation]);

  useEffect(() => {
    const currentIndex = Math.round(wheelState.innerRotation / ANGLE_PER_LETTER);
    if (currentIndex !== lastInnerIndex.current) {
        playWheelTick();
        lastInnerIndex.current = currentIndex;
    }
  }, [wheelState.innerRotation]);


  const calculateAngle = (x: number, y: number) => {
    const cx = 200;
    const cy = 200;
    const dx = x - cx;
    const dy = y - cy;
    let angle = Math.atan2(dy, dx) * (180 / Math.PI);
    return angle + 90;
  };

  const handlePointerDown = (e: React.PointerEvent, ring: 'outer' | 'inner') => {
    if (!svgRef.current) return;
    svgRef.current.setPointerCapture(e.pointerId);
    
    const rect = svgRef.current.getBoundingClientRect();
    const x = e.clientX - rect.left;
    const y = e.clientY - rect.top;
    
    setStartAngle(calculateAngle(x, y));
    setInitialRotation(ring === 'outer' ? wheelState.outerRotation : wheelState.innerRotation);
    setIsDragging(ring);
  };

  const handlePointerMove = (e: React.PointerEvent) => {
    if (!isDragging || !svgRef.current) return;

    const rect = svgRef.current.getBoundingClientRect();
    const x = e.clientX - rect.left;
    const y = e.clientY - rect.top;
    
    const currentAngle = calculateAngle(x, y);
    const delta = currentAngle - startAngle;
    
    setWheelState(prev => {
      const newRotation = initialRotation + delta;
      
      if (prev.isLocked) {
         const diff = newRotation - (isDragging === 'outer' ? prev.outerRotation : prev.innerRotation);
         return {
             ...prev,
             outerRotation: prev.outerRotation + diff,
             innerRotation: prev.innerRotation + diff
         };
      } else {
        return {
          ...prev,
          outerRotation: isDragging === 'outer' ? newRotation : prev.outerRotation,
          innerRotation: isDragging === 'inner' ? newRotation : prev.innerRotation
        };
      }
    });
    
    setStartAngle(currentAngle);
    setInitialRotation(isDragging === 'outer' ? wheelState.outerRotation + (currentAngle - startAngle) : wheelState.innerRotation + (currentAngle - startAngle));
  };

  const handlePointerUp = (e: React.PointerEvent) => {
    if(!svgRef.current) return;
    svgRef.current.releasePointerCapture(e.pointerId);
    
    setWheelState(prev => {
      const snap = (r: number) => Math.round(r / ANGLE_PER_LETTER) * ANGLE_PER_LETTER;
      return {
        ...prev,
        outerRotation: snap(prev.outerRotation),
        innerRotation: snap(prev.innerRotation)
      };
    });
    
    setIsDragging(null);
  };

  const toggleLock = (e: React.MouseEvent) => {
    e.stopPropagation();
    setWheelState(prev => ({ ...prev, isLocked: !prev.isLocked }));
  };

  const sliceAngle = (2 * Math.PI) / 26;
  
  const outerArc = d3.arc()
    .innerRadius(140)
    .outerRadius(195)
    .startAngle(-sliceAngle / 2)
    .endAngle(sliceAngle / 2);

  const innerArc = d3.arc()
    .innerRadius(80)
    .outerRadius(135)
    .startAngle(-sliceAngle / 2)
    .endAngle(sliceAngle / 2);

  const isKeyLetter = (letter: string, ring: 'outer' | 'inner') => {
    if (!puzzleKey) return false;
    return ring === 'outer' ? letter === puzzleKey.outer : letter === puzzleKey.inner;
  };

  return (
    <div className="relative flex flex-col items-center justify-center p-4">
      <div className="absolute top-0 left-1/2 -translate-x-1/2 z-10 translate-y-2 pointer-events-none">
        <div className="w-0 h-0 border-l-[15px] border-l-transparent border-r-[15px] border-r-transparent border-t-[20px] border-t-red-500 drop-shadow-lg"></div>
      </div>

      <svg
        ref={svgRef}
        width="400"
        height="400"
        viewBox="0 0 400 400"
        className="touch-none select-none max-w-full h-auto cursor-grab active:cursor-grabbing"
        onPointerMove={handlePointerMove}
        onPointerUp={handlePointerUp}
        onPointerLeave={handlePointerUp}
      >
        <defs>
           <filter id="shadow" x="-20%" y="-20%" width="140%" height="140%">
             <feDropShadow dx="2" dy="2" stdDeviation="3" floodColor="#000" floodOpacity="0.5"/>
           </filter>
        </defs>

        <g 
            transform={`translate(200,200) rotate(${wheelState.outerRotation})`} 
            onPointerDown={(e) => handlePointerDown(e, 'outer')}
            className="cursor-pointer"
        >
          {LETTERS.map((letter, i) => (
            <g key={`outer-${letter}`} transform={`rotate(${i * (360 / 26)})`}>
              <path 
                d={outerArc(null as any) || ""} 
                fill={isKeyLetter(letter, 'outer') ? '#ef4444' : (i % 2 === 0 ? '#7f1d1d' : '#991b1b')} 
                stroke="#450a0a" 
                strokeWidth="1"
                filter="url(#shadow)"
              />
              <text
                y="-160"
                textAnchor="middle"
                className={`text-[20px] font-bold pointer-events-none ${isKeyLetter(letter, 'outer') ? 'fill-white' : 'fill-red-100'}`}
                style={{ transform: `rotate(0deg)` }}
              >
                {letter}
              </text>
            </g>
          ))}
        </g>

        <g 
            transform={`translate(200,200) rotate(${wheelState.innerRotation})`} 
            onPointerDown={(e) => handlePointerDown(e, 'inner')}
            className="cursor-pointer"
        >
          {LETTERS.map((letter, i) => (
            <g key={`inner-${letter}`} transform={`rotate(${i * (360 / 26)})`}>
              <path 
                d={innerArc(null as any) || ""} 
                fill={isKeyLetter(letter, 'inner') ? '#3b82f6' : (i % 2 === 0 ? '#1e3a8a' : '#1e40af')} 
                stroke="#172554" 
                strokeWidth="1"
                filter="url(#shadow)"
              />
              <text
                y="-100"
                textAnchor="middle"
                className={`text-[16px] font-bold pointer-events-none ${isKeyLetter(letter, 'inner') ? 'fill-white' : 'fill-blue-100'}`}
              >
                {letter}
              </text>
            </g>
          ))}
        </g>
        
        <g 
            onClick={toggleLock} 
            onPointerDown={(e) => e.stopPropagation()}
            className="cursor-pointer group hover:opacity-90 transition-opacity"
        >
            <circle 
                cx="200" 
                cy="200" 
                r="40" 
                fill="#111827" 
                stroke={wheelState.isLocked ? "#ef4444" : "#374151"} 
                strokeWidth="4" 
                className="transition-colors duration-300"
            />
            <text 
                x="200" 
                y="200" 
                dy="5" 
                textAnchor="middle" 
                fill={wheelState.isLocked ? "#ef4444" : "#6b7280"} 
                className="text-xs font-bold tracking-wider select-none transition-colors duration-300"
            >
                {wheelState.isLocked ? "LOCKED" : "UNLOCK"}
            </text>
        </g>

      </svg>
    </div>
  );
};

// --- APP COMPONENT ---
const TOTAL_QUESTIONS = 10;

const App: React.FC = () => {
  const [status, setStatus] = useState<GameStatus>(GameStatus.PLAYING);
  const [sessionPuzzles, setSessionPuzzles] = useState<PuzzleData[]>(() => [...INITIAL_PUZZLES].sort(() => Math.random() - 0.5));
  const [currentLevel, setCurrentLevel] = useState(0);
  const [userAnswer, setUserAnswer] = useState('');
  const [feedback, setFeedback] = useState<'correct' | 'incorrect' | null>(null);
  const [revealedIndex, setRevealedIndex] = useState<number>(() => {
    // Initialize revealed index for the first puzzle
    const firstPuzzle = sessionPuzzles && sessionPuzzles.length > 0 ? sessionPuzzles[0] : INITIAL_PUZZLES[0];
    return Math.floor(Math.random() * firstPuzzle.plainMessage.length);
  });
  const [isAdminMode, setIsAdminMode] = useState(false);
  
  // Menu & Auth States
  const [isMenuOpen, setIsMenuOpen] = useState(false);
  const [showAuthModal, setShowAuthModal] = useState(false);
  const [authInput, setAuthInput] = useState('');

  const inputRef = useRef<HTMLInputElement>(null);
  const authInputRef = useRef<HTMLInputElement>(null);
  
  const [wheelState, setWheelState] = useState<WheelState>({
    outerRotation: 0,
    innerRotation: 0,
    isLocked: false
  });

  const puzzle = sessionPuzzles[currentLevel] || null;

  const startNewGame = useCallback(async () => {
    // Don't set LOADING status to avoid flash
    setFeedback(null);
    setUserAnswer('');
    setIsAdminMode(false);
    setIsMenuOpen(false);
    setWheelState({ outerRotation: 0, innerRotation: 0, isLocked: false });
    
    try {
      const data = await generateGameSession();
      setSessionPuzzles(data);
      setCurrentLevel(0);
      if (data.length > 0 && data[0].plainMessage) {
        setRevealedIndex(Math.floor(Math.random() * data[0].plainMessage.length));
      }
      setStatus(GameStatus.PLAYING);
    } catch (error) {
      console.error(error);
      setStatus(GameStatus.ERROR);
    }
  }, []);

  const handleNextLevel = () => {
    if (currentLevel < TOTAL_QUESTIONS - 1) {
        const nextLevel = currentLevel + 1;
        setCurrentLevel(nextLevel);
        setUserAnswer('');
        setFeedback(null);
        setWheelState({ outerRotation: 0, innerRotation: 0, isLocked: false });
        
        const nextPuzzle = sessionPuzzles[nextLevel];
        if (nextPuzzle) {
            setRevealedIndex(Math.floor(Math.random() * nextPuzzle.plainMessage.length));
        }
        setStatus(GameStatus.PLAYING);
    } else {
        // Game Complete
        setStatus(GameStatus.SUCCESS);
    }
  };

  useEffect(() => {
    if (showAuthModal && authInputRef.current) {
        setTimeout(() => authInputRef.current?.focus(), 100);
    }
  }, [showAuthModal]);

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    if (!puzzle) return;

    const cleanAnswer = userAnswer.trim().toUpperCase();

    // Admin Access Check via Game Input
    if (cleanAnswer === "LDISC") {
        setIsAdminMode(true);
        playSuccess();
        return;
    }

    if (cleanAnswer === puzzle.plainMessage.toUpperCase()) {
      setFeedback('correct');
      playSuccess();
    } else {
      setFeedback('incorrect');
      playError();
      setTimeout(() => setFeedback(null), 2000);
      inputRef.current?.focus();
    }
  };

  const handleAuthSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    if (authInput.trim().toUpperCase() === "LDISC") {
        setIsAdminMode(true);
        setShowAuthModal(false);
        setAuthInput('');
        setIsMenuOpen(false);
        playSuccess();
    } else {
        playError();
        const input = authInputRef.current;
        if (input) {
            input.classList.add('animate-shake');
            setTimeout(() => input.classList.remove('animate-shake'), 500);
        }
    }
  };

  const isGameComplete = currentLevel === TOTAL_QUESTIONS - 1 && feedback === 'correct';

  return (
    <div className="min-h-screen bg-[#0f1115] text-white flex flex-col md:flex-row relative">
      
      {/* Menu Button */}
      <div className="fixed top-4 right-4 z-50">
        <button 
            onClick={() => setIsMenuOpen(true)}
            className="p-2 bg-gray-800/80 hover:bg-gray-700 text-white rounded-lg border border-gray-700 backdrop-blur-sm shadow-lg transition-all"
        >
            <Menu size={16} />
        </button>
      </div>

      {/* Menu Drawer */}
      {isMenuOpen && (
        <>
            <div 
                className="fixed inset-0 z-50 bg-black/60 backdrop-blur-sm transition-opacity"
                onClick={() => setIsMenuOpen(false)}
            ></div>
            <div className="fixed inset-y-0 right-0 z-50 w-72 bg-[#161b22] border-l border-gray-800 shadow-2xl p-6 flex flex-col animate-slide-in-right">
                <div className="flex justify-between items-center mb-8">
                    <h2 className="text-xl font-bold text-gray-200 tracking-wider">MENU</h2>
                    <button 
                        onClick={() => setIsMenuOpen(false)}
                        className="text-gray-400 hover:text-white transition-colors"
                    >
                        <X size={24} />
                    </button>
                </div>

                <div className="space-y-4 flex-1">
                    <button 
                        onClick={startNewGame}
                        className="w-full flex items-center gap-3 p-4 bg-gray-800/50 hover:bg-gray-800 rounded-xl border border-gray-700/50 hover:border-blue-500/50 transition-all group"
                    >
                        <div className="p-2 bg-blue-500/10 rounded-lg group-hover:bg-blue-500/20 text-blue-400">
                            <RotateCcw size={20} />
                        </div>
                        <div className="text-left">
                            <span className="block font-bold text-gray-200">Reset System</span>
                            <span className="text-xs text-gray-500">Restart current session</span>
                        </div>
                    </button>

                    <button 
                        onClick={() => {
                            if (isAdminMode) {
                                setIsAdminMode(false);
                                setIsMenuOpen(false);
                            } else {
                                setShowAuthModal(true);
                            }
                        }}
                        className={`w-full flex items-center gap-3 p-4 rounded-xl border transition-all group ${
                            isAdminMode 
                            ? 'bg-red-900/20 hover:bg-red-900/30 border-red-900/50 hover:border-red-500/50' 
                            : 'bg-gray-800/50 hover:bg-gray-800 border-gray-700/50 hover:border-yellow-500/50'
                        }`}
                    >
                        <div className={`p-2 rounded-lg ${isAdminMode ? 'bg-red-500/10 text-red-400' : 'bg-yellow-500/10 text-yellow-400 group-hover:bg-yellow-500/20'}`}>
                            {isAdminMode ? <LogOut size={20} /> : <KeyRound size={20} />}
                        </div>
                        <div className="text-left">
                            <span className="block font-bold text-gray-200">{isAdminMode ? 'Exit Admin Mode' : 'Admin Access'}</span>
                            <span className="text-xs text-gray-500">{isAdminMode ? 'Lock classified files' : 'Enter security credential'}</span>
                        </div>
                    </button>
                </div>

                <div className="mt-auto pt-6 border-t border-gray-800">
                    <p className="text-xs text-center text-gray-600 font-mono">
                        DEVELOPED BY LEGEND CHEW
                    </p>
                </div>
            </div>
        </>
      )}

      {/* Admin Auth Modal */}
      {showAuthModal && (
        <div className="fixed inset-0 z-[60] flex items-center justify-center p-4">
            <div className="absolute inset-0 bg-black/80 backdrop-blur-sm" onClick={() => setShowAuthModal(false)}></div>
            <div className="relative bg-[#161b22] border border-red-900/50 p-8 rounded-2xl shadow-2xl w-full max-w-md animate-scale-in">
                <button 
                    onClick={() => setShowAuthModal(false)}
                    className="absolute top-4 right-4 text-gray-500 hover:text-white"
                >
                    <X size={20} />
                </button>
                
                <div className="flex flex-col items-center mb-6">
                    <div className="w-16 h-16 bg-red-900/20 rounded-full flex items-center justify-center mb-4 border border-red-500/30">
                        <ShieldAlert className="text-red-500" size={32} />
                    </div>
                    <h3 className="text-xl font-bold text-red-100 tracking-widest">SECURITY CLEARANCE</h3>
                    <p className="text-sm text-red-400/60">Enter command code to proceed</p>
                </div>

                <form onSubmit={handleAuthSubmit}>
                    <input
                        ref={authInputRef}
                        type="password"
                        value={authInput}
                        onChange={(e) => setAuthInput(e.target.value)}
                        placeholder="ENTER PASSCODE"
                        className="w-full bg-black/40 border border-red-900/50 rounded-lg p-4 text-center font-mono text-xl tracking-[0.5em] text-red-500 placeholder-red-900/40 focus:outline-none focus:border-red-500 transition-colors mb-6"
                    />
                    <button 
                        type="submit"
                        className="w-full bg-red-900/30 hover:bg-red-800/50 text-red-400 font-bold py-3 rounded-lg border border-red-800/50 transition-all hover:shadow-[0_0_20px_rgba(220,38,38,0.2)]"
                    >
                        AUTHENTICATE
                    </button>
                </form>
            </div>
        </div>
      )}

      <div className="flex-1 flex flex-col items-center justify-center p-6 border-b md:border-b-0 md:border-r border-gray-800 relative overflow-hidden">
        {/* Decorative Background Elements */}
        <div className="absolute inset-0 bg-[radial-gradient(circle_at_center,_var(--tw-gradient-stops))] from-blue-900/10 via-transparent to-transparent pointer-events-none"></div>
        
        <div className="relative z-10">
            <CipherWheel 
                wheelState={wheelState} 
                setWheelState={setWheelState} 
                puzzleKey={puzzle ? { outer: puzzle.keyOuter, inner: puzzle.keyInner } : null}
            />
        </div>
      </div>

      <div className="flex-1 flex flex-col p-6 md:p-12 overflow-y-auto">
        <div className="max-w-xl mx-auto w-full space-y-8 h-full flex flex-col pt-12 md:pt-0">
            
            {status === GameStatus.ERROR && (
                <div className="bg-red-900/20 border border-red-800 p-6 rounded-xl text-center">
                    <p className="text-red-400 mb-4">Secure Channel Failed.</p>
                    <button 
                        onClick={startNewGame}
                        className="bg-red-600 hover:bg-red-500 text-white px-6 py-2 rounded-lg font-bold transition-colors"
                    >
                        Retry Connection
                    </button>
                </div>
            )}

            {isAdminMode ? (
                <div className="h-full flex flex-col animate-in fade-in slide-in-from-bottom-4 duration-500">
                    <div className="flex items-center justify-between mb-6 border-b-2 border-red-500/50 pb-4">
                        <div className="flex items-center gap-3">
                            <ShieldAlert className="text-red-500 animate-pulse" size={24} />
                            <div>
                                <h2 className="text-xl font-bold text-red-500 tracking-widest">CLASSIFIED ARCHIVES</h2>
                                <p className="text-xs text-red-400/60 uppercase">Admin Access Granted</p>
                            </div>
                        </div>
                        <button 
                            onClick={() => {
                                setIsAdminMode(false);
                            }}
                            className="flex items-center gap-2 text-xs bg-red-900/20 hover:bg-red-900/40 text-red-400 px-4 py-2 rounded-lg border border-red-500/30 transition-colors"
                        >
                            <ArrowLeft size={14} />
                            Close Archives
                        </button>
                    </div>
                    
                    <div className="flex-1 overflow-y-auto pr-2 space-y-4 custom-scrollbar">
                        {sessionPuzzles.map((p, idx) => (
                            <div key={idx} className="bg-gray-800/40 border border-gray-700/50 p-4 rounded-lg relative overflow-hidden group hover:border-red-500/30 transition-colors">
                                {/* Watermark */}
                                <div className="absolute top-2 right-4 text-4xl font-bold text-white/5 pointer-events-none select-none">
                                    #{String(idx + 1).padStart(2, '0')}
                                </div>

                                <div className="relative z-10 space-y-3">
                                    <div className="flex items-center gap-2">
                                        <div className={`w-1.5 h-1.5 rounded-full ${idx === currentLevel && !isGameComplete ? 'bg-blue-500 animate-pulse shadow-[0_0_8px_rgba(59,130,246,0.8)]' : 'bg-gray-600'}`}></div>
                                        <span className="text-xs text-gray-400 uppercase tracking-wider font-bold">Transmission {idx + 1}</span>
                                    </div>
                                    
                                    <div className="grid grid-cols-2 gap-3">
                                        <div className="bg-black/20 p-2 rounded border border-white/5">
                                            <span className="text-gray-500 text-[10px] block uppercase mb-1">Configuration</span>
                                            <span className="font-mono text-sm text-blue-300">Inner 'A' → Outer '{p.keyOuter}'</span>
                                        </div>
                                        <div className="bg-black/20 p-2 rounded border border-white/5">
                                            <span className="text-gray-500 text-[10px] block uppercase mb-1">Intel Hint</span>
                                            <span className="text-yellow-500/80 italic text-xs leading-tight block">{p.hint}</span>
                                        </div>
                                    </div>

                                    <div className="flex flex-col gap-1">
                                         <div className="flex justify-between items-end border-b border-gray-700/50 pb-1">
                                            <span className="text-gray-500 text-[10px] uppercase">Encrypted</span>
                                            <span className="font-mono text-blue-400/80 tracking-widest text-sm">{p.cipherMessage}</span>
                                         </div>
                                         <div className="flex justify-between items-end pt-1">
                                            <span className="text-gray-500 text-[10px] uppercase">Decrypted</span>
                                            <span className="font-mono text-green-400 font-bold tracking-widest text-lg drop-shadow-[0_0_8px_rgba(74,222,128,0.3)]">{p.plainMessage}</span>
                                         </div>
                                    </div>
                                </div>
                            </div>
                        ))}
                    </div>
                </div>
            ) : isGameComplete && feedback === 'correct' ? (
                <div className="flex flex-col items-center justify-center h-full text-center space-y-6 animate-fade-in my-auto">
                    <div className="w-24 h-24 bg-yellow-500/10 rounded-full flex items-center justify-center border-2 border-yellow-500/50 shadow-[0_0_30px_rgba(234,179,8,0.2)]">
                        <Trophy size={48} className="text-yellow-500" />
                    </div>
                    <div>
                        <h2 className="text-3xl font-bold text-yellow-400 mb-2">MISSION ACCOMPLISHED</h2>
                        <p className="text-gray-300">You have successfully decrypted all {TOTAL_QUESTIONS} transmissions.</p>
                    </div>
                    <div className="flex flex-col gap-3 w-full max-w-xs">
                        <button 
                            onClick={startNewGame}
                            className="flex items-center justify-center gap-2 bg-gradient-to-r from-yellow-600 to-yellow-800 hover:from-yellow-500 hover:to-yellow-700 text-white px-8 py-4 rounded-xl font-bold shadow-lg transform active:scale-[0.98] transition-all"
                        >
                            <RefreshCw size={20} />
                            Start New Operation
                        </button>
                        <button 
                            onClick={() => setIsAdminMode(true)}
                            className="flex items-center justify-center gap-2 bg-gray-800 hover:bg-gray-700 text-gray-300 px-6 py-3 rounded-lg font-bold border border-gray-700 transition-colors"
                        >
                            <List size={18} />
                            Review Transmission Log
                        </button>
                    </div>
                </div>
            ) : (status === GameStatus.PLAYING || status === GameStatus.SUCCESS) && puzzle && (
                <>
                    {/* Progress Header */}
                    <div className="flex items-center justify-between mb-4">
                        <div className="flex items-center gap-3">
                            <span className="flex items-center justify-center w-8 h-8 rounded bg-blue-900/30 border border-blue-500/30 text-blue-400 font-bold font-mono text-sm">
                                {currentLevel + 1}
                            </span>
                            <div className="flex flex-col">
                                <span className="text-xs text-blue-400 font-bold tracking-widest uppercase">Transmission</span>
                                <span className="text-xs text-gray-500">{currentLevel + 1} of {TOTAL_QUESTIONS}</span>
                            </div>
                        </div>
                        <div className="h-1.5 flex-1 max-w-[100px] ml-4 bg-gray-800 rounded-full overflow-hidden">
                            <div 
                                className="h-full bg-blue-500 transition-all duration-500 ease-out" 
                                style={{ width: `${((currentLevel) / TOTAL_QUESTIONS) * 100}%` }}
                            ></div>
                        </div>
                    </div>

                    <div className="bg-gray-800/50 border border-gray-700 p-6 rounded-xl space-y-6">
                        {/* Guide */}
                        <div className="flex gap-2">
                             <div className="w-1 bg-gray-600 rounded-full shrink-0"></div>
                             <p className="text-sm text-gray-400">
                                 Align <span className="text-red-400 font-bold">Outer '{puzzle.cipherMessage.charAt(0)}'</span> with <span className="text-blue-400 font-bold">Inner '{puzzle.plainMessage.charAt(0)}'</span> to decrypt.
                             </p>
                        </div>

                        {/* Hint/Riddle */}
                        <div className="flex items-start gap-2 bg-yellow-900/10 border border-yellow-700/30 p-3 rounded">
                            <Sparkles className="text-yellow-500 shrink-0 mt-0.5" size={16} />
                            <p className="text-sm text-yellow-200/80"><span className="font-bold uppercase tracking-wider text-xs block mb-1 text-yellow-500/50">Intel</span>{puzzle.hint}</p>
                        </div>

                        <div className="h-px bg-gray-700/50 w-full"></div>

                        {/* Encrypted Message */}
                        <div>
                            <h2 className="text-sm uppercase tracking-widest text-red-400 mb-4 font-bold">Encrypted Message</h2>
                            <div className="flex flex-wrap gap-2">
                                {puzzle.cipherMessage.split('').map((char, i) => (
                                    <div key={i} className="w-10 h-12 md:w-12 md:h-14 flex items-center justify-center bg-red-900/20 border border-red-500/30 rounded text-xl md:text-2xl font-mono text-red-200 shadow-[0_0_15px_rgba(239,68,68,0.1)]">
                                        {char}
                                    </div>
                                ))}
                            </div>
                        </div>

                        {/* Decrypted Answer */}
                        <form onSubmit={handleSubmit} className="block pt-2">
                            <h2 className="text-sm uppercase tracking-widest text-blue-400 mb-4 font-bold">Decrypted Answer</h2>
                            <div 
                                className="relative group cursor-text" 
                                onClick={() => inputRef.current?.focus()}
                            >
                                {/* Visual Boxes */}
                                <div className="flex flex-wrap gap-2">
                                     {puzzle.plainMessage.split('').map((char, i) => {
                                         const userChar = userAnswer[i];
                                         const isHint = i === revealedIndex && !userChar;
                                         const displayChar = userChar || (isHint ? char : '');
                                         const isCurrent = i === userAnswer.length && !feedback;
                                         const isSuccess = feedback === 'correct';

                                         return (
                                             <div 
                                                key={i} 
                                                style={{ animationDelay: isSuccess ? `${i * 100}ms` : '0ms' }}
                                                className={`
                                                w-10 h-12 md:w-12 md:h-14 flex items-center justify-center rounded text-xl md:text-2xl font-mono transition-all duration-200
                                                ${userChar 
                                                    ? (feedback === 'correct' ? 'bg-green-900/20 border-green-500 text-green-400' : 
                                                       feedback === 'incorrect' ? 'bg-red-900/40 border-red-500 text-red-200' : 
                                                       'bg-blue-900/20 border-blue-500/30 text-white')
                                                    : (isHint ? 'bg-blue-900/10 border-blue-500/20 text-blue-400/70' : 'bg-gray-900/50 border-gray-800')
                                                }
                                                border-2
                                                ${isCurrent ? 'border-blue-500 shadow-[0_0_15px_rgba(59,130,246,0.3)]' : ''}
                                                ${isSuccess ? 'animate-celebrate' : ''}
                                             `}>
                                                {displayChar}
                                             </div>
                                         )
                                     })}
                                     
                                     {/* Feedback Icons */}
                                     <div className="flex items-center ml-2">
                                        {feedback === 'correct' && <CheckCircle className="text-green-500 animate-in fade-in zoom-in duration-300" />}
                                        {feedback === 'incorrect' && <XCircle className="text-red-500 animate-in fade-in zoom-in duration-300" />}
                                     </div>
                                </div>

                                {/* Hidden Input */}
                                <input 
                                    ref={inputRef}
                                    type="text" 
                                    value={userAnswer}
                                    onChange={(e) => {
                                        const val = e.target.value.toUpperCase();
                                        if (val.length <= puzzle.plainMessage.length || val === "LDISC") {
                                            setUserAnswer(val);
                                        }
                                    }}
                                    className="absolute inset-0 w-full h-full opacity-0 cursor-text font-mono"
                                    disabled={feedback === 'correct'}
                                    autoComplete="off"
                                    autoCorrect="off"
                                    spellCheck="false"
                                />
                            </div>

                            {!feedback && (
                                <button 
                                    type="submit" 
                                    className="w-full mt-8 bg-gradient-to-r from-red-600 to-red-800 hover:from-red-500 hover:to-red-700 text-white font-bold py-4 rounded-xl shadow-lg transform active:scale-[0.98] transition-all"
                                >
                                    DECRYPT
                                </button>
                            )}
                        </form>
                    </div>

                    {feedback === 'correct' && !isGameComplete && (
                         <div className="mt-6 p-6 bg-green-900/20 border border-green-500/50 rounded-xl text-center animate-fade-in">
                            <h3 className="text-2xl font-bold text-green-400 mb-2">ACCESS GRANTED</h3>
                            <p className="text-green-200/70 mb-6">Transmission {currentLevel + 1} Decrypted.</p>
                            <button 
                                onClick={handleNextLevel}
                                className="inline-flex items-center gap-2 bg-green-600 hover:bg-green-500 text-white px-8 py-3 rounded-lg font-bold transition-colors"
                            >
                                <Target size={20} />
                                Next Transmission
                            </button>
                        </div>
                    )}
                </>
            )}
        </div>
      </div>
    </div>
  );
};

const rootElement = document.getElementById('root');
if (!rootElement) {
  throw new Error("Could not find root element to mount to");
}

const root = ReactDOM.createRoot(rootElement);
root.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);