(() => {
  'use strict';

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

  const NAVS = {
    'computer-vision': {
      title: 'CV Research Hub', subtitle: 'Computer Vision', mark: 'CV',
      items: [
        ['▦','Overview','/'],
        ['◫','Dataset','/dataset/'],
        ['△','Models','/model/'],
        ['⌁','Results','/results/'],
        ['⚠','Failure Analysis','/analysis/'],
        ['✓','Limitations','/limitations/'],
        ['</>','Source Code','/code/'],
        ['▤','Technical Report','/report/']
      ]
    },
    'incident-monitoring': {
      title: 'Incident Monitoring', subtitle: 'Operations Dashboard', mark: 'IM',
      items: [
        ['▦','Dashboard','/projects/incident-monitoring/'],
        ['⚠','Incidents','/projects/incident-monitoring/incidents/'],
        ['⌁','Timeline','/projects/incident-monitoring/timeline/'],
        ['▤','Reports','/projects/incident-monitoring/reports/']
      ]
    },
    'student-performance': {
      title: 'AcademIQ', subtitle: 'Student Performance', mark: 'AI',
      items: [
        ['▦','Dashboard','/projects/student-performance/'],
        ['♟','Student Explorer','/projects/student-performance/students/'],
        ['△','Models','/projects/student-performance/models/'],
        ['⚖','Fairness','/projects/student-performance/fairness/'],
        ['✦','Recommendations','/projects/student-performance/recommendations/'],
        ['▤','Report','/projects/student-performance/report/']
      ]
    }
  };

  const normalizedPath = () => {
    let p = location.pathname.replace(/\/index\.html$/, '/');
    if (!p.endsWith('/')) p += '/';
    return p;
  };

  function currentItem(config) {
    const path = normalizedPath();
    return config.items.find(([, , href]) => href === path) || config.items[0];
  }

  function closeProject() {
    try {
      if (window.parent && window.parent !== window) {
        window.parent.postMessage({type: 'apu:close-project', project: theme}, location.origin);
        return;
      }
    } catch (_) {}
    location.href = '/';
  }

  function tagLegacyChrome() {
    const text = node => (node?.textContent || '').replace(/\s+/g, ' ').trim();
    if (theme === 'computer-vision') {
      const aside = [...document.querySelectorAll('aside')].find(node => /CV Research Hub/i.test(text(node)) && /Dataset/i.test(text(node)));
      if (aside) aside.dataset.apuFinalOriginalSidebar = 'true';
      const header = [...document.querySelectorAll('#root header')].find(node => node.querySelector('button'));
      if (header) header.dataset.apuFinalLegacyHeader = 'true';
    }
    if (theme === 'incident-monitoring') {
      const aside = [...document.querySelectorAll('aside')].find(node => /Incident Monitoring Dashboard/i.test(text(node)) && /Incidents/i.test(text(node)));
      if (aside) { aside.dataset.apuFinalOriginalSidebar = 'true'; aside.dataset.mobileReady = 'true'; }
    }
    if (theme === 'student-performance') {
      const aside = document.querySelector('.sp-sidebar');
      if (aside) aside.dataset.apuFinalOriginalSidebar = 'true';
      const header = [...document.querySelectorAll('#root header')].find(node => /Student|Academ/i.test(text(node)) && node.querySelector('button'));
      if (header) header.dataset.apuFinalLegacyHeader = 'true';
    }
  }

  function removeLegacyBars() {
    document.querySelectorAll([
      '.apu-v52-cv-bar', '.apu-v52-cv-scrim', '.apu-v54-cv-mobile-bar',
      '.apu-v54-cv-mobile-drawer', '.apu-v54-cv-mobile-scrim',
      '.apu-v5-mobile-project-bar', '.apu-v5-mobile-nav-drawer',
      '.incident-mobile-button', '.incident-mobile-backdrop'
    ].join(',')).forEach(node => {
      if (!node.classList.contains('apu-final-mobile-bar') && !node.classList.contains('apu-final-nav-sentinel')) node.remove();
    });
  }

  function installSharedMobileNav() {
    const config = NAVS[theme];
    if (!config || !mobile.matches || document.querySelector('.apu-final-mobile-bar')) return false;

    root.dataset.apuFinalMobileNav = 'true';
    tagLegacyChrome();
    removeLegacyBars();

    const active = currentItem(config);
    const header = document.createElement('header');
    header.className = 'apu-final-mobile-bar';
    if (theme === 'computer-vision') header.classList.add('apu-v52-cv-bar');
    if (theme === 'student-performance') header.classList.add('apu-v5-mobile-project-bar');
    header.innerHTML = `
      <button class="apu-final-mobile-menu" type="button" aria-label="Open ${config.title} navigation" aria-expanded="false" aria-controls="apuFinalMobileDrawer"><span aria-hidden="true"><i></i></span></button>
      <div class="apu-final-mobile-brand"><strong>${config.title}</strong><small>${active[1]}</small></div>
      <button class="apu-final-mobile-exit" type="button" aria-label="Exit project" title="Exit project">×</button>`;

    const drawer = document.createElement('aside');
    drawer.className = 'apu-final-mobile-drawer';
    drawer.id = 'apuFinalMobileDrawer';
    drawer.setAttribute('aria-hidden', 'true');
    drawer.innerHTML = `
      <div class="apu-final-drawer-head">
        <div><strong>${config.title}</strong><small>${config.subtitle}</small></div>
        <button class="apu-final-drawer-close" type="button" aria-label="Close navigation">×</button>
      </div>
      <nav class="apu-final-mobile-links" aria-label="${config.title} navigation">
        ${config.items.map(([icon,label,href]) => `<a href="${href}"${href === normalizedPath() ? ' aria-current="page"' : ''}><span aria-hidden="true">${icon}</span><span>${label}</span></a>`).join('')}
      </nav>`;

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

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

    const menu = header.querySelector('.apu-final-mobile-menu');
    const exit = header.querySelector('.apu-final-mobile-exit');
    const close = drawer.querySelector('.apu-final-drawer-close');
    let lastFocus = null;
    const setOpen = (open, restore = false) => {
      root.classList.toggle('apu-final-nav-open', open);
      drawer.classList.toggle('is-open', open);
      scrim.classList.toggle('is-open', open);
      drawer.setAttribute('aria-hidden', String(!open));
      menu.setAttribute('aria-expanded', String(open));
      if (open) {
        lastFocus = document.activeElement;
        requestAnimationFrame(() => close.focus({preventScroll:true}));
      } else if (restore) {
        (lastFocus instanceof HTMLElement ? lastFocus : menu).focus({preventScroll:true});
      }
    };
    menu.addEventListener('click', () => setOpen(!drawer.classList.contains('is-open')));
    close.addEventListener('click', () => setOpen(false, true));
    scrim.addEventListener('click', () => setOpen(false, true));
    exit.addEventListener('click', closeProject);
    drawer.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); });
    mobile.addEventListener?.('change', event => { if (!event.matches) setOpen(false); });
    return true;
  }

  function maintainSharedNav() {
    if (!NAVS[theme] || !mobile.matches) return;
    tagLegacyChrome();
    removeLegacyBars();
    installSharedMobileNav();
  }

  function polishViewerToolbar() {
    const language = document.getElementById('viewerLanguageControl');
    const themeButton = document.getElementById('viewerThemeControl');
    const standalone = document.getElementById('viewerStandalone');
    const download = document.getElementById('viewerDownload');
    const music = document.getElementById('viewerMusic');
    const close = document.getElementById('viewerClose');
    if (language) {
      language.setAttribute('aria-label', 'Translate project');
      language.closest('label')?.setAttribute('title', 'Translate');
    }
    if (themeButton) themeButton.title = 'Toggle light or dark theme';
    if (standalone) { standalone.title = 'Open fullscreen'; standalone.setAttribute('aria-label', 'Open fullscreen'); }
    if (download) { download.title = 'Download protected ZIP'; download.setAttribute('aria-label', 'Download protected ZIP'); }
    if (music) { music.title = 'Toggle music'; music.setAttribute('aria-label', 'Toggle music'); }
    if (close) { close.title = 'Close project'; close.setAttribute('aria-label', 'Close project'); }
  }

  function ensureAiArchitectMobile() {
    if (theme !== 'ai-architect' || !matchMedia('(max-width:767px)').matches) return;
    const locate = () => {
      const drawer = document.querySelector('aside.ai-architect-drawer') || [...document.querySelectorAll('aside')].find(node => /Enterprise RAG/.test(node.textContent || '') && /Cloud Compare/.test(node.textContent || ''));
      const trigger = document.querySelector('header .ai-menu-trigger') || document.querySelector('header button.md\\:hidden') || [...document.querySelectorAll('header button')].find(node => node.querySelector('svg'));
      if (drawer) drawer.classList.add('ai-architect-drawer');
      if (trigger) {
        trigger.classList.add('ai-menu-trigger');
        trigger.closest('header')?.classList.add('ai-architect-header');
        trigger.setAttribute('aria-label', 'Open AI Architect navigation');
      }
      const main = document.querySelector('main');
      if (main) main.classList.add('ai-architect-main');
      return Boolean(drawer && trigger);
    };
    if (!locate()) {
      const observer = new MutationObserver(() => { if (locate()) observer.disconnect(); });
      observer.observe(document.documentElement, {childList:true,subtree:true});
      setTimeout(() => observer.disconnect(), 12000);
    }
  }

  function modelFallbackMarkup() {
    return `
      <section class="apu-model-fallback" aria-label="Model evaluation demonstration data">
        <div class="apu-model-fallback__inner">
          <p class="apu-model-fallback__eyebrow">NLP · Model Evaluation · Local Demonstration Data</p>
          <h1>Model Evaluation</h1>
          <p class="apu-model-fallback__lead">Evaluation of a local AFINN and TF-IDF sentiment prototype on 12 labeled student-feedback records. All values remain available without an external API.</p>
          <div class="apu-model-fallback__metrics">
            <article class="apu-model-card"><small>Accuracy</small><strong>75.0%</strong></article>
            <article class="apu-model-card"><small>Precision · Macro</small><strong>82.1%</strong></article>
            <article class="apu-model-card"><small>Recall · Macro</small><strong>69.4%</strong></article>
            <article class="apu-model-card"><small>F1 Score · Macro</small><strong>69.4%</strong></article>
          </div>
          <div class="apu-model-grid">
            <article class="apu-model-section">
              <h2>Confusion Matrix</h2>
              <div class="apu-model-matrix-wrap">
                <table class="apu-model-matrix">
                  <thead><tr><th>Actual ↓</th><th>Positive</th><th>Negative</th><th>Neutral</th></tr></thead>
                  <tbody>
                    <tr><th>Positive</th><td class="is-correct">5</td><td>0</td><td>0</td></tr>
                    <tr><th>Negative</th><td>1</td><td class="is-correct">3</td><td>0</td></tr>
                    <tr><th>Neutral</th><td>1</td><td>1</td><td class="is-correct">1</td></tr>
                  </tbody>
                </table>
              </div>
            </article>
            <article class="apu-model-section">
              <h2>Qualitative Error Analysis</h2>
              <div class="apu-model-errors">
                <div class="apu-model-error"><p>“The library is quiet and comfortable, although more power outlets would help.”</p><div><span class="apu-model-pill">True: neutral</span><span class="apu-model-pill">Predicted: positive</span><span class="apu-model-pill">Mixed sentiment</span></div></div>
                <div class="apu-model-error"><p>“The tutorial was not bad, but it could include more advanced examples.”</p><div><span class="apu-model-pill">True: neutral</span><span class="apu-model-pill">Predicted: negative</span><span class="apu-model-pill">Negation</span></div></div>
                <div class="apu-model-error"><p>“Great, another portal outage exactly when the registration deadline begins.”</p><div><span class="apu-model-pill">True: negative</span><span class="apu-model-pill">Predicted: positive</span><span class="apu-model-pill">Sarcasm</span></div></div>
              </div>
            </article>
          </div>
        </div>
      </section>`;
  }

  function ensureModelEvaluation() {
    if (theme !== 'sentiment-analysis' || !/\/model\/?$/.test(location.pathname)) return;
    document.body.style.background = '#030711';
    const check = (force = false) => {
      const appRoot = document.getElementById('root');
      if (!appRoot) return;
      const text = (appRoot.innerText || '').replace(/\s+/g, ' ').trim();
      const hasEvaluation = /Performance Metrics|Confusion Matrix|Model Evaluation/.test(text);
      const hasVisibleContent = appRoot.children.length > 0 && appRoot.getBoundingClientRect().height > 180;
      if (!hasEvaluation && (force || !hasVisibleContent)) {
        appRoot.innerHTML = modelFallbackMarkup();
        appRoot.dataset.apuModelFallback = 'true';
      }
    };
    setTimeout(() => check(false), 1200);
    setTimeout(() => check(true), 5200);
  }

  function boot() {
    polishViewerToolbar();
    installSharedMobileNav();
    ensureAiArchitectMobile();
    ensureModelEvaluation();

    if (NAVS[theme]) {
      let cycles = 0;
      const observer = new MutationObserver(() => {
        maintainSharedNav();
        if (++cycles > 180) observer.disconnect();
      });
      observer.observe(document.documentElement, {childList:true,subtree:true});
      setTimeout(() => observer.disconnect(), 15000);
    }
  }

  if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', boot, {once:true});
  else boot();
  addEventListener('load', () => {
    polishViewerToolbar();
    maintainSharedNav();
    ensureAiArchitectMobile();
    ensureModelEvaluation();
  }, {once:true});
})();
