"use client"

import { useState } from "react"
import { cn } from "@/lib/utils"

export function CheckoutButton({ plan, label, highlight }: { plan: string; label: string; highlight?: boolean }) {
  const [loading, setLoading] = useState(false)

  async function handleClick() {
    setLoading(true)
    const res = await fetch("/api/stripe/checkout", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ plan }),
    })
    const data = await res.json()
    if (data.url) window.location.href = data.url
    else setLoading(false)
  }

  return (
    <button
      onClick={handleClick}
      disabled={loading}
      className={cn(
        "w-full rounded-lg py-2 text-xs font-semibold transition disabled:opacity-50",
        highlight
          ? "bg-indigo-600 text-white hover:bg-indigo-500"
          : "border border-white/10 text-white/70 hover:border-white/20 hover:text-white"
      )}
    >
      {loading ? "Loading..." : label}
    </button>
  )
}
