import Link from 'next/link'
import { verifyPreferenceToken } from '@/lib/email/tokens'
import { unsubscribeUpdates } from '@/lib/email/send'

/**
 * One-click unsubscribe from the updates stream (2026-09-22, §8). Opening the
 * link is enough (mail clients' List-Unsubscribe uses it too). Idempotent.
 * Transactional mail is never affected.
 */
export default async function UnsubscribePage({ params }: { params: Promise<{ token: string }> }) {
  const { token } = await params
  const t = await verifyPreferenceToken(token)
  const r = t ? await unsubscribeUpdates({ email: t.email, userId: t.userId }, 'one-click unsubscribe') : null
  return (
    <main className="mx-auto max-w-xl px-4 py-10">
      <h1 className="text-2xl font-bold tracking-tight">{t && r?.ok ? 'You are unsubscribed from updates' : 'This link is not valid'}</h1>
      <p className="mt-3 text-sm text-neutral-600">
        {t && r?.ok
          ? `${t.email} will no longer receive HeavyHaul Agent product updates, news, promotions or invitation campaigns. Account, trip and permit emails are not affected.`
          : 'Sign in to HeavyHaul Agent and open Settings → Email to manage your preferences.'}
      </p>
      {t && <p className="mt-4 text-sm"><Link href={`/email/preferences/${token}`} className="font-semibold underline">Manage individual categories</Link></p>}
    </main>
  )
}
