export const PRELOAD_FEED_DISPENSERS_KEY = "wesp_preload_feed_dispensers_v1";
export const PRELOAD_FEED_DISPENSERS_MAX_AGE_MS = 120_000;
export const LOGIN_TRANSITION_KEY = "wesp_login_transition_v1";
export const LOGIN_TRANSITION_MAX_AGE_MS = 120_000;

function readStoredEntry(key, maxAgeMs) {
  try {
    const raw = sessionStorage.getItem(key);
    if (!raw) return null;
    const parsed = JSON.parse(raw);
    if (!parsed || Date.now() - parsed.storedAt > maxAgeMs) {
      sessionStorage.removeItem(key);
      return null;
    }
    return parsed;
  } catch {
    return null;
  }
}

export function markLoginTransition() {
  try {
    sessionStorage.setItem(LOGIN_TRANSITION_KEY, JSON.stringify({
      storedAt: Date.now(),
    }));
  } catch {
    /* ignore */
  }
}

export function storePreloadedApiPayload(key, payload) {
  try {
    sessionStorage.setItem(key, JSON.stringify({
      storedAt: Date.now(),
      payload,
    }));
  } catch {
    /* ignore */
  }
}

export function peekPreloadedApiPayload(key, maxAgeMs = PRELOAD_FEED_DISPENSERS_MAX_AGE_MS) {
  const entry = readStoredEntry(key, maxAgeMs);
  return entry?.payload ?? null;
}

export function clearPreloadedApiPayload(key) {
  try {
    sessionStorage.removeItem(key);
  } catch {
    /* ignore */
  }
}

export function clearRecipesBootOverlay() {
  try {
    sessionStorage.removeItem(LOGIN_TRANSITION_KEY);
  } catch {
    /* ignore */
  }

  document.documentElement.classList.remove("wesp-login-boot-pending");

  const overlay = document.getElementById("wesp-recipes-boot");
  if (overlay) overlay.remove();

  window.WespPageEnter?.reveal?.();
}
