(function () {
  function getBase() {
    // resources pages live at /resources/<file>. We need /includes and /assets.
    // Use absolute paths to avoid path issues.
    return '';
  }

  async function fetchText(url) {
    const res = await fetch(url, { credentials: 'same-origin' });
    if (!res.ok) throw new Error('Failed to fetch ' + url + ' (' + res.status + ')');
    return await res.text();
  }

  function extractBodyInner(html) {
    // partials do not include a full HTML doc, but keep this defensive.
    return html;
  }

  async function inject() {
    const headerTarget = document.getElementById('resources-site-header');
    const footerTarget = document.getElementById('resources-site-footer');
    if (!headerTarget && !footerTarget) return;

    const headerUrl = (getBase() || '.') + '/includes/header.partial.php';
    const footerUrl = (getBase() || '.') + '/includes/footer.partial.php';

    try {
      const [headerHtml, footerHtml] = await Promise.all([
        headerTarget ? fetchText(headerUrl) : Promise.resolve(''),
        footerTarget ? fetchText(footerUrl) : Promise.resolve(''),
      ]);

      if (headerTarget) headerTarget.innerHTML = extractBodyInner(headerHtml);
      if (footerTarget) footerTarget.innerHTML = extractBodyInner(footerHtml);

      // Initialize main.js handlers if it exposes any, or just rely on existing DOMContentLoaded hooks.
      document.dispatchEvent(new Event('resources-layout-injected'));
    } catch (e) {
      console.error('[resources-layout-injector]', e);
    }
  }

  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', inject);
  } else {
    inject();
  }
})();

