/* eslint-disable @next/next/no-img-element */
'use client';

import { type ReactNode, useEffect, useRef, useState } from 'react';

import { AnimatePresence, motion } from 'framer-motion';
import { ArrowRight, ExternalLink, Home, Lightbulb } from 'lucide-react';

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

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

import GameMenu, { CountUp } from './GameMenu';
import GameStage, {
  GAME_CONTROLS_OFFSET,
  GAME_HOME_POSITION,
  gameGlass as glass,
} from './GameStage';
import GuessMap, { type HintArea, type LatLng } from './GuessMap';

export interface GuessItem {
  id: string;
  title: string;
  creator: string | null;
  place: string | null;
  category: string;
  year: number;
  lat: number;
  lng: number;
  imageId: number;
}

interface RoundResult {
  item: GuessItem;
  guess: LatLng;
  distanceKm: number;
  score: number;
  hintCount: number;
}

type Phase = 'intro' | 'guessing' | 'revealed' | 'finished';

const ROUND_COUNT = 5;
const MAX_SCORE = 5000;
const MAX_TOTAL = ROUND_COUNT * MAX_SCORE;
// Points halve roughly every 52 km.
const DISTANCE_SCALE_KM = 75;
const BEST_SCORE_KEY = 'hol-keszult-best';
// The answer is somewhere inside this circle, never right at its center.
const HINT_AREA_RADIUS_KM = 100;
const HINT_AREA_MAX_OFFSET = 0.65;
// The minimap stays open this long after the pointer leaves it.
const MAP_COLLAPSE_DELAY_MS = 400;

type HintId = 'year' | 'creator' | 'title' | 'area';

// Each hint helps more than the previous one and takes a bigger share of the round's points.
// The shares stay behind the scenes: players only see how many hints they used.
const HINTS: { id: HintId; label: string; penalty: number }[] = [
  { id: 'year', label: 'Évszám', penalty: 0.1 },
  { id: 'creator', label: 'Alkotó', penalty: 0.15 },
  { id: 'title', label: 'Cím', penalty: 0.2 },
  { id: 'area', label: 'Körzet', penalty: 0.25 },
];

const hintsFor = (item: GuessItem) => HINTS.filter((hint) => hint.id !== 'creator' || item.creator);

const hintValue = (hint: HintId, item: GuessItem) =>
  hint === 'year'
    ? String(item.year)
    : hint === 'creator'
      ? item.creator
      : hint === 'title'
        ? item.title
        : 'bejelölve a térképen';

const hintCountLabel = (count: number) => `${count} segítséggel`;

function hintAreaAround(answer: LatLng): HintArea {
  const angle = Math.random() * 2 * Math.PI;
  const offsetKm = Math.random() * HINT_AREA_MAX_OFFSET * HINT_AREA_RADIUS_KM;
  return {
    center: {
      lat: answer.lat + (offsetKm * Math.cos(angle)) / 111,
      lng:
        answer.lng + (offsetKm * Math.sin(angle)) / (111 * Math.cos((answer.lat * Math.PI) / 180)),
    },
    radiusKm: HINT_AREA_RADIUS_KM,
  };
}

const formatNumber = (value: number) => value.toLocaleString('hu-HU');

function distanceKm(from: LatLng, to: LatLng): number {
  const toRadians = (degrees: number) => (degrees * Math.PI) / 180;
  const deltaLat = toRadians(to.lat - from.lat);
  const deltaLng = toRadians(to.lng - from.lng);
  const a =
    Math.sin(deltaLat / 2) ** 2 +
    Math.cos(toRadians(from.lat)) * Math.cos(toRadians(to.lat)) * Math.sin(deltaLng / 2) ** 2;
  return 6371 * 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
}

const formatDistance = (km: number) =>
  km < 1 ? `${Math.round(km * 1000)} m` : `${formatNumber(Math.round(km))} km`;

/** Random creations, each from a different place, so a game isn't five times Budapest. */
function pickRounds(items: GuessItem[]): GuessItem[] {
  const shuffled = [...items];
  for (let i = shuffled.length - 1; i > 0; i -= 1) {
    const j = Math.floor(Math.random() * (i + 1));
    [shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]];
  }
  const places = new Set<string>();
  const rounds: GuessItem[] = [];
  for (const item of shuffled) {
    const place = item.place?.trim().toLowerCase() || `${item.lat}|${item.lng}`;
    if (places.has(place)) continue;
    places.add(place);
    rounds.push(item);
    if (rounds.length === ROUND_COUNT) break;
  }
  return rounds;
}

function readBestScore(): number | null {
  try {
    const value = Number(window.localStorage.getItem(BEST_SCORE_KEY));
    return Number.isFinite(value) && value > 0 ? value : null;
  } catch {
    return null;
  }
}

