import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { createAdminClient } from '@/lib/supabase/admin'
import { pilotNetworkAvailable } from '@/lib/data/pilot-network'
import { UnsubscribeButton } from './unsubscribe-button'

/** One-click unsubscribe from pilot invitations (§23). Public. */
export default async function UnsubscribePage({ params }: { params: Promise<{ token: string }> }) {
  const { token } = await params
  const admin = createAdminClient()
  let known = false
  if (await pilotNetworkAvailable(admin) && /^[a-f0-9]{48}$/.test(token)) {
    const { data } = await admin.from('pilot_profiles').select('id, email_opt_in_status').eq('unsubscribe_token', token).maybeSingle()
    known = !!data
    if (data?.email_opt_in_status === 'unsubscribed') {
      return (
        <Shell>
          <CardHeader className="text-center"><CardTitle>You are unsubscribed</CardTitle><CardDescription>You will not receive further pilot invitations from HeavyHaul Agent.</CardDescription></CardHeader>
        </Shell>
      )
    }
  }
  return (
    <Shell>
      <CardHeader className="text-center">
        <CardTitle>{known ? 'Unsubscribe from pilot invitations' : 'Link not valid'}</CardTitle>
        <CardDescription>{known ? 'Confirm below and HeavyHaul Agent will not send you further pilot invitations.' : 'This unsubscribe link is not valid. Reply to the email you received and we will remove you by hand.'}</CardDescription>
      </CardHeader>
      {known && <CardContent><UnsubscribeButton token={token} /></CardContent>}
    </Shell>
  )
}

function Shell({ children }: { children: React.ReactNode }) {
  return (
    <main className="min-h-screen bg-neutral-50 p-4">
      <div className="mx-auto max-w-lg py-10"><Card>{children}</Card></div>
    </main>
  )
}
