import type { Metadata } from 'next';
import Link from 'next/link';
import { DEFAULT_LOCALE, isLocale, localePath, type Locale } from '@ai-radar/shared';
import { getDictionary } from '@/lib/dictionary';
import { apiUrl } from '@/lib/site';

export const metadata: Metadata = {
  title: 'Confirm subscription',
  // A one-off token page has nothing to index and should never appear in
  // search results.
  robots: { index: false, follow: false },
};

/**
 * Completes double opt-in.
 *
 * Outside [lang] because the link comes from an email, where the reader's
 * language is already known from their subscription rather than the URL.
 * The API returns it, and the page renders in that language.
 *
 * Server-rendered so the confirmation happens on load: a client-side
 * fetch would mean the reader sees a spinner and could close the tab
 * before the request lands.
 */
export default async function ConfirmPage({
  searchParams,
}: {
  searchParams: Promise<{ t?: string }>;
}) {
  // Next.js 16 removed synchronous searchParams access.
  const { t } = await searchParams;

  let ok = false;
  let locale: Locale = DEFAULT_LOCALE;

  if (t) {
    try {
      const response = await fetch(`${apiUrl()}/subscribe/confirm?t=${encodeURIComponent(t)}`, {
        cache: 'no-store',
        signal: AbortSignal.timeout(6000),
      });
      const body = (await response.json()) as { ok?: boolean; locale?: string };
      ok = body.ok === true;
      if (body.locale && isLocale(body.locale)) locale = body.locale;
    } catch {
      // API unreachable — falls through to the failure message, which is
      // honest: we genuinely do not know whether it worked.
    }
  }

  const dict = getDictionary(locale);
  const dir = locale === 'ar' ? 'rtl' : 'ltr';

  return (
    <main id="main" className="page token-page" dir={dir} lang={locale}>
      <div className="token-card">
        <p className="token-brand">AI RADAR</p>
        <h1 className="token-title">
          {ok ? dict.subscribe.confirmedTitle : dict.subscribe.confirmFailedTitle}
        </h1>
        <p className="token-body">
          {ok ? dict.subscribe.confirmedBody : dict.subscribe.confirmFailedBody}
        </p>
        <Link href={localePath('/', locale)} className="token-link">
          {dict.subscribe.backHome} →
        </Link>
      </div>
    </main>
  );
}
