"use client";
import { useState } from "react";
import { useRouter } from "next/navigation";

export default function CheckoutButton({
  type,
  label,
  amount,
  description,
  metadata,
  productId,
  interval,
  imageUrl,
  className = "btn-primary px-6 py-3",
}: {
  type: "subscription" | "purchase" | "tip";
  label: string;
  amount: number;
  description: string;
  metadata?: Record<string, string>;
  productId?: string;
  interval?: string;
  imageUrl?: string;
  className?: string;
}) {
  const [loading, setLoading] = useState(false);
  const router = useRouter();

  function handleClick() {
    setLoading(true);
    // Everything needed to build the embedded checkout is passed via the
    // URL — /checkout reads these same params and calls /api/checkout/embedded
    // itself, so no fetch (and no off-site redirect) happens from the button.
    const params = new URLSearchParams({
      type,
      amount: String(amount),
      description,
    });
    if (productId) params.set("productId", productId);
    if (interval) params.set("interval", interval);
    if (metadata?.tier) params.set("tier", metadata.tier);
    if (imageUrl) params.set("imageUrl", imageUrl);
    router.push(`/checkout?${params.toString()}`);
  }

  return (
    <button onClick={handleClick} disabled={loading} className={`w-full block ${className}`}>
      {loading ? "Loading checkout..." : label}
    </button>
  );
}
