import { useState } from 'react';

// --- ASA GENERATED START ---
// React hook for billing/subscribe slice.
// --- ASA GENERATED END ---

// --- USER CODE START ---

export function useSubscribe() {
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  async function subscribe(priceId: string): Promise<void> {
    setLoading(true);
    setError(null);

    try {
      const res = await fetch('/api/billing/subscribe', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ price_id: priceId }),
      });

      const data = await res.json();

      if (data.error) {
        setError(data.error);
        return;
      }

      if (data.checkout_url) {
        window.location.href = data.checkout_url;
      }
    } catch {
      setError('Failed to start checkout. Please try again.');
    } finally {
      setLoading(false);
    }
  }

  return { subscribe, loading, error };
}

// --- USER CODE END ---
