/* AI Project Universe V6.17 — permanent single mobile language trigger */
(()=>{
  'use strict';
  const BREAKPOINT='(max-width:760px)';
  const mq=matchMedia(BREAKPOINT);
  const names={id:'Bahasa Indonesia',en:'English',ms:'Bahasa Melayu',de:'Deutsch',vi:'Tiếng Việt',zh:'中文（简体）',ja:'日本語'};
  const codes={id:'ID',en:'EN',ms:'MS',de:'DE',vi:'VI',zh:'中文',ja:'日本'};
  let menu=null;
  let trigger=null;
  let syncing=false;
  let scheduled=false;

  const isLegacyTrigger=node=>{
    if(!(node instanceof HTMLElement))return false;
    if(node.id==='apuV617MobileLanguageTrigger')return false;
    if(node.matches('.apu-v69-language-button,.apu-v611-language-trigger,.apu-v612-language-trigger,.apu-v617-language-trigger,[data-apu-language-trigger]'))return true;
    const label=(node.getAttribute('aria-label')||'').toLowerCase();
    const text=(node.textContent||'').trim();
    return node.tagName==='BUTTON' && node.closest('#viewerDisplayControls') && (text==='文'||/bahasa|language|translate|terjemah/.test(label));
  };

  function removeLegacyArtifacts(viewer){
    viewer.querySelectorAll('button').forEach(node=>{if(isLegacyTrigger(node))node.remove()});
    viewer.querySelectorAll('.apu-v69-language-menu,.apu-v611-language-menu,.apu-v612-language-menu').forEach(node=>node.remove());
  }

  function closeMenu(){
    if(menu)menu.classList.remove('is-open');
    if(trigger)trigger.setAttribute('aria-expanded','false');
  }

  function positionMenu(){
    if(!menu||!trigger)return;
    const rect=trigger.getBoundingClientRect();
    const width=Math.min(300,Math.max(250,innerWidth-20));
    const maxHeight=Math.min(460,Math.max(250,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(8,rect.top-maxHeight-8);
    menu.style.left=`${left}px`;
    menu.style.top=`${top}px`;
  }

  function updateSelection(select){
    if(!menu)return;
    menu.querySelectorAll('.apu-v617-language-option').forEach(button=>{
      const selected=button.dataset.value===select.value;
      button.setAttribute('aria-current',String(selected));
      button.setAttribute('aria-checked',String(selected));
    });
  }

  function buildMenu(viewer,select){
    menu=document.createElement('div');
    menu.id='apuV617LanguageMenu';
    menu.className='apu-v617-language-menu';
    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-v617-language-option';
      item.dataset.value=value;
      item.setAttribute('role','menuitemradio');
      item.innerHTML=`<span class="apu-v617-language-code">${codes[value]||value.toUpperCase()}</span><span class="apu-v617-language-name">${names[value]||option.textContent||value}</span>`;
      item.addEventListener('click',event=>{
        event.preventDefault();
        event.stopPropagation();
        select.value=value;
        select.dispatchEvent(new Event('input',{bubbles:true}));
        select.dispatchEvent(new Event('change',{bubbles:true}));
        updateSelection(select);
        closeMenu();
      });
      menu.appendChild(item);
    });
    viewer.appendChild(menu);
    updateSelection(select);
  }

  function buildTrigger(controls,viewer,select,label){
    trigger=document.createElement('button');
    trigger.type='button';
    trigger.id='apuV617MobileLanguageTrigger';
    trigger.className='apu-v617-language-trigger';
    trigger.dataset.apuLanguageTrigger='canonical';
    trigger.textContent='文';
    trigger.setAttribute('aria-label','Pilih bahasa terjemahan');
    trigger.setAttribute('aria-haspopup','menu');
    trigger.setAttribute('aria-expanded','false');
    label.insertAdjacentElement('afterend',trigger);
    trigger.addEventListener('click',event=>{
      event.preventDefault();
      event.stopPropagation();
      if(menu?.classList.contains('is-open'))closeMenu();
      else{
        positionMenu();
        menu?.classList.add('is-open');
        trigger.setAttribute('aria-expanded','true');
        menu?.querySelector('[aria-current="true"]')?.focus({preventScroll:true});
      }
    });
    buildMenu(viewer,select);
  }

  function sync(){
    scheduled=false;
    if(syncing)return;
    syncing=true;
    try{
      const viewer=document.getElementById('projectViewer');
      const controls=document.getElementById('viewerDisplayControls');
      const select=document.getElementById('viewerLanguageControl');
      const label=select?.closest('.viewer__language-control');
      if(!viewer||!controls||!select||!label)return;

      const mobile=mq.matches;
      const oldTrigger=trigger;
      const oldMenu=menu;
      trigger=null;
      menu=null;
      removeLegacyArtifacts(viewer);
      oldTrigger?.remove();
      oldMenu?.remove();

      if(mobile){
        label.style.setProperty('display','none','important');
        label.style.setProperty('visibility','hidden','important');
        buildTrigger(controls,viewer,select,label);
      }else{
        label.style.setProperty('display','inline-flex','important');
        label.style.setProperty('visibility','visible','important');
        select.style.setProperty('display','block','important');
        select.style.setProperty('visibility','visible','important');
      }
      viewer.dataset.apuV617CanonicalLanguage=mobile?'mobile':'desktop';
    }finally{
      syncing=false;
    }
  }

  function schedule(){
    if(scheduled||syncing)return;
    scheduled=true;
    requestAnimationFrame(sync);
  }

  function boot(){
    sync();
    const viewer=document.getElementById('projectViewer');
    if(viewer){
      const observer=new MutationObserver(mutations=>{
        if(syncing)return;
        const relevant=mutations.some(m=>[...m.addedNodes].some(node=>node instanceof HTMLElement && (isLegacyTrigger(node)||node.querySelector?.('.apu-v69-language-button,.apu-v611-language-trigger,.apu-v612-language-trigger,[data-apu-language-trigger]'))));
        if(relevant)schedule();
      });
      observer.observe(viewer,{childList:true,subtree:true});
    }
    mq.addEventListener?.('change',sync);
    addEventListener('resize',()=>{closeMenu();schedule()},{passive:true});
    document.addEventListener('pointerdown',event=>{
      if(menu?.classList.contains('is-open')&&!menu.contains(event.target)&&event.target!==trigger)closeMenu();
    },true);
    document.addEventListener('keydown',event=>{if(event.key==='Escape')closeMenu()});
    document.getElementById('viewerLanguageControl')?.addEventListener('change',event=>updateSelection(event.currentTarget));
    [60,180,500,1200,2500,5000,9000,16000,30000].forEach(ms=>setTimeout(schedule,ms));
  }

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