"use client";

import { useCallback, useEffect, useMemo, useState } from "react";
import Link from "next/link";
import type { Game, SystemDef } from "@/lib/types";
import { BootTheater } from "@/components/boot/BootTheater";
import { useProfile } from "@/lib/profile/context";
import { hashGameId } from "@/lib/profile/ids";
import { usePlaySession } from "@/components/player/usePlaySession";

export function PlayClient({
  game,
  system,
  biosUrl = null,
  skipBoot = false,
}: {
  game: Game;
  system: SystemDef;
  /** Optional EmulatorJS BIOS URL (e.g. PSX scph5501.bin) */
  biosUrl?: string | null;
  skipBoot?: boolean;
}) {
  const [booted, setBooted] = useState(skipBoot);
  const [hintDismissed, setHintDismissed] = useState(false);
  const [isTouch, setIsTouch] = useState(false);
  const { ready, profile, account } = useProfile();
  const preferSkip =
    skipBoot ||
    account?.settings?.skipBootByDefault ||
    profile?.settings?.skipBootByDefault;
  const [started, setStarted] = useState(Boolean(preferSkip));
  const { toast } = usePlaySession(game.slug, started && ready);

  useEffect(() => {
    setIsTouch(
      window.matchMedia("(pointer: coarse)").matches ||
        navigator.maxTouchPoints > 0,
    );
  }, []);

  useEffect(() => {
    if (preferSkip) setBooted(true);
  }, [preferSkip]);

  useEffect(() => {
    if (booted) setStarted(true);
  }, [booted]);

  const iframeSrc = useMemo(() => {
    // Cartridge ROMs → /api/rom/...
    // Disc (PSX etc.) → /api/disc-pack/... zip(cue+bin) so PCSX can load both files.
    // Loading a bare .cue URL often fails companion .bin fetch (spaces / proxy) → RetroArch menu.
    const discSystems = new Set(["psx", "segacd", "saturn"]);
    const ext = game.rom.split(".").pop()?.toLowerCase() || "";
    const isDisc =
      discSystems.has(system.id) &&
      (ext === "cue" || ext === "bin" || ext === "chd" || ext === "pbp");

    let romPath = game.rom;
    if (game.rom.startsWith("/roms/")) {
      const rest = game.rom.slice("/roms/".length);
      romPath = isDisc ? `/api/disc-pack/${rest}` : `/api/rom/${rest}`;
    }

    const profileId = profile?.id ?? "guest";
    const params = new URLSearchParams({
      core: system.core,
      rom: romPath,
      title: game.title,
      gameName: `${profileId}:${game.slug}`,
      gameId: String(hashGameId(profileId, game.slug)),
    });
    if (biosUrl) params.set("bios", biosUrl);
    if (isDisc) params.set("disc", "1");
    return `/emulator.html?${params.toString()}`;
  }, [game.rom, game.title, game.slug, system.core, system.id, profile?.id, biosUrl]);

  const onBootDone = useCallback(() => setBooted(true), []);

  const requestFullscreen = useCallback(() => {
    const el = document.documentElement;
    void el.requestFullscreen?.();
  }, []);

  return (
    <div className="fixed inset-0 z-30 bg-black">
      {!booted && (
        <BootTheater
          media={system.media}
          label={game.title}
          accent={system.color}
          onDone={onBootDone}
        />
      )}
      {booted && (
        <>
          <div className="absolute left-0 right-0 top-0 z-40 flex items-center justify-between gap-3 border-b border-white/10 bg-black/70 px-3 py-2 backdrop-blur">
            <div className="min-w-0">
              <p className="truncate font-display text-[0.55rem] tracking-wider text-accent uppercase">
                {system.shortName}
              </p>
              <h1 className="truncate text-sm text-foreground">{game.title}</h1>
            </div>
            <div className="flex shrink-0 gap-2">
              <button
                type="button"
                className="btn-ghost"
                onClick={requestFullscreen}
              >
                Fullscreen
              </button>
              <Link href={`/games/${game.slug}`} className="btn-ghost">
                Details
              </Link>
              <Link href="/" className="btn-ghost">
                Exit
              </Link>
            </div>
          </div>
          <iframe
            title={`${game.title} emulator`}
            src={iframeSrc}
            className="absolute inset-0 h-full w-full border-0 pt-12"
            allow="gamepad *; autoplay *; fullscreen *"
          />
          {!hintDismissed && (
            <div className="absolute bottom-3 left-3 right-3 z-40 mx-auto max-w-lg rounded-sm border border-white/15 bg-black/80 px-3 py-2 text-center text-xs text-foreground/90 backdrop-blur sm:left-1/2 sm:right-auto sm:-translate-x-1/2">
              <p>
                {isTouch
                  ? "On-screen controls appear via EmulatorJS — use landscape + Fullscreen for the best pad layout. Open the emulator Settings menu to remap."
                  : "Keyboard and USB/Bluetooth controllers work through EmulatorJS. Press a gamepad button once if it isn’t detected. Remap in the emulator Settings menu."}
              </p>
              <button
                type="button"
                className="mt-1 text-accent underline-offset-2 hover:underline"
                onClick={() => setHintDismissed(true)}
              >
                Got it
              </button>
            </div>
          )}
          {toast}
        </>
      )}
    </div>
  );
}
