import type { Metadata } from 'next';
import Link from 'next/link';
import { TraitBars } from '@/components/TraitBars';
import { getShare } from '@/lib/api';
import { getChampionDisplayNames, localizeChampionTextWithMap } from '@/lib/champion-labels';
import { getChampionSplashUrl, getChampionSquareUrl, getProfileIconUrl } from '@/lib/lol-assets';

export async function generateMetadata({ params }: { params: Promise<{ shareKey: string }> }): Promise<Metadata> {
  const { shareKey } = await params;
  const share = await getShare(shareKey);
  const localized = await getLocalizedShareContent(share);
  return {
    title: localized.title,
    description: localized.description,
    openGraph: {
      title: localized.title,
      description: localized.description,
      images: [`/api/og/${shareKey}`],
    },
  };
}

export default async function SharePage({ params }: { params: Promise<{ shareKey: string }> }) {
  const { shareKey } = await params;
  const share = await getShare(shareKey);
  const localized = await getLocalizedShareContent(share);
  const splashUrl = getChampionSplashUrl(share.snapshot.primaryChampionName);
  const squareUrl = getChampionSquareUrl(share.snapshot.primaryChampionName);
  const profileIconUrl = getProfileIconUrl(share.snapshot.profileIconId);

  return (
    <main className="mx-auto max-w-5xl px-4 pb-20 pt-8">
      <section className="result-hero rounded-[2rem]">
        {splashUrl ? (
          <div
            className="absolute inset-0 bg-cover bg-center opacity-38"
            style={{ backgroundImage: `url(${splashUrl})` }}
          />
        ) : null}
        <div className="relative z-[2] grid gap-6 px-6 py-8 md:grid-cols-[140px_1fr] md:px-8">
          <div className="champion-frame h-[140px] w-[140px] rounded-[1.5rem] bg-[#111722]">
            {profileIconUrl ? (
              <img
                src={profileIconUrl}
                alt={`${share.snapshot.gameName} 프로필 아이콘`}
                className="h-full w-full object-cover"
              />
            ) : squareUrl ? (
              <img
                src={squareUrl}
                alt={share.snapshot.primaryChampionName ?? '챔피언'}
                className="h-full w-full object-cover"
              />
            ) : null}
          </div>
          <div>
            <p className="text-sm font-black text-[#d8ad53]">
              {share.snapshot.gameName}#{share.snapshot.tagLine}
            </p>
            <h1 className="mt-3 text-5xl font-black text-white">{formatGgtiTypeLabel(share.snapshot.ggtiType)}</h1>
            <p className="mt-5 max-w-2xl text-xl leading-9 text-[#d6e4f7]">
              {localized.summary}
            </p>
          </div>
        </div>
      </section>

      <section className="mt-8 grid gap-6 lg:grid-cols-[1fr_0.72fr]">
        <div className="ggti-card rounded-[1.75rem] p-6">
          <h2 className="mb-5 text-2xl font-black text-white">성향 그래프</h2>
          <TraitBars scores={share.snapshot.traitScores} />
        </div>
        <div className="ggti-card rounded-[1.75rem] p-6">
          <h2 className="text-2xl font-black text-white">나도 분석하기</h2>
          <p className="mt-3 leading-7 text-[#aeb8c9]">
            Riot ID를 입력하면 최근 경기 기준으로 GGTI 플레이 유형과 AI 해설을 함께 확인할 수
            있습니다.
          </p>
          <Link
            href="/"
            className="mt-6 inline-flex rounded-2xl bg-[#d8ad53] px-5 py-3 font-black text-[#111722]"
          >
            GGTI 시작하기
          </Link>
        </div>
      </section>
    </main>
  );
}

async function getLocalizedShareContent(share: Awaited<ReturnType<typeof getShare>>) {
  const championNames = [share.snapshot.primaryChampionName];
  const championDisplayNames = await getChampionDisplayNames(championNames);
  const title = `${formatGgtiTypeLabel(share.snapshot.ggtiType)} 플레이어`;

  return {
    title,
    description: localizeChampionTextWithMap(
      share.description,
      championDisplayNames,
      championNames,
    ),
    summary: localizeChampionTextWithMap(
      share.snapshot.aiSummary,
      championDisplayNames,
      championNames,
    ),
    detail: localizeChampionTextWithMap(
      share.snapshot.aiDetail,
      championDisplayNames,
      championNames,
    ),
  };
}

function formatGgtiTypeLabel(value: string) {
  return value
    .split('-')
    .map((item) => {
      const key = item.trim().toUpperCase();
      const labels: Record<string, string> = {
        BAIT: '유도',
        CARRY: '캐리',
        FARM: '파밍',
        LIMIT: '리밋',
        ROAM: '로밍',
        SAFE: '안정',
        SHOT: '오더',
      };
      return labels[key] ?? key;
    })
    .join(' / ');
}
