// Shared API client for all pages
// Provides: FH_API (base URL), fhFetch (auth fetch), fhCheckout, fhWaitlist

const FH_API = window.location.hostname === 'localhost' ? 'http://localhost:3877' : '/api';

// Authenticated fetch helper
async function fhFetch(path, opts = {}) {
  const token = localStorage.getItem('fp_token');
  const headers = { 'Content-Type': 'application/json', ...opts.headers };
  if (token) headers['Authorization'] = 'Bearer ' + token;
  const res = await fetch(FH_API + path, { ...opts, headers });
  if (!res.ok) throw new Error(res.status + ' ' + res.statusText);
  return res.json();
}

// Stripe checkout flow: redirects to Stripe or shows error
async function fhCheckout(productId, buttonEl) {
  const token = localStorage.getItem('fp_token');
  if (!token) {
    window.location.href = 'dashboard.html?signup=' + encodeURIComponent(productId);
    return;
  }
  const prev = buttonEl ? buttonEl.textContent : null;
  if (buttonEl) { buttonEl.textContent = 'Loading...'; buttonEl.disabled = true; }
  try {
    const data = await fhFetch('/billing/checkout', {
      method: 'POST',
      body: JSON.stringify({ productId }),
    });
    if (data.url) { window.location.href = data.url; }
    else {
      if (buttonEl) {
        buttonEl.textContent = data.error || 'Stripe not configured';
        setTimeout(() => { buttonEl.textContent = prev; buttonEl.disabled = false; }, 3000);
      }
    }
  } catch (err) {
    if (buttonEl) {
      buttonEl.textContent = 'Error';
      setTimeout(() => { buttonEl.textContent = prev; buttonEl.disabled = false; }, 3000);
    }
  }
}

// Waitlist flow for non-live products
async function fhWaitlist(productId, buttonEl) {
  const email = prompt('Enter your email to join the waitlist:');
  if (!email) return;
  const prev = buttonEl ? buttonEl.textContent : null;
  if (buttonEl) { buttonEl.textContent = 'Joining...'; buttonEl.disabled = true; }
  try {
    const res = await fetch(FH_API + '/waitlist', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ email, productId }),
    });
    if (buttonEl) buttonEl.textContent = res.ok ? "You're on the list" : 'Try again';
  } catch {
    if (buttonEl) buttonEl.textContent = 'Error';
  }
}

Object.assign(window, { FH_API, fhFetch, fhCheckout, fhWaitlist });
