import { useState, useEffect, useRef } from 'react';
import { createPortal } from 'react-dom';
import { Trophy, Play, RotateCcw, X, Award, CheckCircle2, AlertTriangle, ArrowRight, Brain, Zap, HelpCircle, Puzzle, Crown, Settings, Trash2, Plus, ArrowLeft, Layers, PlusCircle, CheckCircle, RefreshCw } from 'lucide-react';
import { useAuthStore, api } from '../store/auth';
import { CrosswordPage } from '../pages/crossword/CrosswordPage';
import { CrosswordLeaderboardPage } from '../pages/crossword/CrosswordLeaderboard';
import { useEdutainmentStore } from '../store/edutainment';
import { useEducationTerms } from '../utils/educationTerms';

const DEFAULT_LEADERBOARD = {
  math: [
    { name: 'Sarah Jenkins', score: 180, date: '2026-06-20', isPlayer: false },
    { name: 'David Chen', score: 150, date: '2026-06-19', isPlayer: false },
    { name: 'Alex Rivera', score: 120, date: '2026-06-18', isPlayer: false },
  ],
  scramble: [
    { name: 'Emily Taylor', score: 140, date: '2026-06-20', isPlayer: false },
    { name: 'Marcus Brody', score: 120, date: '2026-06-19', isPlayer: false },
    { name: 'David Chen', score: 100, date: '2026-06-17', isPlayer: false },
  ],
  trivia: [
    { name: 'Alex Rivera', score: 100, date: '2026-06-20', isPlayer: false },
    { name: 'Sarah Jenkins', score: 80, date: '2026-06-19', isPlayer: false },
    { name: 'Jordan Patel', score: 80, date: '2026-06-18', isPlayer: false },
  ]
};

interface GamesProps {
  onClose: () => void;
  activityName?: string;
}

