/**
 * Smooth anchor scrolling helper that dynamically calculates the real-time
 * rendered height of the fixed website header to guarantee perfect breathing room
 * without overlap or double-subtraction.
 */

export function getHeaderOffset(): number {
  if (typeof window === "undefined" || typeof document === "undefined") {
    return 80;
  }

  // 1. Try measuring the actual visible navbar/header element in the DOM
  const header = document.querySelector<HTMLElement>("[data-global-header]");
  if (header) {
    const nav = header.querySelector<HTMLElement>("[data-header-nav]") || header;
    const rect = nav.getBoundingClientRect();
    if (rect.bottom > 0) {
      return Math.round(rect.bottom);
    }
    if (rect.height > 0) {
      return Math.round(rect.height);
    }
  }

  // 2. Try reading the CSS variable set by the header's ResizeObserver
  const cssVar = getComputedStyle(document.documentElement).getPropertyValue("--header-offset");
  if (cssVar) {
    const parsed = parseFloat(cssVar);
    if (!isNaN(parsed) && parsed > 0) {
      return Math.round(parsed);
    }
  }

  // 3. Fallback to 80px (standard desktop header height)
  return 80;
}

export function smoothScrollTo(targetIdOrElement: string | HTMLElement, extraGap = 24) {
  if (typeof window === "undefined" || typeof document === "undefined") {
    return;
  }

  let el: HTMLElement | null = null;
  if (typeof targetIdOrElement === "string") {
    const cleanId = targetIdOrElement.replace(/^#/, "");
    el = document.getElementById(cleanId);
    if (!el) {
      // Also try querying by attribute or name
      el = document.querySelector<HTMLElement>(`[data-section="${cleanId}"], a[name="${cleanId}"]`);
    }
  } else {
    el = targetIdOrElement;
  }

  if (!el) return;

  const headerHeight = getHeaderOffset();
  const targetTop = el.getBoundingClientRect().top + window.scrollY - headerHeight - extraGap;

  window.scrollTo({
    top: Math.max(0, targetTop),
    behavior: "smooth",
  });
}
