'use client'

import { useState } from 'react'
import type { LeadInsert } from '@/types/lead'

interface LeadCaptureResult {
  id: string
  lead_score: number
}

export function useLeadCapture() {
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState<string | null>(null)
  const [result, setResult] = useState<LeadCaptureResult | null>(null)

  const submitLead = async (lead: LeadInsert): Promise<LeadCaptureResult | null> => {
    setLoading(true)
    setError(null)

    try {
      const res = await fetch('/api/leads', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(lead),
      })

      if (!res.ok) {
        const body = await res.json().catch(() => ({}))
        throw new Error(body.error || 'Failed to submit')
      }

      const data = await res.json()
      setResult(data)
      return data
    } catch (err) {
      const message = err instanceof Error ? err.message : 'Something went wrong'
      setError(message)
      return null
    } finally {
      setLoading(false)
    }
  }

  return { submitLead, loading, error, result }
}
