/**
 * Refer & Earn on the website: a visitor who arrives with ?ref=CODE on any page keeps the code for 60 days on this
 * device, so it still counts if they sign up later. The API validates the code (active link, program on) at signup.
 */
const KEY = 'tms.ref';
const DAYS = 60;
const valid = (c: string | null) => !!c && /^[A-Za-z0-9-]{4,20}$/.test(c);

export function rememberReferral(): void {
  try {
    const code = new URLSearchParams(location.search).get('ref');
    if (valid(code)) localStorage.setItem(KEY, JSON.stringify({ code: code!.toUpperCase(), at: Date.now() }));
  } catch { /* private mode */ }
}

export function readReferral(): string | null {
  rememberReferral();
  try {
    const raw = JSON.parse(localStorage.getItem(KEY) || 'null');
    if (raw && valid(raw.code) && Date.now() - raw.at < DAYS * 86400000) return raw.code;
  } catch { /* ignore */ }
  const code = new URLSearchParams(location.search).get('ref');
  return valid(code) ? code!.toUpperCase() : null;
}
