/* AI Project Universe V6.5 — shared Helpdesk design runtime. */
(() => {
  'use strict';
  const root = document.documentElement;
  const project = root.dataset.scrollTheme || 'it-helpdesk';
  const accents = {
    'it-helpdesk':'#2563eb','computer-vision':'#0f766e','incident-monitoring':'#dc2626',
    'kotlin-policy':'#7c3aed','malaysia-cost':'#0f766e','network-subnet':'#0369a1',
    'sentiment-analysis':'#7c3aed','url-shortener':'#4f46e5','academic-evidence':'#1d4ed8',
    'ai-architect':'#4f46e5','student-performance':'#6d28d9'
  };

  root.dataset.apuUnifiedDesign = 'v6.5-helpdesk';

  function updateThemeColor(){
    const meta = document.querySelector('meta[name="theme-color"]') || (() => {
      const node = document.createElement('meta');
      node.name = 'theme-color';
      document.head.appendChild(node);
      return node;
    })();
    meta.content = root.dataset.apuTheme === 'dark' ? '#07101f' : (accents[project] || '#2563eb');
  }

  function removeSentimentDuplicate(){
    if(project !== 'sentiment-analysis') return;
    document.querySelectorAll('#apuSentimentStudio,.apu-studio-jump,#apuSentimentToast').forEach(node => node.remove());
  }

  function initialize(){
    updateThemeColor();
    removeSentimentDuplicate();

    if(project === 'sentiment-analysis'){
      const observer = new MutationObserver(removeSentimentDuplicate);
      observer.observe(document.documentElement,{childList:true,subtree:true});
      window.addEventListener('pagehide',() => observer.disconnect(),{once:true});
    }
  }

  new MutationObserver(updateThemeColor).observe(root,{attributes:true,attributeFilter:['data-apu-theme']});
  window.addEventListener('apu:themechange',updateThemeColor);
  if(document.readyState === 'loading') document.addEventListener('DOMContentLoaded',initialize,{once:true});
  else initialize();
})();


