
'use client';
import { useState, useEffect, useRef } from 'react';
import PageHeader from '@/components/page-header';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card';
import { ArrowRight, RefreshCw, Play, FileDown, X, Copy, ClipboardPaste, Joystick, Plus, LogIn, ArrowLeft, Heart, User, Users2 } from 'lucide-react';
import { Progress } from '@/components/ui/progress';
import { quienEsQuienQuestions } from '@/lib/data';
import { cn } from '@/lib/utils';
import html2canvas from 'html2canvas';
import { Input } from '@/components/ui/input';
import { toast } from '@/hooks/use-toast';
import CompactPageHeader from '@/components/compact-page-header';

type VoteOption = 'user1' | 'user2' | 'both' | 'none';

const VOTE_MAP: Record<VoteOption, string> = {
  user1: 'Adrián',
  user2: 'Anna',
  both: 'Ambos',
  none: 'Ninguno',
};

const VOTE_STYLES: Record<VoteOption, string> = {
  user1: 'bg-blue-100 text-blue-700 border-blue-200',
  user2: 'bg-pink-100 text-pink-700 border-pink-200',
  both: 'bg-purple-100 text-purple-700 border-purple-200',
  none: 'bg-gray-100 text-gray-700 border-gray-200',
};

const VOTE_ICONS: Record<VoteOption, React.ReactNode> = {
  user1: <User className="w-3 h-3 mr-1" />,
  user2: <User className="w-3 h-3 mr-1" />,
  both: <Users2 className="w-3 h-3 mr-1" />,
  none: <X className="w-3 h-3 mr-1" />,
};

const deterministicShuffle = (arr: string[], seed: string) => {
  const numSeed = seed.split('').reduce((acc, char) => acc + char.charCodeAt(0), 0);
  let m = arr.length, t, i;
  const newArr = [...arr];
  const random = (s: number) => () => {
    s = Math.sin(s) * 10000;
    return s - Math.floor(s);
  };
  const seededRandom = random(numSeed);

  while (m) {
    i = Math.floor(seededRandom() * m--);
    t = newArr[m];
    newArr[m] = newArr[i];
    newArr[i] = t;
  }
  return newArr;
};

const pickQuestions = (seed: string, count: number) => {
  const shuffled = deterministicShuffle(quienEsQuienQuestions, seed);
  return shuffled.slice(0, count);
};


const ResultsSummary = ({
  questions,
  votes,
  innerRef,
}: {
  questions: string[];
  votes: (VoteOption | null)[];
  innerRef: React.RefObject<HTMLDivElement>;
}) => {
  return (
    <div
      ref={innerRef}
      className="absolute left-[-9999px] top-[-9999px] w-[800px] p-10 font-sans bg-gradient-to-br from-pink-50 to-blue-50"
    >
        <div className="text-center mb-10">
            <div className="inline-flex items-center justify-center p-3 bg-white rounded-full shadow-sm mb-4">
                <Heart className="w-8 h-8 text-pink-500 fill-pink-500" />
            </div>
            <h2 className="text-4xl font-bold text-gray-800 tracking-tight">Anna & Adrián</h2>
            <p className="text-xl text-gray-500 font-medium">Nuestros Resultados: ¿Quién es Quién?</p>
        </div>
        
        <div className="grid grid-cols-2 gap-6">
            {questions.map((question, index) => (
                <div key={index} className="bg-white p-6 rounded-2xl shadow-md border border-gray-100 flex flex-col justify-between">
                    <p className="text-gray-800 font-semibold text-lg mb-4 leading-tight">{question}</p>
                    <div className={cn(
                        "inline-flex items-center px-4 py-2 rounded-full text-sm font-bold border self-start",
                        votes[index] ? VOTE_STYLES[votes[index]!] : 'bg-gray-100 border-gray-200'
                    )}>
                        {votes[index] && VOTE_ICONS[votes[index]!]}
                        {votes[index] ? VOTE_MAP[votes[index]!] : 'Sin respuesta'}
                    </div>
                </div>
            ))}
        </div>
        
        <div className="mt-12 text-center text-gray-400 font-medium italic">
            "Porque el amor también es conocerse jugando."
        </div>
    </div>
  );
};


