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

export const metadata: Metadata = {
  title: 'Confirm address',
  robots: { index: false, follow: false },
};

/**
 * Confirms an account's email address.
 *
 * Server-rendered so the confirmation happens on load. A client-side
 * fetch would show a spinner and could be abandoned before the request
 * lands, leaving the address unverified for no reason the reader can
 * see.
 */
export default async function VerifyPage({
  params,
  searchParams,
}: {
  params: Promise<{ lang: string }>;
  searchParams: Promise<{ t?: string }>;
}) {
  const { lang } = await params;
  if (!isLocale(lang)) notFound();

  const { t } = await searchParams;
  const dict = getDictionary(lang);

  let ok = false;

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

  return (
    <main id="main" className="page token-page">
      <div className="token-card">
        <p className="token-brand">AI RADAR</p>
        <h1 className="token-title">
          {ok ? dict.auth.verifiedTitle : dict.auth.verifyFailedTitle}
        </h1>
        <p className="token-body">
          {ok ? dict.auth.verifiedBody : dict.auth.verifyFailedBody}
        </p>
        <Link href={localePath('/', lang)} className="token-link">
          {dict.auth.accountBackHome} →
        </Link>
      </div>
    </main>
  );
}
