import { MatchHistoryPanel } from '@/components/MatchHistoryPanel';
import { ResultRefreshButton } from '@/components/ResultRefreshButton';
import { ResultRequestWatcher } from '@/components/ResultRequestWatcher';
import { getSnapshot, getSnapshotMatches } from '@/lib/api';
import { getChampionDisplayNames } from '@/lib/champion-labels';
import { buildSummonerDetailPath } from '@/lib/routes';
import {
  getChampionSplashUrl,
  getChampionSquareUrl,
  getProfileIconUrl,
} from '@/lib/lol-assets';

export async function SnapshotResultPageContent({
  snapshotId,
  requestId = null,
  refreshError = null,
  stablePath = null,
}: {
  snapshotId: string;
  requestId?: string | null;
  refreshError?: string | null;
  stablePath?: string | null;
}) {
  const snapshot = await getSnapshot(snapshotId);
  const matchesResponse = await getSnapshotMatches(snapshotId, 0, 20).catch(() => null);
  const recentMatches = matchesResponse?.items ?? snapshot.recentMatches ?? [];
  const totalMatchCount =
    snapshot.totalMatchCount ?? matchesResponse?.total ?? recentMatches.length;

  const splashUrl = getChampionSplashUrl(snapshot.primaryChampionName);
  const squareUrl = getChampionSquareUrl(snapshot.primaryChampionName);
  const profileIconUrl = getProfileIconUrl(snapshot.profileIconId);

  const championDisplayNames = await getChampionDisplayNames([
    snapshot.primaryChampionName,
    ...recentMatches.map((match) => match.championName),
  ]);

  const winCount = recentMatches.filter((match) => match.win).length;
  const lossCount = Math.max(0, recentMatches.length - winCount);
  const winRate = Math.round((winCount / Math.max(1, recentMatches.length)) * 100);
  const recentRecord = `${winCount}승 ${lossCount}패`;
  const currentSoloRank = snapshot.currentRanks?.solo ?? null;
  const currentFlexRank = snapshot.currentRanks?.flex ?? null;
  const soloRankLabel = formatRankLabel(currentSoloRank);
  const soloTierIcon = getTierIconUrl(currentSoloRank?.tier ?? null);
  const soloLeaguePoints = currentSoloRank?.leaguePoints ?? null;
  const soloRecord = currentSoloRank
    ? `${currentSoloRank.wins}승 ${currentSoloRank.losses}패`
    : '랭크 정보 없음';
  const soloWinRate = currentSoloRank
    ? calculateWinRate(currentSoloRank.wins, currentSoloRank.losses)
    : null;
  const flexRankLabel = formatRankLabel(currentFlexRank);
  const flexTierIcon = getTierIconUrl(currentFlexRank?.tier ?? null);
  const flexRecord = currentFlexRank
    ? `${currentFlexRank.wins}승 ${currentFlexRank.losses}패`
    : '배치 전 또는 정보 없음';
  const flexWinRate = currentFlexRank
    ? calculateWinRate(currentFlexRank.wins, currentFlexRank.losses)
    : null;
  const ggtiTokens = splitGgtiType(snapshot.ggtiType);
  const primaryGgtiType = ggtiTokens[0] ?? 'CARRY';
  const ggtiCode = buildGgtiCode(ggtiTokens);
  const ggtiAccent = getGgtiAccent(primaryGgtiType);
  const dominantTraits = buildDominantTraitRows(snapshot.traitScores);
  const resolvedStablePath =
    stablePath ??
    (snapshot.gameName && snapshot.tagLine
      ? buildSummonerDetailPath(snapshot.gameName, snapshot.tagLine)
      : null);
  const lastUpdated = snapshot.analyzedAt
    ? new Intl.DateTimeFormat('ko-KR', {
        year: 'numeric',
        month: 'numeric',
        day: 'numeric',
        hour: '2-digit',
        minute: '2-digit',
        hour12: false,
      }).format(new Date(snapshot.analyzedAt))
    : '갱신 정보 없음';

  return (
    <main className="pb-20">
      <section className="bg-[#2a2c36]">
        <div className="mx-auto max-w-[1416px] px-3 py-6 sm:px-4 sm:py-10">
          <div className="relative overflow-hidden rounded-t-[8px] border border-b-0 border-[#393d4d] bg-[#2f323d]">
            {splashUrl ? (
              <div
                className="absolute inset-0 opacity-[0.14]"
                style={{
                  backgroundImage: `url(${splashUrl})`,
                  backgroundPosition: 'center',
                  backgroundSize: 'cover',
                }}
              />
            ) : null}
            <div className="absolute inset-0 bg-[linear-gradient(180deg,rgba(47,50,61,0.88),rgba(47,50,61,0.97))]" />

            <div className="relative grid gap-6 px-4 py-6 sm:px-6 sm:py-7 lg:grid-cols-[136px_minmax(0,1fr)] lg:items-start">
              <div className="relative mx-auto w-[132px] self-start lg:mx-0">
                <div className="overflow-hidden rounded-[18px] border border-white/10 shadow-[0_18px_40px_rgba(0,0,0,0.28)]">
                  {profileIconUrl ? (
                    <img
                      src={profileIconUrl}
                      alt={`${snapshot.gameName ?? '소환사'} 프로필 아이콘`}
                      className="h-[132px] w-[132px] object-cover"
                    />
                  ) : squareUrl ? (
                    <img
                      src={squareUrl}
                      alt={snapshot.primaryChampionName ?? '대표 챔피언'}
                      className="h-[132px] w-[132px] object-cover"
                    />
                  ) : (
                    <div className="flex h-[132px] w-[132px] items-center justify-center bg-[#1b1f2b] text-[42px] font-black text-white/30">
                      G
                    </div>
                  )}
                </div>
                {snapshot.summonerLevel ? (
                  <span className="absolute -bottom-4 left-1/2 -translate-x-1/2 rounded-full bg-[#2a3040] px-3 py-1 text-[24px] font-black text-white shadow-[0_8px_24px_rgba(0,0,0,0.24)]">
                    {snapshot.summonerLevel}
                  </span>
                ) : null}
              </div>

              <div className="min-w-0 xl:grid xl:grid-cols-[minmax(0,1fr)_360px] xl:items-start xl:gap-8 2xl:grid-cols-[minmax(0,1fr)_392px]">
                <div className="self-start text-center lg:text-left">
                  <div className="flex flex-wrap items-end justify-center gap-2 lg:justify-start">
                    <h1 className="min-w-0 break-all text-[34px] font-black tracking-[-0.06em] text-white sm:text-[44px]">
                      {snapshot.gameName ?? '이름 없는 소환사'}
                    </h1>
                    <span className="text-[28px] font-black tracking-[-0.06em] text-[#8f97ab] sm:text-[44px]">
                      #{snapshot.tagLine ?? 'KR1'}
                    </span>
                  </div>
                  <div className="mt-3 flex flex-wrap items-center justify-center gap-2 text-[14px] text-[#bcc4d8] sm:gap-3 sm:text-[15px] lg:justify-start">
                    <span>KR</span>
                    <span>|</span>
                    <span>{soloRankLabel}</span>
                    <span>|</span>
                    <span>최근 {totalMatchCount}경기</span>
                  </div>
                  <div className="mt-5 rounded-[6px] border border-[#474d5f] bg-[#323645] px-4 py-3 text-[14px] font-medium text-[#e4e9f8] sm:max-w-[490px] sm:text-[15px]">
                    라이엇 계정을 연동하면 프로필 설정과 공유 기능을 더 정확하게 사용할 수
                    있습니다.
                  </div>
                  <div className="mt-4 flex flex-col items-stretch gap-3 sm:flex-row sm:flex-wrap sm:items-center">
                    <ResultRefreshButton
                      snapshotId={snapshot.snapshotId}
                      gameName={snapshot.gameName ?? ''}
                      tagLine={snapshot.tagLine ?? ''}
                      stablePath={resolvedStablePath}
                    />
                    <div className="flex flex-col gap-2 text-left">
                      <button
                        type="button"
                        disabled
                        className="inline-flex h-[48px] w-full items-center justify-center rounded-[6px] border border-[#46557f] bg-[#283046] px-6 text-[15px] font-semibold text-[#8ea4db] opacity-80 sm:w-auto sm:text-[16px]"
                      >
                        티어 그래프 준비 중
                      </button>
                      <p className="text-[12px] text-[#8d95aa]">
                        최근 티어 이력 API와 저장 구조가 아직 없어 준비 중입니다.
                      </p>
                    </div>
                  </div>
                  {requestId ? (
                    <div className="mt-4 sm:max-w-[540px]">
                      <ResultRequestWatcher
                        requestId={requestId}
                        snapshotId={snapshot.snapshotId}
                        stablePath={resolvedStablePath}
                      />
                    </div>
                  ) : null}
                  {refreshError ? (
                    <div className="mt-4 rounded-[10px] border border-[#6b4650] bg-[#3a2328] px-4 py-3 text-[13px] font-semibold text-[#ffd2da] sm:max-w-[540px]">
                      {refreshError}
                    </div>
                  ) : null}
                  <div className="mt-3 text-[14px] text-[#8d95aa]">마지막 갱신: {lastUpdated}</div>
                </div>

                {requestId ? (
                  <GgtiSkeletonCard />
                ) : (
                  <aside
                    className="relative hidden min-h-[224px] self-start overflow-hidden rounded-[4px] border border-[#31313c] shadow-[inset_0_1px_0_rgba(255,255,255,0.04)] xl:flex xl:flex-col"
                    style={{
                      background: `radial-gradient(circle_at_top_right, ${ggtiAccent.glow}, transparent 34%), linear-gradient(180deg, ${ggtiAccent.top} 0%, ${ggtiAccent.bottom} 100%)`,
                    }}
                  >
                    <div className="pointer-events-none absolute -right-4 top-2 text-[118px] font-black tracking-[-0.08em] text-white/[0.05]">
                      {ggtiCode}
                    </div>

                    <div className="border-b border-white/6 px-6 pb-5 pt-6">
                      <div className="text-[12px] font-semibold tracking-[0.28em] text-[#9fb5ff]">
                        GGTI
                      </div>
                      <div className="mt-4 flex items-end gap-3">
                        <div className="text-[52px] font-black leading-none tracking-[-0.08em] text-white">
                          {ggtiCode}
                        </div>
                        <div className="pb-1 text-[12px] font-semibold tracking-[0.18em] text-[#aebde6]">
                          TYPE
                        </div>
                      </div>
                      <div className="mt-3 text-[24px] font-black tracking-[-0.05em] text-white">
                        {ggtiTokens.map(formatGgtiTypeLabel).join(' / ')}
                      </div>
                      <p className="mt-3 text-[13px] leading-6 text-[#c5d1ef]">
                        최근 전적과 플레이 지표를 기준으로 계산한 현재 GGTI 성향입니다.
                        최신 갱신 결과가 바로 반영됩니다.
                      </p>
                    </div>

                    <div className="flex flex-1 flex-col justify-between gap-5 px-6 py-5">
                      <div className="grid grid-cols-2 gap-3">
                        {ggtiTokens.map((token, index) => (
                          <div
                            key={token}
                            className="rounded-[10px] border border-white/8 bg-white/[0.04] px-4 py-4 shadow-[inset_0_1px_0_rgba(255,255,255,0.05)]"
                          >
                            <div className="text-[11px] font-semibold tracking-[0.16em] text-[#92a3c8]">
                              AXIS 0{index + 1}
                            </div>
                            <div className="mt-2 text-[20px] font-black tracking-[-0.05em] text-white">
                              {formatGgtiTypeLabel(token)}
                            </div>
                            <div className="mt-1 text-[12px] font-semibold text-[#c5d1ef]">
                              {formatGgtiTokenPair(token)}
                            </div>
                          </div>
                        ))}
                      </div>

                      <div className="grid gap-3">
                        {dominantTraits.map((trait) => (
                          <div key={trait.key} className="grid gap-1.5">
                            <div className="flex items-center justify-between text-[12px] font-semibold text-[#e5ebff]">
                              <span>{trait.label}</span>
                              <span>{trait.score}</span>
                            </div>
                            <div className="h-2 overflow-hidden rounded-full bg-black/25">
                              <div
                                className="h-full rounded-full"
                                style={{
                                  width: `${trait.score}%`,
                                  background: ggtiAccent.bar,
                                }}
                              />
                            </div>
                          </div>
                        ))}
                      </div>
                    </div>
                  </aside>
                )}
              </div>
            </div>
          </div>

          <div className="rounded-b-[8px] border border-[#393d4d] bg-[#303340]">
            <div className="border-t border-[#393d4d] bg-[#1f2129] p-3 sm:p-4">
              <div className="grid items-start gap-4 xl:grid-cols-[minmax(0,3fr)_minmax(0,7fr)]">
                <aside className="grid auto-rows-max content-start gap-4 self-start">
                  <section className="self-start overflow-hidden rounded-[4px] border border-[#31313c] bg-[#2b2f3a]">
                    <div className="flex items-center justify-between border-b border-[#3b4050] px-4 py-3">
                      <div className="flex items-center gap-2 text-[15px] font-semibold text-white">
                        <span>랭크 솔로/듀오</span>
                        <span className="flex h-6 w-6 items-center justify-center rounded-full border border-[#646b82] text-[13px] text-[#9aa4bf]">
                          !
                        </span>
                      </div>
                    </div>

                    <div className="border-b border-[#3b4050] px-4 py-5">
                      <div className="grid gap-5 sm:grid-cols-[116px_minmax(0,1fr)] sm:items-center">
                        <div className="flex justify-center">
                          <div className="flex h-[108px] w-[108px] items-center justify-center rounded-full bg-[#242731]">
                            {soloTierIcon ? (
                              <img
                                src={soloTierIcon}
                                alt="랭크 솔로/듀오 티어 엠블럼"
                                className="h-[92px] w-[92px] object-contain"
                              />
                            ) : null}
                          </div>
                        </div>
                        <div className="min-w-0 text-center sm:text-left">
                          <div className="flex flex-wrap items-center justify-center gap-3 sm:justify-start">
                            <div className="whitespace-nowrap text-[28px] font-black tracking-[-0.04em] text-white">
                              {soloRankLabel}
                            </div>
                            <span className="inline-flex whitespace-nowrap rounded-full bg-[#6d84f5] px-4 py-1 text-[14px] font-semibold text-white">
                              실제 랭크
                            </span>
                          </div>
                          <div className="mt-3 flex flex-wrap items-center justify-center gap-x-4 gap-y-2 text-[15px] text-[#c3cad7] sm:justify-start">
                            {soloLeaguePoints != null ? (
                              <span className="whitespace-nowrap text-[18px] font-semibold text-white">
                                {soloLeaguePoints} LP
                              </span>
                            ) : (
                              <span className="whitespace-nowrap text-[18px] font-semibold text-white">
                                언랭크
                              </span>
                            )}
                            <span className="whitespace-nowrap">{soloRecord}</span>
                            {soloWinRate != null ? (
                              <span className="whitespace-nowrap">승률 {soloWinRate}%</span>
                            ) : null}
                          </div>
                        </div>
                        <div className="sm:col-span-2 rounded-[6px] border border-white/6 bg-[#232734] px-4 py-3 text-left">
                          <div className="text-[11px] font-semibold tracking-[0.12em] text-[#8d95aa]">
                            최근 20경기 기준
                          </div>
                          <div className="mt-3 grid gap-2 text-[13px] text-[#cfd5e5] sm:grid-cols-2 sm:gap-x-6">
                            <div className="flex items-center justify-between gap-3 rounded-[4px] bg-black/10 px-3 py-2">
                              <span className="text-[#8d95aa]">전적</span>
                              <span className="whitespace-nowrap font-semibold text-white">
                                {recentRecord}
                              </span>
                            </div>
                            <div className="flex items-center justify-between gap-3 rounded-[4px] bg-black/10 px-3 py-2">
                              <span className="text-[#8d95aa]">승률</span>
                              <span className="whitespace-nowrap font-semibold text-white">
                                {winRate}%
                              </span>
                            </div>
                          </div>
                        </div>
                      </div>
                    </div>

                    <div className="grid grid-cols-[84px_minmax(0,1fr)_48px] border-b border-[#3b4050] px-3 py-3 text-[13px] font-semibold text-white sm:grid-cols-[96px_minmax(0,1fr)_56px] sm:px-4 sm:text-[14px]">
                      <span>큐</span>
                      <span>티어</span>
                      <span className="text-right">LP</span>
                    </div>
                    <div className="grid bg-[#2b2f3a]">
                      <div className="grid grid-cols-[84px_minmax(0,1fr)_48px] items-center px-3 py-3 sm:grid-cols-[96px_minmax(0,1fr)_56px] sm:px-4">
                        <span className="inline-flex w-fit rounded-[4px] bg-[#1f2029] px-2 py-1 text-[12px] font-bold text-[#b7c0d9]">
                          솔로랭크
                        </span>
                        <div className="flex items-center gap-2 text-[15px] text-[#b7c0d9]">
                          {soloTierIcon ? (
                            <img src={soloTierIcon} alt="" className="h-5 w-5 object-contain" />
                          ) : null}
                          <span>{soloRankLabel}</span>
                        </div>
                        <span className="text-right text-[15px] text-[#b7c0d9]">
                          {soloLeaguePoints != null ? soloLeaguePoints : '-'}
                        </span>
                      </div>
                    </div>
                    <div className="border-t border-[#3b4050] px-4 py-4 text-[13px] leading-6 text-[#9aa4bf]">
                      현재 랭크는 Riot league-v4 기준 실데이터입니다. 시즌별 과거 티어 이력은 Riot API 제공 범위가 없어 준비 중입니다.
                    </div>
                  </section>

                  <section className="self-start overflow-hidden rounded-[4px] border border-[#31313c] bg-[#2b2f3a]">
                    <div className="flex items-center justify-between border-b border-[#3b4050] px-4 py-3">
                      <div className="flex items-center gap-2 text-[15px] font-semibold text-white">
                        <span>자유 랭크</span>
                        <span className="flex h-6 w-6 items-center justify-center rounded-full border border-[#646b82] text-[13px] text-[#9aa4bf]">
                          !
                        </span>
                      </div>
                      <span className="text-[15px] font-semibold text-[#787f95]">
                        {currentFlexRank ? '배치 완료' : '배치 전'}
                      </span>
                    </div>

                    <div className="border-b border-[#3b4050] px-4 py-5">
                      <div className="grid gap-4 sm:grid-cols-[84px_minmax(0,1fr)] sm:items-center">
                        <div className="flex justify-center">
                          <div className="flex h-[76px] w-[76px] items-center justify-center rounded-full bg-[#242731]">
                            {flexTierIcon ? (
                              <img src={flexTierIcon} alt="자유 랭크 티어 엠블럼" className="h-[60px] w-[60px] object-contain" />
                            ) : (
                              <span className="text-[12px] font-semibold text-[#8d95aa]">UNRANKED</span>
                            )}
                          </div>
                        </div>
                        <div className="min-w-0 text-center sm:text-left">
                          <div className="text-[24px] font-black tracking-[-0.04em] text-white">{flexRankLabel}</div>
                          <div className="mt-2 flex flex-wrap items-center justify-center gap-x-4 gap-y-2 text-[15px] text-[#c3cad7] sm:justify-start">
                            <span className="whitespace-nowrap text-[18px] font-semibold text-white">
                              {currentFlexRank?.leaguePoints != null ? `${currentFlexRank.leaguePoints} LP` : '언랭크'}
                            </span>
                            <span className="whitespace-nowrap">{flexRecord}</span>
                            {flexWinRate != null ? (
                              <span className="whitespace-nowrap">승률 {flexWinRate}%</span>
                            ) : null}
                          </div>
                        </div>
                      </div>
                    </div>

                    <div className="grid grid-cols-[84px_minmax(0,1fr)_48px] border-b border-[#3b4050] px-3 py-3 text-[13px] font-semibold text-white sm:grid-cols-[96px_minmax(0,1fr)_56px] sm:px-4 sm:text-[14px]">
                      <span>큐</span>
                      <span>티어</span>
                      <span className="text-right">LP</span>
                    </div>
                    <div className="grid">
                      <div className="grid grid-cols-[84px_minmax(0,1fr)_48px] items-center px-3 py-3 sm:grid-cols-[96px_minmax(0,1fr)_56px] sm:px-4">
                        <span className="inline-flex w-fit rounded-[4px] bg-[#1f2029] px-2 py-1 text-[12px] font-bold text-[#b7c0d9]">
                          자유랭크
                        </span>
                        <div className="flex items-center gap-2 text-[15px] text-[#b7c0d9]">
                          {flexTierIcon ? (
                            <img src={flexTierIcon} alt="" className="h-5 w-5 object-contain" />
                          ) : null}
                          <span>{flexRankLabel}</span>
                        </div>
                        <span className="text-right text-[15px] text-[#b7c0d9]">
                          {currentFlexRank?.leaguePoints != null ? currentFlexRank.leaguePoints : '-'}
                        </span>
                      </div>
                    </div>
                  </section>
                </aside>

                <MatchHistoryPanel
                  snapshotId={snapshot.snapshotId}
                  initialMatches={recentMatches}
                  initialTotalMatchCount={totalMatchCount}
                  championDisplayNames={championDisplayNames}
                />
              </div>
            </div>
          </div>
        </div>
      </section>
    </main>
  );
}

