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

import type { MouseEvent } from 'react';

import { CalendarDays, MapPin, Play } from 'lucide-react';

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';

type Game = 'place' | 'year';

const TEASERS: Record<
  Game,
  {
    title: string;
    text: string;
    inline: string;
    icon: typeof MapPin;
    label: string;
    /** Three creations from the Időgép snapshot (time-map.json), picked once by hand. */
    pictures: { id: string; image: number }[];
  }
> = {
  place: {
    title: 'Hol készült? Tippelje meg a térképen!',
    text: 'Öt épület és alkotás, öt helyszín. Minél közelebb jelöl, annál több pontot kap, és ha elakad, segítséget is kérhet.',
    inline: 'Ráismer a helyre? Tippelje meg, hol készült!',
    icon: MapPin,
    label: 'Hol készült? – játék',
    pictures: [
      { id: 'AS0029835', image: 7209 },
      { id: 'AS0013945', image: 2329 },
      { id: 'AS1050909', image: 34215 },
    ],
  },
  year: {
    title: 'Mikor készült? Tippelje meg az évet!',
    text: 'Öt alkotás öt különböző évtizedből. Egy kép és egy cím alapján állítsa be az évet: minél közelebb jár, annál több pontot kap.',
    inline: 'Ráismer a korra? Tippelje meg, mikor készült!',
    icon: CalendarDays,
    label: 'Mikor készült? – játék',
    pictures: [
      { id: 'AS0029835', image: 7209 },
      { id: 'AS0000206', image: 3803 },
      { id: 'AS0034454', image: 23192 },
    ],
  },
};

// The game window's size on desktop; phones open it as a new tab.
const WINDOW_WIDTH = 1200;
const WINDOW_HEIGHT = 820;
// One window per game: a second click brings it forward instead of restarting the game.
const gameWindows = new Map<Game, Window>();

/**
 * Opens the game in its own window over the story, so the reader keeps their place. Modified
 * clicks (new tab, new window) and a blocked window fall back to the link's own behaviour.
 */
function openGameWindow(event: MouseEvent<HTMLAnchorElement>, game: Game) {
  if (event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) {
    return;
  }
  const open = gameWindows.get(game);
  if (open && !open.closed) {
    event.preventDefault();
    open.focus();
    return;
  }
  const width = Math.min(WINDOW_WIDTH, window.screen.availWidth);
  const height = Math.min(WINDOW_HEIGHT, window.screen.availHeight);
  const left = Math.round(window.screenX + (window.outerWidth - width) / 2);
  const top = Math.round(window.screenY + (window.outerHeight - height) / 2);
  const opened = window.open(
    event.currentTarget.href,
    `azopus-${game}`,
    `popup,width=${width},height=${height},left=${left},top=${top}`
  );
  if (!opened) return;
  event.preventDefault();
  gameWindows.set(game, opened);
  opened.focus();
}

export default function GuessGameLauncher({
  variant,
  game = 'place',
  tone = 'dark',
}: {
  variant: 'teaser' | 'inline';
  game?: Game;
  /** The teaser's look: dark over blurred pictures, or bright yellow with picture cards. */
  tone?: 'dark' | 'bright';
}) {
  const href = game === 'place' ? '/hol-keszult' : '/mikor-keszult';
  const teaser = TEASERS[game];
  const pictures = teaser.pictures;
  const Icon = teaser.icon;

  return (
    <div>
      {variant === 'teaser' ? (
        // Regular links: a plain click opens the game window, a modified one the visitor's tab.
        <div
          className={cn(
            'group relative isolate overflow-hidden',
            tone === 'dark' ? 'bg-[#151720] text-white' : 'bg-[#dfcf6f] text-[#151720]'
          )}
        >
          {tone === 'dark' ? (
            <>
              <div aria-hidden className="absolute inset-0 grid grid-cols-3">
                {pictures.map((item) => (
                  <img
                    key={item.id}
                    src={buildMediaUrl(item.image, 'w640')}
                    alt=""
                    loading="lazy"
                    className="h-full w-full object-cover opacity-40 blur-[3px] transition-transform duration-500 group-hover:scale-105"
                  />
                ))}
              </div>
              <div
                aria-hidden
                className="absolute inset-0 bg-gradient-to-t from-[#151720] via-[#151720]/70 to-[#151720]/30"
              />
            </>
          ) : null}
          <div
            className={cn(
              'relative grid items-center gap-8 p-6 sm:p-10',
              tone === 'dark'
                ? 'min-h-[340px] content-end'
                : 'md:grid-cols-[minmax(0,1fr)_minmax(0,22rem)]'
            )}
          >
            <div className="flex flex-col items-start gap-4">
              <Text
                variant="eyebrow"
                tone="inherit"
                className={cn(
                  'flex items-center gap-2',
                  tone === 'dark' ? 'text-white/70' : 'text-[#151720]/70'
                )}
              >
                <Icon className="size-4" aria-hidden /> Játék
              </Text>
              <p className="max-w-xl font-slab text-3xl font-bold leading-tight sm:text-4xl">
                {teaser.title}
              </p>
              <Text
                tone="inherit"
                className={cn('max-w-xl', tone === 'dark' ? 'text-white/80' : 'text-[#151720]/80')}
              >
                {teaser.text}
              </Text>
              <Button
                size="lg"
                inverted={tone === 'dark'}
                className="mt-2 h-14 px-8 text-base"
                asChild
              >
                <Link href={href} prefetch={false} onClick={(event) => openGameWindow(event, game)}>
                  <Play /> Játszom
                </Link>
              </Button>
            </div>
            {/* Three picture cards, fanned out; they spread a little on hover. */}
            {tone === 'bright' ? (
              <div aria-hidden className="relative hidden h-56 md:block">
                {pictures.map((item, index) => (
                  <img
                    key={item.id}
                    src={buildMediaUrl(item.image, 'w640')}
                    alt=""
                    loading="lazy"
                    className={cn(
                      'absolute top-1/2 size-44 border-4 border-white object-cover shadow-lg transition-transform duration-300',
                      index === 0 && 'left-0 -translate-y-1/2 -rotate-6 group-hover:-rotate-12',
                      index === 1 &&
                        'left-1/2 z-10 -translate-x-1/2 -translate-y-1/2 group-hover:-translate-y-[60%]',
                      index === 2 && 'right-0 -translate-y-1/2 rotate-6 group-hover:rotate-12'
                    )}
                  />
                ))}
              </div>
            ) : null}
          </div>
        </div>
      ) : (
        <div className="flex flex-wrap items-center justify-between gap-3 border border-[#151720]/10 bg-white px-4 py-3">
          <Text className="flex items-center gap-2 font-semibold">
            <Icon className="h-4 w-4 shrink-0" /> {teaser.inline}
          </Text>
          <Button size="sm" asChild>
            <Link href={href} prefetch={false} onClick={(event) => openGameWindow(event, game)}>
              <Play /> Játék
            </Link>
          </Button>
        </div>
      )}
    </div>
  );
}
