"use client";

import { useEffect, useState } from "react";
import Link from "next/link";
import { useProfile } from "@/lib/profile/context";
import { getHistoryForProfile } from "@/lib/profile/db";
import { getGameBySlug } from "@/lib/games";
import type { Game } from "@/lib/types";
import { GameCard } from "@/components/GameCard";

export function ContinueRow() {
  const { ready, profile, account } = useProfile();
  const [slugs, setSlugs] = useState<string[]>([]);
  const [liveBySlug, setLiveBySlug] = useState<Map<string, Game> | null>(null);
  const show = account?.settings?.showContinueRow !== false;

  useEffect(() => {
    if (!ready || !profile || !show) return;
    void getHistoryForProfile(profile.id).then((rows) => {
      setSlugs(
        rows
          .filter((r) => r.totalSeconds > 0 || r.sessions > 0)
          .slice(0, 8)
          .map((r) => r.gameSlug),
      );
    });
  }, [ready, profile, show]);

  useEffect(() => {
    void fetch("/api/contribute")
      .then((r) => r.json())
      .then((data: { all?: Game[] }) => {
        const map = new Map<string, Game>();
        for (const g of data.all ?? []) map.set(g.slug, g);
        setLiveBySlug(map);
      })
      .catch(() => setLiveBySlug(null));
  }, []);

  if (!show) return null;

  const games = slugs
    .map((s) => liveBySlug?.get(s) ?? getGameBySlug(s))
    .filter((g): g is Game => Boolean(g));

  if (games.length === 0) return null;

  return (
    <div className="mt-12">
      <div className="mb-5 flex items-end justify-between gap-4">
        <div>
          <h2 className="font-display text-xl tracking-wide text-foreground sm:text-2xl">
            Continue playing
          </h2>
          <p className="mt-1 text-sm text-muted">Pick up where you left off</p>
        </div>
        <Link href="/#library" className="btn-ghost hidden sm:inline-flex">
          Library
        </Link>
      </div>
      <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
        {games.map((g) => (
          <GameCard key={g.slug} game={g} />
        ))}
      </div>
    </div>
  );
}