const ResultsScreen = ({
  questions,
  votes,
  onPlayAgain,
}: {
  questions: string[];
  votes: (VoteOption | null)[];
  onPlayAgain: () => void;
}) => {
    const summaryRef = useRef<HTMLDivElement>(null);

    const handleDownload = async () => {
        if (!summaryRef.current) return;
        toast({ title: "Generando imagen...", description: "Espera un momento." });
        try {
            const canvas = await html2canvas(summaryRef.current, {
                scale: 3,
                useCORS: true,
                backgroundColor: null,
            });
            const image = canvas.toDataURL('image/jpeg', 0.95);
            const link = document.createElement('a');
            link.href = image;
            link.download = 'nuestro-quien-es-quien.jpg';
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
            toast({ title: "¡Listo!", description: "La imagen se ha descargado correctamente." });
        } catch (error) {
            console.error('Error generating image:', error);
            toast({ variant: "destructive", title: "Error", description: "No se pudo generar la imagen." });
        }
    };


  return (
    <>
    <ResultsSummary questions={questions} votes={votes} innerRef={summaryRef} />
    <div className="bg-background min-h-screen text-foreground flex flex-col">
      <PageHeader
        title="¡Partida Terminada!"
        description="Aquí tenéis vuestras respuestas de hoy."
      />
      <main className="container mx-auto px-4 py-8 flex-grow">
        <div className="max-w-4xl mx-auto space-y-8 animate-in fade-in slide-in-from-bottom-4 duration-700">
          
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
             {questions.map((question, index) => (
                <Card key={index} className="shadow-lg border-none bg-card/60 backdrop-blur-md overflow-hidden animate-in fade-in zoom-in-95" style={{ animationDelay: `${index * 100}ms` }}>
                    <div className={cn(
                        "h-1.5 w-full",
                        votes[index] === 'user1' ? 'bg-blue-400' : 
                        votes[index] === 'user2' ? 'bg-pink-400' : 
                        votes[index] === 'both' ? 'bg-purple-400' : 'bg-gray-300'
                    )}></div>
                    <CardHeader className="p-5 pb-2">
                        <CardTitle className="font-headline text-lg leading-snug">{question}</CardTitle>
                    </CardHeader>
                    <CardContent className="p-5 pt-0">
                        <div className={cn(
                            "inline-flex items-center px-3 py-1.5 rounded-full text-xs font-bold border mt-2",
                            votes[index] ? VOTE_STYLES[votes[index]!] : 'bg-gray-100 border-gray-200'
                        )}>
                            {votes[index] && VOTE_ICONS[votes[index]!]}
                            {votes[index] ? VOTE_MAP[votes[index]!] : 'Sin respuesta'}
                        </div>
                    </CardContent>
                </Card>
            ))}
          </div>

          <div className="flex flex-col md:flex-row gap-4 pt-4">
             <Button
              onClick={handleDownload}
              size="lg"
              className="font-headline text-lg w-full h-14 shadow-xl hover:scale-[1.02] transition-transform"
            >
              Descargar Recuerdo <FileDown className="ml-2 h-6 w-6" />
            </Button>
            <Button
              onClick={onPlayAgain}
              size="lg"
              variant="outline"
              className="font-headline text-lg w-full h-14 border-2"
            >
              Jugar de Nuevo <RefreshCw className="ml-2 h-5 w-5" />
            </Button>
          </div>
        </div>
      </main>
      <footer className="text-center p-6 text-muted-foreground font-body">
        <p>¡Que gane el mejor (o el más honesto)!</p>
      </footer>
    </div>
    </>
  );
};

const GAME_DURATION = 120; // 2 minutes