function getQueryParam(value: string | string[] | undefined) {
  if (Array.isArray(value)) {
    return value[0] ?? null;
  }

  return value ?? null;
}

export default async function ResultPage({
  params,
  searchParams,
}: {
  params: Promise<{ snapshotId: string }>;
  searchParams: Promise<{
    requestId?: string | string[];
    refreshError?: string | string[];
  }>;
}) {
  const { snapshotId } = await params;
  const resolvedSearchParams = await searchParams;

  return (
    <SnapshotResultPageContent
      snapshotId={snapshotId}
      requestId={getQueryParam(resolvedSearchParams.requestId)}
      refreshError={getQueryParam(resolvedSearchParams.refreshError)}
    />
  );
}

function GgtiSkeletonCard() {
  return (
    <aside className="hidden min-h-[224px] overflow-hidden rounded-[4px] border border-[#31313c] bg-[radial-gradient(circle_at_top_right,rgba(83,131,232,0.18),transparent_36%),linear-gradient(180deg,#2e3341_0%,#252933_100%)] shadow-[inset_0_1px_0_rgba(255,255,255,0.04)] xl:flex xl:flex-col">
      <div className="border-b border-white/6 px-6 pb-5 pt-6">
        <div className="h-3 w-14 animate-pulse rounded-full bg-white/12" />
        <div className="mt-4 h-12 w-32 animate-pulse rounded-[12px] bg-white/12" />
        <div className="mt-4 h-7 w-40 animate-pulse rounded-full bg-white/10" />
        <div className="mt-4 h-4 w-full animate-pulse rounded-full bg-white/10" />
        <div className="mt-3 h-4 w-5/6 animate-pulse rounded-full bg-white/10" />
      </div>

      <div className="flex flex-1 flex-col justify-between gap-5 px-6 py-5">
        <div className="grid grid-cols-2 gap-3">
          {Array.from({ length: 2 }).map((_, index) => (
            <div key={index} className="rounded-[10px] border border-white/8 bg-white/[0.04] px-4 py-4">
              <div className="h-3 w-14 animate-pulse rounded-full bg-white/10" />
              <div className="mt-3 h-6 w-20 animate-pulse rounded-full bg-white/10" />
              <div className="mt-2 h-3 w-16 animate-pulse rounded-full bg-white/10" />
            </div>
          ))}
        </div>

        <div className="grid gap-3">
          {Array.from({ length: 3 }).map((_, index) => (
            <div key={index} className="grid gap-2">
              <div className="flex items-center justify-between">
                <div className="h-3 w-20 animate-pulse rounded-full bg-white/10" />
                <div className="h-3 w-8 animate-pulse rounded-full bg-white/10" />
              </div>
              <div className="h-2 overflow-hidden rounded-full bg-black/25">
                <div
                  className="h-full animate-pulse rounded-full bg-[#7aa2ff]/60"
                  style={{ width: `${76 - index * 12}%` }}
                />
              </div>
            </div>
          ))}
        </div>
      </div>
    </aside>
  );
}

