(() => {
  'use strict';
  const html = document.documentElement;
  const theme = html.dataset.scrollTheme || '';
  const mobile = matchMedia('(max-width:760px)');


  function ensureViewerLanguageButton(){
    /* V6.14 owns the viewer language control to prevent duplicate mobile triggers. */
    return;
  }

  function compactViewerControls(){
    const bar = document.querySelector('.viewer .viewer__bar');
    if(!bar || !mobile.matches) return;
    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(themeButton){
      const icon = themeButton.querySelector('.viewer__control-icon');
      if(icon) icon.textContent='◐';
      themeButton.setAttribute('aria-label','Ganti tema terang atau gelap');
    }
    if(standalone){standalone.textContent='Full';standalone.setAttribute('aria-label','Buka layar penuh');standalone.title='Buka layar penuh'}
    if(download){download.textContent='.ZIP';download.setAttribute('aria-label','Unduh ZIP terlindungi');download.title='Unduh ZIP terlindungi'}
    if(music){music.textContent='♫';music.setAttribute('aria-label','Putar atau hentikan musik');music.title='Musik'}
    if(close){close.textContent='X';close.setAttribute('aria-label','Tutup proyek');close.title='Tutup proyek'}
    bar.dataset.apuV610Compact='true';
  }

  function hideIncidentPermanentSidebar(){
    if(theme!=='incident-monitoring' || !matchMedia('(max-width:54rem)').matches) return;
    const candidates=[...document.querySelectorAll('#root aside,#root nav,#root [class*="sidebar" i]')];
    for(const node of candidates){
      const text=(node.textContent||'').replace(/\s+/g,' ').trim();
      const links=[...node.querySelectorAll('a')].map(a=>(a.textContent||'').trim()).join(' ');
      if((/Dashboard|Dasbor/i.test(text))&&(/Incident|Insiden/i.test(text))&&(/Timeline|Linimasa/i.test(text))&&(/Report|Laporan/i.test(text+links))){
        node.dataset.apuV610IncidentSidebar='true';
        node.style.setProperty('display','none','important');
      }
    }
    document.querySelectorAll('.apu-final-mobile-exit').forEach(btn=>{
      btn.textContent='X';btn.setAttribute('aria-label','Keluar dari proyek');
    });
  }

  function stabilizeNativeBurger(){
    if(!['sentiment-analysis','computer-vision'].includes(theme) || !matchMedia('(max-width:54rem)').matches) return;
    const toggle=document.querySelector('.apu-v69-native-toggle');
    const menu=document.querySelector('.apu-v69-malaysia-menu');
    if(!toggle||!menu)return;
    const isOpen=menu.classList.contains('is-open');
    toggle.textContent=isOpen?'X':'☰';
    toggle.setAttribute('aria-label',isOpen?'Tutup menu navigasi':'Buka menu navigasi');
    menu.setAttribute('tabindex','-1');
    menu.style.setProperty('opacity','1','important');
    if(menu.classList.contains('is-open')) requestAnimationFrame(()=>menu.scrollTop=Math.max(0,menu.scrollTop));
  }

  function improveNetworkContrast(){
    if(theme!=='network-subnet')return;
    const header=document.querySelector('.app-header');
    if(!header)return;
    const brand=header.querySelector('.brand');
    const toggle=header.querySelector('.menu-toggle');
    if(brand){brand.style.setProperty('opacity','1','important');brand.setAttribute('aria-label','Alat Jaringan')}
    if(toggle){toggle.style.setProperty('opacity','1','important');if(!(toggle.textContent||'').trim())toggle.textContent='Menu'}
  }

  function improveAiArchitectDrawer(){
    if(theme!=='ai-architect'||!matchMedia('(max-width:767px)').matches)return;
    const candidates=[...document.querySelectorAll('aside')];
    const drawer=document.querySelector('aside.ai-architect-drawer')||candidates.find(node=>{
      const text=(node.textContent||'').replace(/\s+/g,' ');
      return (/Enterprise RAG/i.test(text)&&(/Cloud Compare|Bandingkan Awan/i.test(text))) || node.querySelectorAll('a').length>=8;
    });
    if(!drawer)return;
    drawer.classList.add('ai-architect-drawer');
    drawer.setAttribute('role','navigation');
    drawer.setAttribute('aria-label','Navigasi AI Architect Lab');
    drawer.style.setProperty('overflow-y','auto','important');
    drawer.style.setProperty('-webkit-overflow-scrolling','touch','important');
    const nav=drawer.querySelector('nav')||drawer;
    let contact=[...nav.querySelectorAll('a')].find(a=>/contact|kontak/i.test(a.textContent||'')||/\/contact/.test(a.getAttribute('href')||''));
    if(!contact){contact=document.createElement('a');contact.href='/projects/ai-architect/contact/';contact.innerHTML='<span>✉</span><span>Kontak & Book a Call</span>';nav.appendChild(contact)}
    contact.classList.add('apu-v69-contact-link');
  }

  function fallbackModelMarkup(){
    const rows=[
      ['01','Komputer laboratorium baru cepat dan stabil.','Positif','Positif','94%'],
      ['02','Dosen menjelaskan topik sulit dengan jelas.','Positif','Positif','92%'],
      ['03','Wi-Fi kampus lebih stabil semester ini.','Positif','Positif','89%'],
      ['04','Antrean kafetaria masih terlalu panjang.','Negatif','Negatif','86%'],
      ['05','Portal registrasi gagal sebelum tenggat.','Negatif','Negatif','93%'],
      ['06','Proyektor kelas sering terputus.','Negatif','Negatif','88%'],
      ['07','Jadwal kuliah diperbarui kemarin.','Netral','Netral','82%'],
      ['08','Ruangan cukup dan fasilitas rata-rata.','Netral','Netral','79%'],
      ['09','Bagus, portal mati tepat saat dibutuhkan.','Negatif','Positif','61%'],
      ['10','Tutorial tidak buruk, tetapi perlu contoh lanjut.','Netral','Negatif','64%'],
      ['11','Perpustakaan nyaman, tetapi stopkontak kurang.','Netral','Positif','67%'],
      ['12','Layanan dukungan menjawab dengan cepat.','Positif','Positif','91%']
    ].map(r=>`<tr>${r.map(c=>`<td>${c}</td>`).join('')}</tr>`).join('');
    return `<main class="apu-v610-model-fallback" id="apuV610ModelFallback"><div class="apu-v610-model-fallback__inner">
      <p>NLP · Evaluasi Model · Data Lokal</p><h1>Evaluasi Model Sentimen</h1>
      <p>Halaman evaluasi menggunakan 12 rekaman demonstrasi lokal sehingga metrik, confusion matrix, dan data pengujian tetap muncul tanpa API eksternal.</p>
      <section class="apu-v610-model-metrics"><article class="apu-v610-model-card"><small>Akurasi</small><strong>75.0%</strong></article><article class="apu-v610-model-card"><small>Precision Makro</small><strong>73.9%</strong></article><article class="apu-v610-model-card"><small>Recall Makro</small><strong>73.9%</strong></article><article class="apu-v610-model-card"><small>F1 Makro</small><strong>73.9%</strong></article></section>
      <section class="apu-v610-model-grid"><article class="apu-v610-model-panel"><h2>Confusion Matrix</h2><div class="apu-v610-model-table-wrap"><table class="apu-v610-model-table"><thead><tr><th>Aktual</th><th>Positif</th><th>Negatif</th><th>Netral</th></tr></thead><tbody><tr><th>Positif</th><td>4</td><td>0</td><td>1</td></tr><tr><th>Negatif</th><td>1</td><td>3</td><td>0</td></tr><tr><th>Netral</th><td>1</td><td>0</td><td>2</td></tr></tbody></table></div></article><article class="apu-v610-model-panel"><h2>Analisis Kesalahan</h2><p>Sarkasme, negasi, dan sentimen campuran menjadi sumber kesalahan utama. Perbaikan berikutnya adalah penambahan data Indonesia dan embedding kontekstual.</p></article></section>
      <section class="apu-v610-model-panel" style="margin-top:14px"><h2>Dataset Evaluasi — 12 Rekaman</h2><div class="apu-v610-model-table-wrap"><table class="apu-v610-model-table"><thead><tr><th>#</th><th>Teks</th><th>Aktual</th><th>Prediksi</th><th>Keyakinan</th></tr></thead><tbody>${rows}</tbody></table></div></section>
    </div></main>`;
  }

  function ensureModelEvaluation(){
    if(theme!=='sentiment-analysis'||!(html.dataset.apuModelEvaluation==='true'||/\/model\/?(?:index\.html)?$/.test(location.pathname)))return;
    const existing=document.getElementById('apuV69ModelEvaluation');
    if(existing){existing.style.setProperty('display','block','important');existing.style.setProperty('visibility','visible','important');return}
    if(document.getElementById('apuV610ModelFallback'))return;
    const root=document.getElementById('root');
    const text=(root?.innerText||'').replace(/\s+/g,' ').trim();
    const visible=root&&root.getBoundingClientRect().height>260&&/accuracy|akurasi|confusion|evaluasi model/i.test(text);
    if(visible)return;
    const holder=document.createElement('div');holder.innerHTML=fallbackModelMarkup();
    const model=holder.firstElementChild;
    if(root){root.style.setProperty('display','none','important');root.insertAdjacentElement('beforebegin',model)}else document.body.appendChild(model);
  }

  function maintain(){
    ensureViewerLanguageButton();
    compactViewerControls();
    hideIncidentPermanentSidebar();
    stabilizeNativeBurger();
    improveNetworkContrast();
    improveAiArchitectDrawer();
    ensureModelEvaluation();
  }

  function boot(){
    maintain();
    let cycles=0;
    const observer=new MutationObserver(()=>{maintain();if(++cycles>260)observer.disconnect()});
    observer.observe(document.documentElement,{childList:true,subtree:true});
    [250,700,1500,3200,6000].forEach(ms=>setTimeout(maintain,ms));
    setTimeout(()=>observer.disconnect(),22000);
  }
  if(document.readyState==='loading')document.addEventListener('DOMContentLoaded',boot,{once:true});else boot();
  addEventListener('load',maintain,{once:true});
  mobile.addEventListener?.('change',maintain);
})();
