/* AI Project Universe V6.12 — single translate control and clean Incident mobile dashboard */
(()=>{
  'use strict';
  const html=document.documentElement;
  const langNames={id:'Bahasa Indonesia',en:'English',ms:'Bahasa Melayu',de:'Deutsch',vi:'Tiếng Việt',zh:'中文（简体）',ja:'日本語'};
  const langCodes={id:'ID',en:'EN',ms:'MS',de:'DE',vi:'VI',zh:'中文',ja:'日本'};

  function installSingleLanguageControl(){
    const viewer=document.getElementById('projectViewer');
    const select=document.getElementById('viewerLanguageControl');
    const controls=document.getElementById('viewerDisplayControls');
    if(!viewer||!select||!controls)return;

    let trigger=document.getElementById('apuV612LanguageTrigger');
    if(!trigger){
      trigger=document.createElement('button');
      trigger.type='button';
      trigger.id='apuV612LanguageTrigger';
      trigger.className='apu-v69-language-button apu-v612-language-trigger';
      trigger.textContent='文';
      trigger.setAttribute('aria-label','Pilih bahasa terjemahan');
      trigger.setAttribute('aria-haspopup','menu');
      trigger.setAttribute('aria-expanded','false');
      controls.appendChild(trigger);
    }

    /* Remove every legacy duplicate while preserving the single V6.12 trigger. */
    document.querySelectorAll('.apu-v69-language-button,.apu-v611-language-trigger').forEach(node=>{
      if(node!==trigger)node.remove();
    });
    document.querySelectorAll('.apu-v69-language-menu,.apu-v611-language-menu,.apu-v612-language-menu').forEach(node=>node.remove());

    const menu=document.createElement('div');
    menu.className='apu-v612-language-menu';
    menu.id='apuV612LanguageMenu';
    menu.setAttribute('role','menu');
    menu.setAttribute('aria-label','Pilih bahasa terjemahan');
    [...select.options].forEach(option=>{
      const value=option.value;
      const item=document.createElement('button');
      item.type='button';
      item.className='apu-v612-language-option';
      item.dataset.value=value;
      item.setAttribute('role','menuitemradio');
      item.setAttribute('aria-checked',String(select.value===value));
      item.setAttribute('aria-current',String(select.value===value));
      item.innerHTML=`<span class="apu-v612-language-code">${langCodes[value]||value.toUpperCase()}</span><span class="apu-v612-language-name">${langNames[value]||option.textContent||value}</span>`;
      menu.appendChild(item);
    });
    viewer.appendChild(menu);

    const place=()=>{
      const rect=trigger.getBoundingClientRect();
      const width=Math.min(290,Math.max(230,innerWidth-20));
      const maxHeight=Math.min(440,Math.max(230,innerHeight-92));
      const left=Math.max(10,Math.min(innerWidth-width-10,rect.left));
      let top=rect.bottom+8;
      if(top+maxHeight>innerHeight-8)top=Math.max(76,rect.top-maxHeight-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.onclick=event=>{
      event.preventDefault();
      event.stopPropagation();
      menu.classList.contains('is-open')?close():open();
    };
    menu.addEventListener('click',event=>{
      const item=event.target.closest('.apu-v612-language-option');
      if(!item)return;
      event.preventDefault();
      const value=item.dataset.value;
      select.value=value;
      select.dispatchEvent(new Event('input',{bubbles:true}));
      select.dispatchEvent(new Event('change',{bubbles:true}));
      menu.querySelectorAll('.apu-v612-language-option').forEach(button=>{
        const selected=button===item;
        button.setAttribute('aria-current',String(selected));
        button.setAttribute('aria-checked',String(selected));
      });
      close();
    });
    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-v612-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.apuV612LanguageReady='true';
  }

  function incidentMobileActive(){
    if(html.dataset.scrollTheme!=='incident-monitoring')return false;
    if(innerWidth<=1023)return true;
    try{if(parent!==window&&parent.innerWidth<=1023)return true}catch(_){ }
    const bar=document.querySelector('.apu-final-mobile-bar');
    return !!bar&&getComputedStyle(bar).display!=='none';
  }

  function looksLikeIncidentSidebar(node){
    if(!(node instanceof HTMLElement))return false;
    const text=(node.innerText||node.textContent||'').replace(/\s+/g,' ').trim();
    const hasIdentity=/Dashboard Monitoring Insiden|Incident Monitoring Dashboard|Pusat Operasi IT Perusahaan/i.test(text);
    const hasLinks=/(Dasbor|Dashboard)/i.test(text)&&/(Insiden|Incidents)/i.test(text)&&/(Linimasa|Timeline)/i.test(text)&&/(Laporan|Reports)/i.test(text);
    return node.tagName==='ASIDE'||node.classList.contains('w-64')||(hasIdentity&&hasLinks);
  }

  function cleanIncidentMobile(){
    if(!incidentMobileActive())return;
    const root=document.getElementById('root');
    if(!root)return;

    const candidates=new Set([...root.querySelectorAll('aside,[class~="w-64"]')]);
    const shell=root.firstElementChild;
    if(shell){
      [...shell.children].forEach(child=>{if(looksLikeIncidentSidebar(child))candidates.add(child)});
      shell.classList.add('apu-v612-incident-shell');
    }
    candidates.forEach(node=>{
      if(!looksLikeIncidentSidebar(node))return;
      node.classList.add('apu-v612-incident-sidebar');
      node.dataset.apuV612IncidentSidebar='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 main=root.querySelector('main');
    if(main){
      main.classList.add('apu-v612-incident-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('margin','0','important');
      main.style.setProperty('padding-left','0','important');
    }

    document.querySelectorAll('.apu-final-mobile-exit,[data-apu-incident-mobile-exit="true"]').forEach(node=>{
      node.classList.add('apu-v612-incident-exit');
      node.setAttribute('aria-hidden','true');
      node.style.setProperty('display','none','important');
    });
    document.querySelectorAll('.apu-final-drawer-close').forEach(node=>{
      node.setAttribute('aria-hidden','true');
      node.style.setProperty('display','none','important');
    });

    /* Start closed so the dashboard—not the navigation—is immediately below the navbar. */
    if(html.dataset.apuV612IncidentInitialClosed!=='true'){
      html.classList.remove('apu-final-nav-open');
      const drawer=document.querySelector('.apu-final-mobile-drawer');
      const scrim=document.querySelector('.apu-final-mobile-scrim');
      const menu=document.querySelector('.apu-final-mobile-menu');
      drawer?.classList.remove('is-open');
      scrim?.classList.remove('is-open');
      drawer?.setAttribute('aria-hidden','true');
      menu?.setAttribute('aria-expanded','false');
      html.dataset.apuV612IncidentInitialClosed='true';
    }
  }

  function dedupeLanguageControls(){
    const trigger=document.getElementById('apuV612LanguageTrigger');
    if(!trigger)return;
    document.querySelectorAll('.apu-v69-language-button,.apu-v611-language-trigger').forEach(node=>{if(node!==trigger)node.remove()});
    document.querySelectorAll('.apu-v69-language-menu,.apu-v611-language-menu').forEach(node=>node.remove());
  }

  function maintain(){
    if(document.getElementById('projectViewer')){
      if(document.getElementById('projectViewer').dataset.apuV612LanguageReady!=='true')installSingleLanguageControl();
      else dedupeLanguageControls();
    }
    cleanIncidentMobile();
  }
  function boot(){
    maintain();
    const observer=new MutationObserver(maintain);
    observer.observe(document.documentElement,{childList:true,subtree:true});
    [100,250,600,1200,2500,5000,9000].forEach(delay=>setTimeout(maintain,delay));
    setTimeout(()=>observer.disconnect(),30000);
  }
  if(document.readyState==='loading')document.addEventListener('DOMContentLoaded',boot,{once:true});else boot();
  addEventListener('load',maintain,{once:true});
})();