function formatRankLabel(
  rank:
    | {
        tier: string;
        rank: string;
      }
    | null
    | undefined,
) {
  if (!rank) return '언랭크';
  return `${formatTierName(rank.tier)} ${formatRomanRank(rank.rank)}`.trim();
}

function formatTierName(tier: string) {
  const labels: Record<string, string> = {
    IRON: '아이언',
    BRONZE: '브론즈',
    SILVER: '실버',
    GOLD: '골드',
    PLATINUM: '플래티넘',
    EMERALD: '에메랄드',
    DIAMOND: '다이아몬드',
    MASTER: '마스터',
    GRANDMASTER: '그랜드마스터',
    CHALLENGER: '챌린저',
  };

  return labels[tier] ?? tier;
}

function formatRomanRank(rank: string) {
  const labels: Record<string, string> = {
    I: '1',
    II: '2',
    III: '3',
    IV: '4',
  };

  return labels[rank] ?? rank;
}

function calculateWinRate(wins: number, losses: number) {
  return Math.round((wins / Math.max(1, wins + losses)) * 100);
}

function getTierIconUrl(tier: string | null) {
  if (!tier) return null;

  const slug = tier.toLowerCase();
  const supported = new Set([
    'iron',
    'bronze',
    'silver',
    'gold',
    'platinum',
    'emerald',
    'diamond',
    'master',
    'grandmaster',
    'challenger',
  ]);

  if (!supported.has(slug)) {
    return null;
  }

  return `https://opgg-static.akamaized.net/images/medals_new/${slug}.png?image=q_auto:good,f_webp,w_144&v=1777571117`;
}

