import { useEffect, useState } from "react";
import { useParams } from "react-router-dom";
import Hero from "@/components/Hero";
import MatchupHUD from "@/components/MatchupHUD";
import Arena from "@/components/Arena";
import Footer from "@/components/Footer";
import { dict, teamShort } from "@/lib/i18n";
import { useLang } from "@/lib/useLang";
import { getMatch, matchUrl, ApiError } from "@/lib/api";
import type { Match } from "@/lib/types";

// L2. 경기 상세(대결) 페이지
export default function MatchDetail() {
  const { matchId = "" } = useParams();
  const lang = useLang();
  const t = dict(lang);
  const [match, setMatch] = useState<Match | null>(null);
  const [notFound, setNotFound] = useState(false);

  useEffect(() => {
    let alive = true;
    setMatch(null);
    setNotFound(false);
    getMatch(matchId, lang)
      .then((m) => alive && setMatch(m))
      .catch((e) => {
        if (!alive) return;
        if (e instanceof ApiError && e.status === 404) setNotFound(true);
        else setNotFound(true);
      });
    return () => {
      alive = false;
    };
  }, [matchId, lang]);

  if (notFound) {
    return (
      <main className="shell">
        <Hero back lang={lang} />
        <p className="mt-10 text-center text-[15px] font-bold text-white/70">
          {lang === "en" ? "Match not found." : "경기를 찾을 수 없습니다."}
        </p>
        <Footer lang={lang} />
      </main>
    );
  }

  if (!match) {
    return (
      <main className="shell">
        <Hero back lang={lang} />
        <p className="mt-10 text-center text-[14px] text-white/45">…</p>
      </main>
    );
  }

  const aShort = teamShort(match.teamA, lang);
  const bShort = teamShort(match.teamB, lang);
  const hook = lang === "en" ? t.hook(aShort, bShort) : match.hookText;
  const url = matchUrl(match.matchId);

  return (
    <main className="shell">
      <Hero
        back
        lang={lang}
        share={{
          url,
          title: `${aShort} vs ${bShort} — TriplePick`,
          text:
            lang === "en"
              ? `${hook} — see all 3 AI picks and make yours!`
              : `${hook} — AI 셋의 예측을 보고 너의 픽을 찍어봐!`,
        }}
      />

      {/* 경기별 후킹 카피 (한 줄) */}
      <h1 className="mt-6 flex items-center justify-center gap-2 whitespace-nowrap text-[19px] font-extrabold leading-snug">
        <span className="text-[var(--green)]">⫽</span>
        {hook}
        <span className="text-[var(--green)]">⫽</span>
      </h1>

      <MatchupHUD match={match} lang={lang} />
      <Arena
        match={match}
        predictions={match.predictions}
        crowd={
          match.crowd ?? {
            matchId: match.matchId,
            total: 0,
            teamAWin: 0,
            draw: 0,
            teamBWin: 0,
          }
        }
        shareUrl={url}
        lang={lang}
      />
      <Footer lang={lang} />
    </main>
  );
}
