"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 HhKind = Extract<ConsoleUiKind, "gb" | "gbc" | "gba" | "nds" | "gg">;

export function HandheldShell({
  games,
  kind,
  label,
}: {
  games: Game[];
  kind: HhKind;
  label: string;
}) {
  const dual = kind === "nds";
  const [focus, setFocus] = useState(0);

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

  const list = (
    <GameList
      games={games}
      focus={focus}
      kind={kind}
      onFocus={(i) => {
        if (i !== focus) {
          playUi(kind, "move");
          setFocus(i);
        }
      }}
    />
  );

  return (
    <div className={`hh-shell hh-shell--${kind}`}>
      <div className="hh-body">
        <header className="hh-head">
          <div className="hh-head-links">
            <Link
              href="/setup/ui"
              className="hh-back"
              onClick={() => playUi(kind, "back")}
            >
              ← UI
            </Link>
            <Link
              href="/profiles"
              className="hh-back"
              onClick={() => playUi(kind, "confirm")}
            >
              Profiles
            </Link>
            <Link
              href="/settings"
              className="hh-back"
              onClick={() => playUi(kind, "confirm")}
            >
              Settings
            </Link>
          </div>
          <p className="hh-brand">{label}</p>
          <MuteChip />
        </header>

        {dual ? (
          <div className="hh-dual">
            <div className="hh-screen hh-screen-top">
              <p className="hh-screen-title">Nintendo DS</p>
              <p className="hh-screen-sub">
                {games[focus]?.title ?? `${games.length} games`}
              </p>
              {games[focus]?.cover && (
                // eslint-disable-next-line @next/next/no-img-element
                <img
                  className="hh-preview"
                  src={games[focus].cover}
                  alt=""
                />
              )}
            </div>
            <div className="hh-screen hh-screen-bot">{list}</div>
          </div>
        ) : (
          <div className="hh-screen">
            <p className="hh-screen-title">{label}</p>
            {list}
          </div>
        )}

        <div className="hh-controls" aria-hidden>
          <div className="hh-dpad" />
          <div className="hh-btns">
            <span />
            <span />
          </div>
        </div>
        <p className="hh-hint">↑↓ select · Enter start · Esc change UI</p>
      </div>
    </div>
  );
}

function GameList({
  games,
  focus,
  kind,
  onFocus,
}: {
  games: Game[];
  focus: number;
  kind: HhKind;
  onFocus: (i: number) => void;
}) {
  const focusRef = useRef<HTMLAnchorElement | null>(null);

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

  if (games.length === 0) {
    return (
      <div className="hh-empty">
        <p>No carts.</p>
        <Link href="/load">Open ROM</Link>
      </div>
    );
  }
  return (
    <ul className="hh-list">
      {games.map((g, i) => (
        <li key={g.slug}>
          <Link
            ref={i === focus ? focusRef : undefined}
            href={`/play/${g.slug}`}
            className={`hh-row${i === focus ? " is-focus" : ""}`}
            onMouseEnter={() => onFocus(i)}
            onClick={() => playUi(kind, "confirm")}
          >
            <span className="hh-thumb">
              {g.cover ? (
                // eslint-disable-next-line @next/next/no-img-element
                <img src={g.cover} alt="" />
              ) : (
                "■"
              )}
            </span>
            <span className="hh-row-title">{g.title}</span>
          </Link>
        </li>
      ))}
    </ul>
  );
}