function splitGgtiType(ggtiType: string) {
  return ggtiType
    .split('-')
    .map((value) => value.trim().toUpperCase())
    .filter(Boolean);
}

function buildGgtiCode(types: string[]) {
  const codeMap: Record<string, string> = {
    BAIT: 'BT',
    CARRY: 'CY',
    FARM: 'FM',
    LIMIT: 'LM',
    ROAM: 'RM',
    SAFE: 'SF',
    SHOT: 'ST',
  };

  const first = codeMap[types[0] ?? ''] ?? 'GG';
  const second = codeMap[types[1] ?? ''] ?? 'TI';

  return `${first}${second}`;
}

function formatGgtiTypeLabel(type: string) {
  const labels: Record<string, string> = {
    BAIT: '유도',
    CARRY: '캐리',
    FARM: '파밍',
    LIMIT: '리밋',
    ROAM: '로밍',
    SAFE: '안정',
    SHOT: '오더',
  };

  return labels[type] ?? type;
}

function formatGgtiTokenPair(type: string) {
  const labels: Record<string, string> = {
    BAIT: '심리 유도형',
    CARRY: '캐리 주도형',
    FARM: '성장 집중형',
    LIMIT: '한계 시험형',
    ROAM: '합류 순환형',
    SAFE: '안정 축적형',
    SHOT: '오더 집중형',
  };

  return labels[type] ?? type;
}

