"use client"

import { useState, useEffect, useRef, useCallback } from "react"
import { Button } from "@/components/ui/button"
import { Card, CardContent } from "@/components/ui/card"
import { useToast } from "@/hooks/use-toast"
import { useCurrency } from "@/components/currency-provider"
import { useRouter } from "next/navigation"
import Link from "next/link"
import {
  ArrowLeft, Brain, Coins, Zap, Trophy, ChevronRight, CheckCircle2, XCircle,
  Play, Sparkles, BarChart3, Wallet, Clock, RefreshCw, Loader2,
  HelpCircle, Star, Timer, Smartphone, Download
} from "lucide-react"

// ─── Types ─────────────────────────────────────────────
interface QuizQuestion {
  id: number
  question: string
  options: string[]
  correctAnswer: string
  explanation: string
}

type QuizState = "category-select" | "loading" | "playing" | "ad-break" | "results" | "app-required"

const CATEGORIES = [
  { key: "affiliate-marketing", label: "Affiliate Marketing", icon: "📈", color: "text-purple-600", bg: "bg-purple-50" },
  { key: "digital-skills", label: "Digital Skills", icon: "💻", color: "text-blue-600", bg: "bg-blue-50" },
  { key: "crypto-web3", label: "Crypto & Web3", icon: "₿", color: "text-orange-600", bg: "bg-orange-50" },
  { key: "business", label: "Business", icon: "💼", color: "text-indigo-600", bg: "bg-indigo-50" },
  { key: "social-media", label: "Social Media", icon: "📱", color: "text-pink-600", bg: "bg-pink-50" },
  { key: "music", label: "Music", icon: "🎵", color: "text-pink-600", bg: "bg-pink-50" },
  { key: "tech", label: "Tech & AI", icon: "🤖", color: "text-cyan-600", bg: "bg-cyan-50" },
  { key: "movies", label: "Movies", icon: "🎬", color: "text-red-600", bg: "bg-red-50" },
  { key: "general", label: "General Knowledge", icon: "🌍", color: "text-amber-600", bg: "bg-amber-50" },
]

const QUIZ_CATEGORY_LABELS: Record<string, string> = Object.fromEntries(CATEGORIES.map(c => [c.key, c.label]))

const POINTS_CORRECT = 10
const CONVERT_THRESHOLD = 5000
const NAIRA_PER_CONVERT = 1000
const TIMER_SECONDS = 20
const PLAY_STORE_URL = "https://play.google.com/store/apps/details?id=ng.affil.cweb"

// ─── Sound Utility ─────────────────────────────────────
function playSound(type: "correct" | "wrong" | "complete") {
  try {
    const ctx = new (window.AudioContext || (window as any).webkitAudioContext)()
    const osc = ctx.createOscillator()
    const gain = ctx.createGain()
    osc.connect(gain)
    gain.connect(ctx.destination)
    gain.gain.value = 0.12
    if (type === "correct") {
      osc.type = "sine"
      osc.frequency.setValueAtTime(523, ctx.currentTime)
      osc.frequency.setValueAtTime(659, ctx.currentTime + 0.1)
      osc.frequency.setValueAtTime(784, ctx.currentTime + 0.2)
      gain.gain.exponentialRampToValueAtTime(0.001, ctx.currentTime + 0.5)
      osc.start(ctx.currentTime); osc.stop(ctx.currentTime + 0.5)
    } else if (type === "wrong") {
      osc.type = "square"
      osc.frequency.setValueAtTime(200, ctx.currentTime)
      osc.frequency.setValueAtTime(150, ctx.currentTime + 0.15)
      gain.gain.exponentialRampToValueAtTime(0.001, ctx.currentTime + 0.4)
      osc.start(ctx.currentTime); osc.stop(ctx.currentTime + 0.4)
    } else {
      osc.type = "sine"
      ;[523, 659, 784, 1047].forEach((f, i) => osc.frequency.setValueAtTime(f, ctx.currentTime + i * 0.12))
      gain.gain.exponentialRampToValueAtTime(0.001, ctx.currentTime + 0.6)
      osc.start(ctx.currentTime); osc.stop(ctx.currentTime + 0.6)
    }
  } catch {}
}

// ─── Mobile Detection ──────────────────────────────────
function useIsMobile() {
  const [isMobile, setIsMobile] = useState(true)
  useEffect(() => {
    const check = () => {
      const ua = navigator.userAgent || ""
      const mobile = /Android|iPhone|iPad|iPod|webOS/i.test(ua)
      const narrow = window.innerWidth < 768
      setIsMobile(mobile || narrow)
    }
    check()
    window.addEventListener("resize", check)
    return () => window.removeEventListener("resize", check)
  }, [])
  return isMobile
}

