/**
 * Svelte action: positions a dropdown element using fixed coordinates so it
 * escapes `overflow: hidden` parent containers.
 *
 * Expects the dropdown's parent to contain a sibling element with class `menu-btn`.
 *
 * Usage:
 * ```svelte
 * <div class="my-dropdown" use:positionMenu>…</div>
 * ```
 */
export function positionMenu(node: HTMLElement) {
  const btn = node.parentElement?.querySelector(
    ".menu-btn",
  ) as HTMLElement | null;
  if (!btn) return;

  function update() {
    const rect = btn!.getBoundingClientRect();
    node.style.top = `${rect.bottom + 4}px`;
    node.style.left = `${rect.right - node.offsetWidth}px`;
  }

  update();
  window.addEventListener("scroll", update, true);
  window.addEventListener("resize", update);

  return {
    destroy() {
      window.removeEventListener("scroll", update, true);
      window.removeEventListener("resize", update);
    },
  };
}
