(() => {
  'use strict';

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

  function visibleText(node) {
    return (node?.textContent || '').replace(/\s+/g, ' ').trim();
  }

  function findCvSidebar() {
    const candidates = [...document.querySelectorAll('aside, [role="navigation"], nav')];
    const directAside = candidates.find(node => {
      const text = visibleText(node);
      return /CV RESEARCH HUB/i.test(text) && /Overview/i.test(text) && /Dataset/i.test(text) && /Model/i.test(text);
    });
    if (!directAside) return null;
    return directAside.matches('aside') ? directAside : directAside.closest('aside') || directAside.parentElement;
  }

  function findCvMain(sidebar) {
    const main = document.querySelector('main, [role="main"]');
    if (main) return main;
    const parent = sidebar?.parentElement;
    if (!parent) return null;
    return [...parent.children].find(node => node !== sidebar) || null;
  }

  function currentCvLabel(sidebar) {
    const active = sidebar?.querySelector('a[aria-current="page"], a[class*="bg-slate-800"], a[class*="active"]');
    return visibleText(active) || document.title.replace(/\s*[·|—-].*$/, '').trim() || 'Computer Vision';
  }

  function installCvNavigation() {
    if (theme !== 'computer-vision' || !mobileQuery.matches || document.querySelector('.apu-v52-cv-bar')) return false;
    const sidebar = findCvSidebar();
    if (!sidebar) return false;

    sidebar.dataset.apuV52CvSidebar = 'true';
    sidebar.setAttribute('aria-hidden', 'true');
    const main = findCvMain(sidebar);
    if (main) main.dataset.apuV52CvMain = 'true';

    const closeInside = document.createElement('button');
    closeInside.type = 'button';
    closeInside.className = 'apu-v52-cv-drawer-close';
    closeInside.textContent = '✕ Tutup navigasi';
    sidebar.insertBefore(closeInside, sidebar.firstChild);

    const bar = document.createElement('header');
    bar.className = 'apu-v52-cv-bar';
    bar.innerHTML = `
      <div class="apu-v52-cv-brand">
        <span class="apu-v52-cv-mark" aria-hidden="true">CV</span>
        <span class="apu-v52-cv-brand-text"><strong>CV Research Hub</strong><small>${currentCvLabel(sidebar)}</small></span>
      </div>
      <button class="apu-v52-cv-toggle" type="button" aria-expanded="false" aria-controls="apuV52CvDrawer">Menu</button>`;

    sidebar.id = sidebar.id || 'apuV52CvDrawer';
    bar.querySelector('button').setAttribute('aria-controls', sidebar.id);

    const scrim = document.createElement('button');
    scrim.type = 'button';
    scrim.className = 'apu-v52-cv-scrim';
    scrim.setAttribute('aria-label', 'Tutup navigasi CV Research Hub');

    const appRoot = document.querySelector('#root') || document.body.firstElementChild;
    document.body.insertBefore(bar, appRoot || null);
    document.body.insertBefore(scrim, appRoot || null);

    const toggle = bar.querySelector('.apu-v52-cv-toggle');
    let previousFocus = null;

    const setOpen = (open, returnFocus = false) => {
      sidebar.classList.toggle('is-open', open);
      scrim.classList.toggle('is-open', open);
      rootEl.dataset.apuV52CvOpen = String(open);
      toggle.setAttribute('aria-expanded', String(open));
      toggle.lastChild && (toggle.lastChild.textContent = open ? 'Tutup' : 'Menu');
      sidebar.setAttribute('aria-hidden', String(!open));
      if (open) {
        previousFocus = document.activeElement;
        requestAnimationFrame(() => closeInside.focus({preventScroll:true}));
      } else if (returnFocus) {
        (previousFocus instanceof HTMLElement ? previousFocus : toggle).focus({preventScroll:true});
      }
    };

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

    setOpen(false);
    return true;
  }

  function guaranteeAcademIQScroll() {
    if (theme !== 'student-performance' || !mobileQuery.matches) return false;

    [document.documentElement, document.body].forEach(node => {
      if (!node) return;
      node.style.setProperty('height', 'auto', 'important');
      node.style.setProperty('max-height', 'none', 'important');
      node.style.setProperty('overflow-x', 'hidden', 'important');
      node.style.setProperty('overflow-y', 'auto', 'important');
      node.style.setProperty('position', 'static', 'important');
    });

    document.querySelectorAll('.sp-app,.sp-main,.sp-view.is-active').forEach(node => {
      node.style.setProperty('height', 'auto', 'important');
      node.style.setProperty('max-height', 'none', 'important');
      node.style.setProperty('overflow', 'visible', 'important');
      node.style.setProperty('position', 'static', 'important');
    });

    const main = document.querySelector('.sp-main');
    if (main) {
      main.dataset.apuV52NativeScroll = 'true';
      /* V6.15: never copy scrollHeight into min-height. That recursive rule
         caused the mobile document to grow again every time a mutation,
         resize, or pageshow event ran. */
      main.style.setProperty('min-height', '0', 'important');
      main.style.removeProperty('block-size');
      main.style.removeProperty('min-block-size');
    }

    return true;
  }

  function scan() {
    if (!mobileQuery.matches) return;
    if (theme === 'computer-vision') installCvNavigation();
    if (theme === 'student-performance') guaranteeAcademIQScroll();
  }

  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(), 15000);

  if (theme === 'student-performance') {
    addEventListener('load', guaranteeAcademIQScroll, {once:true});
    addEventListener('resize', guaranteeAcademIQScroll, {passive:true});
    addEventListener('pageshow', guaranteeAcademIQScroll, {passive:true});
  }
})();
