// Smooth-scroll for same-page links that use "./#anchor"
(function () {
  function sameDoc(u) {
    var a = document.createElement('a');
    a.href = u;
    var cur = window.location;
    var norm = function (p) { return p.replace(/\/+$/,''); }; // trim trailing slash
    return a.origin === cur.origin && norm(a.pathname) === norm(cur.pathname);
  }

  document.addEventListener('click', function (e) {
    var link = e.target && e.target.closest && e.target.closest('a[href^="./#"]');
    if (!link) return;

    var url = new URL(link.getAttribute('href'), window.location.href);
    if (!sameDoc(url.href)) return; // only hijack same-document jumps

    var id = decodeURIComponent((url.hash || '').slice(1));
    if (!id) return;

    var target = document.getElementById(id) ||
                 document.querySelector('[name="'+ (window.CSS && CSS.supports && CSS.supports('selector(:is(*))') && CSS.escape ? CSS.escape(id) : id) +'"]');
    if (!target) return;

    e.preventDefault();

    // Adjust if you have a fixed header (e.g., const offset = document.querySelector('.l-header')?.offsetHeight || 0;)
    var offset = 0;
    var top = target.getBoundingClientRect().top + window.pageYOffset - offset;

    window.scrollTo({ top: top, behavior: 'smooth' });
    try { history.replaceState(null, '', '#' + encodeURIComponent(id)); } catch (_) {}
  }, { capture: true });
})();
