import { useEffect, useState } from "react";
import Hero from "@/components/Hero";
import Footer from "@/components/Footer";
import { useLang } from "@/lib/useLang";
import { getLeaderboard } from "@/lib/api";
import type { Leaderboard as LB } from "@/lib/types";

// L3. 리더보드 — 누적 포인트 1위. 데이터 없으면 안내 stub.
export default function Leaderboard() {
  const lang = useLang();
  const [data, setData] = useState<LB | null>(null);

  useEffect(() => {
    let alive = true;
    getLeaderboard()
      .then((d) => alive && setData(d))
      .catch(() => alive && setData({ standings: [], scoredMatches: 0 }));
    return () => {
      alive = false;
    };
  }, []);

  const empty = !data || data.standings.length === 0;

  return (
    <main className="shell">
      <Hero back lang={lang} />
      <section className="mt-8">
        <div className="font-impact text-[28px] text-[var(--green)]">LEADERBOARD</div>

        {empty ? (
          <div className="mt-4 rounded-2xl border border-[var(--line-d)] bg-[var(--bg2)] p-8 text-center">
            <p className="text-[15px] font-bold">
              {lang === "en" ? "Rankings open soon" : "랭킹은 곧 공개됩니다"}
            </p>
            <p className="mt-2 text-[13px] leading-relaxed text-[var(--ink-muted)]">
              {lang === "en"
                ? "Points accumulate each match — the overall #1 wins ₩1,000,000."
                : "매 경기 누적 점수로 순위를 매기고, 끝까지 가장 잘 맞힌 한 분께 최종 100만원을 드립니다."}
            </p>
          </div>
        ) : (
          <div className="mt-4 overflow-hidden rounded-2xl border border-[var(--line-d)]">
            {data!.standings.map((s) => (
              <div
                key={s.rank}
                className="flex items-center justify-between border-b border-[var(--line-d)] px-4 py-3 last:border-b-0"
              >
                <div className="flex items-center gap-3">
                  <span className="w-6 text-center font-impact text-[18px] text-[var(--green)]">
                    {s.rank}
                  </span>
                  <span className="text-[14px] font-bold">{s.emailMasked}</span>
                </div>
                <div className="text-right">
                  <span className="text-[16px] font-extrabold">{s.totalPoints}</span>
                  <span className="ml-1 text-[11px] text-[var(--ink-muted)]">
                    {lang === "en" ? "pts" : "점"}
                  </span>
                  <span className="ml-2 text-[11px] text-[var(--ink-muted)]">
                    {lang === "en"
                      ? `${s.exactCount} exact · ${s.matchesPlayed} played`
                      : `정확 ${s.exactCount} · ${s.matchesPlayed}경기`}
                  </span>
                </div>
              </div>
            ))}
          </div>
        )}
      </section>
      <Footer lang={lang} />
    </main>
  );
}
