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

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

/**
 * One-click unsubscribe.
 *
 * Happens on page load, with no confirmation step and no login. That is
 * deliberate: a reader who cannot leave easily reports the sender as
 * spam instead, which costs far more than the subscription was worth.
 *
 * Server-rendered so a mail client that merely follows the
 * List-Unsubscribe URL still completes the action.
 */
export default async function UnsubscribePage({
  searchParams,
}: {
  searchParams: Promise<{ t?: string }>;
}) {
  const { t } = await searchParams;

  let ok = false;
  if (t) {
    try {
      const response = await fetch(
        `${apiUrl()}/subscribe/unsubscribe?t=${encodeURIComponent(t)}`,
        { cache: 'no-store', signal: AbortSignal.timeout(6000) },
      );
      const body = (await response.json()) as { ok?: boolean };
      ok = body.ok === true;
    } catch {
      // Falls through to the failure message.
    }
  }

  const dict = getDictionary(DEFAULT_LOCALE);

  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.subscribe.unsubscribedTitle : dict.subscribe.unsubscribeFailedTitle}
        </h1>
        <p className="token-body">
          {ok ? dict.subscribe.unsubscribedBody : dict.subscribe.unsubscribeFailedBody}
        </p>
        <Link href={localePath('/', DEFAULT_LOCALE)} className="token-link">
          {dict.subscribe.backHome} →
        </Link>
      </div>
    </main>
  );
}
