"use client";

import { useEffect, useState } from "react";
import { GameCard, GameGrid } from "@/components/game/GameCard";
import { EmptyState } from "@/components/ui/Section";
import type { PublicGame } from "@/lib/games";
import { MAX_RECENTLY_PLAYED } from "@/lib/site";
import {
  clearRecentlyPlayed,
  getRecentlyPlayedSnapshot,
  onRecentlyPlayedChange,
} from "@/lib/storage";

/**
 * Client-rendered history grid, most recent first, with Clear History.
 * Entries whose games left the catalog are silently dropped.
 */
export function RecentlyPlayedList({ games }: { games: PublicGame[] }) {
  const [slugs, setSlugs] = useState<string[] | null>(() =>
    typeof window === "undefined"
      ? null
      : getRecentlyPlayedSnapshot().map((e) => e.slug),
  );

  useEffect(
    () =>
      onRecentlyPlayedChange(() =>
        setSlugs(getRecentlyPlayedSnapshot().map((e) => e.slug)),
      ),
    [],
  );

  if (slugs === null) {
    return (
      <GameGrid>
        {Array.from({ length: 4 }, (_, i) => (
          <div
            key={i}
            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>
          </div>
        ))}
      </GameGrid>
    );
  }

  const bySlug = new Map(games.map((g) => [g.slug, g]));
  const played = slugs
    .map((slug) => bySlug.get(slug))
    .filter((g): g is PublicGame => g !== undefined);

  if (played.length === 0) {
    return (
      <EmptyState
        title="Nothing played yet"
        message="Games you play will show up here automatically — stored only in this browser."
        actionHref="/games"
        actionLabel="Find something to play"
      />
    );
  }

  return (
    <div aria-live="polite">
      <div className="mb-4 flex flex-wrap items-center justify-between gap-3">
        <p className="text-sm text-slate-400">
          Your last {MAX_RECENTLY_PLAYED} games on this device.
        </p>
        <button
          type="button"
          onClick={() => {
            clearRecentlyPlayed();
            setSlugs([]);
          }}
          className="inline-flex h-9 items-center rounded-xl border border-slate-700 bg-slate-900 px-3.5 text-sm font-semibold text-slate-200 transition-colors hover:border-red-500/50 hover:text-red-300"
        >
          Clear History
        </button>
      </div>
      <GameGrid>
        {played.map((game) => (
          <GameCard key={game.slug} game={game} />
        ))}
      </GameGrid>
    </div>
  );
}
