import Image from "next/image";
import { notFound } from "next/navigation";
import type { Metadata } from "next";
import { ScoreBadge } from "@/components/ScoreBadge";
import { TrailerFacade } from "@/components/TrailerFacade";
import { GameCard } from "@/components/GameCard";
import { getGameBySlug, getSimilarGames } from "@/lib/queries";

export async function generateMetadata({ params }: { params: { slug: string } }): Promise<Metadata> {
  const game = await getGameBySlug(params.slug);
  if (!game) return {};
  return {
    title: game.meta_title || game.title,
    description: game.meta_description || game.verdict_short || undefined,
    openGraph: game.og_image ? { images: [game.og_image] } : undefined,
  };
}

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

  const similar = await getSimilarGames(game);

  // Review schema — chosen deliberately over AggregateRating, since the site
  // has no user-rating system and a fake aggregate would risk a policy penalty.
  const reviewSchema = {
    "@context": "https://schema.org",
    "@type": "Review",
    itemReviewed: {
      "@type": "VideoGame",
      name: game.title,
      applicationCategory: "Game",
      operatingSystem: (game.platforms ?? []).map((p) => p.name).join(", "),
    },
    reviewRating: {
      "@type": "Rating",
      ratingValue: game.editor_score,
      bestRating: 10,
      worstRating: 0,
    },
    author: { "@type": "Organization", name: "Backlog" },
    datePublished: game.created_at,
    dateModified: game.last_verified_date ?? game.updated_at,
  };

  const faqSchema = game.faq?.length
    ? {
        "@context": "https://schema.org",
        "@type": "FAQPage",
        mainEntity: game.faq.map((f) => ({
          "@type": "Question",
          name: f.question,
          acceptedAnswer: { "@type": "Answer", text: f.answer },
        })),
      }
    : null;

  return (
    <div className="mx-auto max-w-4xl px-4 py-8">
      {/* eslint-disable-next-line react/no-danger */}
      <script type="application/ld+json" dangerouslySetInnerHTML={{ __html: JSON.stringify(reviewSchema) }} />
      {faqSchema && (
        // eslint-disable-next-line react/no-danger
        <script type="application/ld+json" dangerouslySetInnerHTML={{ __html: JSON.stringify(faqSchema) }} />
      )}

      {/* Cover + screenshot carousel */}
      <div className="flex gap-3 overflow-x-auto">
        {[game.cover_image, ...game.screenshots].filter(Boolean).map((src, i) => (
          <div key={i} className="relative h-52 w-96 shrink-0 overflow-hidden rounded-lg bg-ink-800">
            <Image src={src as string} alt="" fill sizes="384px" className="object-cover" priority={i === 0} />
          </div>
        ))}
      </div>

      {/* Trailer */}
      {game.trailer_enabled && game.trailer_youtube_id && (
        <div className="mt-6">
          <TrailerFacade youtubeId={game.trailer_youtube_id} title={game.title} />
        </div>
      )}

      {/* Header: title, score, verdict, quick specs */}
      <div className="mt-8 flex flex-wrap items-start justify-between gap-4">
        <div>
          <h1 className="font-display text-3xl font-semibold sm:text-4xl">{game.title}</h1>
          {game.verdict_short && <p className="mt-2 max-w-prose text-bone-100/80">{game.verdict_short}</p>}
        </div>
        {game.editor_score !== null && <ScoreBadge score={game.editor_score} size="lg" />}
      </div>

      <dl className="mt-6 grid grid-cols-2 gap-x-6 gap-y-3 rounded-lg border border-ink-700/60 bg-ink-900 p-4 text-sm sm:grid-cols-4">
        <Spec label="Platforms" value={(game.platforms ?? []).map((p) => p.name).join(", ") || "—"} />
        <Spec label="Genre" value={(game.genres ?? []).map((g) => g.name).join(", ") || "—"} />
        <Spec label="Developer" value={game.developer ?? "—"} />
        <Spec label="Release date" value={game.release_date ?? "—"} />
        <Spec label="Price" value={game.price_type ?? "—"} />
        <Spec label="Age rating" value={game.age_rating ?? "—"} />
      </dl>

      {/* Sections in required order */}
      <article className="prose-body mt-10 max-w-prose">
        <Section title="Overview">{game.overview}</Section>
        <Section title="Gameplay & Mechanics">{game.gameplay}</Section>

        {(game.pros.length > 0 || game.cons.length > 0) && (
          <section className="my-8 grid gap-6 sm:grid-cols-2">
            <div>
              <h2 className="font-display text-xl font-semibold text-platform-android">Pros</h2>
              <ul className="mt-2 space-y-1 text-bone-100/90">
                {game.pros.map((p, i) => (
                  <li key={i}>+ {p}</li>
                ))}
              </ul>
            </div>
            <div>
              <h2 className="font-display text-xl font-semibold text-bone-100/60">Cons</h2>
              <ul className="mt-2 space-y-1 text-bone-100/90">
                {game.cons.map((c, i) => (
                  <li key={i}>– {c}</li>
                ))}
              </ul>
            </div>
          </section>
        )}

        <Section title="Who It's For">{game.who_its_for}</Section>

        {game.tips?.length > 0 && (
          <section className="my-8">
            <h2 className="font-display text-xl font-semibold">Tips & Tricks</h2>
            <div className="mt-3 space-y-4">
              {game.tips.map((t, i) => (
                <div key={i}>
                  <h3 className="font-medium text-bone-50">{t.heading}</h3>
                  <p className="mt-1 text-bone-100/80">{t.body}</p>
                </div>
              ))}
            </div>
          </section>
        )}

        {(game.system_requirements?.min || game.system_requirements?.recommended) && (
          <section className="my-8">
            <h2 className="font-display text-xl font-semibold">System Requirements</h2>
            <div className="mt-3 grid gap-4 sm:grid-cols-2">
              <SpecTable title="Minimum" spec={game.system_requirements.min} />
              <SpecTable title="Recommended" spec={game.system_requirements.recommended} />
            </div>
          </section>
        )}

        {game.faq?.length > 0 && (
          <section className="my-8">
            <h2 className="font-display text-xl font-semibold">FAQ</h2>
            <div className="mt-3 space-y-4">
              {game.faq.map((f, i) => (
                <div key={i}>
                  <h3 className="font-medium text-bone-50">{f.question}</h3>
                  <p className="mt-1 text-bone-100/80">{f.answer}</p>
                </div>
              ))}
            </div>
          </section>
        )}
      </article>

      {game.last_verified_date && (
        <p className="mt-6 text-xs text-bone-100/50">Last verified {game.last_verified_date}</p>
      )}

      {/* Similar games — internal linking */}
      {similar.length > 0 && (
        <section className="mt-14">
          <h2 className="mb-3 font-display text-xl font-semibold">Similar games</h2>
          <div className="flex gap-4 overflow-x-auto pb-2">
            {similar.map((g: any) => (
              <GameCard key={g.id} game={g} />
            ))}
          </div>
        </section>
      )}
    </div>
  );
}

function Spec({ label, value }: { label: string; value: string }) {
  return (
    <div>
      <dt className="text-bone-100/50">{label}</dt>
      <dd className="font-medium text-bone-50">{value}</dd>
    </div>
  );
}

function Section({ title, children }: { title: string; children: string | null }) {
  if (!children) return null;
  return (
    <section className="my-8">
      <h2 className="font-display text-xl font-semibold">{title}</h2>
      <p className="mt-2 whitespace-pre-line">{children}</p>
    </section>
  );
}

function SpecTable({ title, spec }: { title: string; spec?: Record<string, string | undefined> }) {
  if (!spec) return null;
  return (
    <div className="rounded-lg border border-ink-700/60 p-4 text-sm">
      <h3 className="font-medium text-bone-50">{title}</h3>
      <dl className="mt-2 space-y-1">
        {Object.entries(spec)
          .filter(([, v]) => v)
          .map(([k, v]) => (
            <div key={k} className="flex justify-between gap-4">
              <dt className="uppercase text-bone-100/50">{k}</dt>
              <dd className="text-right text-bone-100/90">{v}</dd>
            </div>
          ))}
      </dl>
    </div>
  );
}
