import Link from 'next/link'
import { createAdminClient } from '@/lib/supabase/admin'
import { notExpired } from '@/lib/domain/time'

/**
 * §14: an account whose address hard-bounced (or is temporarily suppressed)
 * sees it on every page until they update or verify their email.
 */
export async function EmailDeliveryBanner({ email, deliveryEmail }: { email: string; deliveryEmail?: string | null }) {
  const address = (deliveryEmail || email).trim().toLowerCase()
  const admin = createAdminClient()
  const { data, error } = await admin.from('email_suppressions').select('scope, reason, expires_at').eq('email_normalized', address).eq('scope', 'global').is('overridden_at', null)
  if (error || !data?.length) return null
  const active = data.filter((s) => notExpired(s.expires_at))
  if (active.length === 0) return null
  const temporary = active.every((s) => s.reason === 'repeated_soft_bounce')
  return (
    <div className="border-b border-red-200 bg-red-50 px-4 py-2 text-center text-xs text-red-800">
      <span className="font-bold">Your email address could not receive messages.</span>{' '}
      {temporary ? 'Delivery is paused after repeated bounces.' : 'HeavyHaul Agent has stopped sending to it.'}{' '}
      <Link href="/settings#email" className="font-semibold underline">Update or verify your email</Link>
    </div>
  )
}
