/**
 * Shared helper for the in-page CTAs that scroll to a section by id.
 *
 * Most CTAs are `<a href="#anchor">` and are handled by LanguageAwareLink. The
 * rest are plain `<button>`s that called `scrollIntoView` directly — which
 * animated fine but was invisible to the floating back arrow, so it dumped the
 * user at the top of the page instead of returning them. Routing those buttons
 * through here gives them the same behaviour as the anchors.
 */

/** sessionStorage key holding the position to return to. */
const RETURN_KEY = "ye:scroll:return";

/**
 * Anchors that represent a booking/registration form. Only these record where
 * the user came from — jumping to a listing section ("all programs") leaves the
 * arrow as a plain back-to-top.
 */
const FORM_ANCHORS = new Set([
  "footerForm",
  "program-Form",
  "program-from",
  "home-from",
  "registration-form",
]);

type ReturnPoint = { path: string; y: number };

/** Snapshot the current scroll position as "where the user came from". */
export function rememberReturnPosition() {
  if (typeof window === "undefined") return;
  try {
    const point: ReturnPoint = {
      path: window.location.pathname,
      y: window.scrollY,
    };
    sessionStorage.setItem(RETURN_KEY, JSON.stringify(point));
  } catch {
    // sessionStorage throws in some private-browsing modes — the arrow simply
    // falls back to "back to top".
  }
}

/**
 * Read and consume the stored position. Returns null if nothing was stored, or
 * if it was recorded on a different page (so a stale position from a previous
 * route is never applied here).
 */
export function takeReturnPosition(): number | null {
  if (typeof window === "undefined") return null;
  try {
    const raw = sessionStorage.getItem(RETURN_KEY);
    if (!raw) return null;
    sessionStorage.removeItem(RETURN_KEY);

    const point = JSON.parse(raw) as ReturnPoint;
    if (point?.path !== window.location.pathname) return null;
    return typeof point.y === "number" ? point.y : null;
  } catch {
    return null;
  }
}

/**
 * Smooth-scroll to an element by id.
 *
 * @param record Whether to remember the current position first, so the floating
 *   arrow can bring the user back. Defaults to true for form anchors only.
 * @returns false if no such element exists.
 */
export function scrollToId(
  id: string,
  { record }: { record?: boolean } = {}
): boolean {
  if (typeof window === "undefined") return false;

  const target = document.getElementById(id);
  if (!target) return false;

  if (record ?? FORM_ANCHORS.has(id)) rememberReturnPosition();

  // `scrollIntoView` honours any `scroll-mt-*` class on the target, so existing
  // per-page framing keeps working.
  target.scrollIntoView({ behavior: "smooth", block: "start" });
  return true;
}
