"use client";

import Link from "next/link";
import { useEffect, useRef, useState } from "react";
import type { Game } from "@/lib/types";
import type { ConsoleUiKind } from "@/lib/consoleThemes";
import { playUi } from "@/lib/consoleUiAudio";
import { MuteChip } from "./MuteChip";

type CartKind = Extract<
  ConsoleUiKind,
  | "nes"
  | "snes"
  | "n64"
  | "genesis"
  | "sms"
  | "saturn"
  | "segacd"
  | "atari2600"
  | "vb"
>;

export function CartridgeShelf({
  games,
  kind,
  label,
  tagline,
}: {
  games: Game[];
  kind: CartKind;
  label: string;
  tagline: string;
}) {
  const [focus, setFocus] = useState(0);
  const focusRef = useRef<HTMLAnchorElement | null>(null);

  useEffect(() => {
    focusRef.current?.scrollIntoView({
      block: "nearest",
      inline: "nearest",
      behavior: "smooth",
    });
  }, [focus]);

  useEffect(() => {
    const onKey = (e: KeyboardEvent) => {
      if (!games.length) return;
      if (e.key === "ArrowRight" || e.key === "ArrowDown") {
        e.preventDefault();
        playUi(kind, "move");
        setFocus((f) => (f + 1) % games.length);
      }
      if (e.key === "ArrowLeft" || e.key === "ArrowUp") {
        e.preventDefault();
        playUi(kind, "move");
        setFocus((f) => (f - 1 + games.length) % games.length);
      }
      if (e.key === "Enter") {
        e.preventDefault();
        playUi(kind, "confirm");
        window.location.href = `/play/${games[focus].slug}`;
      }
      if (e.key === "Escape") {
        playUi(kind, "back");
        window.location.href = "/setup/ui";
      }
    };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [focus, games, kind]);

  return (
    <div className={`cart-shell cart-shell--${kind}`}>
      <div className="cart-scanlines" aria-hidden />
      <div className="cart-bezel">
        <header className="cart-head">
          <div className="cart-head-links">
            <Link
              href="/setup/ui"
              className="cart-back"
              onClick={() => playUi(kind, "back")}
            >
              ← UI
            </Link>
            <Link
              href="/profiles"
              className="cart-back"
              onClick={() => playUi(kind, "confirm")}
            >
              Profiles
            </Link>
            <Link
              href="/settings"
              className="cart-back"
              onClick={() => playUi(kind, "confirm")}
            >
              Settings
            </Link>
          </div>
          <div>
            <p className="cart-kicker">{tagline}</p>
            <h1 className="cart-title">{label}</h1>
          </div>
          <MuteChip className="cart-mute" />
        </header>

        {games.length === 0 ? (
          <div className="cart-empty">
            <p>No cartridges loaded.</p>
            <Link href="/load" className="cart-cta">
              Open a ROM
            </Link>
          </div>
        ) : (
          <div className="cart-rail">
            {games.map((g, i) => (
              <Link
                key={g.slug}
                ref={i === focus ? focusRef : undefined}
                href={`/play/${g.slug}`}
                className={`cart-slot${i === focus ? " is-focus" : ""}`}
                onMouseEnter={() => {
                  if (i !== focus) {
                    playUi(kind, "move");
                    setFocus(i);
                  }
                }}
                onClick={() => playUi(kind, "confirm")}
              >
                <div className="cart-label">
                  {g.cover ? (
                    // eslint-disable-next-line @next/next/no-img-element
                    <img src={g.cover} alt="" />
                  ) : (
                    <span>{g.title}</span>
                  )}
                </div>
                <p className="cart-name">{g.title}</p>
              </Link>
            ))}
          </div>
        )}
        <p className="cart-hint">
          Arrows move · Enter start · Esc change UI · Scroll for more
        </p>
      </div>
    </div>
  );
}
