import Image from "next/image";
import { notFound } from "next/navigation";
import type { Metadata } from "next";
import { Section } from "../../components/ui/Section";
import { SectionHeading } from "../../components/ui/SectionHeading";
import { ButtonLink } from "../../components/ui/ButtonLink";
import { Reveal } from "../../components/ui/Reveal";
import { GameHero } from "../../components/game/GameHero";
import { GamePillars } from "../../components/game/GamePillars";
import { CoopBand } from "../../components/game/CoopBand";
import { ScreenshotGallery } from "../../components/game/ScreenshotGallery";
import { PostList } from "../../components/devblog/PostList";
import { Newsletter } from "../../components/forms/Newsletter";
import { games, getGame } from "@/lib/games";
import { getPostsByGame } from "@/lib/devblog";
import { SITE_URL, STUDIO } from "@/lib/site";

type Props = { params: Promise<{ slug: string }> };

export function generateStaticParams() {
  return games.map((game) => ({ slug: game.slug }));
}

export async function generateMetadata({ params }: Props): Promise<Metadata> {
  const { slug } = await params;
  const game = getGame(slug);
  if (!game) return {};

  return {
    title: game.title,
    description: game.tagline,
    alternates: { canonical: `${SITE_URL}/games/${game.slug}` },
    openGraph: {
      type: "website",
      title: game.title,
      description: game.tagline,
      url: `${SITE_URL}/games/${game.slug}`,
      images: game.keyArt ? [`${SITE_URL}${game.keyArt}`] : undefined,
    },
  };
}

export default async function GamePage({ params }: Props) {
  const { slug } = await params;
  const game = getGame(slug);
  if (!game) notFound();

  const relatedPosts = getPostsByGame(slug).slice(0, 3);

  // "1-6" → { minValue: 1, maxValue: 6 }, so search engines get the player
  // count as data rather than as a string buried in the description.
  const [minPlayers, maxPlayers] = (game.players ?? "")
    .split(/[-–]/)
    .map((part) => Number(part.trim()));

  const jsonLd = {
    "@context": "https://schema.org",
    "@type": "VideoGame",
    name: game.title,
    description: game.description,
    genre: game.genres,
    gamePlatform: game.platform,
    numberOfPlayers: minPlayers
      ? {
          "@type": "QuantitativeValue",
          minValue: minPlayers,
          maxValue: maxPlayers ?? minPlayers,
        }
      : undefined,
    playMode:
      maxPlayers && maxPlayers > 1
        ? ["SinglePlayer", "CoOp"]
        : minPlayers
          ? "SinglePlayer"
          : undefined,
    publisher: {
      "@type": "Organization",
      name: STUDIO.name,
      url: SITE_URL,
    },
    url: `${SITE_URL}/games/${game.slug}`,
  };

  return (
    <article>
      <script
        type="application/ld+json"
        dangerouslySetInnerHTML={{ __html: JSON.stringify(jsonLd) }}
      />

      <GameHero game={game} />

      {/* ABOUT — the pitch gets its own reading column, the key art sits
          beside it at its real ratio instead of being stretched to match. */}
      <Section>
        <div className="grid items-center gap-10 lg:grid-cols-2 lg:gap-16">
          <Reveal>
            <SectionHeading eyebrow="THE GAME" title="ABOUT" />
            <p className="mt-8 text-base leading-relaxed text-foreground-muted sm:text-lg">
              {game.description}
            </p>
          </Reveal>

          {game.keyArt && (
            <Reveal delay={0.1}>
              <div className="relative aspect-video w-full overflow-hidden rounded-2xl border border-border bg-surface-elevated">
                <Image
                  src={game.keyArt}
                  alt={`${game.title} key art`}
                  fill
                  sizes="(max-width: 1024px) 100vw, 45vw"
                  className="object-cover"
                />
              </div>
            </Reveal>
          )}
        </div>
      </Section>

      {/* PILLARS — what you actually do */}
      <GamePillars pillars={game.pillars} />

      {game.players && <CoopBand players={game.players} />}

      {/* SCREENSHOTS */}
      {game.screenshots.length > 0 && (
        <Section id="gallery" divider width="wide">
          <Reveal>
            <SectionHeading
              eyebrow="GALLERY"
              title="SCREENSHOTS"
              lead="Captured in engine during development. Everything is subject to change."
            />
          </Reveal>
          {/* No `Reveal` here: the gallery deals its own thumbnails out one by
              one, and fading the whole grid in first would animate the same
              pixels twice. */}
          <div className="mt-12">
            <ScreenshotGallery screenshots={game.screenshots} />
          </div>
        </Section>
      )}

      {/* DEVBLOG */}
      {relatedPosts.length > 0 && (
        <Section divider>
          <Reveal>
            <SectionHeading
              eyebrow="DEVBLOG"
              title="LATEST ARTICLES"
              action={
                <ButtonLink href="/devblog" variant="outline">
                  ALL POSTS
                </ButtonLink>
              }
            />
          </Reveal>
          <Reveal delay={0.1} className="mt-12">
            <PostList posts={relatedPosts} as="h3" showGame={false} />
          </Reveal>
        </Section>
      )}

      {/* CLOSING — the page used to end on a list of links. A game in
          development needs one clear ask before the footer. */}
      <div className="relative isolate overflow-hidden border-t border-border">
        <div
          aria-hidden
          className="absolute inset-x-0 top-0 -z-10 h-[70%] bg-[radial-gradient(70%_100%_at_50%_0%,rgba(196,184,150,0.09),transparent_70%)]"
        />
        <Section width="narrow">
          <Reveal>
            <SectionHeading
              eyebrow="STAY CLOSE"
              title={`FOLLOW ${game.title.toUpperCase()}`}
              lead="One mail per major update, covering new builds, milestones and the occasional mistake. Nothing else."
              align="center"
            />
            <div className="mt-10 flex justify-center">
              <Newsletter />
            </div>
            {game.steamUrl && (
              <div className="mt-10 flex justify-center">
                <ButtonLink href={game.steamUrl} variant="outline">
                  WISHLIST ON STEAM
                </ButtonLink>
              </div>
            )}
          </Reveal>
        </Section>
      </div>
    </article>
  );
}
