/**
 * Small browser-cookie helpers (client-side only).
 *
 * Use for NON-sensitive values that should persist across visits/tabs — e.g.
 * remembering a returning user's contact details to prefill a form. Never store
 * payment/card data or anything you wouldn't want readable by client-side JS.
 */

export function setCookie(name: string, value: string, days = 30): void {
  if (typeof document === "undefined") return;
  const maxAge = Math.max(0, Math.floor(days * 24 * 60 * 60)); // seconds
  document.cookie = `${name}=${encodeURIComponent(
    value,
  )}; path=/; max-age=${maxAge}; SameSite=Lax`;
}

export function getCookie(name: string): string | null {
  if (typeof document === "undefined") return null;
  const match = document.cookie.match(
    new RegExp(`(?:^|; )${name.replace(/([.$?*|{}()[\]\\/+^])/g, "\\$1")}=([^;]*)`),
  );
  return match ? decodeURIComponent(match[1]) : null;
}

export function deleteCookie(name: string): void {
  if (typeof document === "undefined") return;
  document.cookie = `${name}=; path=/; max-age=0`;
}

/** Save any JSON-serializable object as a cookie. */
export function setJSONCookie(name: string, value: unknown, days = 30): void {
  try {
    setCookie(name, JSON.stringify(value), days);
  } catch {
    // Ignore values that can't be serialized.
  }
}

/** Read and parse a JSON cookie; returns null if missing or invalid. */
export function getJSONCookie<T>(name: string): T | null {
  const raw = getCookie(name);
  if (!raw) return null;
  try {
    return JSON.parse(raw) as T;
  } catch {
    return null;
  }
}
