'use client'

import { useState } from 'react'

/**
 * Early-access email capture on the landing page. Posts to /api/early-access;
 * duplicates are treated as success ("already on the list").
 */
export function EarlyAccessForm() {
  const [email, setEmail] = useState('')
  const [role, setRole] = useState('broker')
  const [state, setState] = useState<'idle' | 'sending' | 'done' | 'error'>('idle')
  const [message, setMessage] = useState('')

  async function submit(e: React.FormEvent) {
    e.preventDefault()
    if (state === 'sending') return
    setState('sending')
    try {
      const res = await fetch('/api/early-access', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email, role }),
      })
      const json = await res.json().catch(() => ({}))
      if (res.ok) {
        setState('done')
        setMessage(json.message ?? "You're on the list — we'll reach out with your access.")
      } else {
        setState('error')
        setMessage(json.error ?? 'Something went wrong — please try again.')
      }
    } catch {
      setState('error')
      setMessage('Network error — please try again.')
    }
  }

  if (state === 'done') {
    return (
      <p className="mx-auto mt-8 max-w-md rounded-xl border border-amber-brand/40 bg-white/5 px-6 py-4 text-sm font-semibold text-amber-brand">
        ✓ {message}
      </p>
    )
  }

  return (
    <form onSubmit={submit} className="mx-auto mt-8 flex max-w-xl flex-col gap-3 sm:flex-row">
      <select
        value={role}
        onChange={(e) => setRole(e.target.value)}
        aria-label="Your role"
        className="rounded-lg border border-white/20 bg-navy-900 px-3 py-3 text-sm font-medium text-white outline-none focus:border-amber-brand"
      >
        <option value="broker">I&apos;m a broker</option>
        <option value="carrier">I&apos;m a carrier</option>
        <option value="dispatcher">I&apos;m a dispatcher</option>
        <option value="driver">I&apos;m a driver</option>
        <option value="other">Other</option>
      </select>
      <input
        type="email"
        required
        value={email}
        onChange={(e) => setEmail(e.target.value)}
        placeholder="Work email"
        aria-label="Work email"
        className="min-w-0 flex-1 rounded-lg border border-white/20 bg-white/5 px-4 py-3 text-sm text-white outline-none placeholder:text-navy-100/50 focus:border-amber-brand"
      />
      <button
        type="submit"
        disabled={state === 'sending'}
        className="rounded-lg bg-amber-brand px-6 py-3 text-sm font-bold text-navy-950 shadow-lg shadow-amber-brand/20 transition hover:bg-amber-deep disabled:opacity-60"
      >
        {state === 'sending' ? 'Joining…' : 'Get Early Access'}
      </button>
      {state === 'error' && (
        <p className="w-full text-sm font-medium text-red-300 sm:col-span-full">{message}</p>
      )}
    </form>
  )
}