// ─── Component ─────────────────────────────────────────
export default function CashRoomPage() {
  const { toast } = useToast()
  const { formatPrice } = useCurrency()
  const router = useRouter()
  const isMobile = useIsMobile()

  const [quizState, setQuizState] = useState<QuizState>("category-select")
  const [activeCategory, setActiveCategory] = useState<string | null>(null)
  const [questions, setQuestions] = useState<QuizQuestion[]>([])
  const [currentQ, setCurrentQ] = useState(0)
  const [selectedAnswer, setSelectedAnswer] = useState<string | null>(null)
  const [isCorrect, setIsCorrect] = useState<boolean | null>(null)
  const [showExplanation, setShowExplanation] = useState(false)
  const [score, setScore] = useState({ correct: 0, wrong: 0 })
  const [quizPoints, setQuizPoints] = useState(0)
  const [earnedThisSession, setEarnedThisSession] = useState(0)
  const [claimingPoints, setClaimingPoints] = useState(false)
  const [timeLeft, setTimeLeft] = useState(TIMER_SECONDS)
  const [adShowing, setAdShowing] = useState(false)
  const [pendingResultsAd, setPendingResultsAd] = useState(false)
  const [authLoading, setAuthLoading] = useState(true)
  const [isAuthenticated, setIsAuthenticated] = useState(false)
  const [canPlayToday, setCanPlayToday] = useState(true)
  const [nextPlayAt, setNextPlayAt] = useState<string | null>(null)
  const [isWebView, setIsWebView] = useState(false)
  const [timeUntilReset, setTimeUntilReset] = useState('')
  const timerRef = useRef<ReturnType<typeof setInterval> | null>(null)
  const adTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null)
  const countdownRef = useRef<ReturnType<typeof setInterval> | null>(null)

  // Load points, auth status & resume in-progress quiz
  useEffect(() => {
    const init = async () => {
      try {
        const res = await fetch("/api/quiz/status")
        if (res.ok) {
          const data = await res.json()
          setIsAuthenticated(data.authenticated)
          setCanPlayToday(data.canPlay)
          setNextPlayAt(data.nextPlayAt || null)
          // Server is the authoritative source for quiz points (respects admin adjustments)
          const serverPoints = data.quizPoints || 0
          setQuizPoints(serverPoints)
          // Keep localStorage in sync with authoritative server value
          localStorage.setItem("quiz-points", String(serverPoints))
        } else if (res.status === 401) {
          setIsAuthenticated(false)
          setCanPlayToday(false)
        } else {
          setIsAuthenticated(false)
          setCanPlayToday(false)
        }
      } catch {
        setIsAuthenticated(false)
        setCanPlayToday(false)
      } finally {
        setAuthLoading(false)
      }
    }
    init()

    // Detect WebView — ONLY check for the actual Android bridge interface
    // This is the same reliable check used by the Daily Rewards on Account page
    const inWebView = typeof window !== "undefined" && (window as any).Android !== undefined
    setIsWebView(inWebView)

    try {
      const inProgress = localStorage.getItem("quiz-in-progress")
      if (inProgress) {
        const saved = JSON.parse(inProgress)
        if (saved.category && typeof saved.currentQ === "number" && saved.questions?.length > 0) {
          setActiveCategory(saved.category)
          setQuestions(saved.questions)
          setCurrentQ(saved.currentQ)
          setScore(saved.score || { correct: 0, wrong: 0 })
          // Restore answer state so user can't re-answer on remount
          if (saved.selectedAnswer) {
            setSelectedAnswer(saved.selectedAnswer)
            setIsCorrect(saved.isCorrect ?? null)
            setShowExplanation(saved.showExplanation ?? true)
          }
          setQuizState("playing")
        }
      }
    } catch {}
  }, [])

  // Live countdown timer until the user's 24-hour cooldown ends
  useEffect(() => {
    if (!canPlayToday && nextPlayAt) {
      const tick = () => {
        const now = new Date()
        const diff = new Date(nextPlayAt).getTime() - now.getTime()
        if (diff <= 0) {
          setTimeUntilReset('')
          setCanPlayToday(true)
          return
        }
        const h = Math.floor(diff / 3600000)
        const m = Math.floor((diff % 3600000) / 60000)
        const s = Math.floor((diff % 60000) / 1000)
        setTimeUntilReset(`${String(h).padStart(2, '0')}:${String(m).padStart(2, '0')}:${String(s).padStart(2, '0')}`)
      }
      tick()
      countdownRef.current = setInterval(tick, 1000)
      return () => { if (countdownRef.current) clearInterval(countdownRef.current) }
    } else {
      setTimeUntilReset('')
    }
  }, [canPlayToday, nextPlayAt])

  // Start timer when entering playing state after resume
  useEffect(() => {
    if (quizState === "playing" && questions.length > 0 && !timerRef.current) {
      startTimer()
    }
  }, [quizState, questions])

  const addPoints = useCallback((amount: number) => {
    setQuizPoints(p => {
      const n = p + amount
      try { localStorage.setItem("quiz-points", String(n)) } catch {}
      // Fire-and-forget sync to server (survives cache clear)
      fetch("/api/quiz/sync-points", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ points: n }),
      }).catch(() => {})
      return n
    })
    setEarnedThisSession(p => p + amount)
  }, [])

  const savePoints = useCallback((n: number) => {
    setQuizPoints(n)
    try { localStorage.setItem("quiz-points", String(n)) } catch {}
    // Sync to server
    fetch("/api/quiz/sync-points", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ points: n }),
    }).catch(() => {})
  }, [])

  const clearTimer = () => { if (timerRef.current) { clearInterval(timerRef.current); timerRef.current = null } }
  const clearAdTimer = () => { if (adTimerRef.current) { clearTimeout(adTimerRef.current); adTimerRef.current = null } }

  const startTimer = () => {
    clearTimer()
    setTimeLeft(TIMER_SECONDS)
    timerRef.current = setInterval(() => {
      setTimeLeft(prev => { if (prev <= 1) { clearTimer(); return 0 } return prev - 1 })
    }, 1000)
  }

  // Server-side daily limit (set via /api/quiz/status)
  // canPlayToday is now a state variable from the API

  // Auto-submit on timeout
  useEffect(() => {
    if (timeLeft === 0 && quizState === "playing" && !selectedAnswer && questions[currentQ]) {
      const newScore = { correct: score.correct, wrong: score.wrong + 1 }
      setSelectedAnswer("TIMEOUT")
      setIsCorrect(false)
      setShowExplanation(true)
      playSound("wrong")
      // Persist timeout state so network blips don't reset the question
      try { localStorage.setItem("quiz-in-progress", JSON.stringify({ category: activeCategory, currentQ, questions, score: newScore, selectedAnswer: "TIMEOUT", isCorrect: false, showExplanation: true })) } catch {}
    }
  }, [timeLeft])

  useEffect(() => () => { clearTimer(); clearAdTimer() }, [])

  // ─── Start Quiz ──────────────────────────────────────
  const startQuiz = async (catKey: string, resumeFrom?: number) => {
    // Check if there's an in-progress quiz in another category
    const inProgress = (() => { try { return JSON.parse(localStorage.getItem("quiz-in-progress") || "null") } catch { return null } })()
    if (inProgress && inProgress.category && inProgress.category !== catKey) {
      toast({ title: "Complete Current Quiz", description: `Finish your ${QUIZ_CATEGORY_LABELS[inProgress.category] || inProgress.category} quiz first!` })
      return
    }

    if (!canPlayToday && !inProgress) {
      toast({ title: "Cooldown Active", description: "You can play again 24 hours after your last quiz! 🕐" })
      return
    }
    setActiveCategory(catKey)
    setQuizState("loading")
    setScore({ correct: 0, wrong: 0 })
    setCurrentQ(resumeFrom || 0)
    setSelectedAnswer(null); setIsCorrect(null); setShowExplanation(false)
    setEarnedThisSession(0)
    try {
      const res = await fetch("/api/quiz/generate", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ category: catKey, count: 20 }) })
      const data = await res.json()
      if (!res.ok || !data.questions?.length) throw new Error(data.error || "Failed")
      setQuestions(data.questions)
      // Save in-progress state
      try { localStorage.setItem("quiz-in-progress", JSON.stringify({ category: catKey, currentQ: resumeFrom || 0, questions: data.questions, score: { correct: 0, wrong: 0 }, selectedAnswer: null, isCorrect: null, showExplanation: false })) } catch {}
      setQuizState("playing")
      startTimer()
    } catch (e: any) {
      toast({ title: "Error", description: e.message, variant: "destructive" })
      setQuizState("category-select")
      setActiveCategory(null)
    }
  }

  // ─── Answer ──────────────────────────────────────────
  const handleAnswer = (letter: string) => {
    if (selectedAnswer) return
    clearTimer()
    const q = questions[currentQ]
    const correct = letter === q.correctAnswer
    setSelectedAnswer(letter); setIsCorrect(correct); setShowExplanation(true)
    const newScore = correct
      ? { correct: score.correct + 1, wrong: score.wrong }
      : { correct: score.correct, wrong: score.wrong + 1 }
    if (correct) { setScore(newScore); addPoints(POINTS_CORRECT); playSound("correct") }
    else { setScore(newScore); playSound("wrong") }
    // Save in-progress state (including answer so network blips don't reset the question)
    try { localStorage.setItem("quiz-in-progress", JSON.stringify({ category: activeCategory, currentQ, questions, score: newScore, selectedAnswer: letter, isCorrect: correct, showExplanation: true })) } catch {}
  }

  // ─── Next / Ad Break ─────────────────────────────────
  const handleNext = () => {
    const nextQ = currentQ + 1
    if (nextQ % 5 === 0 && nextQ < questions.length) {
      // Only native WebView gets real ads; browser users get STOPPED
      if (isWebView && (window as any).Android?.showInterstitial) {
        setQuizState("ad-break")
        setAdShowing(true)
        triggerAd()
      } else {
        // Browser: NO ad available — STOP quiz, reset points, prompt app download
        clearTimer()
        // Wipe all accrued points (localStorage + server)
        try { localStorage.removeItem("quiz-points") } catch {}
        fetch("/api/quiz/sync-points", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ points: 0 }),
        }).catch(() => {})
        setQuizPoints(0)
        setEarnedThisSession(0)
        try { localStorage.removeItem("quiz-in-progress") } catch {}
        setQuizState("app-required")
      }
      return
    }
    if (nextQ >= questions.length) {
      // Trigger ad before showing results if in native WebView
      if (isWebView && (window as any).Android?.showInterstitial) {
        setPendingResultsAd(true)
        triggerAd()
        setQuizState("ad-break")
        setAdShowing(true)
        return
      }
      finishQuiz()
      return
    }
    setCurrentQ(nextQ); setSelectedAnswer(null); setIsCorrect(null); setShowExplanation(false); startTimer()
    // Save in-progress (cleared answer state for next question)
    try { localStorage.setItem("quiz-in-progress", JSON.stringify({ category: activeCategory, currentQ: nextQ, questions, score, selectedAnswer: null, isCorrect: null, showExplanation: false })) } catch {}
  }

  const triggerAd = () => {
    // Use showInterstitial (NON-REWARDED) — totally separate from account's showRewarded
    // Users earn NOTHING from quiz ads; no notification, no reward, no claim
    (window as any).Android.showInterstitial()
    adTimerRef.current = setTimeout(() => { setAdShowing(false) }, 15000)
  }

  const handleContinueAfterAd = () => {
    clearAdTimer()
    setAdShowing(false)
    // If this ad was triggered by the See Results button, finish the quiz
    if (pendingResultsAd) {
      setPendingResultsAd(false)
      finishQuiz()
      return
    }
    setQuizState("playing")
    const nextQ = currentQ + 1
    setCurrentQ(nextQ); setSelectedAnswer(null); setIsCorrect(null); setShowExplanation(false); startTimer()
    // Save in-progress (cleared answer state)
    try { localStorage.setItem("quiz-in-progress", JSON.stringify({ category: activeCategory, currentQ: nextQ, questions, score, selectedAnswer: null, isCorrect: null, showExplanation: false })) } catch {}
  }

  const finishQuiz = () => {
    try { localStorage.removeItem("quiz-in-progress") } catch {}
    // Record completion server-side (replaces localStorage quiz-last-played)
    fetch("/api/quiz/complete", { method: "POST" }).catch(() => {})
    setCanPlayToday(false)
    playSound("complete")
    setQuizState("results")
    setActiveCategory(null)
    clearTimer()
  }

  // ─── Convert Points ──────────────────────────────────
  const handleConvert = async () => {
    setClaimingPoints(true)
    try {
      const res = await fetch("/api/quiz/claim", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({}) })
      const data = await res.json()
      if (!res.ok) throw new Error(data.error)
      savePoints(data.remainingPoints || 0)
      toast({ title: "💸 Converted!", description: data.message })
    } catch (e: any) { toast({ title: "Failed", description: e.message, variant: "destructive" }) }
    finally { setClaimingPoints(false) }
  }

  // ═══════════════════════════════════════════════════════
  // DESKTOP: Show Play Store download
  // ═══════════════════════════════════════════════════════
  if (!isMobile) {
    return (
      <div className="min-h-screen bg-gradient-to-b from-purple-50 via-white to-amber-50 flex flex-col items-center justify-center px-4 text-center">
        <div className="max-w-md">
          <div className="mx-auto w-24 h-24 bg-gradient-to-br from-purple-400 to-amber-400 rounded-3xl flex items-center justify-center mb-6 shadow-xl">
            <Smartphone className="h-12 w-12 text-white" />
          </div>
          <h1 className="text-2xl font-extrabold text-gray-900 mb-3">Mobile Only 🧠</h1>
          <p className="text-gray-500 mb-2">The Cash Room quiz is available exclusively on the Affiliate+ mobile app.</p>
          <p className="text-xs text-gray-400 mb-8">Earn real cash by answering quiz questions — download the app to get started!</p>
          <a href={PLAY_STORE_URL} target="_blank" rel="noopener noreferrer" className="inline-block">
            <Button className="bg-green-600 hover:bg-green-700 text-white h-14 px-8 rounded-2xl font-bold text-lg shadow-lg shadow-green-200 gap-2">
              <Download className="h-5 w-5" /> Get on Play Store
            </Button>
          </a>
          <p className="text-[11px] text-gray-400 mt-6">Available on Android • Free to play • Earn real money</p>
        </div>
      </div>
    )
  }

  // ═══════════════════════════════════════════════════════
  // APP REQUIRED — Browser user hit ad break, quiz stopped
  // ═══════════════════════════════════════════════════════
  if (quizState === "app-required") {
    return (
      <div className="min-h-screen bg-gradient-to-b from-purple-50 via-white to-amber-50 flex flex-col items-center justify-center px-4 text-center">
        <div className="max-w-md">
          <div className="mx-auto w-24 h-24 bg-gradient-to-br from-purple-400 to-amber-400 rounded-3xl flex items-center justify-center mb-6 shadow-xl">
            <Smartphone className="h-12 w-12 text-white" />
          </div>
          <h1 className="text-2xl font-extrabold text-gray-900 mb-3">App Required 🧠</h1>
          <p className="text-gray-500 mb-2">The Cash Room quiz requires the Affiliate+ mobile app to continue.</p>
          <p className="text-xs text-gray-400 mb-8">Ads support the platform and keep the quiz free. Download the app to play without interruptions!</p>
          <a href={PLAY_STORE_URL} target="_blank" rel="noopener noreferrer" className="inline-block">
            <Button className="bg-green-600 hover:bg-green-700 text-white h-14 px-8 rounded-2xl font-bold text-lg shadow-lg shadow-green-200 gap-2">
              <Download className="h-5 w-5" /> Get on Play Store
            </Button>
          </a>
          <p className="text-[11px] text-gray-400 mt-6">Available on Android • Free to play • Earn real money</p>
        </div>
      </div>
    )
  }

  // ═══════════════════════════════════════════════════════
  // LOADING
  // ═══════════════════════════════════════════════════════
  if (quizState === "loading") {
    return (
      <div className="min-h-screen bg-white flex flex-col items-center justify-center gap-4 px-4">
        <div className="relative">
          <div className="w-20 h-20 rounded-full border-[3px] border-purple-100 border-t-purple-600 animate-spin" />
          <Brain className="absolute inset-0 m-auto h-8 w-8 text-purple-600" />
        </div>
        <p className="text-gray-800 font-bold text-sm text-center animate-pulse">Affiliate+ AI is Generating Your Quiz</p>
        <p className="text-xs text-gray-400">Crafting smart questions just for you...</p>
      </div>
    )
  }

  // ═══════════════════════════════════════════════════════
  // AD BREAK (WebView only — native rewarded ad)
  // ═══════════════════════════════════════════════════════
  if (quizState === "ad-break") {
    // Safety: if we somehow entered ad-break without Android bridge, exit immediately
    if (!isWebView || !(window as any).Android?.showInterstitial) {
      setQuizState("playing")
      const nextQ = currentQ + 1
      setCurrentQ(nextQ); setSelectedAnswer(null); setIsCorrect(null); setShowExplanation(false); startTimer()
      try { localStorage.setItem("quiz-in-progress", JSON.stringify({ category: activeCategory, currentQ: nextQ, questions, score, selectedAnswer: null, isCorrect: null, showExplanation: false })) } catch {}
      return null
    }
    return (
      <div className="min-h-screen bg-gradient-to-b from-indigo-50 to-white flex flex-col items-center justify-center px-4">
        <div className="text-center max-w-sm">
          <div className="text-6xl mb-4 animate-bounce">📺</div>
          <h2 className="text-xl font-bold text-gray-900 mb-2">
            {adShowing ? "Watching Ad..." : "Ad Complete!"}
          </h2>
          <p className="text-gray-500 text-sm mb-6">
            {adShowing ? "Please wait while the ad plays to support the platform..." : "You can now continue the quiz."}
          </p>
          {adShowing ? (
            <div className="flex flex-col items-center gap-3">
              <div className="w-8 h-8 rounded-full border-2 border-indigo-200 border-t-indigo-600 animate-spin" />
              <p className="text-xs text-gray-400">Ad in progress...</p>
            </div>
          ) : (
            <Button onClick={handleContinueAfterAd} className="bg-purple-600 hover:bg-purple-700 text-white h-12 px-8 rounded-xl font-bold">
              Continue Quiz <ChevronRight className="h-5 w-5 ml-1" />
            </Button>
          )}
          <p className="mt-6 text-xs text-gray-400">Question {currentQ + 1} of {questions.length}</p>
        </div>
      </div>
    )
  }

  // ═══════════════════════════════════════════════════════
  // LOADING (auth check in progress)
  // ═══════════════════════════════════════════════════════
  if (authLoading) {
    return (
      <div className="min-h-screen bg-white flex flex-col items-center justify-center gap-4 px-4">
        <div className="w-10 h-10 rounded-full border-[3px] border-purple-100 border-t-purple-600 animate-spin" />
        <p className="text-sm text-gray-400">Loading...</p>
      </div>
    )
  }

  // ═══════════════════════════════════════════════════════
  // NOT AUTHENTICATED — Show login prompt
  // ═══════════════════════════════════════════════════════
  if (!isAuthenticated) {
    return (
      <div className="min-h-screen bg-gradient-to-b from-purple-50 via-white to-amber-50 flex flex-col items-center justify-center px-4 text-center">
        <div className="max-w-md">
          <div className="mx-auto w-20 h-20 bg-gradient-to-br from-purple-400 to-amber-400 rounded-2xl flex items-center justify-center mb-4 shadow-lg">
            <Brain className="h-10 w-10 text-white" />
          </div>
          <h2 className="text-xl font-extrabold text-gray-900 mb-2">Login Required 🧠</h2>
          <p className="text-gray-500 text-sm mb-6">Sign in to your Affiliate+ account to play quizzes and earn cash rewards.</p>
          <Link href={`/login?redirect=/cash-room`}>
            <Button className="bg-purple-600 hover:bg-purple-700 text-white h-12 px-8 rounded-xl font-bold">
              Sign In to Play
            </Button>
          </Link>
          <p className="text-[11px] text-gray-400 mt-4">Don't have an account? <Link href="/register" className="text-purple-600 underline">Register</Link></p>
        </div>
      </div>
    )
  }

  // ═══════════════════════════════════════════════════════
  // CATEGORY SELECT
  // ═══════════════════════════════════════════════════════
  if (quizState === "category-select") {
    const played = !canPlayToday
    // Check for in-progress quiz
    const inProgress = (() => { try { return JSON.parse(localStorage.getItem("quiz-in-progress") || "null") } catch { return null } })()
    const hasInProgress = inProgress && inProgress.category && inProgress.questions?.length > 0
    const inProgressCat = hasInProgress ? CATEGORIES.find(c => c.key === inProgress.category) : null

    return (
      <div className="min-h-screen bg-gradient-to-b from-purple-50 via-white to-amber-50 flex flex-col">
        <div className="bg-white/80 backdrop-blur-md border-b sticky top-0 z-30">
          <div className="max-w-2xl mx-auto px-4 h-14 flex items-center justify-between">
            <div className="flex items-center gap-2">
              <Link href="/"><Button variant="ghost" size="icon" className="h-9 w-9"><ArrowLeft className="h-5 w-5" /></Button></Link>
              <h1 className="font-bold text-gray-900 flex items-center gap-2"><Brain className="h-5 w-5 text-purple-600" />Cash Room</h1>
            </div>
            <div className="flex items-center gap-2 bg-amber-50 rounded-full px-3 py-1.5 border border-amber-200">
              <Coins className="h-4 w-4 text-amber-500" /><span className="text-sm font-bold text-amber-700">{quizPoints} pts</span>
            </div>
          </div>
        </div>
        <div className="flex-1 max-w-2xl mx-auto w-full px-4 py-6 space-y-5 overflow-y-auto">
          <div className="text-center">
            <div className="mx-auto w-16 h-16 bg-gradient-to-br from-purple-400 to-amber-400 rounded-2xl flex items-center justify-center mb-3 shadow-lg">
              <Trophy className="h-8 w-8 text-white" />
            </div>
            <h2 className="text-xl font-extrabold text-gray-900">Answer & Earn</h2>
            <p className="text-gray-500 mt-1 text-xs">Test your knowledge, earn points, convert to cash!</p>
            {played && !hasInProgress && (
              <div className="mt-3 space-y-2">
                <div className="inline-flex items-center gap-2 bg-amber-50 border border-amber-200 rounded-full px-4 py-1.5">
                  <Clock className="h-4 w-4 text-amber-500" /><span className="text-xs font-medium text-amber-700">Come back in 24 hours!</span>
                </div>
                {timeUntilReset && (
                  <div className="text-xs text-gray-500 font-mono">
                    Available in <span className="font-bold text-purple-600">{timeUntilReset}</span>
                  </div>
                )}
              </div>
            )}
          </div>

          {/* In-progress quiz banner */}
          {hasInProgress && inProgressCat && (
            <div className="bg-gradient-to-r from-purple-100 to-purple-50 border-2 border-purple-300 rounded-2xl p-4 text-center">
              <div className="text-3xl mb-2">{inProgressCat.icon}</div>
              <p className="text-sm font-bold text-purple-800 mb-1">Quiz In Progress</p>
              <p className="text-xs text-purple-600 mb-1">{inProgressCat.label} — Q{inProgress.currentQ + 1} of {inProgress.questions.length}</p>
              <p className="text-[10px] text-purple-400 mb-3">Complete this quiz before starting a new one</p>
              <Button onClick={() => startQuiz(inProgress.category, inProgress.currentQ)} className="bg-purple-600 hover:bg-purple-700 text-white h-11 px-6 rounded-xl font-bold text-sm">
                <Play className="h-4 w-4 mr-2" />Continue Quiz
              </Button>
            </div>
          )}

          {!hasInProgress && (
            <>
              <div className="grid grid-cols-3 gap-2 text-center">
                {[{ icon: HelpCircle, label: "20 Questions", color: "text-purple-600", bg: "bg-purple-50" },{ icon: Timer, label: `${TIMER_SECONDS}s Each`, color: "text-blue-600", bg: "bg-blue-50" },{ icon: Coins, label: `${CONVERT_THRESHOLD}pts=₦${NAIRA_PER_CONVERT}`, color: "text-green-600", bg: "bg-green-50" }].map((item, i) => (
                  <div key={i} className={`${item.bg} rounded-xl p-3`}>
                    <item.icon className={`h-5 w-5 mx-auto mb-1 ${item.color}`} />
                    <p className="text-[10px] font-semibold text-gray-700">{item.label}</p>
                  </div>
                ))}
              </div>

              <div>
                <h3 className="font-bold text-gray-900 mb-3 flex items-center gap-2 text-sm"><Sparkles className="h-4 w-4 text-purple-500" />Choose Category</h3>
                <div className="grid grid-cols-2 gap-2.5">
                  {CATEGORIES.map(cat => (
                    <button key={cat.key} onClick={() => startQuiz(cat.key)} disabled={played}
                      className={`${cat.bg} rounded-xl p-3.5 text-left border border-transparent active:scale-[0.98] transition-all ${played ? 'opacity-50 cursor-not-allowed' : 'hover:shadow-md hover:border-purple-200'}`}>
                      <span className="text-xl">{cat.icon}</span>
                      <h4 className={`text-sm font-semibold mt-1.5 ${cat.color}`}>{cat.label}</h4>
                      <p className="text-[10px] text-gray-400 mt-0.5">{played ? 'Played today' : '20 questions'}</p>
                    </button>
                  ))}
                </div>
              </div>
            </>
          )}

          <Button
            onClick={() => {
              if (quizPoints < CONVERT_THRESHOLD) {
                toast({ title: "Keep Going!", description: `You need ${CONVERT_THRESHOLD.toLocaleString()} pts to convert to ₦${NAIRA_PER_CONVERT.toLocaleString()}. You have ${quizPoints.toLocaleString()} pts. Keep playing! 🎯` })
                return
              }
              handleConvert()
            }}
            disabled={claimingPoints}
            className={`w-full h-12 rounded-xl font-bold transition-all ${quizPoints >= CONVERT_THRESHOLD ? 'bg-green-600 hover:bg-green-700 text-white' : 'bg-gray-200 text-gray-400 cursor-not-allowed'}`}>
            {claimingPoints ? <Loader2 className="h-5 w-5 animate-spin mr-2" /> : <Wallet className="h-5 w-5 mr-2" />}
            {quizPoints >= CONVERT_THRESHOLD
              ? `Convert ${quizPoints.toLocaleString()} pts → ${formatPrice(Math.floor(quizPoints / CONVERT_THRESHOLD) * NAIRA_PER_CONVERT)}`
              : `${quizPoints.toLocaleString()} / ${CONVERT_THRESHOLD.toLocaleString()} pts to Convert`}
          </Button>
        </div>
      </div>
    )
  }

  // ═══════════════════════════════════════════════════════
  // PLAYING — compact, no-scroll layout
  // ═══════════════════════════════════════════════════════
  if (quizState === "playing" && questions.length > 0) {
    const q = questions[currentQ]
    const progress = (currentQ / questions.length) * 100
    return (
      <div className="h-dvh bg-white flex flex-col overflow-hidden fixed inset-0">
        {/* Sticky header */}
        <div className="bg-white border-b shrink-0 z-20">
          <div className="px-2 h-12 flex items-center justify-between gap-1">
            <div className="flex items-center gap-1">
              <Button variant="ghost" size="icon" className="h-9 w-9 rounded-lg" onClick={() => router.back()}>
                <ArrowLeft className="h-5 w-5 text-gray-600" />
              </Button>
              <Brain className="h-4 w-4 text-purple-600" />
              <span className="text-sm font-bold text-gray-700">Q{currentQ + 1}/{questions.length}</span>
            </div>
            <div className="flex items-center gap-2">
              <div className="flex items-center gap-1 bg-amber-50 rounded-full px-2.5 py-0.5 border border-amber-200">
                <Coins className="h-3 w-3 text-amber-500" /><span className="text-xs font-bold text-amber-700">{quizPoints}</span>
              </div>
              <div className={`flex items-center gap-1 rounded-full px-2 py-0.5 text-[11px] font-bold ${timeLeft <= 3 ? 'bg-red-50 text-red-600 animate-pulse' : 'bg-gray-100 text-gray-600'}`}>
                <Timer className="h-3 w-3" /><span>{timeLeft}s</span>
              </div>
              <span className="text-[11px] text-gray-400">✓{score.correct} ✗{score.wrong}</span>
            </div>
          </div>
          <div className="h-1 bg-gray-100"><div className="h-full bg-gradient-to-r from-purple-500 to-amber-500 transition-all duration-500" style={{ width: `${progress}%` }} /></div>
        </div>

        {/* Content — flex layout, no scroll needed */}
        <div className="flex-1 flex flex-col px-4 py-3 overflow-y-auto" style={{ minHeight: 0 }}>
          {/* Question */}
          <div className="shrink-0 mb-3">
            <div className="flex items-center gap-2 mb-2">
              <span className="text-[10px] font-bold text-purple-600 bg-purple-50 px-2 py-0.5 rounded-full">Q{currentQ + 1}</span>
              {isCorrect !== null && (
                <span className={`text-[10px] font-bold px-2 py-0.5 rounded-full ${isCorrect ? "bg-green-50 text-green-600" : "bg-red-50 text-red-600"}`}>
                  {isCorrect ? `+${POINTS_CORRECT} pts` : `0 pts`}
                </span>
              )}
            </div>
            <h2 className="text-base font-bold text-gray-900 leading-snug">{q.question}</h2>
          </div>

          {/* Options — 2x2 grid blocks */}
          <div className="flex-1 grid grid-cols-2 gap-2 content-center mb-2">
            {q.options.map((opt, idx) => {
              const letter = String.fromCharCode(65 + idx)
              const isSel = selectedAnswer === letter
              const isRight = letter === q.correctAnswer
              let cls = "border-gray-200 active:bg-purple-50 active:border-purple-300"
              if (showExplanation) {
                if (isRight) cls = "border-green-400 bg-green-50"
                else if (isSel && !isRight) cls = "border-red-400 bg-red-50"
                else cls = "border-gray-100 opacity-40"
              }
              return (
                <button key={idx} onClick={() => handleAnswer(letter)} disabled={showExplanation}
                  className={`flex flex-col items-center justify-center gap-1.5 p-3 rounded-xl border-2 transition-all text-center ${cls}`}>
                  <span className={`shrink-0 w-8 h-8 rounded-full flex items-center justify-center text-sm font-bold ${isSel && !isRight && showExplanation ? "bg-red-500 text-white" : isRight && showExplanation ? "bg-green-500 text-white" : "bg-gray-100 text-gray-600"}`}>
                    {showExplanation && isRight ? <CheckCircle2 className="h-4 w-4" /> : showExplanation && isSel && !isRight ? <XCircle className="h-4 w-4" /> : letter}
                  </span>
                  <span className="text-xs text-gray-800 leading-tight line-clamp-3">{opt.replace(/^[A-D]\)\s*/, "")}</span>
                </button>
              )
            })}
          </div>

          {/* Explanation + Next */}
          {showExplanation && (
            <div className="shrink-0 space-y-2 animate-in fade-in slide-in-from-bottom-2 duration-200">
              <div className={`p-3 rounded-xl text-xs ${isCorrect ? "bg-green-50 border border-green-200" : "bg-red-50 border border-red-200"}`}>
                <p className="font-semibold mb-0.5">{isCorrect ? "✅ Correct!" : "❌ Wrong!"}</p>
                <p className="text-gray-600">{q.explanation}</p>
              </div>
              <Button onClick={handleNext} className="w-full bg-purple-600 hover:bg-purple-700 text-white h-11 rounded-xl font-bold text-sm">
                {currentQ + 1 >= questions.length ? "See Results 🎉" : "Next Question"} <ChevronRight className="h-4 w-4 ml-1" />
              </Button>
            </div>
          )}
        </div>
      </div>
    )
  }

  // ═══════════════════════════════════════════════════════
  // RESULTS
  // ═══════════════════════════════════════════════════════
  if (quizState === "results") {
    const pct = Math.round((score.correct / questions.length) * 100)
    return (
      <div className="min-h-screen bg-gradient-to-b from-purple-50 via-white to-amber-50 flex flex-col items-center justify-center px-4">
        <div className={`w-20 h-20 rounded-full flex items-center justify-center mb-4 ${pct >= 80 ? "bg-gradient-to-br from-amber-300 to-yellow-500" : pct >= 50 ? "bg-gradient-to-br from-purple-300 to-purple-500" : "bg-gradient-to-br from-gray-300 to-gray-500"}`}>
          <Trophy className="h-10 w-10 text-white" />
        </div>
        <h2 className="text-xl font-extrabold text-gray-900 mb-1">Quiz Complete!</h2>
        <p className="text-gray-500 text-xs mb-5">{pct >= 80 ? "Outstanding! 🌟" : pct >= 50 ? "Good job! 👍" : "Keep practicing! 💪"}</p>
        <div className="grid grid-cols-3 gap-3 w-full max-w-xs mb-5">
          {[{ icon: CheckCircle2, color: "text-green-500", val: score.correct, label: "Correct" },{ icon: XCircle, color: "text-red-400", val: score.wrong, label: "Wrong" },{ icon: BarChart3, color: "text-purple-500", val: `${pct}%`, label: "Score" }].map((s, i) => (
            <Card key={i}><CardContent className="p-3 text-center">
              <s.icon className={`h-5 w-5 ${s.color} mx-auto mb-1`} /><p className="text-lg font-bold text-gray-900">{s.val}</p><p className="text-[10px] text-gray-500">{s.label}</p>
            </CardContent></Card>
          ))}
        </div>
        <Card className="w-full max-w-xs bg-gradient-to-r from-amber-50 to-yellow-50 border-amber-200 mb-5">
          <CardContent className="p-3 text-center">
            <p className="text-[10px] text-amber-600 font-medium">Earned This Session</p>
            <div className="flex items-center justify-center gap-1.5"><Coins className="h-5 w-5 text-amber-500" /><span className="text-xl font-extrabold text-amber-700">+{earnedThisSession}</span></div>
            <p className="text-[10px] text-amber-600">points</p>
          </CardContent>
        </Card>
        <div className="w-full max-w-xs space-y-2.5">
          <Button disabled className="w-full bg-gray-300 text-gray-500 h-11 rounded-xl font-bold cursor-not-allowed"><Clock className="h-4 w-4 mr-2" />Come Back In 24hrs</Button>
          <Button
            onClick={() => {
              if (quizPoints < CONVERT_THRESHOLD) {
                toast({ title: "Keep Going!", description: `You need ${CONVERT_THRESHOLD.toLocaleString()} pts to convert to ₦${NAIRA_PER_CONVERT.toLocaleString()}. You have ${quizPoints.toLocaleString()} pts. Keep playing! 🎯` })
                return
              }
              handleConvert()
            }}
            disabled={claimingPoints}
            variant={quizPoints >= CONVERT_THRESHOLD ? "outline" : "ghost"}
            className={`w-full h-11 rounded-xl font-bold transition-all ${quizPoints >= CONVERT_THRESHOLD ? 'border-green-500 text-green-600 hover:bg-green-50' : 'border-gray-200 text-gray-400'}`}>
            {claimingPoints ? <Loader2 className="h-4 w-4 animate-spin mr-2" /> : <Wallet className="h-4 w-4 mr-2" />}
            {quizPoints >= CONVERT_THRESHOLD
              ? `Convert ${quizPoints.toLocaleString()} pts → ${formatPrice(Math.floor(quizPoints / CONVERT_THRESHOLD) * NAIRA_PER_CONVERT)}`
              : `${quizPoints.toLocaleString()} / ${CONVERT_THRESHOLD.toLocaleString()} pts to Convert`}
          </Button>
        </div>
      </div>
    )
  }

  return null
}