document.addEventListener('DOMContentLoaded', function () {
  const pageContent = document.querySelector('.page-content');
  if (!pageContent) return;

  // Kill accidental big top gaps on legacy pages.
  const firstElement = pageContent.firstElementChild;
  if (firstElement) {
    firstElement.style.marginTop = '0';
  }

  // Upgrade legacy headings where possible.
  const legacyHeaders = pageContent.querySelectorAll('.topbar, .page-header, .page-header-box, .page-topbar, .ofr-page-title, .stg-top, .nay-module-header, .module-header');
  legacyHeaders.forEach((el) => {
    el.classList.add('ui-upgraded-hero');
  });

  // Add a soft card wrapper to plain forms/tables that are directly inside content.
  pageContent.querySelectorAll('table').forEach((table) => {
    if (!table.closest('.table-wrap, .ns-table-wrap, .table-responsive')) {
      const wrap = document.createElement('div');
      wrap.className = 'table-wrap ui-autowrap';
      table.parentNode.insertBefore(wrap, table);
      wrap.appendChild(table);
    }
  });

  // Normalize page titles when only h2 exists at page root inside a .container.
  pageContent.querySelectorAll('.container').forEach((container) => {
    const first = container.firstElementChild;
    if (!first) return;
    if ((first.tagName === 'H1' || first.tagName === 'H2') && !first.closest('.topbar, .page-header, .page-header-box, .page-topbar, .hero-card')) {
      const hero = document.createElement('div');
      hero.className = 'page-header ui-upgraded-hero';
      const title = document.createElement('div');
      const h1 = document.createElement('h1');
      h1.textContent = first.textContent.trim();
      title.appendChild(h1);
      hero.appendChild(title);
      container.insertBefore(hero, first);
      first.remove();
    }
  });
});
