// referral.js — Handles capturing referral codes from URL

const KEY = 'pendingRefCode';
const VALID_REF = /^[A-Za-z0-9_-]{4,32}$/;

/**
 * Checks URL for ?ref=... and stores it for later use.
 * @returns {string|null} The captured referral code or null
 */
export function captureReferralFromURL() {
  const params = new URLSearchParams(window.location.search);
  const ref = params.get('ref');
  if (!ref) return null;

  const code = ref.trim();
  if (VALID_REF.test(code)) {
    localStorage.setItem(KEY, code);
    return code;
  }
  return null;
}

/**
 * Gets the stored referral code (if valid).
 * @returns {string|null}
 */
export function getPendingReferral() {
  const code = localStorage.getItem(KEY);
  return code && VALID_REF.test(code) ? code : null;
}

/**
 * Clears the stored referral code.
 */
export function clearPendingReferral() {
  localStorage.removeItem(KEY);
}

/**
 * Builds a referral link for a given landing page and code.
 * @param {string} landingPath - e.g., "therapist.html"
 * @param {string} code - referral code
 * @returns {string} Full referral URL
 */
export function buildReferralLink(landingPath, code) {
  if (!VALID_REF.test(code)) throw new Error('Invalid referral code');
  const base = location.origin + location.pathname.replace(/[^/]+$/, '');
  const url = new URL(landingPath, base);
  url.searchParams.set('ref', code);
  return url.toString();
}

// Auto-capture referral on page load
captureReferralFromURL();