"use client";

import { useSyncExternalStore } from "react";

/**
 * The viewport width, as an external store rather than mirrored state.
 *
 * Several hooks read `window.innerWidth` in a mount effect, called `setState`
 * with it, and subscribed to `resize` to do the same again. That is what
 * `react-hooks/set-state-in-effect` flags, and the usual fix — a lazy
 * `useState` initialiser — is wrong here: these are Client Components that are
 * still rendered on the server, where `window` does not exist, so reading it
 * during the first render would either throw or hydrate against a different
 * value than the server produced.
 *
 * `useSyncExternalStore` is React's answer to exactly that shape. It takes a
 * separate `getServerSnapshot`, so the server and the first client render agree
 * on a declared value, and React swaps in the real measurement without a
 * post-paint state write. The subscription is the same `resize` listener as
 * before.
 *
 * The snapshot must be a primitive: React compares snapshots with `Object.is`,
 * and a fresh object every call would re-render forever. A number is safe.
 */
function subscribe(onStoreChange: () => void): () => void {
  window.addEventListener("resize", onStoreChange);
  return () => window.removeEventListener("resize", onStoreChange);
}

function clientWidth(): number {
  return window.innerWidth;
}

/**
 * The width to assume before the browser has been measured.
 *
 * Mobile-first, matching what every one of the replaced hooks initialised its
 * state to — so the first paint is unchanged from before this hook existed.
 */
const SERVER_WIDTH = 0;

function serverWidth(): number {
  return SERVER_WIDTH;
}

export function useViewportWidth(): number {
  return useSyncExternalStore(subscribe, clientWidth, serverWidth);
}

/**
 * The first entry whose `minWidth` the viewport meets, widest first.
 *
 * A width of 0 — the pre-measurement snapshot — matches only an entry with
 * `minWidth: 0`, which is why every caller's table ends with one.
 */
export function useResponsiveValue<T>(
  table: ReadonlyArray<{ minWidth: number; value: T }>,
  fallback: T
): T {
  const width = useViewportWidth();
  return table.find((entry) => width >= entry.minWidth)?.value ?? fallback;
}