export default function QuienEsQuienPage() {
  const [gameMode, setGameMode] = useState<'welcome' | 'create' | 'join' | 'playing' | 'results'>('welcome');
  const [gameCode, setGameCode] = useState('');
  const [inputCode, setInputCode] = useState('');
  const [gameQuestions, setGameQuestions] = useState<string[]>([]);
  const [currentQuestionIndex, setCurrentQuestionIndex] = useState(0);
  const [votes, setVotes] = useState<(VoteOption | null)[]>([]);
  const [timeLeft, setTimeLeft] = useState(GAME_DURATION);
  
  const timerRef = useRef<NodeJS.Timeout | null>(null);

  const isGameFinished = gameMode === 'results';
  const gameStarted = gameMode === 'playing';

  useEffect(() => {
    if (gameStarted && !isGameFinished) {
      timerRef.current = setInterval(() => {
        setTimeLeft(prevTime => {
          if (prevTime <= 1) {
            clearInterval(timerRef.current!);
            setGameMode('results');
            return 0;
          }
          return prevTime - 1;
        });
      }, 1000);
    } else if (isGameFinished && timerRef.current) {
      clearInterval(timerRef.current);
    }
    
    return () => {
      if (timerRef.current) {
        clearInterval(timerRef.current);
      }
    };
  }, [gameStarted, isGameFinished]);

  const resetGame = () => {
    setGameMode('welcome');
    setGameCode('');
    setInputCode('');
    setGameQuestions([]);
    setVotes([]);
    setCurrentQuestionIndex(0);
    setTimeLeft(GAME_DURATION);
    if (timerRef.current) clearInterval(timerRef.current);
  };

  const handleCreateGame = () => {
    const code = Math.random().toString(36).substring(2, 8).toUpperCase();
    setGameCode(code);
    setGameMode('create');
  };

  const handleJoinGame = () => {
    if (inputCode.trim().length === 6) {
      const questions = pickQuestions(inputCode.trim().toLowerCase(), 6);
      setGameQuestions(questions);
      setVotes(Array(6).fill(null));
      setCurrentQuestionIndex(0);
      setTimeLeft(GAME_DURATION);
      setGameMode('playing');
    } else {
      toast({
        variant: "destructive",
        title: "Código inválido",
        description: "El código debe tener 6 caracteres.",
      });
    }
  };

  const handleStartCreatedGame = () => {
    const questions = pickQuestions(gameCode.toLowerCase(), 6);
    setGameQuestions(questions);
    setVotes(Array(6).fill(null));
    setCurrentQuestionIndex(0);
    setTimeLeft(GAME_DURATION);
    setGameMode('playing');
  };

  const handleVote = (user: VoteOption) => {
    const newVotes = [...votes];
    newVotes[currentQuestionIndex] = user;
    setVotes(newVotes);
  };

  const handleNextQuestion = () => {
    if (currentQuestionIndex < gameQuestions.length - 1) {
      setCurrentQuestionIndex(prev => prev + 1);
    } else {
      setGameMode('results');
    }
  };

  const handlePreviousQuestion = () => {
    if (currentQuestionIndex > 0) {
      setCurrentQuestionIndex(prev => prev - 1);
    }
  };

  const handleCopyToClipboard = () => {
    navigator.clipboard.writeText(gameCode);
    toast({
        title: "¡Copiado!",
        description: "Código de la partida copiado al portapapeles.",
    });
  };

  const handlePasteFromClipboard = async () => {
    try {
        const text = await navigator.clipboard.readText();
        setInputCode(text.trim().substring(0, 6).toUpperCase());
        toast({
            title: "¡Pegado!",
            description: "Código pegado desde el portapapeles.",
        });
    } catch (err) {
        console.error('Failed to read clipboard contents: ', err);
        toast({
            variant: "destructive",
            title: "Error",
            description: "No se pudo pegar el código.",
        });
    }
  };

  const currentQuestion = gameQuestions[currentQuestionIndex];
  const currentVote = votes[currentQuestionIndex];
  
  if (gameMode === 'welcome') {
    return (
      <div className="bg-background min-h-screen text-foreground flex flex-col">
        <CompactPageHeader title="¿Quién es Quién?" description="¿Listos para un nuevo desafío?" backButtonHref="/juegos" />
        <main className="container mx-auto px-4 pb-8 flex justify-center pt-8">
            <Card className="shadow-2xl border-0 bg-card/80 backdrop-blur-sm animate-in fade-in zoom-in-95 duration-500 w-full max-w-md text-center">
                <CardHeader className="p-4 pb-2">
                <div className="flex justify-center mb-4"><Joystick className="w-12 h-12 text-primary" /></div>
                <CardTitle className="font-headline text-2xl md:text-3xl text-card-foreground leading-tight">Jugar a ¿Quién es Quién?</CardTitle>
                <CardDescription className="pt-2 font-body text-foreground/70">
                    Uno de los dos crea una partida para obtener un código. El otro, usa ese código para unirse y jugar juntos con las mismas preguntas.
                </CardDescription>
                </CardHeader>
                <CardContent className="space-y-4 pt-4 px-6 pb-6">
                <Button onClick={handleCreateGame} size="lg" className="w-full font-body text-lg"><Plus className="mr-2" /> Crear Partida</Button>
                <Button onClick={() => setGameMode('join')} size="lg" variant="outline" className="w-full font-body text-lg"><LogIn className="mr-2" /> Unirse a Partida</Button>
                </CardContent>
            </Card>
        </main>
      </div>
    );
  }

  if (gameMode === 'create') {
    return (
      <div className="bg-background min-h-screen text-foreground flex flex-col">
        <CompactPageHeader title="Crear Partida" description="Comparte este código con tu pareja" backButtonHref="/juegos" />
        <main className="container mx-auto px-4 pb-8 flex justify-center pt-8">
          <Card className="shadow-2xl border-0 bg-card/80 backdrop-blur-sm animate-in fade-in zoom-in-95 duration-500 w-full max-w-md text-center">
            <CardHeader>
              <CardTitle className="font-headline text-xl text-card-foreground">Código de la Partida</CardTitle>
            </CardHeader>
            <CardContent className="space-y-6">
              <div className="bg-muted p-4 rounded-lg relative">
                <p className="font-mono text-2xl font-bold tracking-widest text-primary text-center py-2">{gameCode}</p>
                <Button onClick={handleCopyToClipboard} size="icon" variant="ghost" className="absolute top-1/2 right-2 -translate-y-1/2"><Copy /></Button>
              </div>
              <p className="text-muted-foreground font-body text-sm">Cuando ambos estéis listos, pulsa "Empezar a Jugar".</p>
              <Button onClick={handleStartCreatedGame} size="lg" className="w-full font-body text-lg"><Play className="mr-2 h-5 w-5" /> Empezar a Jugar</Button>
               <Button onClick={() => setGameMode('welcome')} variant="link">Volver</Button>
            </CardContent>
          </Card>
        </main>
      </div>
    );
  }

  if (gameMode === 'join') {
     return (
      <div className="bg-background min-h-screen text-foreground flex flex-col">
        <CompactPageHeader title="Unirse a Partida" description="Introduce el código que te ha dado tu pareja" backButtonHref="/juegos" />
        <main className="container mx-auto px-4 pb-8 flex justify-center pt-8">
          <Card className="shadow-2xl border-0 bg-card/80 backdrop-blur-sm animate-in fade-in zoom-in-95 duration-500 w-full max-w-md text-center">
            <CardHeader>
              <CardTitle className="font-headline text-xl text-card-foreground">Introduce el Código</CardTitle>
            </CardHeader>
            <CardContent className="space-y-4">
                <div className="bg-muted p-4 rounded-lg relative">
                    <Input 
                        value={inputCode}
                        onChange={(e) => setInputCode(e.target.value.toUpperCase())}
                        maxLength={6}
                        placeholder="Código"
                        className="font-mono text-xl text-center tracking-widest font-bold text-primary bg-transparent border-0 focus-visible:ring-0 focus-visible:ring-offset-0 py-2"
                    />
                    <Button onClick={handlePasteFromClipboard} size="icon" variant="ghost" className="absolute top-1/2 right-2 -translate-y-1/2"><ClipboardPaste /></Button>
                </div>
                <Button onClick={handleJoinGame} size="lg" className="w-full font-body text-lg"><Play className="mr-2 h-5 w-5" /> Unirse y Jugar</Button>
                <Button onClick={() => setGameMode('welcome')} variant="link">Volver</Button>
            </CardContent>
          </Card>
        </main>
      </div>
    );
  }


  if (isGameFinished) {
    return <ResultsScreen questions={gameQuestions} votes={votes} onPlayAgain={resetGame} />;
  }
  
  const progressValue = (timeLeft / GAME_DURATION) * 100;

  return (
    <div className="bg-background min-h-screen text-foreground flex flex-col overflow-hidden h-screen">
      <div className="flex-none">
        <PageHeader
            title="¿Quién es Quién?"
            description="Descubran quién es el más... ¡A votar!"
        />
      </div>
      <main className="flex-grow flex items-center justify-center px-4 overflow-hidden">
        <div className="w-full max-w-2xl text-center">
          {gameQuestions.length > 0 && (
            <Card className="shadow-2xl border-0 bg-card/80 backdrop-blur-sm animate-in fade-in zoom-in-95 duration-500 overflow-hidden">
              <Progress value={progressValue} className="w-full h-2 rounded-none" />
              <CardHeader className="pt-6">
                 <div className="flex justify-between items-center">
                    <div className="font-body text-muted-foreground mb-2">
                        {currentQuestionIndex + 1} / {gameQuestions.length}
                    </div>
                     <Button onClick={resetGame} variant="ghost" size="sm" className="text-muted-foreground"><X className="mr-1 h-4 w-4" /> Salir</Button>
                </div>
                <CardTitle className="font-headline text-2xl md:text-3xl text-card-foreground leading-tight">
                  {currentQuestion}
                </CardTitle>
              </CardHeader>
              <CardContent>
                <div className="grid grid-cols-2 gap-3 mt-6">
                   <Button
                    onClick={() => handleVote('user2')}
                    size="lg"
                    variant={'outline'}
                    className={cn(
                        "font-body text-base h-20 md:h-16 transition-all duration-200 hover:bg-pink-50 px-2 border-2",
                        currentVote === 'user2' && "bg-pink-100 border-pink-400 text-pink-700 hover:bg-pink-200"
                    )}
                  >
                    Anna
                  </Button>
                  <Button
                    onClick={() => handleVote('user1')}
                    size="lg"
                    variant={'outline'}
                    className={cn(
                        "font-body text-base h-20 md:h-16 transition-all duration-200 hover:bg-blue-50 px-2 border-2",
                        currentVote === 'user1' && "bg-blue-100 border-blue-400 text-blue-700 hover:bg-blue-200"
                    )}
                  >
                    Adrián
                  </Button>
                  <Button
                    onClick={() => handleVote('both')}
                    size="lg"
                    variant={'outline'}
                    className={cn(
                        "font-body text-base h-20 md:h-16 transition-all duration-200 hover:bg-purple-50 px-2 border-2",
                        currentVote === 'both' && "bg-purple-100 border-purple-400 text-purple-700 hover:bg-purple-200"
                    )}
                  >
                    Ambos
                  </Button>
                  <Button
                    onClick={() => handleVote('none')}
                    size="lg"
                    variant={'outline'}
                    className={cn(
                        "font-body text-base h-20 md:h-16 transition-all duration-200 hover:bg-gray-100 px-2 border-2",
                        currentVote === 'none' && "bg-gray-200 border-gray-400 text-gray-700 hover:bg-gray-300"
                    )}
                  >
                    Ninguno
                  </Button>
                </div>

                <div className="mt-8 flex justify-between items-center gap-4">
                  {currentQuestionIndex > 0 ? (
                    <>
                      <Button
                        onClick={handlePreviousQuestion}
                        size="lg"
                        variant="outline"
                        className="w-1/2"
                        aria-label="Anterior"
                      >
                        <ArrowLeft className="mr-2 h-5 w-5" />
                        Anterior
                      </Button>
                      <Button
                        onClick={handleNextQuestion}
                        size="lg"
                        disabled={!currentVote}
                        className="w-1/2"
                        aria-label={currentQuestionIndex < gameQuestions.length - 1 ? 'Siguiente' : 'Finalizar Juego'}
                      >
                         {currentQuestionIndex < gameQuestions.length - 1 ? 'Siguiente' : 'Finalizar'}
                        <ArrowRight className="ml-2 h-5 w-5" />
                      </Button>
                    </>
                  ) : (
                     <Button
                      onClick={handleNextQuestion}
                      size="lg"
                      className="w-full"
                      disabled={!currentVote}
                      aria-label="Siguiente"
                    >
                      Siguiente
                      <ArrowRight className="ml-2 h-5 w-5" />
                    </Button>
                  )}
                </div>
              </CardContent>
            </Card>
          )}
        </div>
      </main>
      <footer className="flex-none text-center p-6 text-muted-foreground font-body">
        <p>¡Que gane el mejor (o el más honesto)!</p>
      </footer>
    </div>
  );
}
