import Link from "next/link";
import type { ReactNode } from "react";
import type { GameSummary } from "@/lib/site";
import { FavoriteButton } from "./FavoriteButton";
import { categoryBySlug } from "@/lib/site";

function initials(title: string): string {
  return title
    .split(/\s+/)
    .slice(0, 2)
    .map((w) => w[0] ?? "")
    .join("")
    .toUpperCase();
}

/**
 * Generated placeholder artwork (gradient + initials). Used when a game has
 * no admin-attached thumbnail. Decorative — always aria-hidden.
 */
export function GameArt({
  title,
  className = "aspect-[16/9]",
}: {
  title: string;
  className?: string;
}) {
  return (
    <div
      aria-hidden="true"
      className={`relative flex items-center justify-center bg-gradient-to-br from-brand-600 via-indigo-900 to-slate-900 ${className}`}
    >
      <span className="text-5xl font-black tracking-tight text-white/90">
        {initials(title)}
      </span>
      <span className="absolute inset-0 bg-gradient-to-t from-slate-950/60 to-transparent" />
    </div>
  );
}

/**
 * Game artwork: admin-attached thumbnail when present, otherwise the
 * generated placeholder. Thumbnail URLs are validated (HTTPS or /-relative)
 * on write in the admin panel.
 */
export function GameThumb({
  title,
  thumbnail,
  className = "aspect-[16/9]",
  eager = false,
}: {
  title: string;
  thumbnail?: string | null;
  className?: string;
  /** Above-the-fold artwork (detail page) loads eagerly for LCP. */
  eager?: boolean;
}) {
  if (thumbnail) {
    return (
      // Plain <img>: thumbnails are arbitrary admin-provided external URLs,
      // which next/image cannot optimize without per-host remotePatterns.
      // eslint-disable-next-line @next/next/no-img-element
      <img
        src={thumbnail}
        alt={`${title} artwork`}
        loading={eager ? "eager" : "lazy"}
        fetchPriority={eager ? "high" : "auto"}
        className={`w-full bg-slate-800 object-cover ${className}`}
      />
    );
  }
  return <GameArt title={title} className={className} />;
}

/**
 * Reusable game card (presentational). No ratings, no play counts —
 * never invent popularity data.
 */
export function GameCard({ game }: { game: GameSummary }) {
  const category = categoryBySlug(game.categorySlug);
  return (
    <div className="card-lift group relative flex flex-col overflow-hidden rounded-2xl border border-slate-800 bg-slate-900">
      <div className="absolute top-3 right-3 z-10">
        <FavoriteButton slug={game.slug} title={game.title} />
      </div>
      <Link
        href={`/games/${game.slug}`}
        className="flex flex-1 flex-col"
        aria-label={`View details for ${game.title}`}
      >
        <GameThumb title={game.title} thumbnail={game.thumbnail} />
        <div className="flex flex-1 flex-col gap-2 p-4">
          <div className="flex items-center gap-2">
            {category ? (
              <span className="rounded-full bg-slate-800 px-2.5 py-0.5 text-xs font-medium text-slate-300">
                {category.name}
              </span>
            ) : null}
            {game.trending ? (
              <span className="rounded-full bg-brand-600/20 px-2.5 py-0.5 text-xs font-semibold text-brand-300">
                Trending
              </span>
            ) : null}
          </div>
          <h3 className="font-semibold text-white group-hover:text-brand-300">
            {game.title}
          </h3>
          <p className="line-clamp-2 text-sm text-slate-400">{game.description}</p>
          {typeof game.developer === "string" && game.developer ? (
            <p className="mt-auto pt-2 text-xs text-slate-500">
              by {game.developer}
            </p>
          ) : null}
        </div>
      </Link>
    </div>
  );
}

/** Responsive grid wrapper for game cards. */
export function GameGrid({ children }: { children: ReactNode }) {
  return (
    <div className="grid grid-cols-1 gap-5 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4">
      {children}
    </div>
  );
}

/** Skeleton placeholders shown while game lists load. */
export function GameCardSkeleton() {
  return (
    <div
      aria-hidden="true"
      className="overflow-hidden rounded-2xl border border-slate-800 bg-slate-900"
    >
      <div className="skeleton aspect-[16/9]" />
      <div className="space-y-2 p-4">
        <div className="skeleton h-4 w-2/3 rounded" />
        <div className="skeleton h-3 w-full rounded" />
        <div className="skeleton h-3 w-4/5 rounded" />
      </div>
    </div>
  );
}