/* AI Project Universe V6.5 — Helpdesk-style mobile project navigation and exit control. */
(() => {
  'use strict';
  if (window.__APU_MOBILE_HELPDESK_V65__) return;
  window.__APU_MOBILE_HELPDESK_V65__ = true;

  const root = document.documentElement;
  const project = root.dataset.scrollTheme || '';
  const mq = matchMedia('(max-width: 54rem)');
  const base = project ? `/projects/${project}/` : '/';

  const projects = {
    'computer-vision': {mark:'CV', title:'Computer Vision', subtitle:'Image Classification', routes:[['Overview',''],['Dataset','dataset/'],['Models','model/'],['Results','results/'],['Failure Analysis','analysis/'],['Limitations','limitations/'],['Source Code','code/'],['Technical Report','report/']]},
    'incident-monitoring': {mark:'IM', title:'Incident Monitoring', subtitle:'Operations Dashboard', routes:[['Dashboard','dashboard/'],['Incidents','incidents/'],['Timeline','timeline/'],['Reports','reports/']]},
    'kotlin-policy': {mark:'AP', title:'Android Policy', subtitle:'Kotlin Device Demo', routes:[['Dashboard','']]},
    'malaysia-cost': {mark:'MY', title:'Malaysia Cost', subtitle:'Living Planner', routes:[['Overview',''],['Costs','costs/'],['Housing','housing/'],['Simulator','simulator/'],['Methodology','methodology/']]},
    'network-subnet': {mark:'NT', title:'Network Tools', subtitle:'Subnet Intelligence', routes:[['Summary',''],['Subnet Calculator','calculator/'],['Troubleshooting','troubleshoot/'],['Segmentation / VLSM','segmentation/'],['History','history/'],['Tutorial','tutorial/']]},
    'sentiment-analysis': {mark:'S', title:'SentiScope', subtitle:'Text Sentiment Analysis', routes:[['Dashboard',''],['Feedback Explorer','feedback/'],['Submit Feedback','feedback/new/'],['Topic Analysis','topics/'],['Keywords','keywords/'],['Categories','categories/'],['Recommendations','recommendations/'],['Model Evaluation','model/']]},
    'url-shortener': {mark:'US', title:'URL Shortener', subtitle:'Modern Link Studio', routes:[['Overview',''],['Create','create/'],['Analytics','analytics/'],['Campaigns','campaigns/']]},
    'academic-evidence': {mark:'AE', title:'Academic Evidence', subtitle:'AI Portfolio Hub', routes:[['Overview',''],['Projects','projects/'],['CV','cv/'],['Certificates','certificates/'],['Research','research/'],['GitHub','github/'],['Reports','reports/'],['Source Code','source/'],['Admission','admission/']]},
    'ai-architect': {mark:'AI', title:'AI Architect', subtitle:'Solutions Lab', routes:[['Overview',''],['RAG','rag/'],['Support','support/'],['Predict','predict/'],['MLOps','mlops/'],['Security','security/'],['Agents','agents/'],['Governance','governance/'],['ROI','roi/'],['Cloud Compare','cloud-compare/'],['Blueprints','blueprints/'],['Documents','documents/'],['Resume','resume/'],['Contact','contact/']]},
    'student-performance': {mark:'AI', title:'AcademIQ', subtitle:'Student Performance', routes:[['Dashboard',''],['Students','students/'],['Model Lab','models/'],['Fairness','fairness/'],['Recommendations','recommendations/'],['Report','report/']]}
  };

  const ui = {
    id:{menu:'Menu proyek',close:'Tutup menu',exit:'Keluar dari proyek',navigation:'Navigasi proyek'},
    en:{menu:'Project menu',close:'Close menu',exit:'Exit project',navigation:'Project navigation'},
    ms:{menu:'Menu projek',close:'Tutup menu',exit:'Keluar daripada projek',navigation:'Navigasi projek'},
    de:{menu:'Projektmenü',close:'Menü schließen',exit:'Projekt verlassen',navigation:'Projektnavigation'},
    vi:{menu:'Menu dự án',close:'Đóng menu',exit:'Thoát dự án',navigation:'Điều hướng dự án'},
    zh:{menu:'项目菜单',close:'关闭菜单',exit:'退出项目',navigation:'项目导航'},
    ja:{menu:'プロジェクトメニュー',close:'メニューを閉じる',exit:'プロジェクトを終了',navigation:'プロジェクトナビゲーション'}
  };

  const normalizePath = value => {
    try { return new URL(value, location.href).pathname.replace(/\/index\.html$/,'/').replace(/\/$/,'') || '/'; }
    catch (_) { return ''; }
  };
  const currentLanguage = () => root.dataset.apuLanguage || localStorage.getItem('apu-ui-language') || root.lang || 'en';
  const words = () => ui[currentLanguage()] || ui.en;

  function sendExit(){
    if (window.self !== window.top) {
      window.parent.postMessage({type:'apu:close-project', project}, location.origin);
      return;
    }
    const ref = document.referrer;
    try {
      const prior = ref ? new URL(ref) : null;
      if (prior && prior.origin === location.origin && !prior.pathname.startsWith(base)) { history.back(); return; }
    } catch (_) {}
    location.assign('/');
  }

  function activeRouteLabel(config){
    const here = normalizePath(location.pathname);
    const match = config.routes.find(([,tail]) => normalizePath(base + tail) === here);
    return match?.[0] || config.subtitle;
  }

  function markNativeNavigation(){
    const candidates = [...document.querySelectorAll('aside,nav,.sidebar,.sp-sidebar,.main-nav,[data-sidebar]')];
    for (const node of candidates) {
      if (node.closest('#apuMobileDrawerV65')) continue;
      const links = [...node.querySelectorAll('a[href]')].filter(a => {
        try { return new URL(a.href, location.href).pathname.startsWith(base); } catch (_) { return false; }
      });
      if (links.length >= 3) {
        const container = node.matches('nav') ? (node.closest('aside,.sidebar,.sp-sidebar,[data-sidebar]') || node) : node;
        container.dataset.apuNativeSidebarV65 = 'true';
        break;
      }
    }
    if (project === 'network-subnet') document.querySelector('.app-header')?.setAttribute('data-apu-native-sidebar-v65','true');
    document.querySelectorAll('button,[role="button"]').forEach(button => {
      if (button.closest('#apuMobileHeaderV65,#apuMobileDrawerV65,#apu-ui-dock-v62')) return;
      const text = (button.textContent || button.getAttribute('aria-label') || '').replace(/\s+/g,' ').trim().toLowerCase();
      const controls = button.getAttribute('aria-controls') || '';
      if (/^(menu|close|tutup|incident menu|open menu|navigation menu|research navigation)$/i.test(text) || /nav|menu|sidebar/i.test(controls)) {
        const rect = button.getBoundingClientRect();
        if (rect.top < 260 || project === 'incident-monitoring' || project === 'computer-vision') button.dataset.apuNativeMenuTriggerV65 = 'true';
      }
    });
  }

  function install(){
    if (!project || project === 'it-helpdesk' || document.getElementById('apuMobileHeaderV65')) return;
    const config = projects[project];
    if (!config) return;
    root.dataset.apuMobileHelpdesk = 'v6.5';

    const header = document.createElement('header');
    header.id = 'apuMobileHeaderV65';
    header.className = 'apu-mobile-header-v65';
    header.innerHTML = `
      <button class="apu-mobile-menu-v65" id="apuMobileMenuV65" type="button" aria-expanded="false" aria-controls="apuMobileDrawerV65">
        <span aria-hidden="true"><i></i><i></i><i></i></span><b class="apu-sr-v65">${words().menu}</b>
      </button>
      <div class="apu-mobile-title-v65"><strong>${config.title}</strong><small>${activeRouteLabel(config)}</small></div>
      <button class="apu-mobile-exit-v65" id="apuProjectExitV65" type="button" title="${words().exit}" aria-label="${words().exit}"><span aria-hidden="true">×</span></button>`;

    const overlay = document.createElement('button');
    overlay.id = 'apuMobileOverlayV65';
    overlay.className = 'apu-mobile-overlay-v65';
    overlay.type = 'button';
    overlay.tabIndex = -1;
    overlay.setAttribute('aria-label', words().close);

    const drawer = document.createElement('aside');
    drawer.id = 'apuMobileDrawerV65';
    drawer.className = 'apu-mobile-drawer-v65';
    drawer.setAttribute('aria-label', words().navigation);
    const links = config.routes.map(([label,tail]) => {
      const href = base + tail;
      const active = normalizePath(href) === normalizePath(location.pathname);
      return `<a href="${href}"${active?' aria-current="page"':''}><span>${label}</span><b aria-hidden="true">›</b></a>`;
    }).join('');
    drawer.innerHTML = `
      <div class="apu-mobile-drawer-head-v65">
        <span class="apu-mobile-mark-v65" aria-hidden="true">${config.mark}</span>
        <div><strong>${config.title}</strong><small>${config.subtitle}</small></div>
        <button id="apuMobileDrawerCloseV65" type="button" aria-label="${words().close}">×</button>
      </div>
      <nav>${links}</nav>
      <button class="apu-mobile-drawer-exit-v65" id="apuMobileDrawerExitV65" type="button"><span aria-hidden="true">↩</span><span>${words().exit}</span></button>`;

    document.body.prepend(overlay);
    document.body.prepend(drawer);
    document.body.prepend(header);

    const menu = header.querySelector('#apuMobileMenuV65');
    const closeButton = drawer.querySelector('#apuMobileDrawerCloseV65');
    const setOpen = (open, focus=false) => {
      root.classList.toggle('apu-mobile-menu-open-v65', open);
      menu.setAttribute('aria-expanded', String(open));
      drawer.setAttribute('aria-hidden', String(!open));
      overlay.setAttribute('aria-hidden', String(!open));
      if (focus) (open ? closeButton : menu).focus();
    };
    menu.addEventListener('click', () => setOpen(!root.classList.contains('apu-mobile-menu-open-v65'), true));
    closeButton.addEventListener('click', () => setOpen(false, true));
    overlay.addEventListener('click', () => setOpen(false, true));
    drawer.querySelector('nav').addEventListener('click', e => { if (e.target.closest('a')) setOpen(false); });
    header.querySelector('#apuProjectExitV65').addEventListener('click', sendExit);
    drawer.querySelector('#apuMobileDrawerExitV65').addEventListener('click', sendExit);
    document.addEventListener('keydown', e => { if (e.key === 'Escape' && root.classList.contains('apu-mobile-menu-open-v65')) setOpen(false, true); });
    mq.addEventListener?.('change', e => { if (!e.matches) setOpen(false); });

    const updateLanguage = () => {
      const w = words();
      menu.querySelector('.apu-sr-v65').textContent = w.menu;
      header.querySelector('#apuProjectExitV65').title = w.exit;
      header.querySelector('#apuProjectExitV65').setAttribute('aria-label',w.exit);
      overlay.setAttribute('aria-label',w.close);
      closeButton.setAttribute('aria-label',w.close);
      drawer.setAttribute('aria-label',w.navigation);
      drawer.querySelector('.apu-mobile-drawer-exit-v65 span:last-child').textContent = w.exit;
    };
    window.addEventListener('apu:languagechange', updateLanguage);
    setOpen(false);
    markNativeNavigation();

    let scans = 0;
    const observer = new MutationObserver(() => {
      markNativeNavigation();
      if (++scans > 50) observer.disconnect();
    });
    observer.observe(document.body,{childList:true,subtree:true});
    setTimeout(() => observer.disconnect(),15000);
  }

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