/* AI Project Universe V6.11 — Incident mobile full-width dashboard and toolbar cleanup */
(()=>{
  'use strict';
  const html=document.documentElement;
  const theme=html.dataset.scrollTheme||'';
  const compact=matchMedia('(max-width: 1023px)');

  function cleanViewerToolbar(){
    const viewer=document.getElementById('projectViewer');
    if(!viewer)return;
    const standalone=document.getElementById('viewerStandalone');
    const download=document.getElementById('viewerDownload');
    if(standalone){
      if((standalone.textContent||'').trim()!=='Full')standalone.textContent='Full';
      standalone.setAttribute('aria-label','Buka layar penuh');
      standalone.title='Buka layar penuh';
    }
    if(download){
      if((download.textContent||'').trim()!=='.ZIP')download.textContent='.ZIP';
      download.setAttribute('aria-label','Unduh ZIP terlindungi');
      download.title='Unduh ZIP terlindungi';
    }
    viewer.querySelectorAll('.viewer__actions > a, .viewer__actions > button').forEach(control=>{
      const visibleText=(control.textContent||'').replace(/\s+/g,' ').trim();
      const meaningful=visibleText||control.querySelector('svg,img,use,[class*="icon" i]')||control.getAttribute('aria-label');
      if(!meaningful)control.remove();
    });
  }

  function isIncidentSidebar(node){
    if(!(node instanceof HTMLElement))return false;
    if(node.tagName==='ASIDE' && node.classList.contains('w-64'))return true;
    const text=(node.innerText||node.textContent||'').replace(/\s+/g,' ').trim();
    return /Dashboard|Dasbor/i.test(text) && /Incident|Insiden/i.test(text) && /Timeline|Linimasa/i.test(text) && /Report|Laporan/i.test(text);
  }

  function fixIncidentMobile(){
    if(theme!=='incident-monitoring'||!compact.matches)return;
    const root=document.getElementById('root');
    if(!root)return;

    const direct=[...root.querySelectorAll('aside')];
    const semantic=[...root.querySelectorAll('nav')].map(nav=>nav.closest('aside,section,div')).filter(Boolean);
    const candidates=[...new Set([...direct,...semantic])];
    for(const node of candidates){
      if(!isIncidentSidebar(node))continue;
      node.dataset.apuV611IncidentSidebar='true';
      node.setAttribute('aria-hidden','true');
      node.style.setProperty('display','none','important');
      node.style.setProperty('width','0','important');
      node.style.setProperty('min-width','0','important');
      node.style.setProperty('max-width','0','important');
      node.style.setProperty('flex','0 0 0','important');
    }

    const shell=root.firstElementChild;
    const main=root.querySelector('main');
    if(shell){
      shell.style.setProperty('display','block','important');
      shell.style.setProperty('width','100%','important');
      shell.style.setProperty('max-width','100%','important');
      shell.style.setProperty('min-width','0','important');
      shell.style.setProperty('height','auto','important');
      shell.style.setProperty('overflow','visible','important');
    }
    if(main){
      main.style.setProperty('display','block','important');
      main.style.setProperty('width','100%','important');
      main.style.setProperty('max-width','100%','important');
      main.style.setProperty('min-width','0','important');
      main.style.setProperty('height','auto','important');
      main.style.setProperty('margin','0','important');
      main.style.setProperty('padding-left','0','important');
      main.style.setProperty('overflow-x','hidden','important');
      main.style.setProperty('overflow-y','visible','important');
    }

    document.querySelectorAll('.apu-final-mobile-exit').forEach(button=>{
      button.dataset.apuIncidentMobileExit='true';
      button.remove();
    });
  }

  function maintain(){cleanViewerToolbar();fixIncidentMobile()}
  function boot(){
    maintain();
    const observer=new MutationObserver(maintain);
    observer.observe(document.documentElement,{childList:true,subtree:true});
    [100,300,700,1400,3000,6000].forEach(delay=>setTimeout(maintain,delay));
    setTimeout(()=>observer.disconnect(),20000);
  }
  if(document.readyState==='loading')document.addEventListener('DOMContentLoaded',boot,{once:true});else boot();
  addEventListener('load',maintain,{once:true});
  compact.addEventListener?.('change',()=>location.reload());
})();

