(() => {
  'use strict';
  const mq = matchMedia('(max-width: 54rem)');
  const theme = document.documentElement.dataset.scrollTheme || '';
  const configs = {
    'academic-evidence': {title:'AI Portfolio Hub', subtitle:'Academic Evidence', mark:'AI', nav:'nav[aria-label="Main navigation"]', base:'/projects/academic-evidence/'},
    'sentiment-analysis': {title:'SentiScope', subtitle:'Text Sentiment Analysis', mark:'S', nav:'nav', base:'/projects/sentiment-analysis/'},
    'student-performance': {title:'AcademIQ', subtitle:'Student Performance', mark:'AI', nav:'.sp-nav', base:'/projects/student-performance/'}
  };
  let installed = false;

  const normalizeHref = (href, base) => {
    try {
      const url = new URL(href, location.href);
      if (url.origin !== location.origin) return url.href;
      if (url.pathname.startsWith('/projects/')) return url.pathname + url.search + url.hash;
      const tail = url.pathname.replace(/^\/+/, '');
      return base + tail + url.search + url.hash;
    } catch (_) { return href; }
  };

  function findNav(config) {
    if (theme === 'sentiment-analysis') {
      return [...document.querySelectorAll('nav')].find(nav => /Feedback Explorer|Topic Analysis|Model Evaluation/.test(nav.textContent || '')) || null;
    }
    return document.querySelector(config.nav);
  }

  function closestSidebar(nav) {
    if (theme === 'student-performance') return document.querySelector('.sp-sidebar');
    const direct = nav.closest('aside');
    if (direct) return direct;
    let node = nav.parentElement;
    while (node && node !== document.body) {
      const text = node.textContent || '';
      if (node.children.length <= 6 && text.length < 1800 && node.querySelector('nav') === nav) return node;
      node = node.parentElement;
    }
    return nav.parentElement;
  }

  function installGeneratedNav(config, nav) {
    if (installed || document.querySelector('.apu-v5-mobile-project-bar')) return;
    installed = true;
    document.documentElement.dataset.apuMobileNavV5 = 'true';

    const sidebar = closestSidebar(nav);
    sidebar?.setAttribute('data-apu-mobile-sidebar','true');
    const main = document.querySelector('main,[role="main"],.sp-main');
    main?.setAttribute('data-apu-mobile-main','true');

    const links = [...nav.querySelectorAll('a[href]')];
    const current = links.find(a => a.getAttribute('aria-current') === 'page' || a.classList.contains('is-active'));
    const header = document.createElement('header');
    header.className = 'apu-v5-mobile-project-bar';
    header.innerHTML = `
      <div class="apu-v5-mobile-project-brand">
        <span class="apu-v5-mobile-project-mark" aria-hidden="true">${config.mark}</span>
        <span class="apu-v5-mobile-project-brand-text"><strong>${config.title}</strong><small>${current?.textContent?.trim() || config.subtitle}</small></span>
      </div>
      <button class="apu-v5-mobile-project-toggle" type="button" aria-expanded="false" aria-controls="apuV5MobileDrawer">Menu</button>`;

    const drawer = document.createElement('nav');
    drawer.id = 'apuV5MobileDrawer';
    drawer.className = 'apu-v5-mobile-nav-drawer';
    drawer.setAttribute('aria-label', `${config.title} mobile navigation`);
    links.forEach(link => {
      const clone = document.createElement('a');
      clone.textContent = link.textContent.trim();
      const normalized = normalizeHref(link.getAttribute('href') || '', config.base);
      clone.href = normalized;
      let normalizedPath = '';
      try { normalizedPath = new URL(normalized, document.baseURI || location.href).pathname.replace(/\/$/, '') || '/'; } catch (_) {}
      const currentPath = location.pathname.replace(/\/$/, '') || '/';
      if (link.getAttribute('aria-current') === 'page' || link.classList.contains('is-active') || (normalizedPath && normalizedPath === currentPath)) clone.setAttribute('aria-current','page');
      drawer.appendChild(clone);
    });

    const root = document.querySelector('#root,#app,.sp-app') || document.body.firstElementChild;
    document.body.insertBefore(header, root || null);
    document.body.insertBefore(drawer, root || null);

    const button = header.querySelector('button');
    const close = (returnFocus=false) => {
      drawer.classList.remove('is-open');
      button.setAttribute('aria-expanded','false');
      button.lastChild && (button.lastChild.textContent = 'Menu');
      if (returnFocus) button.focus();
    };
    const open = () => {
      drawer.classList.add('is-open');
      button.setAttribute('aria-expanded','true');
      button.lastChild && (button.lastChild.textContent = 'Tutup');
    };
    button.addEventListener('click', () => drawer.classList.contains('is-open') ? close() : open());
    drawer.addEventListener('click', e => { if (e.target.closest('a')) close(); });
    document.addEventListener('pointerdown', e => {
      if (!drawer.classList.contains('is-open')) return;
      if (!drawer.contains(e.target) && !header.contains(e.target)) close();
    }, {passive:true});
    document.addEventListener('keydown', e => { if (e.key === 'Escape' && drawer.classList.contains('is-open')) close(true); });
    mq.addEventListener?.('change', e => { if (!e.matches) close(); });
  }

  function enhanceNetwork() {
    if (theme !== 'network-subnet') return;
    document.documentElement.dataset.apuMobileNavV5 = 'true';
    const button = document.getElementById('menuToggle');
    const nav = document.getElementById('mainNav');
    if (!button || !nav || button.dataset.v5Ready) return;
    button.dataset.v5Ready = 'true';
    const sync = open => {
      nav.classList.toggle('is-open', open);
      button.setAttribute('aria-expanded', String(open));
      button.textContent = open ? '✕ Tutup' : '☰ Menu';
    };
    button.addEventListener('click', e => { e.stopImmediatePropagation(); sync(!nav.classList.contains('is-open')); }, true);
    nav.addEventListener('click', e => { if (e.target.closest('a')) sync(false); });
    document.addEventListener('pointerdown', e => { if (nav.classList.contains('is-open') && !nav.contains(e.target) && !button.contains(e.target)) sync(false); }, {passive:true});
    document.addEventListener('keydown', e => { if (e.key === 'Escape') { sync(false); button.focus(); } });
    sync(false);
  }

  function scan() {
    if (!mq.matches) return;
    if (theme === 'network-subnet') return enhanceNetwork();
    const config = configs[theme];
    if (!config) return;
    const nav = findNav(config);
    if (nav) installGeneratedNav(config, nav);
  }

  if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', scan, {once:true}); else scan();
  const observer = new MutationObserver(() => { scan(); if (installed) observer.disconnect(); });
  observer.observe(document.documentElement, {childList:true, subtree:true});
  setTimeout(() => observer.disconnect(), 12000);
})();
