import { useState, useCallback } from 'react';
import { apiUrl, authHeaders, assertOk } from '../lib/api';
import { trackEvent } from '../lib/analytics';

export function useLicense() {
  const [checkingOut, setCheckingOut] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const startCheckout = useCallback(async (returnPath?: string) => {
    trackEvent('Checkout Start', { has_referral: 'false' });
    setCheckingOut(true);
    setError(null);
    try {
      const res = await fetch(apiUrl('checkout'), {
        method: 'POST',
        ...authHeaders({
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify(returnPath ? { return_path: returnPath } : {}),
        }),
      });
      assertOk(res, 'Checkout');
      const data = await res.json();
      if (data.url) {
        trackEvent('Checkout Redirect');
        window.location.href = data.url;
      }
    } catch (err) {
      const msg = err instanceof Error ? err.message : 'Checkout failed';
      setError(msg);
      throw err;
    } finally {
      setCheckingOut(false);
    }
  }, []);

  return { startCheckout, checkingOut, error };
}
