(function () {
  'use strict';

  const body = document.body;
  const qs = (selector, root = document) => root.querySelector(selector);
  const qsa = (selector, root = document) => Array.from(root.querySelectorAll(selector));

  const setViewportHeight = () => {
    document.documentElement.style.setProperty('--app-vh', `${window.innerHeight * 0.01}px`);
  };
  setViewportHeight();
  window.addEventListener('resize', setViewportHeight, {passive: true});

  // Navigation accessibility and predictable mobile drawer behavior.
  qsa('.sidebar-nav a.active').forEach(link => link.setAttribute('aria-current', 'page'));
  document.addEventListener('keydown', event => {
    if (event.key === 'Escape' && body.classList.contains('sidebar-open')) {
      body.classList.remove('sidebar-open');
      qs('[data-mobile-menu]')?.focus();
    }
  });
  qsa('.sidebar-nav a').forEach(link => link.addEventListener('click', () => body.classList.remove('sidebar-open')));

  // Header gains a subtle elevation after scrolling.
  const topbar = qs('.topbar-v4');
  const updateTopbar = () => topbar?.classList.toggle('is-scrolled', window.scrollY > 8);
  updateTopbar();
  window.addEventListener('scroll', updateTopbar, {passive: true});

  // Close open profile menu after selecting another surface.
  document.addEventListener('click', event => {
    qsa('.profile-menu[open]').forEach(menu => {
      if (!menu.contains(event.target)) menu.removeAttribute('open');
    });
  });

  // Keep dynamically inserted tables mobile-readable too.
  const prepareTable = table => {
    if (!(table instanceof HTMLTableElement) || table.matches('.invoice-table')) return;
    const headers = qsa('thead th', table).map(th => th.textContent.trim());
    if (!headers.length) return;
    qsa('tbody tr', table).forEach(row => {
      qsa(':scope > td', row).forEach((cell, index) => {
        if (!cell.dataset.label) cell.dataset.label = headers[index] || 'Details';
      });
    });
    table.dataset.responsiveReady = '1';
  };
  qsa('.table-wrap table').forEach(prepareTable);
  const tableObserver = new MutationObserver(records => {
    records.forEach(record => record.addedNodes.forEach(node => {
      if (!(node instanceof Element)) return;
      if (node.matches?.('.table-wrap table')) prepareTable(node);
      qsa('.table-wrap table', node).forEach(prepareTable);
    }));
  });
  tableObserver.observe(document.body, {childList: true, subtree: true});

  // Command-palette single-key shortcuts only while the palette is visible.
  document.addEventListener('keydown', event => {
    const palette = qs('[data-command-palette]');
    if (!palette || palette.hidden || event.metaKey || event.ctrlKey || event.altKey || event.shiftKey) return;
    const active = document.activeElement;
    if (active && ['INPUT', 'TEXTAREA', 'SELECT'].includes(active.tagName)) return;
    const destinations = {
      l: '.command-shortcuts a[href*="/loads/create"]',
      a: '.command-shortcuts a[href*="/ai/automation"]',
      d: '.command-shortcuts a[href*="/documents/create"]',
      f: '.command-shortcuts a[href*="/fuel"]'
    };
    const destination = destinations[event.key.toLowerCase()];
    if (!destination) return;
    const link = qs(destination, palette);
    if (link) {
      event.preventDefault();
      window.location.href = link.href;
    }
  });

  // Prevent accidental horizontal page overflow without blocking intentional scrollers.
  const markOverflowingSections = () => {
    qsa('.page-content > *').forEach(section => {
      section.classList.toggle('has-horizontal-overflow', section.scrollWidth > section.clientWidth + 2);
    });
  };
  requestAnimationFrame(markOverflowingSections);
  window.addEventListener('resize', markOverflowingSections, {passive: true});
})();
