import { useEffect, useState } from "react";
import { Link, useParams } from "react-router-dom";
import Hero from "@/components/Hero";
import MatchupHUD from "@/components/MatchupHUD";
import Arena from "@/components/Arena";
import Comments from "@/components/Comments";
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}
      />

      {/* 한마디(댓글) — 전 경기 노출 (경기 상태 무관) */}
      <Comments matchId={match.matchId} lang={lang} />

      {/* 하단 CTA — 전체 일정으로(다른 경기 투표). ADO2 버튼과 동일 사양(퍼플 #A65EFF) */}
      <Link
        to={lang === "en" ? "/?lang=en" : "/"}
        className="mt-7 flex items-center justify-center gap-1.5 rounded-full bg-[#A65EFF] px-6 py-3 text-[15px] font-extrabold text-white transition active:scale-[0.99]"
        style={{ boxShadow: "0 10px 28px rgba(166,94,255,0.40)" }}
      >
        {t.moreMatches}
        <span aria-hidden>→</span>
      </Link>

      <Footer lang={lang} />
    </main>
  );
}