/* V6.11 final additions: top-layer language chooser and model table scrolling. */
(()=>{
  'use strict';
  const mobile=matchMedia('(max-width: 760px)');
  const languageCodes={id:'ID',en:'EN',ms:'MS',de:'DE',vi:'VI',zh:'中文',ja:'日本'};

  function installTopLayerLanguageChooser(){
    return; /* Superseded by the single V6.12 language control. */
    if(!mobile.matches)return;
    const viewer=document.getElementById('projectViewer');
    const select=document.getElementById('viewerLanguageControl');
    const controls=document.getElementById('viewerDisplayControls');
    if(!viewer||!select||!controls)return;
    if(viewer.dataset.apuV611LanguageReady==='true')return;

    document.querySelectorAll('.apu-v69-language-menu,.apu-v611-language-menu').forEach(node=>node.remove());
    document.querySelectorAll('.apu-v69-language-button').forEach(node=>node.remove());

    const trigger=document.createElement('button');
    trigger.type='button';
    trigger.className='apu-v69-language-button apu-v611-language-trigger';
    trigger.textContent='文';
    trigger.setAttribute('aria-label','Pilih bahasa terjemahan');
    trigger.setAttribute('aria-haspopup','menu');
    trigger.setAttribute('aria-expanded','false');
    controls.appendChild(trigger);

    const menu=document.createElement('div');
    menu.className='apu-v611-language-menu';
    menu.setAttribute('role','menu');
    menu.setAttribute('aria-label','Daftar bahasa terjemahan');
    [...select.options].forEach(option=>{
      const item=document.createElement('button');
      item.type='button';
      item.className='apu-v611-language-option';
      item.dataset.value=option.value;
      item.setAttribute('role','menuitemradio');
      item.setAttribute('aria-checked',String(select.value===option.value));
      item.setAttribute('aria-current',String(select.value===option.value));
      const code=document.createElement('span');
      code.className='apu-v611-language-code';
      code.textContent=languageCodes[option.value]||option.value.toUpperCase();
      const name=document.createElement('span');
      name.className='apu-v611-language-name';
      name.textContent=option.textContent||option.value;
      item.append(code,name);
      item.addEventListener('click',event=>{
        event.preventDefault();
        select.value=option.value;
        select.dispatchEvent(new Event('input',{bubbles:true}));
        select.dispatchEvent(new Event('change',{bubbles:true}));
        menu.querySelectorAll('.apu-v611-language-option').forEach(button=>{
          const selected=button===item;
          button.setAttribute('aria-current',String(selected));
          button.setAttribute('aria-checked',String(selected));
        });
        close();
      });
      menu.appendChild(item);
    });
    viewer.appendChild(menu);

    const place=()=>{
      const rect=trigger.getBoundingClientRect();
      const width=Math.min(280,Math.max(220,innerWidth-20));
      const estimated=Math.min(430,innerHeight-92);
      const left=Math.max(10,Math.min(innerWidth-width-10,rect.left));
      let top=rect.bottom+8;
      if(top+estimated>innerHeight-8)top=Math.max(74,rect.top-estimated-8);
      menu.style.left=`${left}px`;
      menu.style.top=`${top}px`;
    };
    const close=()=>{
      menu.classList.remove('is-open');
      trigger.setAttribute('aria-expanded','false');
    };
    const open=()=>{
      place();
      menu.classList.add('is-open');
      trigger.setAttribute('aria-expanded','true');
      menu.querySelector('[aria-current="true"]')?.focus({preventScroll:true});
    };
    trigger.addEventListener('click',event=>{
      event.preventDefault();
      event.stopPropagation();
      menu.classList.contains('is-open')?close():open();
    });
    document.addEventListener('pointerdown',event=>{
      if(!menu.contains(event.target)&&event.target!==trigger)close();
    },true);
    document.addEventListener('keydown',event=>{if(event.key==='Escape')close()});
    addEventListener('resize',()=>{if(menu.classList.contains('is-open'))place()},{passive:true});
    select.addEventListener('change',()=>{
      menu.querySelectorAll('.apu-v611-language-option').forEach(button=>{
        const selected=button.dataset.value===select.value;
        button.setAttribute('aria-current',String(selected));
        button.setAttribute('aria-checked',String(selected));
      });
    });
    viewer.dataset.apuV611LanguageReady='true';
  }

  function makeScrollable(table,kind){
    if(!(table instanceof HTMLTableElement))return;
    let wrap=table.parentElement;
    if(!wrap||!wrap.classList.contains('apu-v611-horizontal-scroll')){
      if(wrap?.classList.contains('apu-v69-table-wrap')){
        wrap.classList.add('apu-v611-horizontal-scroll');
      }else{
        const holder=document.createElement('div');
        holder.className='apu-v611-horizontal-scroll';
        table.before(holder);holder.appendChild(table);wrap=holder;
      }
    }
    wrap.classList.add(`apu-v611-horizontal-scroll--${kind}`);
    table.classList.add(kind==='dataset'?'apu-v611-dataset-table':'apu-v611-class-table');
    wrap.setAttribute('tabindex','0');
    wrap.setAttribute('role','region');
    wrap.setAttribute('aria-label',kind==='dataset'?'Dataset evaluasi, geser horizontal untuk melihat semua kolom':'Laporan per kelas, geser horizontal untuk melihat semua kolom');
  }

  function ensureEvaluationTableScrolling(){
    const html=document.documentElement;
    if(html.dataset.scrollTheme!=='sentiment-analysis')return;
    if(!(html.dataset.apuModelEvaluation==='true'||/\/model\/?(?:index\.html)?$/.test(location.pathname)))return;
    document.querySelectorAll('h1,h2,h3,h4').forEach(heading=>{
      const text=(heading.textContent||'').replace(/\s+/g,' ').trim();
      let kind='';
      if(/laporan\s+per\s+kelas|class\s+report/i.test(text))kind='class';
      if(/dataset\s+evaluasi|evaluation\s+dataset/i.test(text))kind='dataset';
      if(!kind)return;
      const scope=heading.closest('section,article,main,div')||heading.parentElement;
      const table=scope?.querySelector('table')||heading.parentElement?.querySelector('table');
      if(table)makeScrollable(table,kind);
    });
    document.querySelectorAll('.apu-v69-model-evaluation .apu-v69-table-wrap').forEach(wrap=>{
      wrap.classList.add('apu-v611-horizontal-scroll');
    });
  }

  function maintain(){installTopLayerLanguageChooser();ensureEvaluationTableScrolling()}
  function boot(){
    maintain();
    const observer=new MutationObserver(maintain);
    observer.observe(document.documentElement,{childList:true,subtree:true});
    [150,400,900,1800,3600,7000].forEach(delay=>setTimeout(maintain,delay));
    setTimeout(()=>observer.disconnect(),24000);
  }
  if(document.readyState==='loading')document.addEventListener('DOMContentLoaded',boot,{once:true});else boot();
  addEventListener('load',maintain,{once:true});
})();