export default function EdutainmentGames({ onClose, activityName }: GamesProps) {
  const { user } = useAuthStore();
  const terms = useEducationTerms();
  const [selectedGame, setSelectedGame] = useState<string | null>(null); // null, 'math', 'scramble', 'trivia'
  const [activeGame, setActiveGame] = useState<any | null>(null); // null, 'general', or EdutainmentGame

  const [leaderboard, setLeaderboard] = useState<any>(() => {
    const saved = localStorage.getItem('edutainment_leaderboard');
    if (saved) {
      try {
        return JSON.parse(saved);
      } catch (e) {
        return DEFAULT_LEADERBOARD;
      }
    }
    return DEFAULT_LEADERBOARD;
  });

  const [students, setStudents] = useState<any[]>([]);

  useEffect(() => {
    const fetchStudents = async () => {
      try {
        const res = await api.get('/users', { params: { role: 'student', limit: 100 } });
        const data = Array.isArray(res.data) ? res.data : (res.data?.users || []);
        setStudents(data);
      } catch (err) {
        console.error('Failed to fetch students for scoreboard', err);
      }
    };
    fetchStudents();
  }, []);

  useEffect(() => {
    if (students.length > 0) {
      setLeaderboard((prev: any) => {
        const getSeededScores = (gameKey: 'math' | 'scramble' | 'trivia', baseScores: number[]) => {
          const saved = localStorage.getItem('edutainment_leaderboard');
          let playerScoreEntry: any = null;
          if (saved) {
            try {
              const parsed = JSON.parse(saved);
              playerScoreEntry = parsed[gameKey]?.find((entry: any) => entry.isPlayer) || null;
            } catch (e) {}
          }

          const seeded: any[] = [];
          const shuffled = [...students].sort(() => 0.5 - Math.random());
          
          baseScores.forEach((score, idx) => {
            const student = shuffled[idx % shuffled.length];
            seeded.push({
              name: student ? `${student.first_name} ${student.last_name}` : `Student ${idx + 1}`,
              score: score,
              date: new Date(Date.now() - (idx + 1) * 24 * 60 * 60 * 1000).toISOString().split('T')[0],
              isPlayer: false
            });
          });

          if (playerScoreEntry) {
            seeded.push(playerScoreEntry);
          }

          return seeded.sort((a, b) => b.score - a.score).slice(0, 5);
        };

        const updated = {
          math: getSeededScores('math', [180, 150, 120]),
          scramble: getSeededScores('scramble', [140, 120, 100]),
          trivia: getSeededScores('trivia', [100, 80, 60])
        };

        localStorage.setItem('edutainment_leaderboard', JSON.stringify(updated));
        return updated;
      });
    }
  }, [students]);

  const handleEndGame = async (gameType: 'math' | 'scramble' | 'trivia', score: number) => {
    saveScore(gameType, score);
    if (activeGame && activeGame !== 'general') {
      try {
        await useEdutainmentStore.getState().submitSession(activeGame.id, score);
      } catch (err) {
        console.error(err);
      }
    }
    setActiveGame(null);
  };

  const saveScore = (gameKey: 'math' | 'scramble' | 'trivia', score: number) => {
    const playerName = user ? `${user.first_name} ${user.last_name}` : 'You';
    const newEntry = {
      name: playerName,
      score: score,
      date: new Date().toISOString().split('T')[0],
      isPlayer: true
    };

    setLeaderboard((prev: any) => {
      const gameScores = [...(prev[gameKey] || [])];
      const existingIdx = gameScores.findIndex(entry => entry.isPlayer);
      if (existingIdx !== -1) {
        if (score > gameScores[existingIdx].score) {
          gameScores[existingIdx] = newEntry;
        }
      } else {
        gameScores.push(newEntry);
      }

      const sorted = gameScores
        .sort((a, b) => b.score - a.score)
        .slice(0, 5);

      const updated = { ...prev, [gameKey]: sorted };
      localStorage.setItem('edutainment_leaderboard', JSON.stringify(updated));
      return updated;
    });
  };
  
  return (
    <div className="bg-card border border-border rounded-[2.5rem] p-6 md:p-8 shadow-xl relative overflow-hidden animate-in fade-in duration-300">
      <div className="absolute top-0 right-0 w-64 h-64 bg-primary/5 rounded-bl-[10rem] -z-10"></div>
      
      {/* Header */}
      <div className="flex justify-between items-center mb-8 border-b border-border pb-4">
        <div>
          <h3 className="text-2xl font-black text-text tracking-tight uppercase flex items-center gap-3">
            <Brain className="text-primary" size={28} />
            Edutainment Arena
          </h3>
          <p className="text-text-muted text-xs font-bold uppercase tracking-widest mt-1">
            Learning through play {activityName ? `• ${activityName}` : ''}
          </p>
        </div>
        <button 
          onClick={onClose} 
          className="p-2.5 text-text-muted hover:text-rose-500 hover:bg-rose-500/10 rounded-xl transition-all"
        >
          <X size={20} />
        </button>
      </div>

      {!selectedGame ? (
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6 py-6">
          {/* Game 1: Math Sprint */}
          <div className="bg-muted/30 border border-border hover:border-primary/30 rounded-[2rem] p-6 transition-all hover:shadow-lg flex flex-col justify-between group">
            <div className="space-y-4">
              <div className="w-12 h-12 rounded-2xl bg-orange-500/10 text-orange-500 flex items-center justify-center font-black text-xl">
                <Zap size={24} />
              </div>
              <h4 className="text-lg font-black text-text uppercase tracking-tight">Math Sprint</h4>
              <p className="text-xs text-text-muted font-medium">Solve as many math equations as you can in 30 seconds. Speed and accuracy count!</p>
            </div>
            <button 
              onClick={() => setSelectedGame('math')} 
              className="mt-6 w-full py-3 bg-orange-500 hover:bg-orange-600 text-white rounded-xl font-bold text-xs uppercase tracking-widest transition-all flex items-center justify-center gap-2 group-hover:scale-[1.02]"
            >
              <Play size={14} /> Start Sprint
            </button>
          </div>

          {/* Game 2: Word Scramble */}
          <div className="bg-muted/30 border border-border hover:border-primary/30 rounded-[2rem] p-6 transition-all hover:shadow-lg flex flex-col justify-between group">
            <div className="space-y-4">
              <div className="w-12 h-12 rounded-2xl bg-blue-500/10 text-blue-500 flex items-center justify-center font-black text-xl">
                <Brain size={24} />
              </div>
              <h4 className="text-lg font-black text-text uppercase tracking-tight">Word Scramble</h4>
              <p className="text-xs text-text-muted font-medium">Unscramble educational terms with helpful context clues. Boost your vocabulary!</p>
            </div>
            <button 
              onClick={() => setSelectedGame('scramble')} 
              className="mt-6 w-full py-3 bg-blue-600 hover:bg-blue-700 text-white rounded-xl font-bold text-xs uppercase tracking-widest transition-all flex items-center justify-center gap-2 group-hover:scale-[1.02]"
            >
              <Play size={14} /> Unscramble
            </button>
          </div>

          {/* Game 3: General Trivia */}
          <div className="bg-muted/30 border border-border hover:border-primary/30 rounded-[2rem] p-6 transition-all hover:shadow-lg flex flex-col justify-between group">
            <div className="space-y-4">
              <div className="w-12 h-12 rounded-2xl bg-emerald-500/10 text-emerald-500 flex items-center justify-center font-black text-xl">
                <HelpCircle size={24} />
              </div>
              <h4 className="text-lg font-black text-text uppercase tracking-tight">Academia Trivia</h4>
              <p className="text-xs text-text-muted font-medium">Test your knowledge across science, history, geography, and general school subjects.</p>
            </div>
            <button 
              onClick={() => setSelectedGame('trivia')} 
              className="mt-6 w-full py-3 bg-emerald-600 hover:bg-emerald-700 text-white rounded-xl font-bold text-xs uppercase tracking-widest transition-all flex items-center justify-center gap-2 group-hover:scale-[1.02]"
            >
              <Play size={14} /> Take Quiz
            </button>
          </div>

          {/* Game 4: Crossword Puzzle */}
          <div className="bg-muted/30 border border-border hover:border-primary/30 rounded-[2rem] p-6 transition-all hover:shadow-lg flex flex-col justify-between group">
            <div className="space-y-4">
              <div className="w-12 h-12 rounded-2xl bg-purple-500/10 text-purple-500 flex items-center justify-center font-black text-xl">
                <Puzzle size={24} />
              </div>
              <h4 className="text-lg font-black text-text uppercase tracking-tight">Crossword Puzzle</h4>
              <p className="text-xs text-text-muted font-medium">Solve custom crossword puzzles. Test your vocabulary and knowledge of course concepts!</p>
            </div>
            <button 
              onClick={() => setSelectedGame('crossword')} 
              className="mt-6 w-full py-3 bg-purple-600 hover:bg-purple-700 text-white rounded-xl font-bold text-xs uppercase tracking-widest transition-all flex items-center justify-center gap-2 group-hover:scale-[1.02]"
            >
              <Play size={14} /> Play Crossword
            </button>
          </div>

          {/* Game 5: Puzzle Leaders */}
          <div className="bg-muted/30 border border-border hover:border-primary/30 rounded-[2rem] p-6 transition-all hover:shadow-lg flex flex-col justify-between group">
            <div className="space-y-4">
              <div className="w-12 h-12 rounded-2xl bg-amber-500/10 text-amber-500 flex items-center justify-center font-black text-xl">
                <Award size={24} />
              </div>
              <h4 className="text-lg font-black text-text uppercase tracking-tight">Puzzle Leaders</h4>
              <p className="text-xs text-text-muted font-medium">See who is leading the crossword standings! Check out the top solvers in the school.</p>
            </div>
            <button 
              onClick={() => setSelectedGame('leaderboard')} 
              className="mt-6 w-full py-3 bg-amber-500 hover:bg-amber-600 text-white rounded-xl font-bold text-xs uppercase tracking-widest transition-all flex items-center justify-center gap-2 group-hover:scale-[1.02]"
            >
              <Award size={14} /> View Leaders
            </button>
          </div>
          {/* Game 6: Manage Game Content (visible to teachers/admins) */}
          {user?.role !== 'student' && (
            <div className="bg-indigo-600/5 border border-indigo-500/20 hover:border-indigo-500/40 rounded-[2rem] p-6 transition-all hover:shadow-lg flex flex-col justify-between group">
              <div className="space-y-4">
                <div className="w-12 h-12 rounded-2xl bg-indigo-500/10 text-indigo-500 flex items-center justify-center font-black text-xl">
                  <Settings size={24} />
                </div>
                <h4 className="text-lg font-black text-text uppercase tracking-tight">Game Content</h4>
                <p className="text-xs text-text-muted font-medium">Add and manage custom Word Scramble terms and Trivia Questions for your subjects.</p>
              </div>
              <button 
                onClick={() => setSelectedGame('manage')} 
                className="mt-6 w-full py-3 bg-indigo-600 hover:bg-indigo-700 text-white rounded-xl font-bold text-xs uppercase tracking-widest transition-all flex items-center justify-center gap-2 group-hover:scale-[1.02]"
              >
                <Settings size={14} /> Manage Content
              </button>
            </div>
          )}
        </div>
      ) : (
        <div className="animate-in zoom-in-95 duration-200">
          {activeGame === null ? (
            <>
              {(selectedGame === 'math' || selectedGame === 'scramble' || selectedGame === 'trivia') ? (
                <PuzzleList
                  gameType={selectedGame}
                  onSelect={(g) => setActiveGame(g)}
                  onBack={() => setSelectedGame(null)}
                />
              ) : (
                <>
                  <button 
                    onClick={() => setSelectedGame(null)} 
                    className="mb-6 text-[0.65rem] font-black uppercase tracking-widest text-primary flex items-center gap-1.5 hover:underline"
                  >
                    ← Back to Arena
                  </button>
                  {selectedGame === 'crossword' && <CrosswordPage />}
                  {selectedGame === 'leaderboard' && <CrosswordLeaderboardPage />}
                  {selectedGame === 'manage' && <GameContentManager />}
                </>
              )}
            </>
          ) : (
            <>
              <button 
                onClick={() => setActiveGame(null)} 
                className="mb-6 text-[0.65rem] font-black uppercase tracking-widest text-primary flex items-center gap-1.5 hover:underline"
              >
                ← Back to Challenges
              </button>
              {selectedGame === 'math' && <MathSprintGame activeGame={activeGame} onEnd={(score) => handleEndGame('math', score)} />}
              {selectedGame === 'scramble' && <WordScrambleGame activeGame={activeGame} onEnd={(score) => handleEndGame('scramble', score)} />}
              {selectedGame === 'trivia' && <TriviaGame activeGame={activeGame} onEnd={(score) => handleEndGame('trivia', score)} />}
            </>
          )}
        </div>
      )}

      {/* Scoreboards Section */}
      {!selectedGame && (
        <div className="mt-12 pt-10 border-t border-border/80 animate-in fade-in slide-in-from-bottom-4 duration-500">
          <div className="flex items-center gap-3 mb-8">
            <Trophy className="text-yellow-500 animate-bounce" size={24} />
            <div>
              <h4 className="text-lg font-black text-text uppercase tracking-tight">Arena Leaderboards</h4>
              <p className="text-[0.65rem] text-text-muted dark:text-text-light font-black uppercase tracking-widest mt-0.5">Top scores in each category</p>
            </div>
          </div>
          
          <div className="grid grid-cols-1 md:grid-cols-3 gap-8">
            {/* Column 1: Math Sprint */}
            <div className="bg-muted/15 border border-border rounded-[2rem] p-6 space-y-4 shadow-sm hover:shadow-md transition-shadow">
              <h5 className="text-[0.7rem] font-black uppercase tracking-widest text-orange-500 flex items-center gap-1.5 pb-2 border-b border-border/50">
                ⚡ Math Sprint
              </h5>
              <div className="space-y-2">
                {leaderboard.math.map((entry: any, index: number) => (
                  <div key={index} className={`flex justify-between items-center px-4 py-2.5 rounded-xl border transition-all ${entry.isPlayer ? 'bg-orange-500/10 border-orange-500/30 font-bold scale-[1.02]' : 'bg-card border-border/40'}`}>
                    <div className="flex items-center gap-3 min-w-0">
                      <span className={`w-5 h-5 rounded-full flex items-center justify-center text-[0.6rem] font-black shrink-0 ${
                        index === 0 ? 'bg-yellow-500 text-white' : index === 1 ? 'bg-slate-400 text-white' : index === 2 ? 'bg-amber-700 text-white' : 'bg-muted text-text-muted'
                      }`}>{index + 1}</span>
                      <span className="text-xs text-text truncate">{entry.name}</span>
                    </div>
                    <span className="text-xs font-black text-primary shrink-0">{entry.score} pts</span>
                  </div>
                ))}
              </div>
            </div>

            {/* Column 2: Word Scramble */}
            <div className="bg-muted/15 border border-border rounded-[2rem] p-6 space-y-4 shadow-sm hover:shadow-md transition-shadow">
              <h5 className="text-[0.7rem] font-black uppercase tracking-widest text-blue-600 flex items-center gap-1.5 pb-2 border-b border-border/50">
                🧠 Word Scramble
              </h5>
              <div className="space-y-2">
                {leaderboard.scramble.map((entry: any, index: number) => (
                  <div key={index} className={`flex justify-between items-center px-4 py-2.5 rounded-xl border transition-all ${entry.isPlayer ? 'bg-blue-600/10 border-blue-500/30 font-bold scale-[1.02]' : 'bg-card border-border/40'}`}>
                    <div className="flex items-center gap-3 min-w-0">
                      <span className={`w-5 h-5 rounded-full flex items-center justify-center text-[0.6rem] font-black shrink-0 ${
                        index === 0 ? 'bg-yellow-500 text-white' : index === 1 ? 'bg-slate-400 text-white' : index === 2 ? 'bg-amber-700 text-white' : 'bg-muted text-text-muted'
                      }`}>{index + 1}</span>
                      <span className="text-xs text-text truncate">{entry.name}</span>
                    </div>
                    <span className="text-xs font-black text-primary shrink-0">{entry.score} pts</span>
                  </div>
                ))}
              </div>
            </div>

            {/* Column 3: Academia Trivia */}
            <div className="bg-muted/15 border border-border rounded-[2rem] p-6 space-y-4 shadow-sm hover:shadow-md transition-shadow">
              <h5 className="text-[0.7rem] font-black uppercase tracking-widest text-emerald-600 flex items-center gap-1.5 pb-2 border-b border-border/50">
                ❓ Trivia Quiz
              </h5>
              <div className="space-y-2">
                {leaderboard.trivia.map((entry: any, index: number) => (
                  <div key={index} className={`flex justify-between items-center px-4 py-2.5 rounded-xl border transition-all ${entry.isPlayer ? 'bg-emerald-500/10 border-emerald-500/30 font-bold scale-[1.02]' : 'bg-card border-border/40'}`}>
                    <div className="flex items-center gap-3 min-w-0">
                      <span className={`w-5 h-5 rounded-full flex items-center justify-center text-[0.6rem] font-black shrink-0 ${
                        index === 0 ? 'bg-yellow-500 text-white' : index === 1 ? 'bg-slate-400 text-white' : index === 2 ? 'bg-amber-700 text-white' : 'bg-muted text-text-muted'
                      }`}>{index + 1}</span>
                      <span className="text-xs text-text truncate">{entry.name}</span>
                    </div>
                    <span className="text-xs font-black text-primary shrink-0">{entry.score} pts</span>
                  </div>
                ))}
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
/* ==========================================================================
   GAME 1: MATH SPRINT
   ========================================================================== */
function MathSprintGame({ onEnd, activeGame }: { onEnd: (score: number) => void; activeGame: any }) {
  const terms = useEducationTerms();
  const [gameState, setGameState] = useState<'idle' | 'playing' | 'ended'>('idle');
  const [score, setScore] = useState(0);
  
  const isCustom = activeGame !== 'general';
  const timeLimit = isCustom ? activeGame.time_limit_seconds : 30;
  const [timeLeft, setTimeLeft] = useState(timeLimit);
  const [question, setQuestion] = useState({ text: '', answer: 0 });
  const [userAnswer, setUserAnswer] = useState('');
  const [feedback, setFeedback] = useState<'correct' | 'wrong' | null>(null);
  
  const timerRef = useRef<NodeJS.Timeout | null>(null);

  const generateQuestion = () => {
    let operators = ['+', '-', '*'];
    let maxValue = 50;

    if (isCustom && activeGame.game_config) {
      if (Array.isArray(activeGame.game_config.operators) && activeGame.game_config.operators.length > 0) {
        operators = activeGame.game_config.operators;
      }
      if (typeof activeGame.game_config.max_value === 'number') {
        maxValue = activeGame.game_config.max_value;
      }
    }

    const op = operators[Math.floor(Math.random() * operators.length)];
    let num1 = 0, num2 = 0, ans = 0;

    if (op === '+') {
      num1 = Math.floor(Math.random() * maxValue) + 1;
      num2 = Math.floor(Math.random() * maxValue) + 1;
      ans = num1 + num2;
    } else if (op === '-') {
      num1 = Math.floor(Math.random() * maxValue) + 20;
      num2 = Math.floor(Math.random() * num1);
      ans = num1 - num2;
    } else if (op === '*') {
      const multMax = Math.min(maxValue, 12);
      num1 = Math.floor(Math.random() * multMax) + 1;
      num2 = Math.floor(Math.random() * multMax) + 1;
      ans = num1 * num2;
    } else if (op === '/') {
      const divMax = Math.min(maxValue, 10);
      num2 = Math.floor(Math.random() * divMax) + 1;
      ans = Math.floor(Math.random() * 10) + 1;
      num1 = num2 * ans;
    } else {
      num1 = Math.floor(Math.random() * 50) + 1;
      num2 = Math.floor(Math.random() * 50) + 1;
      ans = num1 + num2;
    }

    setQuestion({ text: `${num1} ${op} ${num2} = ?`, answer: ans });
    setUserAnswer('');
  };

  const startGame = () => {
    setScore(0);
    setTimeLeft(timeLimit);
    setGameState('playing');
    generateQuestion();
  };

  useEffect(() => {
    if (gameState === 'playing' && timeLeft > 0) {
      timerRef.current = setTimeout(() => {
        setTimeLeft(t => t - 1);
      }, 1000);
    } else if (timeLeft === 0 && gameState === 'playing') {
      setGameState('ended');
      onEnd(score);
    }
    return () => {
      if (timerRef.current) clearTimeout(timerRef.current);
    };
  }, [timeLeft, gameState]);

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    if (gameState !== 'playing' || !userAnswer) return;

    if (parseInt(userAnswer) === question.answer) {
      setScore(s => s + 10);
      setFeedback('correct');
      setTimeout(() => setFeedback(null), 400);
      generateQuestion();
    } else {
      setFeedback('wrong');
      setTimeout(() => setFeedback(null), 400);
      setUserAnswer('');
    }
  };

  if (gameState === 'idle') {
    return (
      <div className="text-center py-12 space-y-6">
        <Zap size={64} className="mx-auto text-orange-500 animate-bounce" />
        <h4 className="text-2xl font-black text-text uppercase tracking-tight">Math Sprint</h4>
        <p className="text-sm text-text-muted max-w-sm mx-auto">Beat the clock! Get +10 points for every correct answer. Challenge your calculations!</p>
        <button onClick={startGame} className="px-8 py-3.5 bg-orange-500 hover:bg-orange-600 text-white rounded-xl font-bold uppercase tracking-widest text-xs transition-all shadow-md active:scale-95">
          Start Game
        </button>
      </div>
    );
  }

  if (gameState === 'ended') {
    return (
      <div className="text-center py-12 space-y-6">
        <Award size={64} className="mx-auto text-yellow-500" />
        <h4 className="text-3xl font-black text-text uppercase tracking-tight">Sprint Completed!</h4>
        <div className="inline-block bg-muted px-8 py-4 rounded-3xl border border-border">
          <span className="text-xs font-black uppercase text-text-muted block tracking-widest">Final Score</span>
          <span className="text-4xl font-black text-primary">{score} PTS</span>
        </div>
        <p className="text-sm text-text-muted max-w-sm mx-auto">Fantastic job! Keep playing to improve your mental math reflexes.</p>
        <button onClick={startGame} className="px-8 py-3.5 bg-primary text-white rounded-xl font-bold uppercase tracking-widest text-xs transition-all flex items-center gap-2 mx-auto active:scale-95">
          <RotateCcw size={14} /> Play Again
        </button>
      </div>
    );
  }

  return (
    <div className="max-w-md mx-auto bg-muted/20 border border-border rounded-3xl p-8 space-y-8 relative overflow-hidden">
      <div className="flex justify-between items-center">
        <div className="flex items-center gap-2">
          <span className="text-[0.65rem] font-black uppercase tracking-widest text-text-muted">Time Left:</span>
          <span className={`text-xl font-black ${timeLeft <= 5 ? 'text-rose-500 animate-pulse' : 'text-text'}`}>{timeLeft}s</span>
        </div>
        <div className="flex items-center gap-2">
          <span className="text-[0.65rem] font-black uppercase tracking-widest text-text-muted">Score:</span>
          <span className="text-xl font-black text-primary">{score}</span>
        </div>
      </div>

      <div className="w-full h-2 bg-muted rounded-full overflow-hidden">
        <div 
          className={`h-full transition-all duration-1000 ${timeLeft <= 5 ? 'bg-rose-500' : 'bg-orange-500'}`} 
          style={{ width: `${(timeLeft / timeLimit) * 100}%` }}
        ></div>
      </div>

      <div className={`py-12 bg-card border border-border rounded-[2rem] text-center shadow-inner relative transition-all duration-200 ${
        feedback === 'correct' ? 'bg-emerald-500/10 border-emerald-500' : feedback === 'wrong' ? 'bg-rose-500/10 border-rose-500 animate-shake' : ''
      }`}>
        <span className="text-4xl font-black text-text tracking-wide">{question.text}</span>
      </div>

      <form onSubmit={handleSubmit} className="flex gap-4">
        <input 
          type="number"
          pattern="[0-9]*"
          inputMode="numeric"
          className="flex-1 bg-card border border-border rounded-2xl px-6 py-4 text-xl font-black text-center focus:outline-none focus:ring-4 focus:ring-primary/5 focus:border-primary text-text shadow-sm"
          placeholder="Type answer..."
          value={userAnswer}
          onChange={e => setUserAnswer(e.target.value)}
          autoFocus
        />
        <button type="submit" className="px-6 bg-primary text-white rounded-2xl font-bold uppercase tracking-widest text-xs flex items-center justify-center hover:bg-primary/95 transition-colors shadow-md active:scale-95">
          Submit
        </button>
      </form>
    </div>
  );
}

const SCRAMBLE_WORDS = [
  { original: 'PHOTOSYNTHESIS', scrambled: 'SISHTNYSOHTOEP', hint: 'The process by which green plants use sunlight to synthesize nutrients.' },
  { original: 'MITOCHONDRIA', scrambled: 'AIRDNOHCOTIM', hint: 'An organelle found in large numbers in most cells, key to energy production.' },
  { original: 'ATMOSPHERE', scrambled: 'EREHPSOMTA', hint: 'The envelope of gases surrounding the earth or another planet.' },
  { original: 'DEMOCRACY', scrambled: 'YCARCOEMD', hint: 'A system of government by the whole population, typically through elected representatives.' },
  { original: 'LITERATURE', scrambled: 'ERUTARETIL', hint: 'Written works, especially those considered of superior or lasting artistic merit.' },
  { original: 'GEOGRAPHY', scrambled: 'YHPAGROEG', hint: 'The study of the physical features of the earth and its atmosphere.' }
];

function WordScrambleGame({ onEnd, activeGame }: { onEnd: (score: number) => void; activeGame: any }) {
  const terms = useEducationTerms();
  const [wordIndex, setWordIndex] = useState(0);
  const [userGuess, setUserGuess] = useState('');
  const [score, setScore] = useState(0);
  const [gameState, setGameState] = useState<'idle' | 'loading' | 'playing' | 'ended'>('idle');
  const [feedback, setFeedback] = useState<'correct' | 'wrong' | null>(null);

  const [subjects, setSubjects] = useState<{ id: number; name: string }[]>([]);
  const [selectedSubjectId, setSelectedSubjectId] = useState<number | null>(null);
  const [gameItems, setGameItems] = useState<any[]>([]);

  useEffect(() => {
    api.get('/subjects').then(res => {
      setSubjects(res.data || []);
    }).catch(err => console.error(err));
  }, []);

  const scrambleWord = (word: string): string => {
    const arr = word.split('');
    for (let i = arr.length - 1; i > 0; i--) {
      const j = Math.floor(Math.random() * (i + 1));
      [arr[i], arr[j]] = [arr[j], arr[i]];
    }
    let result = arr.join('');
    if (result === word && word.length > 1) {
      result = word.split('').reverse().join('');
    }
    return result;
  };

  const startGame = async () => {
    setScore(0);
    setWordIndex(0);
    setUserGuess('');

    if (activeGame !== 'general') {
      const items = activeGame.game_config?.items || [];
      if (items.length > 0) {
        const mapped = items.map((item: any) => ({
          original: item.original.toUpperCase(),
          scrambled: scrambleWord(item.original),
          hint: item.hint || 'No clue provided.'
        }));
        setGameItems(mapped);
      } else {
        setGameItems(SCRAMBLE_WORDS);
      }
      setGameState('playing');
    } else {
      if (!selectedSubjectId) {
        setGameItems(SCRAMBLE_WORDS);
        setGameState('playing');
      } else {
        setGameState('loading');
        try {
          const response = await api.get(`/edutainment/content?game_type=scramble&subject_id=${selectedSubjectId}`);
          const items = response.data || [];
          if (items.length > 0) {
            const mapped = items.map((item: any) => ({
              original: item.question_text.toUpperCase(),
              scrambled: scrambleWord(item.question_text),
              hint: item.hint_text || 'No clue provided.'
            }));
            setGameItems(mapped);
          } else {
            alert('No custom terms found for this subject. Playing general terms instead!');
            setGameItems(SCRAMBLE_WORDS);
          }
        } catch (err) {
          console.error(err);
          setGameItems(SCRAMBLE_WORDS);
        }
        setGameState('playing');
      }
    }
  };

  const handleGuess = (e: React.FormEvent) => {
    e.preventDefault();
    if (gameState !== 'playing' || !userGuess) return;

    const currentWord = gameItems[wordIndex];
    if (userGuess.trim().toUpperCase() === currentWord.original) {
      setScore(s => s + 20);
      setFeedback('correct');
      setTimeout(() => {
        setFeedback(null);
        if (wordIndex < gameItems.length - 1) {
          setWordIndex(idx => idx + 1);
          setUserGuess('');
        } else {
          setGameState('ended');
          onEnd(score + 20);
        }
      }, 800);
    } else {
      setFeedback('wrong');
      setTimeout(() => setFeedback(null), 800);
    }
  };

  if (gameState === 'idle') {
    return (
      <div className="text-center py-12 space-y-6">
        <Brain size={64} className="mx-auto text-blue-500 animate-pulse" />
        <h4 className="text-2xl font-black text-text uppercase tracking-tight">Word Scramble</h4>
        <p className="text-sm text-text-muted max-w-sm mx-auto">Unscramble the educational words! Get +20 points for each correct word. Read the hints carefully.</p>
        
        {activeGame === 'general' && (
          <div className="max-w-xs mx-auto text-left space-y-2">
            <label className="text-[0.65rem] font-black uppercase text-text-muted tracking-widest block">Choose {terms.subject}</label>
            <select
              value={selectedSubjectId || ''}
              onChange={(e) => setSelectedSubjectId(e.target.value ? Number(e.target.value) : null)}
              className="w-full bg-card border border-border rounded-xl px-4 py-3 text-xs font-bold text-text focus:outline-none focus:border-primary shadow-sm"
            >
              <option value="">General (Default)</option>
              {subjects.map(s => (
                <option key={s.id} value={s.id}>{s.name}</option>
              ))}
            </select>
          </div>
        )}

        <button onClick={startGame} className="px-8 py-3.5 bg-blue-600 hover:bg-blue-700 text-white rounded-xl font-bold uppercase tracking-widest text-xs transition-all shadow-md active:scale-95">
          Start Game
        </button>
      </div>
    );
  }

  if (gameState === 'loading') {
    return (
      <div className="flex flex-col items-center justify-center py-20 space-y-4">
        <div className="w-10 h-10 border-4 border-blue-600 border-t-transparent rounded-full animate-spin" />
        <p className="text-xs font-black uppercase tracking-widest text-text-muted">Loading subject terms…</p>
      </div>
    );
  }

  if (gameState === 'ended') {
    return (
      <div className="text-center py-12 space-y-6">
        <Award size={64} className="mx-auto text-yellow-500" />
        <h4 className="text-3xl font-black text-text uppercase tracking-tight">Scramble Master!</h4>
        <div className="inline-block bg-muted px-8 py-4 rounded-3xl border border-border">
          <span className="text-xs font-black uppercase text-text-muted block tracking-widest">Final Score</span>
          <span className="text-4xl font-black text-primary">{score} PTS</span>
        </div>
        <p className="text-sm text-text-muted max-w-sm mx-auto">Amazing word skills! You successfully unscrambled all terms.</p>
        <button onClick={startGame} className="px-8 py-3.5 bg-primary text-white rounded-xl font-bold uppercase tracking-widest text-xs transition-all flex items-center gap-2 mx-auto active:scale-95">
          <RotateCcw size={14} /> Play Again
        </button>
      </div>
    );
  }

  const current = gameItems[wordIndex];

  return (
    <div className="max-w-md mx-auto bg-muted/20 border border-border rounded-3xl p-8 space-y-6 relative overflow-hidden">
      <div className="flex justify-between items-center text-xs font-black uppercase tracking-widest text-text-muted">
        <span>Word {wordIndex + 1} of {gameItems.length}</span>
        <span>Score: <span className="text-primary text-sm font-black">{score}</span></span>
      </div>

      <div className={`py-10 bg-card border border-border rounded-[2rem] text-center shadow-inner relative transition-all duration-200 ${
        feedback === 'correct' ? 'bg-emerald-500/10 border-emerald-500' : feedback === 'wrong' ? 'bg-rose-500/10 border-rose-500 animate-shake' : ''
      }`}>
        <span className="text-3xl font-black text-primary tracking-widest">{current?.scrambled}</span>
      </div>

      <div className="bg-card border border-border rounded-2xl p-4 text-[0.8rem] text-text-muted font-medium flex gap-3 items-start">
        <HelpCircle size={18} className="text-blue-500 shrink-0 mt-0.5" />
        <div>
          <span className="font-bold text-text uppercase tracking-widest text-[0.6rem] block mb-1">Clue</span>
          {current?.hint}
        </div>
      </div>

      <form onSubmit={handleGuess} className="flex gap-4">
        <input 
          type="text"
          className="flex-1 bg-card border border-border rounded-2xl px-5 py-3.5 font-bold uppercase focus:outline-none focus:ring-4 focus:ring-primary/5 focus:border-primary text-text shadow-sm"
          placeholder="Unscramble guess..."
          value={userGuess}
          onChange={e => setUserGuess(e.target.value)}
          autoFocus
        />
        <button type="submit" className="px-6 bg-primary text-white rounded-2xl font-bold uppercase tracking-widest text-xs flex items-center justify-center hover:bg-primary/95 transition-colors shadow-md active:scale-95">
          Submit
        </button>
      </form>
    </div>
  );
}

const TRIVIA_QUESTIONS = [
  { question: 'What is the largest organ in the human body?', options: ['Brain', 'Liver', 'Skin', 'Lungs'], answer: 'Skin' },
  { question: 'Which planet is known as the Red Planet?', options: ['Venus', 'Mars', 'Jupiter', 'Saturn'], answer: 'Mars' },
  { question: 'What is the chemical symbol for Gold?', options: ['Gd', 'Au', 'Ag', 'Fe'], answer: 'Au' },
  { question: 'In which continent is the Sahara Desert located?', options: ['Asia', 'Australia', 'Africa', 'South America'], answer: 'Africa' },
  { question: 'Who is the author of "Romeo and Juliet"?', options: ['Charles Dickens', 'William Shakespeare', 'Jane Austen', 'Mark Twain'], answer: 'William Shakespeare' }
];

function TriviaGame({ onEnd, activeGame }: { onEnd: (score: number) => void; activeGame: any }) {
  const terms = useEducationTerms();
  const [questionIndex, setQuestionIndex] = useState(0);
  const [selectedOption, setSelectedOption] = useState<string | null>(null);
  const [score, setScore] = useState(0);
  const [gameState, setGameState] = useState<'idle' | 'loading' | 'playing' | 'ended'>('idle');
  const [answered, setAnswered] = useState(false);

  const [subjects, setSubjects] = useState<{ id: number; name: string }[]>([]);
  const [selectedSubjectId, setSelectedSubjectId] = useState<number | null>(null);
  const [gameItems, setGameItems] = useState<any[]>([]);

  useEffect(() => {
    api.get('/subjects').then(res => {
      setSubjects(res.data || []);
    }).catch(err => console.error(err));
  }, []);

  const startGame = async () => {
    setScore(0);
    setQuestionIndex(0);
    setSelectedOption(null);
    setAnswered(false);

    if (activeGame !== 'general') {
      const questions = activeGame.game_config?.questions || [];
      if (questions.length > 0) {
        setGameItems(questions);
      } else {
        setGameItems(TRIVIA_QUESTIONS);
      }
      setGameState('playing');
    } else {
      if (!selectedSubjectId) {
        setGameItems(TRIVIA_QUESTIONS);
        setGameState('playing');
      } else {
        setGameState('loading');
        try {
          const response = await api.get(`/edutainment/content?game_type=trivia&subject_id=${selectedSubjectId}`);
          const items = response.data || [];
          if (items.length > 0) {
            const mapped = items.map((item: any) => ({
              question: item.question_text,
              options: item.options || [],
              answer: item.correct_answer
            }));
            setGameItems(mapped);
          } else {
            alert('No custom questions found for this subject. Playing general questions instead!');
            setGameItems(TRIVIA_QUESTIONS);
          }
        } catch (err) {
          console.error(err);
          setGameItems(TRIVIA_QUESTIONS);
        }
        setGameState('playing');
      }
    }
  };

  const handleOptionSelect = (option: string) => {
    if (answered) return;
    setSelectedOption(option);
    setAnswered(true);

    const current = gameItems[questionIndex];
    if (option === current.answer) {
      setScore(s => s + 20);
    }
  };

  const nextQuestion = () => {
    setSelectedOption(null);
    setAnswered(false);
    if (questionIndex < gameItems.length - 1) {
      setQuestionIndex(idx => idx + 1);
    } else {
      setGameState('ended');
      onEnd(score);
    }
  };

  if (gameState === 'idle') {
    return (
      <div className="text-center py-12 space-y-6">
        <HelpCircle size={64} className="mx-auto text-emerald-500 animate-spin-slow" />
        <h4 className="text-2xl font-black text-text uppercase tracking-tight">Academia Trivia</h4>
        <p className="text-sm text-text-muted max-w-sm mx-auto">Answer multiple choice questions on core academic subjects. Earn +20 points per correct answer!</p>
        
        {activeGame === 'general' && (
          <div className="max-w-xs mx-auto text-left space-y-2">
            <label className="text-[0.65rem] font-black uppercase text-text-muted tracking-widest block">Choose {terms.subject}</label>
            <select
              value={selectedSubjectId || ''}
              onChange={(e) => setSelectedSubjectId(e.target.value ? Number(e.target.value) : null)}
              className="w-full bg-card border border-border rounded-xl px-4 py-3 text-xs font-bold text-text focus:outline-none focus:border-primary shadow-sm"
            >
              <option value="">General (Default)</option>
              {subjects.map(s => (
                <option key={s.id} value={s.id}>{s.name}</option>
              ))}
            </select>
          </div>
        )}

        <button onClick={startGame} className="px-8 py-3.5 bg-emerald-600 hover:bg-emerald-700 text-white rounded-xl font-bold uppercase tracking-widest text-xs transition-all shadow-md active:scale-95">
          Start Quiz
        </button>
      </div>
    );
  }

  if (gameState === 'loading') {
    return (
      <div className="flex flex-col items-center justify-center py-20 space-y-4">
        <div className="w-10 h-10 border-4 border-emerald-600 border-t-transparent rounded-full animate-spin" />
        <p className="text-xs font-black uppercase tracking-widest text-text-muted">Loading trivia questions…</p>
      </div>
    );
  }

  if (gameState === 'ended') {
    return (
      <div className="text-center py-12 space-y-6">
        <Award size={64} className="mx-auto text-yellow-500" />
        <h4 className="text-3xl font-black text-text uppercase tracking-tight">Quiz Finished!</h4>
        <div className="inline-block bg-muted px-8 py-4 rounded-3xl border border-border">
          <span className="text-xs font-black uppercase text-text-muted block tracking-widest">Final Score</span>
          <span className="text-4xl font-black text-primary">{score} PTS</span>
        </div>
        <p className="text-sm text-text-muted max-w-sm mx-auto">Awesome performance! Challenge yourself again to get a perfect score.</p>
        <button onClick={startGame} className="px-8 py-3.5 bg-primary text-white rounded-xl font-bold uppercase tracking-widest text-xs transition-all flex items-center gap-2 mx-auto active:scale-95">
          <RotateCcw size={14} /> Play Again
        </button>
      </div>
    );
  }

  const current = gameItems[questionIndex];

  return (
    <div className="max-w-md mx-auto bg-muted/20 border border-border rounded-3xl p-8 space-y-6 relative overflow-hidden">
      <div className="flex justify-between items-center text-xs font-black uppercase tracking-widest text-text-muted">
        <span>Question {questionIndex + 1} of {gameItems.length}</span>
        <span>Score: <span className="text-primary text-sm font-black">{score}</span></span>
      </div>

      <div className="bg-card border border-border rounded-[2rem] p-6 text-center">
        <p className="text-lg font-bold text-text">{current?.question}</p>
      </div>

      <div className="space-y-3">
        {current?.options.map(option => {
          let optionStyle = 'bg-card border-border hover:bg-muted/50';
          if (answered) {
            if (option === current.answer) {
              optionStyle = 'bg-emerald-500/10 border-emerald-500/30 text-emerald-600 dark:text-emerald-400 font-bold';
            } else if (option === selectedOption) {
              optionStyle = 'bg-rose-500/10 border-rose-500/30 text-rose-600 dark:text-rose-400 font-bold';
            } else {
              optionStyle = 'bg-card border-border opacity-50';
            }
          }

          return (
            <button
              key={option}
              disabled={answered}
              onClick={() => handleOptionSelect(option)}
              className={`w-full py-4 px-6 text-left rounded-2xl border transition-all text-sm font-medium ${optionStyle}`}
            >
              {option}
            </button>
          );
        })}
      </div>

      {answered && (
        <button 
          onClick={nextQuestion} 
          className="w-full py-3.5 bg-primary hover:bg-primary/95 text-white rounded-2xl font-bold uppercase tracking-widest text-xs transition-all flex items-center justify-center gap-2 shadow-md active:scale-95"
        >
          Next Question <ArrowRight size={14} />
        </button>
      )}
    </div>
  );
}

function PuzzleList({ gameType, onSelect, onBack }: { gameType: 'math' | 'scramble' | 'trivia'; onSelect: (game: any) => void; onBack: () => void }) {
  const terms = useEducationTerms();
  const { games, fetchGames, isLoading, deleteGame } = useEdutainmentStore();
  const { user } = useAuthStore();
  const isStaff = user?.role !== 'student';
  const [showWizard, setShowWizard] = useState(false);

  useEffect(() => {
    fetchGames(gameType);
  }, [gameType, fetchGames]);

  return (
    <div className="space-y-6 animate-in fade-in duration-300">
      <button 
        onClick={onBack} 
        className="text-[0.65rem] font-black uppercase tracking-widest text-primary flex items-center gap-1.5 hover:underline"
      >
        ← Back to Arena
      </button>

      <div className="flex flex-col md:flex-row md:items-center justify-between gap-4 border-b border-border/50 pb-4">
        <div>
          <h4 className="text-xl font-black text-text uppercase tracking-tight">
            {gameType === 'math' ? 'Math Sprint Puzzles' : gameType === 'scramble' ? 'Word Scramble Puzzles' : 'Trivia Quizzes'}
          </h4>
          <p className="text-xs text-text-muted font-bold uppercase tracking-widest mt-1">Select a challenge to start playing</p>
        </div>
        {isStaff && (
          <button
            onClick={() => setShowWizard(true)}
            className="px-5 py-2.5 bg-indigo-600 hover:bg-indigo-700 text-white rounded-xl font-bold text-xs uppercase tracking-widest transition-all flex items-center gap-1.5 shadow-sm active:scale-95 shrink-0"
          >
            <Plus size={14} /> New Puzzle
          </button>
        )}
      </div>

      {isLoading && games.length === 0 ? (
        <div className="flex justify-center items-center py-20">
          <div className="w-10 h-10 border-4 border-primary border-t-transparent rounded-full animate-spin" />
        </div>
      ) : (
        <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
          <div className="bg-card border border-border rounded-[2rem] p-6 hover:shadow-xl hover:shadow-primary/5 transition-all group relative overflow-hidden flex flex-col justify-between">
            <div className="absolute top-0 right-0 w-32 h-32 bg-primary/5 rounded-bl-full" />
            <div className="space-y-4">
              <span className="px-2.5 py-1 rounded-lg text-[0.6rem] font-black uppercase tracking-widest border bg-muted text-text-muted border-border">
                Practice
              </span>
              <h5 className="text-lg font-black text-text uppercase tracking-tight mt-2">General Training</h5>
              <p className="text-xs text-text-muted font-medium">Practice with general terms and equations. Perfect for quick training!</p>
            </div>
            <button 
              onClick={() => onSelect('general')}
              className="mt-6 w-full py-3.5 bg-primary hover:bg-primary/95 text-white rounded-xl font-bold text-xs uppercase tracking-widest transition-all flex items-center justify-center gap-2 active:scale-95"
            >
              <Play size={14} /> Practice Now
            </button>
          </div>

          {games.map(game => (
            <div key={game.id} className="bg-card border border-border rounded-[2rem] p-6 hover:shadow-xl hover:shadow-primary/5 transition-all group relative overflow-hidden flex flex-col justify-between">
              <div className="space-y-4">
                <div className="flex items-center justify-between gap-2 flex-wrap">
                  <span className="px-2.5 py-1 rounded-lg text-[0.6rem] font-black uppercase tracking-widest border bg-indigo-50 text-indigo-600 border-indigo-100 dark:bg-indigo-950/20 dark:text-indigo-400 dark:border-indigo-900/30">
                    {game.subject_name || terms.subject}
                  </span>
                  <span className="text-[0.65rem] font-bold text-text-muted uppercase flex items-center gap-1">
                    Award: <span className="text-indigo-600 dark:text-indigo-400">+{game.reward_points} PTS</span>
                  </span>
                </div>
                <div>
                  <h5 className="text-lg font-black text-text uppercase tracking-tight">{game.title}</h5>
                  {game.description && (
                    <p className="text-xs text-text-muted font-medium mt-1">{game.description}</p>
                  )}
                </div>
                <div className="flex items-center justify-between text-[0.65rem] font-bold text-text-muted border-t border-border/50 pt-3">
                  <span>Creator: {game.first_name} {game.last_name}</span>
                  <span>Time: {game.time_limit_seconds}s</span>
                </div>
              </div>
              <div className="flex gap-2 mt-6">
                <button 
                  onClick={() => onSelect(game)}
                  className="flex-1 py-3.5 bg-indigo-600 hover:bg-indigo-700 text-white rounded-xl font-bold text-xs uppercase tracking-widest transition-all flex items-center justify-center gap-2 active:scale-95"
                >
                  <Play size={14} /> Start Challenge
                </button>
                {isStaff && (
                  <button
                    onClick={async () => {
                      if (confirm('Delete this custom puzzle?')) {
                        await deleteGame(game.id);
                        fetchGames(gameType);
                      }
                    }}
                    className="p-2.5 bg-card border border-border text-text-muted hover:text-rose-500 hover:border-rose-100 rounded-xl transition-all"
                    title="Delete"
                  >
                    <Trash2 size={16} />
                  </button>
                )}
              </div>
            </div>
          ))}
        </div>
      )}
      {showWizard && (
        <NewPuzzleWizard
          onClose={() => setShowWizard(false)}
          onSuccess={() => {
            fetchGames(gameType);
          }}
          defaultGameType={gameType}
        />
      )}
    </div>
  );
}

function NewPuzzleWizard({ onClose, onSuccess, defaultGameType }: { onClose: () => void; onSuccess: () => void; defaultGameType?: 'math' | 'scramble' | 'trivia' }) {
  const terms = useEducationTerms();
  const { createGame } = useEdutainmentStore();
  const [subjects, setSubjects] = useState<{ id: number; name: string }[]>([]);
  const [step, setStep] = useState<1 | 2>(1);
  const [error, setError] = useState<string | null>(null);
  const [submitting, setSubmitting] = useState(false);

  const [gameType, setGameType] = useState<'math' | 'scramble' | 'trivia'>(defaultGameType || 'scramble');
  const [title, setTitle] = useState('');
  const [description, setDescription] = useState('');
  const [subjectId, setSubjectId] = useState<number | null>(null);
  const [difficulty, setDifficulty] = useState<'easy' | 'medium' | 'hard'>('medium');
  const [rewardPoints, setRewardPoints] = useState(10);
  const [timeLimit, setTimeLimit] = useState(60);

  const [mathOperators, setMathOperators] = useState<string[]>(['+', '-']);
  const [mathMaxValue, setMathMaxValue] = useState(20);

  const [scrambleList, setScrambleList] = useState<{ original: string; hint: string }[]>([
    { original: '', hint: '' }
  ]);

  const [triviaList, setTriviaList] = useState<{ question: string; options: string[]; answer: string }[]>([
    { question: '', options: ['', '', '', ''], answer: '' }
  ]);

  useEffect(() => {
    api.get('/subjects').then(res => {
      const list = res.data || [];
      setSubjects(list);
      if (list.length > 0) {
        setSubjectId(list[0].id);
      }
    }).catch(err => console.error(err));
  }, []);

  const handleAddScrambleItem = () => {
    setScrambleList([...scrambleList, { original: '', hint: '' }]);
  };

  const handleRemoveScrambleItem = (idx: number) => {
    setScrambleList(scrambleList.filter((_, i) => i !== idx));
  };

  const handleAddTriviaItem = () => {
    setTriviaList([...triviaList, { question: '', options: ['', '', '', ''], answer: '' }]);
  };

  const handleRemoveTriviaItem = (idx: number) => {
    setTriviaList(triviaList.filter((_, i) => i !== idx));
  };

  const handleCreate = async () => {
    setError(null);
    if (!subjectId) return;
    if (!title.trim()) {
      setError('Title is required');
      return;
    }

    let config: any = {};
    if (gameType === 'math') {
      if (mathOperators.length === 0) {
        setError('Select at least one operator');
        return;
      }
      config = { operators: mathOperators, max_value: mathMaxValue };
    } else if (gameType === 'scramble') {
      const filtered = scrambleList.filter(item => item.original.trim());
      if (filtered.length === 0) {
        setError('Add at least one scramble word');
        return;
      }
      config = {
        items: filtered.map(item => ({
          original: item.original.trim().toUpperCase().replace(/[^A-Z]/g, ''),
          hint: item.hint.trim()
        }))
      };
    } else if (gameType === 'trivia') {
      const filtered = triviaList.filter(item => item.question.trim() && item.answer.trim());
      if (filtered.length === 0) {
        setError('Add at least one trivia question with selected correct answer');
        return;
      }
      config = {
        questions: filtered.map(item => ({
          question: item.question.trim(),
          options: item.options.map(o => o.trim()).filter(Boolean),
          answer: item.answer.trim()
        }))
      };
    }

    setSubmitting(true);
    try {
      await createGame({
        game_type: gameType,
        title: title.trim(),
        description: description.trim() || undefined,
        subject_id: subjectId,
        difficulty,
        reward_points: rewardPoints,
        time_limit_seconds: timeLimit,
        game_config: config
      });
      onSuccess();
      onClose();
    } catch (err: any) {
      setError(err.message || 'Failed to create puzzle');
    } finally {
      setSubmitting(false);
    }
  };

  return createPortal(
    <div className="fixed inset-0 bg-[#002147]/60 backdrop-blur-sm z-[150] flex items-center justify-center p-4" onClick={onClose}>
      <div className="bg-card border border-border rounded-[2.5rem] w-full max-w-2xl max-h-[90vh] overflow-hidden flex flex-col shadow-2xl animate-in zoom-in-95 duration-200" onClick={(e) => e.stopPropagation()}>
        <div className="px-8 py-6 bg-muted/50 border-b border-border flex items-center justify-between shrink-0 relative">
          <div className="absolute right-[-20px] top-[-20px] opacity-[0.03] rotate-12">
            <Puzzle size={180} />
          </div>
          <div>
            <h2 className="text-xl font-black text-text uppercase tracking-tight">New Game / Puzzle</h2>
            <p className="text-xs text-text-muted uppercase tracking-widest mt-1 font-bold">
              {step === 1 ? 'Configure Settings' : 'Define Questions & Custom Config'}
            </p>
          </div>
          <button onClick={onClose} className="w-9 h-9 flex items-center justify-center rounded-xl bg-card border border-border text-text-muted hover:text-rose-500 transition-colors">
            <X size={18} />
          </button>
        </div>

        <div className="p-8 overflow-y-auto flex-1 custom-scrollbar space-y-6">
          {error && (
            <div className="bg-rose-50 dark:bg-rose-950/20 border border-rose-100 dark:border-rose-900/30 rounded-xl p-4 text-rose-700 dark:text-rose-400 text-xs font-bold flex items-center gap-2">
              <AlertTriangle size={14} className="shrink-0" />
              <span>{error}</span>
            </div>
          )}

          {step === 1 ? (
            <div className="space-y-4">
              <div className="grid grid-cols-2 gap-4">
                <div className="space-y-1.5 col-span-2">
                  <label className="text-[0.65rem] font-black uppercase text-text-muted tracking-widest block">Game Type</label>
                  <select
                    value={gameType}
                    onChange={(e: any) => setGameType(e.target.value)}
                    className="w-full bg-muted/20 border border-border rounded-xl px-4 py-3 text-xs font-bold text-text focus:outline-none focus:border-primary shadow-sm"
                  >
                    <option value="math">⚡ Math Sprint</option>
                    <option value="scramble">🧩 Word Scramble</option>
                    <option value="trivia">❓ Academia Trivia</option>
                  </select>
                </div>

                <div className="space-y-1.5 col-span-2">
                  <label className="text-[0.65rem] font-black uppercase text-text-muted tracking-widest block">Puzzle Title</label>
                  <input
                    type="text"
                    required
                    placeholder="e.g. Chemistry Atoms Scramble"
                    value={title}
                    onChange={e => setTitle(e.target.value)}
                    className="w-full bg-muted/20 border border-border rounded-xl px-4 py-3 text-xs font-bold text-text focus:outline-none focus:border-primary focus:bg-card shadow-sm"
                  />
                </div>

                <div className="space-y-1.5 col-span-2">
                  <label className="text-[0.65rem] font-black uppercase text-text-muted tracking-widest block">Description</label>
                  <textarea
                    placeholder="Provide context or instructions for your students..."
                    value={description}
                    onChange={e => setDescription(e.target.value)}
                    rows={2}
                    className="w-full bg-muted/20 border border-border rounded-xl px-4 py-3 text-xs font-bold text-text focus:outline-none focus:border-primary focus:bg-card shadow-sm"
                  />
                </div>

                <div className="space-y-1.5">
                  <label className="text-[0.65rem] font-black uppercase text-text-muted tracking-widest block">Associated {terms.subject}</label>
                  <select
                    value={subjectId || ''}
                    onChange={e => setSubjectId(Number(e.target.value))}
                    className="w-full bg-muted/20 border border-border rounded-xl px-4 py-3 text-xs font-bold text-text focus:outline-none focus:border-primary shadow-sm"
                  >
                    {subjects.map(s => (
                      <option key={s.id} value={s.id}>{s.name}</option>
                    ))}
                  </select>
                </div>

                <div className="space-y-1.5">
                  <label className="text-[0.65rem] font-black uppercase text-text-muted tracking-widest block">Difficulty</label>
                  <select
                    value={difficulty}
                    onChange={(e: any) => setDifficulty(e.target.value)}
                    className="w-full bg-muted/20 border border-border rounded-xl px-4 py-3 text-xs font-bold text-text focus:outline-none focus:border-primary shadow-sm"
                  >
                    <option value="easy">Easy</option>
                    <option value="medium">Medium</option>
                    <option value="hard">Hard</option>
                  </select>
                </div>

                <div className="space-y-1.5">
                  <label className="text-[0.65rem] font-black uppercase text-text-muted tracking-widest block">Points Reward</label>
                  <input
                    type="number"
                    value={rewardPoints}
                    onChange={e => setRewardPoints(Number(e.target.value))}
                    className="w-full bg-muted/20 border border-border rounded-xl px-4 py-3 text-xs font-bold text-text focus:outline-none focus:border-primary focus:bg-card shadow-sm"
                  />
                </div>

                <div className="space-y-1.5">
                  <label className="text-[0.65rem] font-black uppercase text-text-muted tracking-widest block">Time Limit (seconds)</label>
                  <input
                    type="number"
                    value={timeLimit}
                    onChange={e => setTimeLimit(Number(e.target.value))}
                    className="w-full bg-muted/20 border border-border rounded-xl px-4 py-3 text-xs font-bold text-text focus:outline-none focus:border-primary focus:bg-card shadow-sm"
                  />
                </div>
              </div>
            </div>
          ) : (
            <div className="space-y-4">
              {gameType === 'math' && (
                <div className="space-y-6">
                  <div className="space-y-2">
                    <label className="text-[0.65rem] font-black uppercase text-text-muted tracking-widest block">Allowed Arithmetic Operators</label>
                    <div className="flex gap-4">
                      {['+', '-', '*', '/'].map(op => {
                        const active = mathOperators.includes(op);
                        return (
                          <button
                            key={op}
                            type="button"
                            onClick={() => {
                              if (active) {
                                setMathOperators(mathOperators.filter(o => o !== op));
                              } else {
                                setMathOperators([...mathOperators, op]);
                              }
                            }}
                            className={`w-12 h-12 rounded-xl text-lg font-black border transition-all ${
                              active ? 'bg-indigo-600 text-white border-indigo-700 shadow-sm' : 'bg-muted/40 border-border text-text-muted'
                            }`}
                          >
                            {op}
                          </button>
                        );
                      })}
                    </div>
                  </div>

                  <div className="space-y-2">
                    <label className="text-[0.65rem] font-black uppercase text-text-muted tracking-widest block">Maximum Numbers Range</label>
                    <input
                      type="number"
                      value={mathMaxValue}
                      onChange={e => setMathMaxValue(Number(e.target.value))}
                      className="max-w-[200px] bg-muted/20 border border-border rounded-xl px-4 py-3 text-xs font-bold text-text focus:outline-none focus:border-primary focus:bg-card shadow-sm"
                    />
                    <p className="text-[0.65rem] text-text-muted font-medium">Equations will use numbers between 1 and this value.</p>
                  </div>
                </div>
              )}

              {gameType === 'scramble' && (
                <div className="space-y-4">
                  <div className="flex justify-between items-center pb-2 border-b border-border">
                    <label className="text-[0.65rem] font-black uppercase text-text-muted tracking-widest">Word & Hint Entries</label>
                    <button
                      type="button"
                      onClick={handleAddScrambleItem}
                      className="text-xs font-black uppercase text-primary tracking-widest hover:underline flex items-center gap-1"
                    >
                      <Plus size={14} /> Add Row
                    </button>
                  </div>

                  <div className="space-y-4 max-h-[300px] overflow-y-auto pr-1 custom-scrollbar">
                    {scrambleList.map((item, idx) => (
                      <div key={idx} className="flex gap-2 items-start bg-muted/10 border border-border/60 p-4 rounded-2xl relative">
                        <div className="flex-1 grid grid-cols-3 gap-2">
                          <input
                            type="text"
                            required
                            placeholder="WORD"
                            value={item.original}
                            onChange={e => {
                              const next = [...scrambleList];
                              next[idx].original = e.target.value.toUpperCase().replace(/[^A-Z]/g, '');
                              setScrambleList(next);
                            }}
                            className="bg-card border border-border rounded-xl px-3 py-2.5 text-xs font-bold text-text focus:outline-none focus:border-primary shadow-sm"
                          />
                          <input
                            type="text"
                            placeholder="Clue / context hint..."
                            value={item.hint}
                            onChange={e => {
                              const next = [...scrambleList];
                              next[idx].hint = e.target.value;
                              setScrambleList(next);
                            }}
                            className="col-span-2 bg-card border border-border rounded-xl px-3 py-2.5 text-xs font-bold text-text focus:outline-none focus:border-primary shadow-sm"
                          />
                        </div>
                        {scrambleList.length > 1 && (
                          <button
                            type="button"
                            onClick={() => handleRemoveScrambleItem(idx)}
                            className="p-2 text-text-muted hover:text-rose-500 hover:bg-rose-500/10 rounded-xl transition-all shrink-0 mt-0.5"
                          >
                            <Trash2 size={14} />
                          </button>
                        )}
                      </div>
                    ))}
                  </div>
                </div>
              )}

              {gameType === 'trivia' && (
                <div className="space-y-4">
                  <div className="flex justify-between items-center pb-2 border-b border-border">
                    <label className="text-[0.65rem] font-black uppercase text-text-muted tracking-widest">Question & Options Entries</label>
                    <button
                      type="button"
                      onClick={handleAddTriviaItem}
                      className="text-xs font-black uppercase text-primary tracking-widest hover:underline flex items-center gap-1"
                    >
                      <Plus size={14} /> Add Question
                    </button>
                  </div>

                  <div className="space-y-6 max-h-[350px] overflow-y-auto pr-1 custom-scrollbar">
                    {triviaList.map((item, idx) => (
                      <div key={idx} className="bg-muted/10 border border-border p-5 rounded-2xl space-y-3 relative">
                        <div className="flex justify-between items-start gap-2">
                          <span className="text-[0.65rem] font-black text-indigo-600 dark:text-indigo-400 uppercase tracking-widest">Question {idx + 1}</span>
                          {triviaList.length > 1 && (
                            <button
                              type="button"
                              onClick={() => handleRemoveTriviaItem(idx)}
                              className="p-1.5 text-text-muted hover:text-rose-500 hover:bg-rose-500/10 rounded-lg transition-all"
                            >
                              <Trash2 size={14} />
                            </button>
                          )}
                        </div>

                        <input
                          type="text"
                          required
                          placeholder="e.g. What chemical element is represented by O?"
                          value={item.question}
                          onChange={e => {
                            const next = [...triviaList];
                            next[idx].question = e.target.value;
                            setTriviaList(next);
                          }}
                          className="w-full bg-card border border-border rounded-xl px-3.5 py-2.5 text-xs font-bold text-text focus:outline-none focus:border-primary shadow-sm"
                        />

                        <div className="grid grid-cols-2 gap-2">
                          {item.options.map((opt, oIdx) => (
                            <div key={oIdx} className="flex gap-2 items-center">
                              <input
                                type="radio"
                                name={`correct-${idx}`}
                                checked={item.answer === opt && opt !== ''}
                                onChange={() => {
                                  const next = [...triviaList];
                                  next[idx].answer = opt;
                                  setTriviaList(next);
                                }}
                                className="text-primary focus:ring-primary w-4 h-4 cursor-pointer"
                                title="Mark as correct answer"
                              />
                              <input
                                type="text"
                                required
                                placeholder={`Option ${String.fromCharCode(65 + oIdx)}`}
                                value={opt}
                                onChange={e => {
                                  const next = [...triviaList];
                                  next[idx].options[oIdx] = e.target.value;
                                  if (item.answer === opt) {
                                    next[idx].answer = e.target.value;
                                  }
                                  setTriviaList(next);
                                }}
                                className="flex-1 bg-card border border-border rounded-xl px-3 py-2.5 text-xs font-bold text-text focus:outline-none focus:border-primary shadow-sm"
                              />
                            </div>
                          ))}
                        </div>
                      </div>
                    ))}
                  </div>
                </div>
              )}
            </div>
          )}
        </div>

        <div className="px-8 py-5 bg-muted/50 border-t border-border flex items-center justify-between shrink-0">
          {step === 1 ? (
            <>
              <button type="button" onClick={onClose} className="px-5 py-2.5 bg-card border border-border hover:bg-muted text-text rounded-xl font-bold text-xs uppercase tracking-widest transition-colors">
                Cancel
              </button>
              <button
                type="button"
                onClick={() => {
                  if (title.trim()) {
                    setStep(2);
                  } else {
                    setError('Title is required');
                  }
                }}
                className="px-6 py-2.5 bg-primary hover:bg-primary/95 text-white rounded-xl font-bold text-xs uppercase tracking-widest transition-colors shadow-md"
              >
                Next Step
              </button>
            </>
          ) : (
            <>
              <button type="button" onClick={() => setStep(1)} className="px-5 py-2.5 bg-card border border-border hover:bg-muted text-text rounded-xl font-bold text-xs uppercase tracking-widest transition-colors">
                Back
              </button>
              <button
                type="button"
                disabled={submitting}
                onClick={handleCreate}
                className="px-6 py-2.5 bg-indigo-600 hover:bg-indigo-700 text-white rounded-xl font-bold text-xs uppercase tracking-widest transition-colors shadow-md flex items-center gap-2"
              >
                {submitting ? (
                  <div className="w-3 h-3 border-2 border-white border-t-transparent rounded-full animate-spin" />
                ) : (
                  <Check size={14} />
                )}
                Create Puzzle
              </button>
            </>
          )}
        </div>
      </div>
    </div>
  ,
    document.body
  );
}

function GameContentManager() {
  const terms = useEducationTerms();
  const { content, games, isLoading, error, fetchContent, createContent, deleteContent, fetchGames, deleteGame } = useEdutainmentStore();
  const [subjects, setSubjects] = useState<{ id: number; name: string }[]>([]);
  const [selectedSubjectId, setSelectedSubjectId] = useState<number | null>(null);
  const [activeTab, setActiveTab] = useState<'scramble' | 'trivia'>('scramble');
  const [managerView, setManagerView] = useState<'pool' | 'puzzles'>('puzzles');
  const [showWizard, setShowWizard] = useState(false);

  const [scrambleWord, setScrambleWord] = useState('');
  const [scrambleHint, setScrambleHint] = useState('');

  const [triviaQuestion, setTriviaQuestion] = useState('');
  const [triviaOptions, setTriviaOptions] = useState<string[]>(['', '', '', '']);
  const [triviaCorrectIndex, setTriviaCorrectIndex] = useState<number>(0);
  const [formError, setFormError] = useState<string | null>(null);

  useEffect(() => {
    api.get('/subjects').then(res => {
      const list = res.data || [];
      setSubjects(list);
      if (list.length > 0) {
        setSelectedSubjectId(list[0].id);
      }
    }).catch(err => console.error(err));
  }, []);

  useEffect(() => {
    if (selectedSubjectId) {
      if (managerView === 'pool') {
        fetchContent(activeTab, selectedSubjectId);
      } else {
        fetchGames(undefined, selectedSubjectId);
      }
    }
  }, [managerView, activeTab, selectedSubjectId, fetchContent, fetchGames]);

  const handleAddScramble = async (e: React.FormEvent) => {
    e.preventDefault();
    setFormError(null);
    if (!selectedSubjectId) return;
    if (!scrambleWord.trim()) {
      setFormError('Word is required');
      return;
    }
    const cleanWord = scrambleWord.trim().toUpperCase().replace(/[^A-Z]/g, '');
    if (cleanWord.length < 2) {
      setFormError('Word must be at least 2 letters long');
      return;
    }

    try {
      await createContent({
        game_type: 'scramble',
        subject_id: selectedSubjectId,
        question_text: cleanWord,
        hint_text: scrambleHint.trim() || undefined,
      });
      setScrambleWord('');
      setScrambleHint('');
    } catch (err: any) {
      setFormError(err.message || 'Failed to create scramble term');
    }
  };

  const handleAddTrivia = async (e: React.FormEvent) => {
    e.preventDefault();
    setFormError(null);
    if (!selectedSubjectId) return;
    if (!triviaQuestion.trim()) {
      setFormError('Question is required');
      return;
    }
    const filledOptions = triviaOptions.map(o => o.trim()).filter(Boolean);
    if (filledOptions.length < 2) {
      setFormError('Trivia question must have at least 2 options');
      return;
    }
    const correctVal = triviaOptions[triviaCorrectIndex]?.trim();
    if (!correctVal) {
      setFormError('Please fill out the selected correct answer option');
      return;
    }

    try {
      await createContent({
        game_type: 'trivia',
        subject_id: selectedSubjectId,
        question_text: triviaQuestion.trim(),
        options: filledOptions,
        correct_answer: correctVal,
      });
      setTriviaQuestion('');
      setTriviaOptions(['', '', '', '']);
      setTriviaCorrectIndex(0);
    } catch (err: any) {
      setFormError(err.message || 'Failed to create trivia question');
    }
  };

  return (
    <div className="space-y-8 animate-in fade-in duration-300">
      <div className="flex flex-col md:flex-row md:items-center justify-between gap-4 border-b border-border pb-6">
        <div>
          <h4 className="text-xl font-black text-text uppercase tracking-tight">Game Content Manager</h4>
          <p className="text-xs text-text-muted font-bold uppercase tracking-widest mt-1">Configure words and quizzes for subjects</p>
        </div>
        
        <div className="flex items-center gap-3">
          <label className="text-xs font-black uppercase text-text-muted tracking-widest shrink-0">Active {terms.subject}:</label>
          <select
            value={selectedSubjectId || ''}
            onChange={(e) => setSelectedSubjectId(e.target.value ? Number(e.target.value) : null)}
            className="bg-card border border-border rounded-xl px-4 py-2.5 text-xs font-bold text-text focus:outline-none focus:border-primary shadow-sm min-w-[200px]"
          >
            {subjects.map(s => (
              <option key={s.id} value={s.id}>{s.name}</option>
            ))}
          </select>
        </div>
      </div>

      <div className="flex justify-between items-center flex-wrap gap-4 border-b border-border pb-4">
        <div className="flex border border-border p-0.5 bg-muted/30 rounded-xl">
          <button
            onClick={() => setManagerView('puzzles')}
            className={`px-4 py-2 rounded-lg text-xs font-black uppercase tracking-widest transition-all ${
              managerView === 'puzzles' ? 'bg-card text-primary shadow-sm' : 'text-text-muted hover:text-text'
            }`}
          >
            🏆 {terms.subject} Puzzles
          </button>
          <button
            onClick={() => setManagerView('pool')}
            className={`px-4 py-2 rounded-lg text-xs font-black uppercase tracking-widest transition-all ${
              managerView === 'pool' ? 'bg-card text-primary shadow-sm' : 'text-text-muted hover:text-text'
            }`}
          >
            🗂️ General Pools
          </button>
        </div>

        {managerView === 'puzzles' && (
          <button
            onClick={() => setShowWizard(true)}
            className="px-4 py-2.5 bg-indigo-600 hover:bg-indigo-700 text-white rounded-xl font-bold text-xs uppercase tracking-widest transition-colors flex items-center gap-1.5 shadow-sm active:scale-95 animate-in slide-in-from-right-3 duration-200"
          >
            <Plus size={14} /> Create Puzzle
          </button>
        )}
      </div>

      {managerView === 'puzzles' ? (
        <div className="bg-card border border-border rounded-[2.5rem] p-6 min-h-[300px] flex flex-col justify-between shadow-sm">
          <div>
            <h5 className="text-sm font-black uppercase tracking-widest text-text pb-3 border-b border-border">
              Published Custom Puzzles ({games.length})
            </h5>
            
            {isLoading && games.length === 0 ? (
              <div className="flex justify-center items-center py-12">
                <div className="w-8 h-8 border-4 border-indigo-600 border-t-transparent rounded-full animate-spin" />
              </div>
            ) : games.length === 0 ? (
              <div className="flex flex-col justify-center items-center text-center py-12 text-text-muted min-h-[200px]">
                <Layers size={40} className="text-text-muted/30 mb-3" />
                <p className="font-black uppercase tracking-widest text-[0.65rem]">No custom puzzles created for this subject yet.</p>
              </div>
            ) : (
              <div className="divide-y divide-border pr-1 mt-4 max-h-[450px] overflow-y-auto custom-scrollbar">
                {games.map(game => (
                  <div key={game.id} className="py-4 first:pt-0 last:pb-0 flex items-start justify-between gap-4">
                    <div className="space-y-1 min-w-0">
                      <div className="flex items-center gap-2 flex-wrap">
                        <span className="font-bold text-sm text-text truncate max-w-md">{game.title}</span>
                        <span className="px-2 py-0.5 rounded-md text-[0.55rem] font-bold uppercase border bg-indigo-50/50 text-indigo-600 border-indigo-100 dark:bg-indigo-950/20 dark:text-indigo-400 dark:border-indigo-900/30">
                          {game.game_type === 'math' ? 'Math Sprint' : game.game_type === 'scramble' ? 'Word Scramble' : 'Trivia Quiz'}
                        </span>
                        <span className="px-2 py-0.5 rounded-md text-[0.55rem] font-bold uppercase border bg-muted text-text-muted border-border">
                          {game.difficulty}
                        </span>
                      </div>
                      {game.description && (
                        <p className="text-xs text-text-muted font-medium truncate max-w-xl">{game.description}</p>
                      )}
                      <p className="text-[0.65rem] text-text-muted/70 font-semibold">
                        Limit: {game.time_limit_seconds}s • Reward: +{game.reward_points} PTS • Creator: {game.first_name} {game.last_name}
                      </p>
                    </div>

                    <button
                      onClick={async () => {
                        if (confirm(`Delete puzzle "${game.title}"?`)) {
                          await deleteGame(game.id);
                          fetchGames(undefined, selectedSubjectId || undefined);
                        }
                      }}
                      className="p-2 text-text-muted hover:text-rose-500 hover:bg-rose-500/10 rounded-xl transition-all shrink-0"
                      title="Delete"
                    >
                      <Trash2 size={16} />
                    </button>
                  </div>
                ))}
              </div>
            )}
          </div>
        </div>
      ) : (
        <>
          <div className="flex border-b border-border p-1 bg-muted/30 rounded-2xl max-w-sm shrink-0">
            <button
              onClick={() => setActiveTab('scramble')}
              className={`flex-1 py-2.5 rounded-xl text-xs font-black uppercase tracking-widest transition-all ${
                activeTab === 'scramble' ? 'bg-card text-primary shadow-sm border border-border' : 'text-text-muted hover:text-text'
              }`}
            >
              🧩 Word Scramble
            </button>
            <button
              onClick={() => setActiveTab('trivia')}
              className={`flex-1 py-2.5 rounded-xl text-xs font-black uppercase tracking-widest transition-all ${
                activeTab === 'trivia' ? 'bg-card text-primary shadow-sm border border-border' : 'text-text-muted hover:text-text'
              }`}
            >
              ❓ Academia Trivia
            </button>
          </div>

          <div className="grid grid-cols-1 lg:grid-cols-12 gap-8 animate-in fade-in duration-200">
            <div className="lg:col-span-5 bg-card border border-border rounded-[2rem] p-6 shadow-sm space-y-6">
              <h5 className="text-sm font-black uppercase tracking-widest text-text pb-3 border-b border-border">
                Add New {activeTab === 'scramble' ? 'Scramble Word' : 'Trivia Question'}
              </h5>

              {formError && (
                <div className="bg-rose-50 dark:bg-rose-950/20 border border-rose-100 dark:border-rose-900/30 rounded-xl p-4 text-rose-700 dark:text-rose-400 text-xs font-bold flex items-center gap-2">
                  <AlertTriangle size={14} className="shrink-0" />
                  <span>{formError}</span>
                </div>
              )}

              {activeTab === 'scramble' ? (
                <form onSubmit={handleAddScramble} className="space-y-4">
                  <div className="space-y-1.5">
                    <label className="text-[0.65rem] font-black uppercase text-text-muted tracking-widest block">Word (A-Z only)</label>
                    <input
                      type="text"
                      required
                      placeholder="e.g. MOLECULE"
                      value={scrambleWord}
                      onChange={e => setScrambleWord(e.target.value.toUpperCase().replace(/[^A-Z]/g, ''))}
                      className="w-full bg-muted/20 border border-border rounded-xl px-4 py-3 text-xs font-bold text-text focus:outline-none focus:border-primary focus:bg-card shadow-sm"
                    />
                  </div>

                  <div className="space-y-1.5">
                    <label className="text-[0.65rem] font-black uppercase text-text-muted tracking-widest block">Clue / Hint text</label>
                    <textarea
                      placeholder="e.g. Group of atoms bonded together representing the smallest fundamental unit of a compound."
                      value={scrambleHint}
                      onChange={e => setScrambleHint(e.target.value)}
                      rows={3}
                      className="w-full bg-muted/20 border border-border rounded-xl px-4 py-3 text-xs font-bold text-text focus:outline-none focus:border-primary focus:bg-card shadow-sm"
                    />
                  </div>

                  <button
                    type="submit"
                    disabled={isLoading}
                    className="w-full py-3.5 bg-indigo-600 hover:bg-indigo-700 text-white rounded-xl font-bold uppercase tracking-widest text-xs transition-all shadow-md flex items-center justify-center gap-2"
                  >
                    <Plus size={14} /> Add Word
                  </button>
                </form>
              ) : (
                <form onSubmit={handleAddTrivia} className="space-y-4">
                  <div className="space-y-1.5">
                    <label className="text-[0.65rem] font-black uppercase text-text-muted tracking-widest block">Question text</label>
                    <textarea
                      required
                      placeholder="e.g. Which particle in an atom has a negative charge?"
                      value={triviaQuestion}
                      onChange={e => setTriviaQuestion(e.target.value)}
                      rows={2}
                      className="w-full bg-muted/20 border border-border rounded-xl px-4 py-3 text-xs font-bold text-text focus:outline-none focus:border-primary focus:bg-card shadow-sm"
                    />
                  </div>

                  <div className="space-y-2">
                    <label className="text-[0.65rem] font-black uppercase text-text-muted tracking-widest block">Answer Options & Correct Answer</label>
                    {triviaOptions.map((option, idx) => (
                      <div key={idx} className="flex gap-2 items-center">
                        <input
                          type="radio"
                          name="correct-answer"
                          checked={triviaCorrectIndex === idx}
                          onChange={() => setTriviaCorrectIndex(idx)}
                          className="text-primary focus:ring-primary w-4 h-4 cursor-pointer"
                          title="Mark as correct answer"
                        />
                        <input
                          type="text"
                          required
                          placeholder={`Option ${String.fromCharCode(65 + idx)}`}
                          value={option}
                          onChange={e => {
                            const next = [...triviaOptions];
                            next[idx] = e.target.value;
                            setTriviaOptions(next);
                          }}
                          className="flex-1 bg-muted/20 border border-border rounded-xl px-3.5 py-2.5 text-xs font-bold text-text focus:outline-none focus:border-primary focus:bg-card shadow-sm"
                        />
                      </div>
                    ))}
                  </div>

                  <button
                    type="submit"
                    disabled={isLoading}
                    className="w-full py-3.5 bg-indigo-600 hover:bg-indigo-700 text-white rounded-xl font-bold uppercase tracking-widest text-xs transition-all shadow-md flex items-center justify-center gap-2"
                  >
                    <Plus size={14} /> Add Question
                  </button>
                </form>
              )}
            </div>

            <div className="lg:col-span-7 bg-card border border-border rounded-[2rem] p-6 shadow-sm flex flex-col min-h-[400px]">
              <h5 className="text-sm font-black uppercase tracking-widest text-text pb-3 border-b border-border">
                Active Pool List ({content.length})
              </h5>

              {isLoading && content.length === 0 ? (
                <div className="flex justify-center items-center flex-1 py-12">
                  <div className="w-8 h-8 border-4 border-indigo-600 border-t-transparent rounded-full animate-spin" />
                </div>
              ) : content.length === 0 ? (
                <div className="flex flex-col justify-center items-center text-center flex-1 py-12 text-text-muted">
                  <Brain size={40} className="text-text-muted/30 mb-3" />
                  <p className="font-black uppercase tracking-widest text-[0.65rem]">No pool content added for this subject yet.</p>
                </div>
              ) : (
                <div className="flex-1 divide-y divide-border overflow-y-auto max-h-[450px] custom-scrollbar pr-1 mt-4">
                  {content.map(item => (
                    <div key={item.id} className="py-4 first:pt-0 last:pb-0 flex items-start justify-between gap-4">
                      <div className="space-y-1 min-w-0">
                        <p className="font-bold text-sm text-text break-words">
                          {item.game_type === 'scramble' ? (
                            <span className="tracking-wider font-black text-indigo-600 dark:text-indigo-400">{item.question_text}</span>
                          ) : (
                            item.question_text
                          )}
                        </p>
                        {item.hint_text && (
                          <p className="text-xs text-text-muted font-medium break-words">
                            <span className="font-bold">Clue:</span> {item.hint_text}
                          </p>
                        )}
                        {item.options && (
                          <div className="flex flex-wrap gap-1.5 mt-2">
                            {item.options.map(o => (
                              <span
                                key={o}
                                className={`px-2 py-1 rounded-lg text-[0.6rem] font-bold border ${
                                  o === item.correct_answer
                                    ? 'bg-emerald-50 text-emerald-600 border-emerald-100 dark:bg-emerald-950/20 dark:text-emerald-400 dark:border-emerald-900/30'
                                    : 'bg-muted text-text-muted/70 border-border'
                                }`}
                              >
                                {o}
                              </span>
                            ))}
                          </div>
                        )}
                      </div>

                      <button
                        onClick={() => {
                          if (confirm('Delete this item?')) {
                            deleteContent(item.id);
                          }
                        }}
                        className="p-2 text-text-muted hover:text-rose-500 hover:bg-rose-500/10 rounded-xl transition-all shrink-0"
                        title="Delete"
                      >
                        <Trash2 size={16} />
                      </button>
                    </div>
                  ))}
                </div>
              )}
            </div>
          </div>
        </>
      )}

      {/* New game/puzzle wizard */}
      {showWizard && (
        <NewPuzzleWizard
          onClose={() => setShowWizard(false)}
          onSuccess={() => {
            if (selectedSubjectId) {
              fetchGames(undefined, selectedSubjectId);
            }
          }}
        />
      )}
    </div>
  );
}
