import { SearchStatus } from '@/components/SearchStatus';
import { SnapshotResultPageContent } from '@/app/result/[snapshotId]/page';
import { lookupAnalysis } from '@/lib/api';
import { buildSummonerDetailPath } from '@/lib/routes';

export default async function SummonerDetailPage({
  params,
  searchParams,
}: {
  params: Promise<{ gameName: string; tagLine: string }>;
  searchParams: Promise<{ refreshError?: string | string[] }>;
}) {
  const { gameName, tagLine } = await params;
  const decodedGameName = decodeURIComponent(gameName);
  const decodedTagLine = decodeURIComponent(tagLine);
  const resolvedSearchParams = await searchParams;
  const stablePath = buildSummonerDetailPath(decodedGameName, decodedTagLine);
  const lookup = await lookupAnalysis({
    gameName: decodedGameName,
    tagLine: decodedTagLine,
    region: 'KR',
    syncIfMissing: false,
  }).catch(() => null);

  if (lookup?.latestSnapshotId) {
    const refreshError = Array.isArray(resolvedSearchParams.refreshError)
      ? resolvedSearchParams.refreshError[0] ?? null
      : resolvedSearchParams.refreshError ?? null;

    return (
      <SnapshotResultPageContent
        snapshotId={String(lookup.latestSnapshotId)}
        requestId={lookup.pendingRequestId ? String(lookup.pendingRequestId) : null}
        refreshError={refreshError}
        stablePath={stablePath}
      />
    );
  }

  return (
    <SearchStatus
      requestId={lookup?.pendingRequestId ? String(lookup.pendingRequestId) : null}
      gameName={decodedGameName}
      tagLine={decodedTagLine}
      autoStart
      stablePath={stablePath}
    />
  );
}
