(() => {
  'use strict';

  const html = document.documentElement;
  const theme = html.dataset.scrollTheme || '';
  const mobile54 = matchMedia('(max-width: 54rem)');

  const text = node => (node?.textContent || '').replace(/\s+/g, ' ').trim();
  const important = (node, declarations) => {
    if (!(node instanceof HTMLElement)) return;
    Object.entries(declarations).forEach(([property, value]) => node.style.setProperty(property, value, 'important'));
  };

  function markSingleDocumentScroll() {
    if (!['sentiment-analysis', 'academic-evidence'].includes(theme)) return false;
    const root = document.querySelector('#root,#app,#__next,[data-reactroot]');
    if (!root) return false;

    const shells = [...root.children].filter(node => node instanceof HTMLElement);
    const shell = shells.find(node => node.querySelector(':scope > main') || node.querySelector('main')) || root.firstElementChild;
    if (!(shell instanceof HTMLElement)) return false;

    const sidebar = shell.querySelector(':scope > aside') || shell.querySelector('aside');
    const main = shell.querySelector(':scope > main') || shell.querySelector('main,[role="main"]');
    if (!main) return false;

    shell.dataset.apuV54ScrollShell = 'true';
    main.dataset.apuV54ScrollMain = 'true';
    if (sidebar) sidebar.dataset.apuV54ScrollSidebar = 'true';

    let content = [...main.children].find(node => {
      if (!(node instanceof HTMLElement) || node.tagName === 'HEADER' || node.tagName === 'FOOTER') return false;
      const style = getComputedStyle(node);
      return /(auto|scroll)/.test(style.overflowY) || /overflow-(auto|y-auto)/.test(String(node.className || ''));
    });
    if (!content && theme === 'academic-evidence') content = main.querySelector(':scope > div:first-child');
    if (!content && theme === 'sentiment-analysis') content = main.querySelector(':scope > div:last-child');
    if (content instanceof HTMLElement) content.dataset.apuV54ScrollContent = 'true';

    important(html, {height:'auto','max-height':'none','overflow-x':'hidden','overflow-y':'auto'});
    important(document.body, {height:'auto','max-height':'none','min-height':'100dvh','overflow-x':'clip','overflow-y':'visible',position:'relative'});
    important(root, {height:'auto','max-height':'none','min-height':'100dvh',overflow:'visible'});
    important(shell, {height:'auto','max-height':'none','min-height':'100dvh',overflow:'visible'});
    important(main, {height:'auto','max-height':'none','min-height':'100dvh',overflow:'visible'});
    if (content) important(content, {height:'auto','max-height':'none','min-height':'0','overflow-y':'visible'});

    if (theme === 'academic-evidence' && mobile54.matches) {
      shell.querySelectorAll('button[aria-label="Open navigation"],button[aria-label="Close navigation"]').forEach(button => {
        let node = button.parentElement;
        while (node && node !== shell && getComputedStyle(node).position !== 'fixed') node = node.parentElement;
        if (node && node !== shell) node.dataset.apuV54AcademicLegacy = 'true';
      });
      shell.querySelectorAll(':scope > div[class*="md:hidden"][class*="fixed"]').forEach(node => {
        node.dataset.apuV54AcademicLegacy = 'true';
      });
    }
    return true;
  }

  function currentCvLabel(links) {
    const active = links.find(link => link.getAttribute('aria-current') === 'page' || link.closest('[data-active="true"]'));
    if (active) return text(active);
    const pathname = location.pathname.replace(/\/$/, '');
    const route = links.find(link => {
      try { return new URL(link.href, location.href).pathname.replace(/\/$/, '') === pathname; }
      catch (_) { return false; }
    });
    return text(route) || 'Image Classification';
  }

  function enhanceComputerVision() {
    if (theme !== 'computer-vision') return false;
    const root = document.getElementById('root');
    const sidebar = document.querySelector('[data-slot="sidebar"]');
    const main = document.querySelector('main,[role="main"]');
    if (!root || !sidebar || !main || !/CV Research Hub/i.test(text(sidebar))) return false;

    const shell = sidebar.closest('[data-slot="sidebar-wrapper"]') || root.firstElementChild;
    const mainColumn = main.parentElement;
    const topbar = mainColumn?.querySelector(':scope > header') || document.querySelector('header');
    const links = [...sidebar.querySelectorAll('a[href]')];

    if (shell instanceof HTMLElement) shell.dataset.apuV54CvShell = 'true';
    if (mainColumn instanceof HTMLElement) mainColumn.dataset.apuV54CvMainColumn = 'true';
    main.dataset.apuV54CvMain = 'true';
    sidebar.dataset.apuV54CvSidebar = 'true';

    important(document.body, {height:'auto','max-height':'none','min-height':'100dvh','overflow-x':'clip'});
    important(root, {height:'auto','max-height':'none','min-height':'100dvh',overflow:'visible'});
    important(mainColumn, {height:'auto','max-height':'none','min-height':'100dvh','overflow':'visible'});
    important(main, {height:'auto','max-height':'none','min-height':'0',overflow:'visible'});

    if (topbar) {
      topbar.classList.add('apu-v54-cv-topbar');
      if (!topbar.querySelector('.apu-v54-cv-topbar-title')) {
        const title = document.createElement('div');
        title.className = 'apu-v54-cv-topbar-title';
        title.innerHTML = '<strong>Computer Vision Image Classification</strong><small>Research Dashboard</small>';
        topbar.appendChild(title);
      }
    }

    if (!document.querySelector('.apu-v54-cv-mobile-bar') && links.length) {
      const bar = document.createElement('header');
      bar.className = 'apu-v54-cv-mobile-bar';
      bar.innerHTML = `
        <div class="apu-v54-cv-mobile-brand">
          <span class="apu-v54-cv-mobile-mark" aria-hidden="true">CV</span>
          <span class="apu-v54-cv-mobile-brand-copy">
            <strong>CV Research Hub</strong>
            <small>${currentCvLabel(links)}</small>
          </span>
        </div>
        <button class="apu-v54-cv-mobile-toggle" type="button" aria-expanded="false" aria-controls="apuV54CvDrawer">Menu</button>`;

      const scrim = document.createElement('button');
      scrim.type = 'button';
      scrim.className = 'apu-v54-cv-mobile-scrim';
      scrim.setAttribute('aria-label', 'Close Computer Vision navigation');

      const drawer = document.createElement('aside');
      drawer.id = 'apuV54CvDrawer';
      drawer.className = 'apu-v54-cv-mobile-drawer';
      drawer.setAttribute('aria-label', 'Computer Vision navigation');
      drawer.setAttribute('aria-hidden', 'true');
      drawer.innerHTML = `
        <div class="apu-v54-cv-mobile-drawer-head">
          <strong>Research Navigation</strong>
          <button class="apu-v54-cv-mobile-close" type="button">Close</button>
        </div>
        <nav class="apu-v54-cv-mobile-nav"></nav>`;

      const mobileNav = drawer.querySelector('nav');
      links.forEach(source => {
        const clone = source.cloneNode(true);
        clone.removeAttribute('class');
        clone.removeAttribute('style');
        [...clone.querySelectorAll('*')].forEach(child => {
          child.removeAttribute('class');
          child.removeAttribute('style');
        });
        const isActive = source.getAttribute('aria-current') === 'page' || source.closest('[data-active="true"]');
        if (isActive) clone.setAttribute('aria-current', 'page');
        mobileNav.appendChild(clone);
      });

      document.body.insertBefore(bar, root);
      document.body.insertBefore(scrim, root);
      document.body.insertBefore(drawer, root);

      const toggle = bar.querySelector('.apu-v54-cv-mobile-toggle');
      const closeButton = drawer.querySelector('.apu-v54-cv-mobile-close');
      let previousFocus = null;
      const setOpen = (open, restoreFocus = false) => {
        drawer.classList.toggle('is-open', open);
        scrim.classList.toggle('is-open', open);
        html.dataset.apuV54CvMenuOpen = String(open);
        drawer.setAttribute('aria-hidden', String(!open));
        toggle.setAttribute('aria-expanded', String(open));
        toggle.textContent = open ? 'Close' : 'Menu';
        if (open) {
          previousFocus = document.activeElement;
          requestAnimationFrame(() => closeButton.focus({preventScroll:true}));
        } else if (restoreFocus) {
          (previousFocus instanceof HTMLElement ? previousFocus : toggle).focus({preventScroll:true});
        }
      };

      toggle.addEventListener('click', () => setOpen(!drawer.classList.contains('is-open')));
      closeButton.addEventListener('click', () => setOpen(false, true));
      scrim.addEventListener('click', () => setOpen(false, true));
      mobileNav.addEventListener('click', event => { if (event.target.closest('a[href]')) setOpen(false); });
      document.addEventListener('keydown', event => {
        if (event.key === 'Escape' && drawer.classList.contains('is-open')) setOpen(false, true);
      });
      mobile54.addEventListener?.('change', event => { if (!event.matches) setOpen(false); });
      setOpen(false);
    }
    return true;
  }

  let raf = 0;
  const scan = () => {
    cancelAnimationFrame(raf);
    raf = requestAnimationFrame(() => {
      markSingleDocumentScroll();
      enhanceComputerVision();
    });
  };

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

  const observer = new MutationObserver(scan);
  observer.observe(document.documentElement, {childList:true,subtree:true});
  setTimeout(() => observer.disconnect(), 20000);

  addEventListener('pageshow', scan, {passive:true});
  addEventListener('resize', scan, {passive:true});
  addEventListener('orientationchange', () => setTimeout(scan, 120), {passive:true});
})();
