/* eslint-disable @next/next/no-img-element */
'use client';
import { useEffect, useState } from 'react';

import { animate, motion } from 'framer-motion';
import { Home, Play, RotateCcw } from 'lucide-react';

import { Button } from '@/components/ui/button';
import { Text } from '@/components/ui/typography';
import { buildMediaUrl } from '@/utils/images';

import { Link } from '@/i18n/navigation';

import { GameBackdrop, GameSpinner } from './GameStage';

const formatNumber = (value: number) => value.toLocaleString('hu-HU');
/** Counts up to the value, so a new score lands with a little drama. */
export function CountUp({ value, className }: { value: number; className?: string }) {
  const [shown, setShown] = useState(0);
  useEffect(() => {
    const controls = animate(0, value, {
      duration: 1.1,
      ease: 'easeOut',
      onUpdate: (latest) => setShown(Math.round(latest)),
    });
    return () => controls.stop();
  }, [value]);
  return <span className={className}>{formatNumber(shown)}</span>;
}

export default function GameMenu({
  phase,
  title,
  description,
  totalScore,
  bestScore,
  message,
  results,
  startGame,
  backToIntro,
}: {
  phase: 'intro' | 'finished';
  title: string;
  description: string;
  totalScore: number;
  bestScore: number | null;
  message: string;
  results: {
    item: { id: string; title: string; imageId: number };
    score: number;
    detail: string;
  }[];
  startGame: () => void;
  backToIntro: () => void;
}) {
  // The server sends the menu ready to read; the start button waits until it can start the game.
  const [ready, setReady] = useState(false);
  useEffect(() => setReady(true), []);
  return (
    <>
      <GameBackdrop />

      {phase === 'intro' ? (
        <motion.div
          key="intro"
          initial={{ opacity: 0, y: 16 }}
          animate={{ opacity: 1, y: 0 }}
          className="relative flex max-w-xl flex-col items-center px-6 py-16 text-center"
        >
          <h1 className="font-slab text-5xl font-bold leading-none tracking-tight sm:text-7xl">
            {title}
          </h1>
          <Text variant="lead" className="mt-5 text-white/75">
            {description}
          </Text>
          {ready ? (
            <Button inverted size="lg" className="mt-8" onClick={startGame}>
              <Play /> Játék indítása
            </Button>
          ) : (
            <div className="mt-8">
              <GameSpinner label="A játék betöltése…" />
            </div>
          )}
          <Text variant="meta" className="mt-6 text-white/50">
            {5} kör · körönként {formatNumber(5000)} pont
            {bestScore !== null ? ` · Legjobb: ${formatNumber(bestScore)}` : ''}
          </Text>
        </motion.div>
      ) : (
        <motion.div
          key="finished"
          initial={{ opacity: 0, y: 16 }}
          animate={{ opacity: 1, y: 0 }}
          className="relative flex w-full max-w-3xl flex-col items-center px-6 py-12 text-center"
        >
          <Text variant="meta" className="text-white/50">
            Végeredmény
          </Text>
          <div className="mt-3 font-slab text-6xl font-bold leading-none sm:text-8xl">
            <CountUp value={totalScore} />
          </div>
          <Text variant="meta" className="mt-3 text-white/50">
            / {formatNumber(25000)} pont
            {bestScore !== null ? ` · Legjobb: ${formatNumber(bestScore)}` : ''}
          </Text>
          <Text variant="lead" className="mt-5 text-white/80">
            {message}
          </Text>

          <ol className="mt-10 grid w-full grid-cols-5 gap-2 sm:gap-3">
            {results.map((round, index) => (
              <motion.li
                key={round.item.id}
                initial={{ opacity: 0, y: 12 }}
                animate={{ opacity: 1, y: 0 }}
                transition={{ delay: 0.4 + index * 0.08 }}
                className="min-w-0"
              >
                <Link
                  href={{ pathname: '/alkotas/[id]', params: { id: round.item.id } }}
                  target="_blank"
                  rel="noopener noreferrer"
                  className="group block text-left"
                  title={round.item.title}
                >
                  <span className="block aspect-square overflow-hidden bg-white/5">
                    <img
                      src={buildMediaUrl(round.item.imageId, 'w256')}
                      alt={round.item.title}
                      className="h-full w-full object-cover transition-transform duration-300 group-hover:scale-105"
                    />
                  </span>
                  <span className="mt-2 block font-slab text-lg font-bold leading-none">
                    {formatNumber(round.score)}
                  </span>
                  <span className="mt-1 block truncate text-[11px] text-white/55">
                    {round.detail}
                  </span>
                </Link>
              </motion.li>
            ))}
          </ol>

          <div className="mt-10 flex flex-wrap justify-center gap-3">
            <Button inverted size="lg" onClick={startGame}>
              <RotateCcw /> Új játék
            </Button>
            <Button inverted variant="quiet" size="lg" onClick={backToIntro}>
              <Home /> Kezdőképernyő
            </Button>
          </div>
        </motion.div>
      )}
    </>
  );
}
