"use client";

import * as React from "react";

/** The gap kept between what has the focus and the top of a bar. */
export const RESERVED_GAP = 16;

/** The nearest ancestor that scrolls: the shell's `main`, or the document. */
export function scrollParent(node: HTMLElement): HTMLElement {
  for (let el = node.parentElement; el; el = el.parentElement) {
    const { overflowY } = getComputedStyle(el);
    if (overflowY === "auto" || overflowY === "scroll") return el;
  }
  return document.documentElement;
}

// What moves the scroller or unsticks a bar: below 1024px in a window under
// 600px tall the shell's column scrolls rather than `main` (Z2), and a bar
// may be in the flow there. Both edges, so a window resized across either
// re-resolves.
const LAYOUT_QUERIES = ["(max-height: 599px)", "(min-width: 64rem)"];

/**
 * A bar stuck to the bottom of the window covers what scrolls under it, and
 * the keyboard's focus must not end up there (WCAG 2.4.11): while it is
 * shown and stuck, its height and `extra` are reserved at the bottom of
 * whatever scrolls the page. A bar that is hidden (0px) or in the flow at
 * this size reserves nothing.
 */
export function useBottomReserve(
  barRef: React.RefObject<HTMLElement | null>,
  { on = true, extra = RESERVED_GAP }: { on?: boolean; extra?: number } = {},
) {
  React.useEffect(() => {
    const bar = barRef.current;
    if (!on || !bar) return;
    let scroller = scrollParent(bar);
    let previous = scroller.style.scrollPaddingBottom;
    const reserve = () => {
      const height = Math.ceil(bar.getBoundingClientRect().height);
      const { position } = getComputedStyle(bar);
      const stuck = position !== "static" && position !== "relative";
      scroller.style.scrollPaddingBottom =
        height > 0 && stuck ? `${height + extra}px` : previous;
    };
    const move = () => {
      scroller.style.scrollPaddingBottom = previous;
      scroller = scrollParent(bar);
      previous = scroller.style.scrollPaddingBottom;
      reserve();
    };
    reserve();
    const queries = LAYOUT_QUERIES.map((query) => window.matchMedia?.(query));
    for (const query of queries) query?.addEventListener("change", move);
    const observer =
      typeof ResizeObserver === "undefined"
        ? null
        : new ResizeObserver(reserve);
    observer?.observe(bar);
    return () => {
      observer?.disconnect();
      for (const query of queries) query?.removeEventListener("change", move);
      scroller.style.scrollPaddingBottom = previous;
    };
  }, [barRef, on, extra]);
}
