(() => {
  '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 main = qs('.main-content');
  const sidebar = qs('.sidebar');

  // Persisted fixed sidebar state on desktop.
  const applyDesktopSidebarState = () => {
    if (window.innerWidth <= 1024) {
      body.classList.remove('sidebar-collapsed');
      return;
    }
    body.classList.toggle('sidebar-collapsed', localStorage.getItem('fleetlume.sidebar.v6.collapsed') === '1');
  };
  applyDesktopSidebarState();

  document.addEventListener('click', (event) => {
    const collapse = event.target.closest('[data-sidebar-collapse]');
    if (collapse) {
      event.preventDefault();
      const collapsed = !body.classList.contains('sidebar-collapsed');
      body.classList.toggle('sidebar-collapsed', collapsed);
      localStorage.setItem('fleetlume.sidebar.v6.collapsed', collapsed ? '1' : '0');
    }
    if (event.target.closest('[data-mobile-menu]')) {
      event.preventDefault();
      body.classList.add('sidebar-open');
      setTimeout(() => qs('[data-sidebar-close]')?.focus(), 20);
    }
    if (event.target.closest('[data-sidebar-close]')) {
      event.preventDefault();
      body.classList.remove('sidebar-open');
    }
  });

  window.addEventListener('resize', () => {
    if (window.innerWidth > 1024) body.classList.remove('sidebar-open');
    applyDesktopSidebarState();
  }, {passive: true});

  // Sticky topbar elevation must follow the main application scroller.
  const topbar = qs('.topbar');
  const updateTopbar = () => topbar?.classList.toggle('is-scrolled', (main?.scrollTop || window.scrollY) > 8);
  main?.addEventListener('scroll', updateTopbar, {passive: true});
  window.addEventListener('scroll', updateTopbar, {passive: true});
  updateTopbar();

  // Restore the active item into the visible part of the independently scrolling sidebar.
  requestAnimationFrame(() => {
    const active = qs('.sidebar-nav .nav-item.active');
    if (active) active.scrollIntoView({block: 'nearest'});
  });

  // Add accessible labels/tooltips for icon-only collapsed navigation.
  qsa('.sidebar-nav .nav-item').forEach((link) => {
    const label = link.querySelector('.nav-label')?.textContent?.trim() || link.dataset.navLabel || '';
    if (label) {
      link.title = label;
      link.setAttribute('aria-label', label);
    }
  });

  // Mark current page and reinforce colored navigation sections.
  const path = window.location.pathname.toLowerCase();
  const pageMap = [
    ['ai', /\/ai/], ['fuel', /\/fuel/], ['hos', /\/hos/], ['border', /\/borders/],
    ['invoice', /\/invoices/], ['accounting', /\/accounting|\/settlements/], ['tracking', /\/tracking/],
    ['equipment', /\/trucks|\/trailers|\/maintenance/], ['people', /\/drivers|\/carriers|\/users|\/brokers/],
    ['documents', /\/documents/], ['loads', /\/loads/], ['dashboard', /\/dashboard/]
  ];
  const pageKey = pageMap.find(([, pattern]) => pattern.test(path))?.[0] || 'general';
  body.dataset.page = pageKey;

  // Add a small colored indicator to generic panel headers that contain no icon after v5 decoration.
  const panelTones = ['blue', 'violet', 'green', 'cyan', 'orange', 'teal', 'red'];
  qsa('.panel-header').forEach((header, index) => {
    header.dataset.tone = panelTones[index % panelTones.length];
  });

  // Tables remain usable on every phone, including dynamically rendered rows.
  const prepareTable = (table) => {
    if (!(table instanceof HTMLTableElement) || table.matches('.invoice-table,.dashboard-load-table')) return;
    const headers = qsa('thead th', table).map((th) => th.textContent.trim());
    if (!headers.length) return;
    table.dataset.responsiveReady = '1';
    qsa('tbody tr', table).forEach((row) => {
      Array.from(row.children).forEach((cell, index) => {
        if (!cell.dataset.label) cell.dataset.label = headers[index] || 'Details';
      });
    });
  };
  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});

  // Keep sidebar footer visible while navigation has independent scroll.
  const syncSidebarRoom = () => {
    if (!sidebar) return;
    const footer = qs('.sidebar-footer', sidebar);
    const help = qs('.sidebar-help', sidebar);
    const nav = qs('.sidebar-nav', sidebar);
    if (!footer || !nav) return;
    const reserved = (footer.offsetHeight || 0) + (help?.offsetHeight || 0) + 126;
    nav.style.maxHeight = `calc(100dvh - ${reserved}px)`;
  };
  syncSidebarRoom();
  window.addEventListener('resize', syncSidebarRoom, {passive: true});

  // Close the drawer on navigation and Escape.
  qsa('.sidebar-nav a').forEach((link) => link.addEventListener('click', () => body.classList.remove('sidebar-open')));
  document.addEventListener('keydown', (event) => {
    if (event.key === 'Escape' && body.classList.contains('sidebar-open')) {
      body.classList.remove('sidebar-open');
      qs('[data-mobile-menu]')?.focus();
    }
  });

  // Detect horizontal overflow during QA and expose it for targeted styling.
  const markOverflow = () => {
    qsa('.page-content > *').forEach((element) => {
      element.classList.toggle('ui-overflowing', element.scrollWidth > element.clientWidth + 3);
    });
  };
  requestAnimationFrame(markOverflow);
  window.addEventListener('resize', markOverflow, {passive: true});

  body.classList.add('ui-v6-ready');
})();
