(() => {
  'use strict';

  const root = document.documentElement;
  const body = document.body;
  if (!body || body.dataset.modernUiReady === '1') return;
  body.dataset.modernUiReady = '1';

  const main = document.querySelector('main, .desk-main, [role="main"], .content');
  if (main && !main.id) main.id = 'mavela-main-content';
  const skipLink = document.querySelector('.mavela-skip-link');
  if (skipLink && main) skipLink.href = `#${main.id}`;

  document.querySelectorAll('table').forEach((table) => {
    if (table.closest('.mavela-table-scroll') || table.closest('[data-no-table-scroll]')) return;
    const wrapper = document.createElement('div');
    wrapper.className = 'mavela-table-scroll';
    wrapper.tabIndex = 0;
    wrapper.setAttribute('role', 'region');
    wrapper.setAttribute('aria-label', table.getAttribute('aria-label') || 'Scrollable data table');
    table.parentNode?.insertBefore(wrapper, table);
    wrapper.appendChild(table);
  });

  const sidebar = document.querySelector('.desk-sidebar, aside.sidebar, aside.nav');
  const nav = sidebar?.querySelector('nav, .desk-nav, .menu') || sidebar;
  if (sidebar) sidebar.classList.add('mavela-enhanced-sidebar');

  if (nav) {
    const navButtons = Array.from(nav.querySelectorAll('button, a')).filter((item) => {
      return item.textContent.trim() !== '' && !item.classList.contains('mavela-menu-search');
    });

    if (navButtons.length >= 7) {
      const searchWrap = document.createElement('div');
      searchWrap.className = 'mavela-menu-search-wrap';
      const search = document.createElement('input');
      search.type = 'search';
      search.className = 'mavela-menu-search';
      search.placeholder = 'Find a section…';
      search.autocomplete = 'off';
      search.setAttribute('aria-label', 'Filter menu sections');
      const empty = document.createElement('p');
      empty.className = 'mavela-menu-empty';
      empty.textContent = 'No matching sections';
      searchWrap.append(search, empty);
      nav.insertBefore(searchWrap, nav.firstChild);

      search.addEventListener('input', () => {
        const query = search.value.trim().toLocaleLowerCase();
        let visible = 0;
        navButtons.forEach((item) => {
          const matches = query === '' || item.textContent.toLocaleLowerCase().includes(query);
          item.hidden = !matches;
          if (matches) visible += 1;
        });
        empty.classList.toggle('visible', visible === 0);
      });
    }
  }

  const dock = document.createElement('div');
  dock.className = 'mavela-utility-dock';
  dock.setAttribute('aria-label', 'Display and navigation tools');

  const makeButton = (label, title, handler, extraClass = '') => {
    const button = document.createElement('button');
    button.type = 'button';
    button.className = `mavela-utility-btn ${extraClass}`.trim();
    button.textContent = label;
    button.title = title;
    button.setAttribute('aria-label', title);
    button.addEventListener('click', handler);
    dock.appendChild(button);
    return button;
  };

  const schoolRoles = ['admin', 'teacher', 'hop', 'accountant', 'ancillary', 'learner', 'parent'];
  if (schoolRoles.includes(body.dataset.userRole || '') && !location.pathname.endsWith('/academic_planner.php')) {
    const planner = document.createElement('a');
    planner.className = 'mavela-utility-btn';
    planner.textContent = 'Planner';
    planner.title = 'Open the academic timetable and events calendar';
    planner.setAttribute('aria-label', planner.title);
    planner.href = 'academic_planner.php';
    dock.appendChild(planner);
  }

  let navBackdrop = null;
  if (sidebar) {
    navBackdrop = document.createElement('div');
    navBackdrop.className = 'mavela-nav-backdrop';
    navBackdrop.setAttribute('aria-hidden', 'true');
    body.appendChild(navBackdrop);

    const closeNav = () => {
      body.classList.remove('mavela-nav-open');
      menuButton?.setAttribute('aria-expanded', 'false');
    };
    const menuButton = makeButton('Menu', 'Open or close the page menu', () => {
      const isOpen = body.classList.toggle('mavela-nav-open');
      menuButton.setAttribute('aria-expanded', String(isOpen));
      if (isOpen) sidebar.querySelector('button, a, input')?.focus();
    }, 'mavela-mobile-nav');
    menuButton.setAttribute('aria-expanded', 'false');
    navBackdrop.addEventListener('click', closeNav);
    sidebar.addEventListener('click', (event) => {
      if (event.target.closest('button, a') && window.matchMedia('(max-width: 900px)').matches) {
        closeNav();
      }
    });
    document.addEventListener('keydown', (event) => {
      if (event.key === 'Escape') closeNav();
    });
  }

  const savedTheme = localStorage.getItem('mavela-theme');
  if (savedTheme === 'dark') root.dataset.mavelaTheme = 'dark';
  const themeButton = makeButton(
    savedTheme === 'dark' ? 'Light' : 'Dark',
    'Switch between light and dark appearance',
    () => {
      const useDark = root.dataset.mavelaTheme !== 'dark';
      if (useDark) root.dataset.mavelaTheme = 'dark';
      else delete root.dataset.mavelaTheme;
      localStorage.setItem('mavela-theme', useDark ? 'dark' : 'light');
      themeButton.textContent = useDark ? 'Light' : 'Dark';
    }
  );

  const largeTypeEnabled = localStorage.getItem('mavela-large-type') === '1';
  body.classList.toggle('mavela-large-type', largeTypeEnabled);
  const typeButton = makeButton(largeTypeEnabled ? 'A−' : 'A+', 'Increase or reset text size', () => {
    const enabled = !body.classList.contains('mavela-large-type');
    body.classList.toggle('mavela-large-type', enabled);
    localStorage.setItem('mavela-large-type', enabled ? '1' : '0');
    typeButton.textContent = enabled ? 'A−' : 'A+';
  });

  body.appendChild(dock);

  document.querySelectorAll('form').forEach((form) => {
    form.addEventListener('submit', (event) => {
      const submitter = event.submitter;
      if (!(submitter instanceof HTMLElement)) return;
      submitter.classList.add('mavela-submit-busy');
      submitter.setAttribute('aria-busy', 'true');
    });
  });

  document.addEventListener('keydown', (event) => {
    if (event.key !== '/' || event.ctrlKey || event.metaKey || event.altKey) return;
    const activeTag = document.activeElement?.tagName?.toLowerCase();
    if (['input', 'textarea', 'select'].includes(activeTag)) return;
    const search = document.querySelector('.mavela-menu-search, input[type="search"]');
    if (search) {
      event.preventDefault();
      search.focus();
    }
  });
})();
