/* Waitlist persistence — tries window.storage (shared), falls back to localStorage */
const PP_KEY = 'pp_waitlist_v1';
const PP_SEED = 247; // seed count so the page never reads "1 agency owner"

// Automatically capture and store referral source in sessionStorage on load
function ppCaptureReferralSource() {
  try {
    if (sessionStorage.getItem('pp_referral_source')) return;

    const params = new URLSearchParams(window.location.search);
    const utmSource = params.get('utm_source') || params.get('ref') || params.get('source');
    
    if (utmSource) {
      sessionStorage.setItem('pp_referral_source', utmSource.toLowerCase());
      return;
    }

    const referrer = document.referrer;
    if (referrer) {
      const url = new URL(referrer);
      const host = url.hostname.toLowerCase();
      
      if (host.includes('facebook.com') || host.includes('fb.me')) {
        sessionStorage.setItem('pp_referral_source', 'facebook');
        return;
      }
      if (host.includes('linkedin.com') || host.includes('lnkd.in')) {
        sessionStorage.setItem('pp_referral_source', 'linkedin');
        return;
      }
      if (host.includes('twitter.com') || host.includes('t.co') || host.includes('x.com')) {
        sessionStorage.setItem('pp_referral_source', 'twitter');
        return;
      }
      if (host.includes('instagram.com')) {
        sessionStorage.setItem('pp_referral_source', 'instagram');
        return;
      }
      if (host.includes('google.com')) {
        sessionStorage.setItem('pp_referral_source', 'google');
        return;
      }
      if (!host.includes(window.location.hostname)) {
        sessionStorage.setItem('pp_referral_source', host);
        return;
      }
    }
    sessionStorage.setItem('pp_referral_source', 'direct');
  } catch (err) {
    sessionStorage.setItem('pp_referral_source', 'direct');
  }
}

// Run immediately on script load
ppCaptureReferralSource();

async function ppLoad() {
  try {
    if (window.storage && window.storage.get) {
      const r = await window.storage.get(PP_KEY, true).catch(() => null);
      if (r && r.value) return JSON.parse(r.value);
    }
  } catch {}
  try {
    const raw = localStorage.getItem(PP_KEY);
    if (raw) return JSON.parse(raw);
  } catch {}
  return [];
}

async function ppSave(list) {
  try {
    if (window.storage && window.storage.set) {
      await window.storage.set(PP_KEY, JSON.stringify(list), true);
    }
  } catch {}
  try { localStorage.setItem(PP_KEY, JSON.stringify(list)); } catch {}
}

async function ppSaveEmail(email) {
  const list = await ppLoad();
  if (!list.includes(email)) list.push(email);
  await ppSave(list);

  // Fire-and-forget Airtable sync — never blocks the user's join flow
  if (window.ppSaveToAirtable) {
    const source = sessionStorage.getItem('pp_referral_source') || 'direct';
    window.ppSaveToAirtable(email, source).catch(() => {});
  }

  return list.length + PP_SEED;
}

async function ppGetCount() {
  const list = await ppLoad();
  return list.length + PP_SEED;
}

Object.assign(window, { ppSaveEmail, ppGetCount });
