import type { Metadata } from "next";
import Link from "next/link";
import { notFound } from "next/navigation";
import { GamePlayer } from "@/components/game/GamePlayer";
import { RecentlyPlayedTracker } from "@/components/game/RecentlyPlayedTracker";
import { Button } from "@/components/ui/Button";
import { db } from "@/lib/db";
import { checkEmbedAllowed } from "@/lib/embeds";
import { getGameBySlug, getPlayableGame } from "@/lib/games";

interface PlayPageProps {
  params: Promise<{ slug: string }>;
}

export async function generateStaticParams() {
  const games = await db.game.findMany({
    where: { status: "published" },
    select: { slug: true },
  });
  return games.map((g) => ({ slug: g.slug }));
}

export async function generateMetadata({
  params,
}: PlayPageProps): Promise<Metadata> {
  const { slug } = await params;
  const game = await getGameBySlug(slug);
  if (!game) return { title: "Game not found" };
  return {
    title: `Play ${game.title}`,
    description: `Play ${game.title} — ${game.embedAllowed ? "in our game player or " : ""}on the official source.`,
    alternates: { canonical: `/games/${game.slug}/play` },
  };
}

/**
 * Dedicated player experience.
 * - embedAllowed + safe URL + allowlisted host → authorized in-site iframe.
 * - otherwise → official-source fallback (never bypass framing protections).
 * - embed flagged but failing checks → explicit "unavailable" error state.
 */
export default async function PlayPage({ params }: PlayPageProps) {
  const { slug } = await params;
  const game = await getPlayableGame(slug);
  if (!game) notFound();

  const embed = checkEmbedAllowed(game.embedAllowed, game.embedUrl);

  return (
    <div className="shell py-10">
      <RecentlyPlayedTracker slug={game.slug} />
      <nav aria-label="Breadcrumb" className="mb-4 text-sm text-slate-400">
        <Link href="/games" className="hover:text-white">
          All Games
        </Link>
        <span aria-hidden="true" className="mx-2">
          /
        </span>
        <Link href={`/games/${game.slug}`} className="hover:text-white">
          {game.title}
        </Link>
        <span aria-hidden="true" className="mx-2">
          /
        </span>
        <span aria-current="page" className="text-slate-200">
          Play
        </span>
      </nav>

      <h1 className="text-2xl font-bold tracking-tight text-white sm:text-3xl">
        Play {game.title}
      </h1>
      <p className="mt-1 text-sm text-slate-400">
        {game.developer ? `by ${game.developer} · ` : ""}
        {game.categoryName}
      </p>

      <div className="mt-6">
        {embed.ok ? (
          <GamePlayer
            embedUrl={embed.embedUrl}
            title={game.title}
            officialUrl={game.officialUrl}
            sourceDomain={game.sourceDomain}
          />
        ) : embed.reason === "not-permitted" ||
          embed.reason === "missing-url" ? (
          <section
            aria-labelledby="official-source"
            className="rounded-2xl border border-slate-800 bg-slate-900 p-8 text-center sm:p-12"
          >
            <div
              aria-hidden="true"
              className="mx-auto mb-4 flex h-12 w-12 items-center justify-center rounded-2xl bg-slate-800 text-2xl"
            >
              🔗
            </div>
            <h2 id="official-source" className="text-xl font-semibold text-white">
              This game is available on the official source.
            </h2>
            <p className="mx-auto mt-2 max-w-md text-sm text-slate-400">
              The publisher hasn&apos;t permitted embedding, so {game.title}{" "}
              plays on {game.sourceDomain || "its official site"}. We link
              there directly instead of copying the game.
            </p>
            <div className="mt-6 flex flex-wrap justify-center gap-3">
              <a
                href={game.officialUrl}
                target="_blank"
                rel="noopener noreferrer"
                className="inline-flex h-12 items-center rounded-xl bg-brand-600 px-6 text-base font-semibold text-white shadow-lg shadow-brand-600/25 transition-colors hover:bg-brand-500"
              >
                Play on Official Site
              </a>
              <Button href={`/games/${game.slug}`} variant="secondary" size="lg">
                Back to details
              </Button>
            </div>
          </section>
        ) : (
          <section
            aria-labelledby="embed-unavailable"
            role="alert"
            className="rounded-2xl border border-amber-500/40 bg-amber-500/10 p-8 text-center sm:p-12"
          >
            <div
              aria-hidden="true"
              className="mx-auto mb-4 flex h-12 w-12 items-center justify-center rounded-2xl bg-slate-800 text-2xl"
            >
              ⚠️
            </div>
            <h2 id="embed-unavailable" className="text-xl font-semibold text-white">
              Embed unavailable
            </h2>
            <p className="mx-auto mt-2 max-w-md text-sm text-slate-300">
              This game is flagged as embeddable, but its embed URL failed our
              safety checks (
              {embed.reason === "unsafe-url"
                ? "unsafe URL"
                : "domain not on the embed allowlist"}
              ), so it was blocked. You can still play on the official source.
            </p>
            <div className="mt-6 flex flex-wrap justify-center gap-3">
              <a
                href={game.officialUrl}
                target="_blank"
                rel="noopener noreferrer"
                className="inline-flex h-12 items-center rounded-xl bg-brand-600 px-6 text-base font-semibold text-white transition-colors hover:bg-brand-500"
              >
                Play on Official Site
              </a>
              <Button href={`/games/${game.slug}`} variant="secondary" size="lg">
                Back to details
              </Button>
            </div>
          </section>
        )}
      </div>

      <div className="mt-6 flex flex-wrap items-center justify-between gap-3">
        <Link
          href={`/games/${game.slug}`}
          className="text-sm font-medium text-brand-300 hover:text-brand-200"
        >
          ← Back to {game.title} details
        </Link>
        <Link
          href="/about#report"
          className="text-sm text-slate-400 hover:text-white"
        >
          Report a Problem
        </Link>
      </div>
    </div>
  );
}
