"use client";

import { useCallback, useEffect, useRef, useState } from "react";

interface GamePlayerProps {
  embedUrl: string;
  title: string;
  officialUrl: string;
  sourceDomain: string;
}

/**
 * In-site player for authorized embeds only. The server guarantees the URL
 * passed the embed allowlist before this component ever renders.
 */
export function GamePlayer({
  embedUrl,
  title,
  officialUrl,
  sourceDomain,
}: GamePlayerProps) {
  const frameRef = useRef<HTMLIFrameElement>(null);
  const shellRef = useRef<HTMLDivElement>(null);
  const [loaded, setLoaded] = useState(false);
  const [isFullscreen, setIsFullscreen] = useState(false);

  useEffect(() => {
    const onChange = () =>
      setIsFullscreen(document.fullscreenElement !== null);
    document.addEventListener("fullscreenchange", onChange);
    return () => document.removeEventListener("fullscreenchange", onChange);
  }, []);

  const toggleFullscreen = useCallback(() => {
    if (document.fullscreenElement) {
      void document.exitFullscreen().catch(() => {});
      return;
    }
    void shellRef.current?.requestFullscreen().catch(() => {});
  }, []);

  return (
    <div>
      <div
        ref={shellRef}
        className="overflow-hidden rounded-2xl border border-slate-800 bg-black"
      >
        <div className="relative aspect-video w-full">
          {!loaded ? (
            <div
              className="absolute inset-0 flex flex-col items-center justify-center gap-3 bg-slate-950"
              role="status"
              aria-live="polite"
              aria-label={`Loading ${title}`}
            >
              <div className="skeleton h-10 w-10 rounded-full" aria-hidden="true" />
              <p className="text-sm text-slate-400">Loading game…</p>
            </div>
          ) : null}
          <iframe
            ref={frameRef}
            src={embedUrl}
            title={`${title} — playable game`}
            className="absolute inset-0 h-full w-full"
            loading="lazy"
            allowFullScreen
            referrerPolicy="strict-origin-when-cross-origin"
            allow="fullscreen; gamepad; autoplay; pointer-lock"
            sandbox="allow-scripts allow-same-origin allow-forms allow-pointer-lock allow-popups"
            onLoad={() => setLoaded(true)}
          />
        </div>
      </div>

      <div className="mt-4 flex flex-wrap items-center gap-3">
        <button
          type="button"
          onClick={toggleFullscreen}
          className="inline-flex h-10 items-center rounded-xl bg-slate-800 px-4 text-sm font-semibold text-white transition-colors hover:bg-slate-700"
          aria-pressed={isFullscreen}
        >
          <span aria-hidden="true">{isFullscreen ? "⤓" : "⤢"}</span>{" "}
          {isFullscreen ? "Exit fullscreen" : "Fullscreen"}
        </button>
        <a
          href={officialUrl}
          target="_blank"
          rel="noopener noreferrer"
          className="inline-flex h-10 items-center rounded-xl border border-slate-700 px-4 text-sm font-semibold text-slate-200 transition-colors hover:border-slate-500 hover:text-white"
        >
          Open official source{sourceDomain ? ` (${sourceDomain})` : ""}
        </a>
      </div>
      <p className="mt-3 text-xs text-slate-500">
        Having trouble? The game may block embedding on its side
        (X-Frame-Options / CSP). Use the official source link above — we never
        bypass such protections.
      </p>
    </div>
  );
}
