(function () {
  'use strict';

  function isObservabilityPage() {
    return document.querySelector('.momo-observability-mode') !== null;
  }

  function normalizeLabel(text) {
    return (text || '').replace(/\s+/g, ' ').trim();
  }

  function enhanceTable(table) {
    if (!table || table.dataset.obsCardReady === '1') return;
    const headers = Array.from(table.querySelectorAll('thead th')).map((th) => normalizeLabel(th.textContent));
    if (!headers.length) return;

    table.querySelectorAll('tbody tr').forEach((row) => {
      Array.from(row.children).forEach((cell, index) => {
        if (!cell.hasAttribute('data-label')) {
          cell.setAttribute('data-label', headers[index] || '');
        }
      });
    });

    table.dataset.obsCardReady = '1';
    table.classList.add('obs-card-ready');
  }

  function enhanceTables() {
    if (!isObservabilityPage()) return;
    document.querySelectorAll('.table-responsive table').forEach(enhanceTable);
  }

  document.addEventListener('DOMContentLoaded', enhanceTables);

  let queued = false;
  const observer = new MutationObserver(() => {
    if (queued) return;
    queued = true;
    window.requestAnimationFrame(() => {
      queued = false;
      enhanceTables();
    });
  });

  document.addEventListener('DOMContentLoaded', () => {
    if (!isObservabilityPage()) return;
    observer.observe(document.body, { childList: true, subtree: true });
  });
})();
