'use client';

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

import { motion } from 'framer-motion';
import { Maximize2, Minimize2, X } from 'lucide-react';

import { Button } from '@/components/ui/button';
import { cn } from '@/lib/utils';

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

import MosaicPicture from './MosaicPicture';

export const gameGlass = 'border border-white/10 bg-black/45 backdrop-blur-md';
/** Where a game's own top-right controls end: left of the stage's two window buttons. */
export const GAME_CONTROLS_OFFSET = 'right-[108px] top-3 sm:right-28 sm:top-4';
/** A game's top-left corner, for its Home button. */
export const GAME_HOME_POSITION = 'absolute left-3 top-3 sm:left-4 sm:top-4';

/** The spinner of the game's loading states. */
export function GameSpinner({ label }: { label: string }) {
  return (
    <div role="status" className="flex flex-col items-center gap-4">
      <div className="size-10 animate-spin rounded-full border-4 border-white/15 border-t-mma-yellow" />
      <p className="text-xs font-semibold uppercase tracking-[0.2em] text-white/60">{label}</p>
    </div>
  );
}

/** The slowly moving mosaic behind a game's menus, there already while the game loads. */
export function GameBackdrop() {
  return (
    <>
      <motion.div
        aria-hidden
        className="absolute inset-0"
        initial={{ scale: 1 }}
        animate={{ scale: 1.08 }}
        transition={{ duration: 24, ease: 'linear', repeat: Infinity, repeatType: 'reverse' }}
      >
        <MosaicPicture className="opacity-35" />
      </motion.div>
      <div
        aria-hidden
        className="absolute inset-0 bg-gradient-to-b from-[#151720]/70 via-[#151720]/85 to-[#151720]"
      />
    </>
  );
}

/** The loading screen of a game route: its title on the mosaic, until the game arrives. */
export function GameLoading({ title }: { title: string }) {
  return (
    <GameStage menu>
      <GameBackdrop />
      <div className="relative flex flex-col items-center gap-10 px-6 text-center">
        <h1 className="font-slab text-5xl font-bold leading-none tracking-tight sm:text-7xl">
          {title}
        </h1>
        <GameSpinner label="A játék betöltése…" />
      </div>
    </GameStage>
  );
}

/**
 * The way out of a game, which has no site header: the game window (opened by the launcher)
 * closes; a game opened as a page, in a tab or from a link, goes back to the story.
 */
function ExitControl() {
  const [inWindow, setInWindow] = useState(false);
  useEffect(() => {
    setInWindow(Boolean(window.opener) && window.name.startsWith('azopus-'));
  }, []);
  const label = inWindow ? 'Bezárás' : 'Vissza az oldalra';
  const className = cn(gameGlass, 'text-white');

  return inWindow ? (
    <Button
      inverted
      variant="quiet"
      size="icon"
      className={className}
      onClick={() => window.close()}
      aria-label={label}
      title={label}
    >
      <X />
    </Button>
  ) : (
    <Button inverted variant="quiet" size="icon" className={className} asChild>
      <Link href="/felfedezes" aria-label={label} title={label}>
        <X />
      </Link>
    </Button>
  );
}

/** Shared stage keeps fullscreen active while the game changes rounds and screens. */
export default function GameStage({
  menu,
  embedded = false,
  children,
}: {
  menu: boolean;
  embedded?: boolean;
  children: ReactNode;
}) {
  const stage = useRef<HTMLDivElement>(null);
  const [canFullscreen, setCanFullscreen] = useState(false);
  const [fullscreen, setFullscreen] = useState(false);

  useEffect(() => {
    setCanFullscreen(Boolean(document.fullscreenEnabled));
    const onChange = () => setFullscreen(document.fullscreenElement === stage.current);
    document.addEventListener('fullscreenchange', onChange);
    return () => document.removeEventListener('fullscreenchange', onChange);
  }, []);

  const toggleFullscreen = async () => {
    try {
      if (document.fullscreenElement) await document.exitFullscreen();
      else await stage.current?.requestFullscreen();
    } catch {
      // Fullscreen is optional; some browsers do not allow it.
    }
  };

  return (
    // The game fills its window (the page has no header or footer, see SiteFrame); on short
    // screens it scrolls inside the stage.
    <div className={embedded ? 'h-full' : 'h-[calc(100dvh-var(--admin-h))]'}>
      <div
        ref={stage}
        className={cn(
          'relative isolate h-full overflow-y-auto bg-[#151720] text-white lg:overflow-hidden',
          // Safe centering: a menu taller than the window scrolls instead of losing its top.
          menu && 'flex items-center justify-center [align-items:safe_center]',
          fullscreen && 'h-[100dvh] lg:h-[100dvh]',
          embedded && 'min-h-0'
        )}
      >
        {children}
        {/* Window controls, as on Windows: fullscreen, then close in the corner. The games keep
            their own top-right controls left of GAME_CONTROLS_OFFSET. */}
        {embedded ? null : (
          <div className="absolute right-3 top-3 z-40 flex gap-2 sm:right-4 sm:top-4">
            {canFullscreen ? (
              <Button
                inverted
                variant="quiet"
                size="icon"
                className={cn(gameGlass, 'text-white')}
                onClick={() => void toggleFullscreen()}
                aria-label={fullscreen ? 'Kilépés a teljes képernyőből' : 'Teljes képernyő'}
                title={fullscreen ? 'Kilépés a teljes képernyőből' : 'Teljes képernyő'}
              >
                {fullscreen ? <Minimize2 /> : <Maximize2 />}
              </Button>
            ) : null}
            <ExitControl />
          </div>
        )}
      </div>
    </div>
  );
}
