/**
 * The email "remember me" keeps, as an external store.
 *
 * `localStorage` is the real owner of this value, which is why the login form
 * holds no copy of it. It used to: a `useState` seeded empty and overwritten by
 * a mount effect, reported by `react-hooks/set-state-in-effect`. The rule's
 * advice for exactly this shape is to subscribe to the external system instead,
 * and `useSyncExternalStore` needs three things — a subscribe, a snapshot and a
 * *server* snapshot — which is what this module provides.
 *
 * The snapshot is a string or `null`, never an object: React compares snapshots
 * with `Object.is`, so returning a fresh `{ email }` on every call would
 * re-render forever.
 *
 * Writes go through `rememberEmail` / `forgetEmail` rather than
 * `localStorage.setItem` directly, because a same-tab write does not fire the
 * `storage` event — only another tab's does — so the subscribers have to be
 * told explicitly.
 */

const REMEMBERED_EMAIL_KEY = "rememberedEmail";

/** Pre-fix key that held `{ email, password }` in clear text. */
const LEGACY_CREDENTIALS_KEY = "rememberedCredentials";

const listeners = new Set<() => void>();

function emit(): void {
  for (const listener of listeners) listener();
}

export function subscribeRememberedEmail(onChange: () => void): () => void {
  listeners.add(onChange);
  /* Another tab signing in or out is a legitimate change to this value, and
     `storage` is the only notification for it. */
  window.addEventListener("storage", onChange);
  return () => {
    listeners.delete(onChange);
    window.removeEventListener("storage", onChange);
  };
}

export function getRememberedEmail(): string | null {
  try {
    return localStorage.getItem(REMEMBERED_EMAIL_KEY) || null;
  } catch {
    // Private mode / blocked storage — the form just starts empty.
    return null;
  }
}

/**
 * The value to assume before the browser has been read.
 *
 * `null`, matching the empty `useState` this replaces, so the server render and
 * the first client render agree and the form's first paint is unchanged.
 */
export function getServerRememberedEmail(): null {
  return null;
}

export function rememberEmail(email: string): void {
  try {
    localStorage.setItem(REMEMBERED_EMAIL_KEY, email);
  } catch {
    // Nothing to remember it with; the sign-in itself is unaffected.
  }
  emit();
}

export function forgetEmail(): void {
  try {
    localStorage.removeItem(REMEMBERED_EMAIL_KEY);
  } catch {
    // ignore
  }
  emit();
}

/**
 * Drop any `{ email, password }` left by an older build, keeping the email.
 *
 * The password is deliberately not carried over: "remember me" is a
 * server-side concept here — it makes `POST /login/` issue a 30-day token
 * instead of a 1-day one — so the session survives on the token alone and a
 * stored password would buy nothing but risk.
 *
 * Idempotent: it removes the legacy entry before doing anything else, so a
 * second call (StrictMode's double-invoked mount effect, for one) finds
 * nothing and leaves the migrated email alone.
 */
export function migrateLegacyCredentials(): void {
  let legacy: string | null = null;
  try {
    legacy = localStorage.getItem(LEGACY_CREDENTIALS_KEY);
    if (legacy === null) return;
    localStorage.removeItem(LEGACY_CREDENTIALS_KEY);
  } catch {
    return;
  }
  try {
    const { email } = JSON.parse(legacy) as { email?: unknown };
    if (typeof email === "string" && email && !getRememberedEmail()) {
      rememberEmail(email);
    }
  } catch {
    // Unparseable leftover — removing it was the point.
  }
}
