import { Link } from "@tanstack/react-router";
import { ArrowRight, Trophy } from "lucide-react";
import { getStadiumBoard, type StadiumTeamBoard } from "@/lib/server/api-stadium";
import { downLabel, footballFromPoints } from "@/lib/stadium-scoring";
import { useStadiumLive, type LiveLink } from "@/lib/stadium-live";
import { cn } from "@/lib/utils";

const EMPTY: Awaited<ReturnType<typeof getStadiumBoard>> = {
  match: null,
  home: null,
  away: null,
  plays: [],
  alerts: 0,
  arena: "football",
  roster: [],
};

export function LiveBadge({ link, watching }: { link: LiveLink; watching: number }) {
  const label = link === "socket" ? "Live socket" : link === "poll" ? "Live poll" : "Offline";
  return (
    <span className={cn("stadium-live-badge", `is-${link}`)}>
      <span className="stadium-live-dot" />
      {label}
      <span className="tabular"> · {watching} watching</span>
    </span>
  );
}

export function StadiumLiveStrip() {
  const { board, link, watching } = useStadiumLive("football", EMPTY, { socket: false });
  const home = board.home as StadiumTeamBoard | null;
  const away = board.away as StadiumTeamBoard | null;
  const round = board.match?.round_label ?? "Sweet 16";

  if (!home || !away) {
    return (
      <Link to="/public/stadium" className="stadium-strip mb-6">
        <Trophy className="size-4 text-primary" />
        <div className="min-w-0 flex-1">
          <p className="text-[11px] font-medium tracking-[0.16em] text-primary uppercase">Enter the stadium</p>
          <p className="text-sm text-sidebar-muted">Choose an arena. The public scoreboard is live.</p>
        </div>
        <span className="inline-flex items-center gap-1 text-sm font-semibold text-primary">
          Walk in
          <ArrowRight className="size-3.5" />
        </span>
      </Link>
    );
  }

  const h = footballFromPoints(home.points);
  const a = footballFromPoints(away.points);

  return (
    <Link to="/public/stadium" className="stadium-strip mb-6">
      <LiveBadge link={link} watching={watching} />
      <span className="rounded-full bg-live/20 px-2 py-0.5 text-[10px] font-medium tracking-[0.16em] text-live uppercase">
        {round}
      </span>
      <div className="min-w-0 flex-1">
        <p className="truncate font-display text-lg text-sidebar-foreground">
          {home.name}{" "}
          <span className="tabular text-primary">
            {h.displayScore}–{a.displayScore}
          </span>{" "}
          {away.name}
        </p>
        <p className="truncate text-xs text-sidebar-muted">
          {home.driveYards} yd · {downLabel(h)} · {away.driveYards} yd · {downLabel(a)} · 1 pt = 1 yard
        </p>
      </div>
      <span className="inline-flex items-center gap-1 text-sm font-semibold text-primary">
        Enter stadium
        <ArrowRight className="size-3.5" />
      </span>
    </Link>
  );
}
