"use client";

import { useSyncExternalStore } from "react";

/**
 * The current time, re-read on a fixed interval.
 *
 * For state that is a function of *now*: an attendance scan window that opens
 * and shuts on the clock, a countdown, a "starts in" label. A query refetch
 * cannot drive those — the data has not changed, the time has.
 *
 * `useSyncExternalStore` rather than `useState` + an interval that calls
 * `setState`:
 *
 *  - it has no post-paint state write, so `set-state-in-effect` has nothing to
 *    report and there is no extra render pass per tick;
 *  - it takes an explicit `getServerSnapshot`, which is what makes reading a
 *    browser-only value safe in a Client Component that is still rendered on the
 *    server. A plain `Date.now()` in a lazy `useState` initialiser runs during
 *    render on *both* sides and hydrates against a different number.
 *
 * The snapshot is a number, which React can compare with `Object.is`; an object
 * would re-render forever.
 *
 * One interval per distinct period is shared by every subscriber, so ten
 * components on a minute clock cost one timer and all tick together.
 */

interface ClockStore {
  value: number;
  listeners: Set<() => void>;
  timer: ReturnType<typeof setInterval> | null;
}

const stores = new Map<number, ClockStore>();
/**
 * One subscribe function per period, kept for the module's lifetime.
 * `useSyncExternalStore` resubscribes whenever it receives a new function; a
 * fresh closure per render made every render unsubscribe (stopping the timer),
 * resubscribe (resetting `value` to `Date.now()`), see a changed snapshot and
 * render again — "Maximum update depth exceeded" in the header.
 */
const subscribers = new Map<number, (onStoreChange: () => void) => () => void>();

function storeFor(periodMs: number): ClockStore {
  let store = stores.get(periodMs);
  if (!store) {
    store = { value: Date.now(), listeners: new Set(), timer: null };
    stores.set(periodMs, store);
  }
  return store;
}

function subscribeTo(periodMs: number) {
  const cached = subscribers.get(periodMs);
  if (cached) return cached;
  const subscribe = (onStoreChange: () => void) => {
    const store = storeFor(periodMs);
    store.listeners.add(onStoreChange);
    if (store.timer === null) {
      // A store survives its last subscriber. Reopening a page hours later
      // must not briefly restore the old registration/edit window.
      store.value = Date.now();
      store.timer = setInterval(() => {
        store.value = Date.now();
        store.listeners.forEach((listener) => listener());
      }, periodMs);
    }
    return () => {
      store.listeners.delete(onStoreChange);
      if (store.listeners.size === 0 && store.timer !== null) {
        clearInterval(store.timer);
        store.timer = null;
      }
    };
  };
  subscribers.set(periodMs, subscribe);
  return subscribe;
}

/**
 * The server snapshot, and the value every reader sees before the first tick.
 *
 * `0` rather than a real time: the server and the hydrating client must agree,
 * and they cannot agree on a clock reading. A consumer comparing a window
 * against `0` finds it shut, which is the correct pre-measurement answer —
 * nothing is "live" until the browser has told us when now is.
 */
function serverSnapshot(): number {
  return 0;
}

export function useClock(periodMs: number): number {
  return useSyncExternalStore(
    subscribeTo(periodMs),
    () => storeFor(periodMs).value,
    serverSnapshot
  );
}