function getGgtiAccent(type: string) {
  const accents: Record<
    string,
    { top: string; bottom: string; glow: string; bar: string }
  > = {
    BAIT: {
      top: '#313445',
      bottom: '#252838',
      glow: 'rgba(237,130,163,0.26)',
      bar: 'linear-gradient(90deg,#ff8db0 0%,#f25d91 100%)',
    },
    CARRY: {
      top: '#2e3347',
      bottom: '#24293a',
      glow: 'rgba(255,178,92,0.24)',
      bar: 'linear-gradient(90deg,#ffcf7d 0%,#ff9150 100%)',
    },
    FARM: {
      top: '#2a3646',
      bottom: '#232d3a',
      glow: 'rgba(112,175,255,0.22)',
      bar: 'linear-gradient(90deg,#7ca6ff 0%,#4e76ff 100%)',
    },
    LIMIT: {
      top: '#332f45',
      bottom: '#25283b',
      glow: 'rgba(176,138,255,0.22)',
      bar: 'linear-gradient(90deg,#8f7cff 0%,#6a54f8 100%)',
    },
    ROAM: {
      top: '#25394a',
      bottom: '#22313d',
      glow: 'rgba(88,220,210,0.2)',
      bar: 'linear-gradient(90deg,#63dfd7 0%,#3eb2d7 100%)',
    },
    SAFE: {
      top: '#2f3746',
      bottom: '#27303c',
      glow: 'rgba(143,209,133,0.2)',
      bar: 'linear-gradient(90deg,#a7df86 0%,#67bb7d 100%)',
    },
    SHOT: {
      top: '#373148',
      bottom: '#27283a',
      glow: 'rgba(247,188,100,0.2)',
      bar: 'linear-gradient(90deg,#ffcf76 0%,#e39a46 100%)',
    },
  };

  return (
    accents[type] ?? {
      top: '#2e3341',
      bottom: '#252933',
      glow: 'rgba(83,131,232,0.18)',
      bar: 'linear-gradient(90deg,#7aa2ff 0%,#5b7fff 100%)',
    }
  );
}

function buildDominantTraitRows(scores: {
  aggression: number;
  stability: number;
  roaming: number;
  vision: number;
  objective: number;
  growth: number;
  fightJoin: number;
}) {
  const labels: Record<string, string> = {
    aggression: '공격성',
    stability: '안정성',
    roaming: '로밍',
    vision: '시야',
    objective: '오브젝트',
    growth: '성장',
    fightJoin: '교전 합류',
  };

  return Object.entries(scores)
    .sort((left, right) => right[1] - left[1])
    .slice(0, 3)
    .map(([key, score]) => ({
      key,
      label: labels[key] ?? key,
      score: Math.round(score),
    }));
}
