import { TossPaymentsBillingAuth } from "@/components/toss-payments-billing-auth";
import { getTossPaymentsBillingAuthSession } from "@/lib/toss-pay";
import { headers } from "next/headers";
import Link from "next/link";
import { resolveOriginFromHeaders } from "@/lib/mail-urls";

export default async function TossPaymentsBillingRegisterPage({
  searchParams,
}: {
  searchParams: Promise<{ registration?: string }>;
}) {
  const params = await searchParams;
  const requestHeaders = await headers();
  const registrationToken = params.registration?.trim() ?? "";
  let session = null;

  try {
    session = await getTossPaymentsBillingAuthSession(
      registrationToken,
      resolveOriginFromHeaders(requestHeaders, "https://mail.officialsite.kr"),
    );
  } catch {
    session = null;
  }

  if (session) {
    return <TossPaymentsBillingAuth session={session} />;
  }

  return (
    <main className="flex min-h-screen items-center justify-center bg-[#f5f8ff] px-4">
      <section className="w-full max-w-[460px] rounded-[24px] border border-[#e1e9f7] bg-white p-8 text-center shadow-[0_24px_60px_rgba(24,44,86,0.1)]">
        <h1 className="text-[22px] font-bold tracking-[-0.04em] text-[#17243d]">
          카드 등록 요청이 만료되었습니다
        </h1>
        <p className="mt-3 text-[14px] leading-6 text-[#6d7d96]">
          보안을 위해 카드 등록 링크는 15분 동안만 유효합니다. 오피셜메일 결제 설정에서 다시 시작해주세요.
        </p>
        <Link
          href="/mail?panel=setup&section=billing"
          className="mt-6 inline-flex h-11 items-center justify-center rounded-[14px] bg-[#2f6df6] px-5 text-[14px] font-bold text-white"
        >
          결제 설정으로 이동
        </Link>
      </section>
    </main>
  );
}
