(() => {
  const page = document.getElementById('asset-list-page');
  const loader = document.getElementById('asset-page-loader');
  const table = document.getElementById('asset-table');
  if (!page || !table) return;

  const required = [
    'tableToolsReady',
    'browserStateReady',
    'columnOrderReady',
    'columnManagerReady'
  ];
  let revealed = false;
  let fallbackTimer = 0;

  function ready() {
    return required.every(marker => table.dataset[marker] === '1');
  }

  function reveal() {
    if (revealed) return;
    revealed = true;
    clearTimeout(fallbackTimer);

    const finish = () => requestAnimationFrame(() => {
      page.classList.remove('asset-list-initializing');
      page.setAttribute('aria-busy', 'false');
      document.documentElement.classList.remove('asset-page-booting');
      loader?.setAttribute('hidden', '');
      window.dispatchEvent(new CustomEvent('asset-page-ready', {
        detail: { table }
      }));
    });

    if (document.fonts?.ready) {
      document.fonts.ready.then(finish, finish);
    } else {
      finish();
    }
  }

  function check() {
    if (ready()) reveal();
  }

  [
    'asset-table-structure-ready',
    'asset-table-state-ready',
    'asset-table-column-order-ready',
    'asset-table-columns-ready',
    'asset-list-count-updated'
  ].forEach(name => window.addEventListener(name, check));

  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', check, { once: true });
  } else {
    check();
  }

  fallbackTimer = window.setTimeout(reveal, 2500);
})();
