"use client";

import { useState } from "react";
import type { PlanId, BillingInterval } from "@/lib/pricing";

export function useStripeCheckout() {
  const [loading, setLoading] = useState<PlanId | null>(null);

  async function startCheckout(plan: Exclude<PlanId, "free">, interval: BillingInterval) {
    setLoading(plan);
    try {
      const res = await fetch("/api/stripe/checkout", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ plan, interval })
      });
      const data = await res.json();
      if (data.url) {
        window.location.href = data.url;
      } else {
        console.error("[tidyly] Checkout failed:", data.error);
      }
    } finally {
      setLoading(null);
    }
  }

  return { startCheckout, loading };
}