function saveBestScore(score: number) {
  try {
    window.localStorage.setItem(BEST_SCORE_KEY, String(score));
  } catch {
    // Storage may be blocked; the best score is only a convenience.
  }
}

function verdict(score: number): string {
  const share = score / MAX_TOTAL;
  if (share >= 0.85) return 'Térképész-zseni! Szinte mindent eltalált.';
  if (share >= 0.6) return 'Remek érzéke van a hazai kultúra helyszíneihez.';
  if (share >= 0.35) return 'Szép eredmény, de van még mit felfedezni.';
  return 'Most kezdődik a felfedezés: nézzen bele az alkotásokba!';
}

function roundMessage(score: number): string {
  const share = score / MAX_SCORE;
  if (share >= 0.95) return 'Telitalálat!';
  if (share >= 0.75) return 'Nagyon közel!';
  if (share >= 0.4) return 'Jó irány!';
  if (share >= 0.15) return 'Még messze.';
  return 'Ez most nem jött be.';
}

export default function GuessGame({
  items,
  embedded = false,
}: {
  items: GuessItem[];
  /** Inside a full-screen layer of another page: it fills the layer and has no fullscreen button. */
  embedded?: boolean;
}) {
  const [phase, setPhase] = useState<Phase>('intro');
  const [rounds, setRounds] = useState<GuessItem[]>([]);
  const [roundIndex, setRoundIndex] = useState(0);
  const [guess, setGuess] = useState<LatLng | null>(null);
  const [hintsUsed, setHintsUsed] = useState(0);
  const [hintArea, setHintArea] = useState<HintArea | null>(null);
  const [results, setResults] = useState<RoundResult[]>([]);
  const [bestScore, setBestScore] = useState<number | null>(null);
  const [mapOpen, setMapOpen] = useState(false);
  const collapseTimer = useRef<number | null>(null);

  useEffect(() => {
    setBestScore(readBestScore());
  }, []);

  const item = rounds[roundIndex];
  const result = phase === 'revealed' ? results[roundIndex] : null;
  const totalScore = results.reduce((sum, round) => sum + round.score, 0);
  const availableHints = item ? hintsFor(item) : [];
  const usedHints = availableHints.slice(0, hintsUsed);
  const nextHint = availableHints[hintsUsed];
  const hintPenalty = usedHints.reduce((sum, hint) => sum + hint.penalty, 0);
  const isLastRound = roundIndex + 1 >= rounds.length;

  const resetRound = () => {
    setGuess(null);
    setHintsUsed(0);
    setHintArea(null);
    setMapOpen(false);
    setPhase('guessing');
  };

  const revealHint = () => {
    if (!item || !nextHint) return;
    if (nextHint.id === 'area') setHintArea(hintAreaAround(item));
    setHintsUsed((count) => count + 1);
  };

  const startGame = () => {
    setRounds(pickRounds(items));
    setRoundIndex(0);
    setResults([]);
    resetRound();
  };

  const submitGuess = () => {
    if (!item || !guess || phase !== 'guessing') return;
    const distance = distanceKm(guess, item);
    setResults((current) => [
      ...current,
      {
        item,
        guess,
        distanceKm: distance,
        score: Math.round(MAX_SCORE * (1 - hintPenalty) * Math.exp(-distance / DISTANCE_SCALE_KM)),
        hintCount: usedHints.length,
      },
    ]);
    setPhase('revealed');
  };

  const nextRound = () => {
    if (isLastRound) {
      if (bestScore === null || totalScore > bestScore) {
        saveBestScore(totalScore);
        setBestScore(totalScore);
      }
      setPhase('finished');
      return;
    }
    setRoundIndex((index) => index + 1);
    resetRound();
  };

  // Enter or Space confirms the guess, then moves on to the next round.
  const keyActionRef = useRef<() => void>(() => undefined);
  useEffect(() => {
    keyActionRef.current =
      phase === 'guessing' ? submitGuess : phase === 'revealed' ? nextRound : () => undefined;
  });
  useEffect(() => {
    const onKeyDown = (event: KeyboardEvent) => {
      if (event.key !== 'Enter' && event.key !== ' ') return;
      if ((event.target as HTMLElement | null)?.closest('button, a, input')) return;
      event.preventDefault();
      keyActionRef.current();
    };
    window.addEventListener('keydown', onKeyDown);
    return () => window.removeEventListener('keydown', onKeyDown);
  }, []);

  const openMap = () => {
    if (collapseTimer.current !== null) window.clearTimeout(collapseTimer.current);
    setMapOpen(true);
  };
  const closeMapSoon = () => {
    collapseTimer.current = window.setTimeout(() => setMapOpen(false), MAP_COLLAPSE_DELAY_MS);
  };

  const backToIntro = () => {
    setPhase('intro');
    setRounds([]);
    setResults([]);
    setRoundIndex(0);
  };

  const isMenu = phase === 'intro' || phase === 'finished' || items.length < ROUND_COUNT;
  const revealed = Boolean(result);
  let content: ReactNode = null;

  if (items.length < ROUND_COUNT) {
    content = (
      <Text tone="inherit" className="relative p-10">
        Nincs elég képes, helyszínnel ellátott alkotás a játékhoz.
      </Text>
    );
  } else if (isMenu) {
    content = (
      <GameMenu
        phase={phase === 'finished' ? 'finished' : 'intro'}
        title="Hol készült?"
        description="Öt alkotás, egy térkép. Mennyire ismeri az ország épületeit és köztéri alkotásait? Ha elakad, kérjen segítséget! A segítségek csökkentik az elérhető pontszámot."
        totalScore={totalScore}
        bestScore={bestScore}
        message={verdict(totalScore)}
        results={results.map((round) => ({
          ...round,
          detail:
            formatDistance(round.distanceKm) +
            (round.hintCount ? ' · ' + hintCountLabel(round.hintCount) : ''),
        }))}
        startGame={startGame}
        backToIntro={backToIntro}
      />
    );
  } else if (item) {
    content = (
      <>
        {/* The artwork is the scene. */}
        <div className="relative h-[46svh] min-h-[300px] overflow-hidden lg:absolute lg:inset-0 lg:h-auto">
          <img
            key={`backdrop-${item.id}`}
            src={buildMediaUrl(item.imageId, 'w640')}
            alt=""
            aria-hidden
            className="absolute inset-0 h-full w-full scale-110 object-cover opacity-40 blur-2xl"
          />
          <motion.img
            key={item.id}
            src={buildMediaUrl(item.imageId, 'w1024')}
            alt="A kitalálandó alkotás"
            initial={{ opacity: 0, scale: 0.97 }}
            animate={{ opacity: 1, scale: 1 }}
            transition={{ duration: 0.5 }}
            className="relative h-full w-full object-contain p-4 pb-16 pt-16 lg:p-16"
          />
          <div
            aria-hidden
            className="pointer-events-none absolute inset-x-0 top-0 h-28 bg-gradient-to-b from-black/60 to-transparent"
          />
          {!revealed && nextHint ? (
            <div className="absolute bottom-3 left-3 z-20 sm:bottom-4 sm:left-4">
              <Button
                inverted
                variant="quiet"
                className={cn(glass, 'text-white')}
                onClick={revealHint}
              >
                <Lightbulb /> Segítség {hintsUsed + 1}/{availableHints.length}
              </Button>
            </div>
          ) : null}
        </div>

        {/* HUD: Home and category with hints on the left; rounds and score on the right. */}
        <div className="pointer-events-none absolute inset-x-0 top-0 z-20 p-3 pt-16 sm:p-4 sm:pt-16">
          <div className="flex max-w-full flex-col items-start gap-2 sm:max-w-sm">
            <Badge variant="accent" size="sm">
              {item.category}
            </Badge>
            <AnimatePresence initial={false}>
              {!revealed
                ? usedHints.map((hint) => (
                    <motion.div
                      key={hint.id}
                      initial={{ opacity: 0, x: -12 }}
                      animate={{ opacity: 1, x: 0 }}
                      exit={{ opacity: 0 }}
                      className={cn(glass, 'px-3 py-2')}
                    >
                      <span className="block text-[10px] font-semibold uppercase tracking-[0.2em] text-white/55">
                        {hint.label}
                      </span>
                      <span className="mt-0.5 block text-sm font-semibold leading-snug">
                        {hintValue(hint.id, item)}
                      </span>
                    </motion.div>
                  ))
                : null}
            </AnimatePresence>
          </div>

          <div className={cn('absolute flex items-start gap-2', GAME_CONTROLS_OFFSET)}>
            <div className={cn(glass, 'flex h-10 items-center gap-3 px-3')}>
              <ol
                className="flex items-center gap-1.5"
                aria-label={`${roundIndex + 1}. kör / ${rounds.length}`}
              >
                {rounds.map((round, index) => (
                  <li
                    key={round.id}
                    className={cn(
                      'h-2 w-2 rounded-full',
                      index < results.length
                        ? 'bg-mma-yellow'
                        : index === roundIndex
                          ? 'bg-white'
                          : 'bg-white/25'
                    )}
                  />
                ))}
              </ol>
              <span className="font-slab text-lg font-bold leading-none">
                {formatNumber(totalScore)}
              </span>
            </div>
          </div>
          <Button
            inverted
            variant="quiet"
            size="icon"
            className={cn(glass, GAME_HOME_POSITION, 'pointer-events-auto text-white')}
            onClick={backToIntro}
            aria-label="Vissza a kezdőképernyőre"
            title="Vissza a kezdőképernyőre"
          >
            <Home />
          </Button>
        </div>

        {/* Minimap with the guess button; fills the stage on reveal. */}
        <div
          onMouseEnter={revealed ? undefined : openMap}
          onMouseLeave={revealed ? undefined : closeMapSoon}
          className={cn(
            'relative z-10 flex flex-col transition-all duration-500 ease-out lg:absolute',
            revealed
              ? 'lg:bottom-0 lg:right-0 lg:h-full lg:w-full'
              : cn(
                  'lg:bottom-4 lg:right-4 lg:gap-2',
                  mapOpen ? 'lg:w-[min(640px,60%)]' : 'lg:w-[340px]'
                )
          )}
        >
          <div
            className={cn(
              'relative h-[46svh] min-h-[300px] overflow-hidden transition-all duration-500 ease-out lg:min-h-0',
              revealed
                ? 'lg:h-full'
                : cn(
                    'lg:border lg:border-white/15 lg:shadow-2xl',
                    // The wrapper has no height of its own, so the open size follows the viewport.
                    mapOpen ? 'lg:h-[min(460px,calc(100svh-20rem))]' : 'lg:h-[220px]',
                    !mapOpen && 'lg:opacity-90'
                  )
            )}
          >
            <GuessMap
              guess={result?.guess ?? guess}
              answer={result ? { lat: item.lat, lng: item.lng } : null}
              roundKey={item.id}
              hintArea={hintArea}
              onGuess={(position) => {
                setGuess(position);
                openMap();
              }}
            />
          </div>
          {!revealed ? (
            <div className="p-3 lg:p-0">
              <Button size="lg" className="w-full" inverted disabled={!guess} onClick={submitGuess}>
                {guess ? 'Tippelek' : 'Jelölje be a térképen'}
              </Button>
            </div>
          ) : null}
        </div>

        {/* Result card. */}
        <AnimatePresence>
          {result ? (
            <motion.div
              key={`result-${item.id}`}
              initial={{ opacity: 0, y: 40 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ duration: 0.45, delay: 0.35, ease: 'easeOut' }}
              className="relative z-30 flex justify-center p-3 lg:absolute lg:inset-x-0 lg:bottom-0 lg:p-6"
            >
              <div className="grid w-full max-w-3xl gap-4 bg-white p-4 text-[#151720] shadow-2xl sm:grid-cols-[96px_minmax(0,1fr)_auto] sm:items-center sm:p-5">
                <img
                  src={buildMediaUrl(item.imageId, 'w256')}
                  alt=""
                  className="hidden h-24 w-24 object-cover sm:block"
                />
                <div className="min-w-0">
                  <Text variant="meta" className="text-[#151720]/55">
                    {roundMessage(result.score)}
                  </Text>
                  <div className="mt-1 line-clamp-2 text-lg font-bold leading-tight">
                    {item.title}
                  </div>
                  <Text variant="bodySm" tone="muted" className="mt-1 line-clamp-1">
                    {[item.creator, item.place, item.year].filter(Boolean).join(' · ')}
                  </Text>
                  <Link
                    href={{ pathname: '/alkotas/[id]', params: { id: item.id } }}
                    target="_blank"
                    rel="noopener noreferrer"
                    className="mt-1 inline-flex items-center gap-1 text-xs font-semibold text-[#151720]/70 hover:text-[#151720] hover:underline"
                  >
                    Az alkotás oldala <ExternalLink size={12} />
                  </Link>
                </div>
                <div className="flex flex-col gap-3 sm:min-w-[200px] sm:items-end">
                  <div className="flex items-baseline gap-3 sm:flex-col sm:items-end sm:gap-0">
                    <CountUp
                      value={result.score}
                      className="font-slab text-4xl font-bold leading-none"
                    />
                    <Text variant="caption" tone="muted" className="sm:mt-1">
                      {formatDistance(result.distanceKm)}
                      {result.hintCount > 0 ? ` · ${hintCountLabel(result.hintCount)}` : ''}
                    </Text>
                  </div>
                  <div className="h-1.5 w-full bg-[#151720]/10 sm:w-[200px]">
                    <motion.div
                      className="h-full bg-mma-yellow"
                      initial={{ width: 0 }}
                      animate={{ width: `${(result.score / MAX_SCORE) * 100}%` }}
                      transition={{ duration: 1.1, ease: 'easeOut', delay: 0.35 }}
                    />
                  </div>
                  <Button className="w-full sm:w-auto" onClick={nextRound}>
                    {isLastRound ? 'Eredmény' : 'Következő kör'} <ArrowRight />
                  </Button>
                </div>
              </div>
            </motion.div>
          ) : null}
        </AnimatePresence>
      </>
    );
  }

  return (
    <GameStage menu={isMenu} embedded={embedded}>
      {content}
    </GameStage>
  );
}
