import Link from "next/link";
import { matchesByDate, matchPhase, type MatchPhase } from "@/lib/schedule";
import { getPredictions, getCrowd } from "@/lib/mockData";
import { dateHeading, timeOnly } from "@/lib/format";
import type { Match } from "@/lib/types";
import TeamFlag from "./TeamFlag";

const STROKE = "#94FBE0"; // 일정 텍스트·선택 아웃라인 스트로크 컬러

const PHASE_META: Record<MatchPhase, { label: string; cls: string }> = {
  open: { label: "투표 중", cls: "border-[#94FBE0] text-[#94FBE0]" },
  scheduled: { label: "오픈 예정", cls: "border-[var(--line-d)] text-[var(--ink-muted)]" },
  locked: { label: "투표 마감", cls: "border-[var(--line-d)] text-[var(--ink-muted)]" },
  finished: { label: "종료", cls: "border-white/15 text-white/55" },
};

export default function ScheduleBoard() {
  const groups = matchesByDate();
  return (
    <section className="mt-6">
      <div className="mb-3 flex items-baseline gap-2.5">
        <h2 className="shrink-0 text-[22px] font-extrabold">전체 일정</h2>
        <span className="whitespace-nowrap text-[12px] text-white/55">
          투표하고 싶은 경기를 선택해주세요
        </span>
      </div>

      <div className="flex flex-col gap-5">
        {groups.map((g) => (
          <div key={g.date}>
            <div className="mb-2 text-[13px] font-bold" style={{ color: STROKE }}>
              {dateHeading(g.date)}
            </div>
            <div className="flex flex-col gap-2.5">
              {g.matches.map((m) => (
                <MatchCard key={m.matchId} match={m} />
              ))}
            </div>
          </div>
        ))}
      </div>
    </section>
  );
}

function MatchCard({ match }: { match: Match }) {
  const phase = matchPhase(match);
  const meta = PHASE_META[phase];
  const preds = getPredictions(match);
  const crowd = getCrowd(match);

  // AI 픽 갈림 요약
  const tally = { a: 0, d: 0, b: 0 };
  for (const p of preds) {
    if (p.outcome === "TEAM_A_WIN") tally.a++;
    else if (p.outcome === "DRAW") tally.d++;
    else tally.b++;
  }
  const split: string[] = [];
  if (tally.a) split.push(`${match.teamA.shortName} ${tally.a}`);
  if (tally.d) split.push(`무 ${tally.d}`);
  if (tally.b) split.push(`${match.teamB.shortName} ${tally.b}`);

  return (
    <Link
      href={`/match/${match.matchId}`}
      className="block rounded-2xl border-2 border-[#94FBE0]/45 bg-[#171b21] p-4 transition active:scale-[0.99] hover:border-[#94FBE0]"
    >
      <div className="flex items-center justify-between text-[11px]">
        <span className="font-mono font-bold text-white/70">
          {timeOnly(match.kickoffKst)} <span className="text-white/40">KST</span> · {match.roundLabel}
        </span>
        <span className={`rounded-md border px-2 py-0.5 font-semibold ${meta.cls}`}>
          {meta.label}
        </span>
      </div>

      <div className="mt-3 grid grid-cols-[1fr_auto_1fr] items-center gap-2">
        <div className="flex items-center gap-2">
          <TeamFlag team={match.teamA} className="h-6 w-9 shrink-0" />
          <span className="truncate text-[15px] font-extrabold">{match.teamA.shortName}</span>
        </div>
        <span className="font-impact text-[18px] italic text-[#94FBE0]">VS</span>
        <div className="flex items-center justify-end gap-2">
          <span className="truncate text-right text-[15px] font-extrabold">{match.teamB.shortName}</span>
          <TeamFlag team={match.teamB} className="h-6 w-9 shrink-0" />
        </div>
      </div>

      <div className="mt-3 flex items-center justify-between text-[11px] font-bold text-[#F4F3FE]">
        <span>
          <span className="font-semibold text-white/55">AI 픽</span> {split.join(" · ")}
        </span>
        <span className="flex items-center gap-2">
          <span>{crowd.total.toLocaleString()}명 참여</span>
          <span className="text-[#94FBE0]">→</span>
        </span>
      </div>
    </Link>
  );
}
