import { redirect } from 'next/navigation'
import { headers } from 'next/headers'
import BrandName from '@/app/BrandName'
import ThemeToggle from '@/app/ThemeToggle'
import { getI18nByEmail } from '@/lib/i18n/server'

type Props = {
  searchParams: Promise<{ token?: string; email?: string; callbackUrl?: string }>
}

export default async function ConfirmPage({ searchParams }: Props) {
  const { token, email, callbackUrl = '/' } = await searchParams

  if (!token || !email) redirect('/login')

  const headersList = await headers()
  const acceptLanguage = headersList.get('accept-language') ?? ''
  const browserLang = acceptLanguage.split(',')[0]?.split('-')[0]?.trim()
  const { t } = await getI18nByEmail(email, browserLang)

  // Split the body string around the {email} placeholder so we can bold the email.
  const bodyTemplate = t('loginConfirm.body')
  const [bodyBefore, bodyAfter] = bodyTemplate.split('{email}')

  // Reconstruct the Auth.js one-time callback URL. We only navigate here after
  // the user manually clicks the button, so email scanners can't consume the token.
  const authCallbackUrl =
    `/api/auth/callback/nodemailer` +
    `?token=${encodeURIComponent(token)}` +
    `&email=${encodeURIComponent(email)}` +
    `&callbackUrl=${encodeURIComponent(callbackUrl)}`

  return (
    <main className="relative flex min-h-screen items-center justify-center bg-zinc-50 px-4 text-zinc-950 dark:bg-zinc-950 dark:text-zinc-100">
      <div className="absolute top-4 right-4">
        <ThemeToggle />
      </div>
      <div className="w-full max-w-sm rounded-lg border border-zinc-200 bg-white p-8 shadow-sm dark:border-zinc-800 dark:bg-zinc-900">
        <h1 className="mb-1 text-xl font-semibold text-zinc-950 dark:text-white">
          {t('loginConfirm.heading')} <BrandName />
        </h1>
        <p className="mb-6 text-sm text-zinc-600 dark:text-zinc-400">
          {bodyBefore}
          <span className="font-medium text-zinc-800 dark:text-zinc-200">{email}</span>
          {bodyAfter}
        </p>
        <a
          href={authCallbackUrl}
          className="flex w-full items-center justify-center rounded-md bg-zinc-900 px-4 py-2.5 text-sm font-semibold text-white transition hover:bg-zinc-700 dark:bg-white dark:text-zinc-900 dark:hover:bg-zinc-100"
        >
          {t('loginConfirm.cta')}
        </a>
        <a
          href="/login"
          className="mt-4 block w-full rounded-md px-4 py-2 text-center text-sm font-medium text-zinc-600 transition hover:text-zinc-900 dark:text-zinc-400 dark:hover:text-zinc-100"
        >
          {t('loginConfirm.back')}
        </a>
      </div>
    </main>
  )
}
