export const AUTOMATIC_RENEWAL_AGREEMENT_VERSION = "2026-07-29";

const STORAGE_PREFIX = "cozsweet.automatic-renewal-acknowledged";

function storageKey(subjectId: string | null | undefined): string | null {
  const normalized = subjectId?.trim();
  if (!normalized) return null;
  return `${STORAGE_PREFIX}:${AUTOMATIC_RENEWAL_AGREEMENT_VERSION}:${encodeURIComponent(normalized)}`;
}

export function hasAutomaticRenewalAcknowledgement(
  subjectId: string | null | undefined,
): boolean {
  const key = storageKey(subjectId);
  if (!key || typeof window === "undefined") return false;
  try {
    return window.localStorage.getItem(key) === "confirmed";
  } catch {
    return false;
  }
}

export function rememberAutomaticRenewalAcknowledgement(
  subjectId: string | null | undefined,
): void {
  const key = storageKey(subjectId);
  if (!key || typeof window === "undefined") return;
  try {
    window.localStorage.setItem(key, "confirmed");
  } catch {
    // Storage can be unavailable in privacy-restricted in-app browsers.
  }
}
