(function () {
  'use strict';
  const body = document.body;
  const $ = (selector, root = document) => root.querySelector(selector);
  const $$ = (selector, root = document) => Array.from(root.querySelectorAll(selector));

  // Sidebar state and mobile drawer.
  const collapsed = localStorage.getItem('fleetlume.sidebar.collapsed') === '1';
  if (collapsed && window.innerWidth > 1024) body.classList.add('sidebar-collapsed');
  document.addEventListener('click', (event) => {
    if (event.target.closest('[data-sidebar-collapse]')) {
      body.classList.toggle('sidebar-collapsed');
      localStorage.setItem('fleetlume.sidebar.collapsed', body.classList.contains('sidebar-collapsed') ? '1' : '0');
    }
    if (event.target.closest('[data-sidebar-close]')) body.classList.remove('sidebar-open');
  });
  window.addEventListener('resize', () => { if (window.innerWidth > 1024) body.classList.remove('sidebar-open'); });

  // Navigation filter.
  const navFilter = $('[data-nav-filter]');
  if (navFilter) navFilter.addEventListener('input', () => {
    const value = navFilter.value.trim().toLowerCase();
    $$('.nav-item', $('[data-nav-container]')).forEach(link => {
      const match = !value || (link.dataset.navLabel || link.textContent).includes(value);
      link.hidden = !match;
    });
    $$('.nav-section', $('[data-nav-container]')).forEach(section => {
      const visible = $$('.nav-item', section).some(link => !link.hidden);
      section.hidden = !visible;
      if (value && visible) section.open = true;
    });
  });

  // Command palette. It must always begin closed and only open by an explicit user action.
  const palette = $('[data-command-palette]');
  let paletteOpener = null;
  const openPalette = (opener = null) => {
    if (!palette) return;
    paletteOpener = opener instanceof HTMLElement ? opener : document.activeElement;
    palette.hidden = false;
    palette.setAttribute('aria-hidden', 'false');
    body.classList.add('command-open');
    body.style.overflow = 'hidden';
    setTimeout(() => $('[data-command-input]', palette)?.focus(), 0);
  };
  const closePalette = () => {
    if (!palette) return;
    palette.hidden = true;
    palette.setAttribute('aria-hidden', 'true');
    body.classList.remove('command-open');
    body.style.overflow = '';
    if (paletteOpener && typeof paletteOpener.focus === 'function') paletteOpener.focus();
    paletteOpener = null;
  };
  if (palette) closePalette();
  document.addEventListener('click', event => {
    const openButton = event.target.closest('[data-command-open]');
    if (openButton) {
      event.preventDefault();
      openPalette(openButton);
      return;
    }
    if (event.target.closest('[data-command-close]')) {
      event.preventDefault();
      closePalette();
    }
  });
  document.addEventListener('keydown', event => {
    if ((event.metaKey || event.ctrlKey) && event.key.toLowerCase() === 'k') {
      event.preventDefault();
      palette && !palette.hidden ? closePalette() : openPalette();
      return;
    }
    if (event.key === 'Escape' && palette && !palette.hidden) {
      event.preventDefault();
      closePalette();
    }
  });

  // Make every table readable as cards on mobile, without editing each view.
  $$('.table-wrap table').forEach(table => {
    const headers = $$('thead th', table).map(th => th.textContent.trim());
    if (!headers.length) return;
    $$('tbody tr', table).forEach(row => {
      $$('td', row).forEach((cell, index) => { if (!cell.dataset.label) cell.dataset.label = headers[index] || 'Details'; });
    });
    table.dataset.responsiveReady = '1';
  });

  // Preserve open navigation group across reloads.
  $$('.sidebar-v3 .nav-section').forEach((section, index) => {
    const key = 'fleetlume.nav.' + index;
    if (!section.open && localStorage.getItem(key) === '1' && !$('.nav-item.active', section)) section.open = true;
    section.addEventListener('toggle', () => localStorage.setItem(key, section.open ? '1' : '0'));
  });

  // Forms: disable submit button briefly to prevent duplicate actions.
  $$('form').forEach(form => form.addEventListener('submit', () => {
    const button = form.querySelector('button[type="submit"], button:not([type])');
    if (!button || button.dataset.noLock !== undefined) return;
    button.dataset.originalText = button.textContent;
    button.setAttribute('aria-busy', 'true');
    setTimeout(() => { button.disabled = true; }, 0);
    setTimeout(() => { button.disabled = false; button.removeAttribute('aria-busy'); }, 12000);
  }));

  // Scroll active sidebar item into view after layout settles.
  setTimeout(() => $('.sidebar-v3 .nav-item.active')?.scrollIntoView({block:'nearest'}), 80);
})();
