'use client'

import { useState } from 'react'
import { toast } from 'sonner'
import { Button } from '@/components/ui/button'

export function UnsubscribeButton({ token }: { token: string }) {
  const [state, setState] = useState<'idle' | 'busy' | 'done'>('idle')
  async function go() {
    setState('busy')
    const res = await fetch('/api/pilot/unsubscribe', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ token }) })
    if (!res.ok) { toast.error('Could not unsubscribe — please try again.'); setState('idle'); return }
    setState('done')
  }
  if (state === 'done') return <p className="rounded-xl border border-green-200 bg-green-50 p-4 text-center text-sm text-green-800">✓ Unsubscribed. You will not receive further pilot invitations.</p>
  return <Button className="w-full" disabled={state === 'busy'} onClick={go}>Unsubscribe me</Button>
}
