import Link from 'next/link';
import { prisma } from '@/lib/db/client';
import { GameCard } from '@/components/games/GameCard';
import { CTA } from '@/components/games/CTA';

export const revalidate = 900;

const PLAY_URL = process.env.GAMESJI_PLAY_URL ?? 'https://gamesji.com/games';

async function getRails() {
  const select = {
    slug: true,
    name: true,
    coverUrl: true,
    genres: true,
    releaseDate: true,
    igdbRating: true,
  } as const;

  const [trending, newest, upcoming, totalCount] = await Promise.all([
    prisma.game.findMany({ where: { status: 'PUBLISHED' }, orderBy: { igdbRatingCount: 'desc' }, take: 12, select }),
    prisma.game.findMany({
      where: { status: 'PUBLISHED', releaseDate: { lte: new Date() } },
      orderBy: { releaseDate: 'desc' },
      take: 6,
      select,
    }),
    prisma.game.findMany({
      where: { status: 'PUBLISHED', releaseDate: { gt: new Date() } },
      orderBy: { releaseDate: 'asc' },
      take: 6,
      select,
    }),
    prisma.game.count({ where: { status: 'PUBLISHED' } }),
  ]);

  return { trending, newest, upcoming, totalCount };
}

export default async function HomePage() {
  const { trending, newest, upcoming, totalCount } = await getRails();

  return (
    <div>
      <section className="hud-panel mx-4 mt-6 flex flex-col items-start gap-5 px-6 py-14 sm:mx-6 sm:px-12 lg:mx-auto lg:max-w-7xl">
        <span className="chip !border-signal !text-signal">
          <span className="h-1.5 w-1.5 bg-signal" aria-hidden /> {totalCount.toLocaleString()} games tracked
        </span>
        <h1 className="max-w-3xl text-4xl font-bold leading-tight sm:text-6xl">
          A gaming reference that <span className="text-signal">updates itself</span>
        </h1>
        <p className="prose-content max-w-xl text-base sm:text-lg">
          Release info, guides, and FAQs for games across every platform — sourced from official APIs,
          written fresh, and checked by an automated quality gate before it ever goes live. No scraped
          articles, no filler.
        </p>
        <div className="flex flex-wrap gap-3">
          <Link href="/games" className="btn-secondary">
            Browse the Directory
          </Link>
          <a href={PLAY_URL} className="btn-primary">
            🎮 Play Free Games on GamesJi
          </a>
        </div>
      </section>

      <Rail title="Trending Now" games={trending} viewAllHref="/games?sort=trending" />
      <Rail title="Recently Released" games={newest} viewAllHref="/games?sort=newest" />
      {upcoming.length > 0 && <Rail title="Upcoming" games={upcoming} viewAllHref="/games?sort=upcoming" />}

      <div className="mx-4 my-16 sm:mx-6 lg:mx-auto lg:max-w-7xl">
        <CTA gameName="your favorite games" playUrl={PLAY_URL} />
      </div>
    </div>
  );
}

function Rail({
  title,
  games,
  viewAllHref,
}: {
  title: string;
  games: { slug: string; name: string; coverUrl: string | null; genres: string[]; releaseDate: Date | null; igdbRating: number | null }[];
  viewAllHref: string;
}) {
  if (games.length === 0) return null;
  return (
    <section className="mx-4 mt-12 sm:mx-6 lg:mx-auto lg:max-w-7xl">
      <div className="mb-3 flex items-center justify-between">
        <h2 className="stat-label !text-signal">{title}</h2>
        <Link href={viewAllHref} className="font-mono text-xs uppercase tracking-wide text-haze hover:text-signal">
          View all →
        </Link>
      </div>
      <div className="grid grid-cols-2 gap-3 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-6">
        {games.map((g) => (
          <GameCard key={g.slug} game={g} />
        ))}
      </div>
    </section>
  );
}
