/* AI Project Universe V6.14 — canonical responsive language control */
(()=>{
  'use strict';
  const mq=matchMedia('(max-width:760px)');
  let scheduled=false;

  function important(node,property,value){
    if(node)node.style.setProperty(property,value,'important');
  }

  function canonicalize(){
    scheduled=false;
    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;

    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');
      label.insertAdjacentElement('afterend',trigger);
    }

    /* Keep one and only one language icon. */
    document.querySelectorAll('.apu-v69-language-button,.apu-v611-language-trigger,.apu-v612-language-trigger').forEach(node=>{
      if(node!==trigger)node.remove();
    });

    const mobile=mq.matches;
    important(label,'display',mobile?'none':'inline-flex');
    important(label,'visibility',mobile?'hidden':'visible');
    important(trigger,'display',mobile?'inline-flex':'none');
    important(trigger,'visibility',mobile?'visible':'hidden');

    /* The V6.12 menu is the sole mobile chooser and contains the full language names. */
    document.querySelectorAll('.apu-v69-language-menu,.apu-v611-language-menu').forEach(menu=>{
      if(!menu.classList.contains('apu-v612-language-menu'))important(menu,'display','none');
    });
    const menu=document.getElementById('apuV612LanguageMenu')||document.querySelector('.apu-v612-language-menu');
    if(!mobile&&menu){
      menu.classList.remove('is-open');
      trigger.setAttribute('aria-expanded','false');
    }

    viewer.dataset.apuV614ResponsiveLanguage='true';
  }

  function schedule(){
    if(scheduled)return;
    scheduled=true;
    requestAnimationFrame(canonicalize);
  }

  function boot(){
    canonicalize();
    const observer=new MutationObserver(schedule);
    observer.observe(document.documentElement,{childList:true,subtree:true});
    mq.addEventListener?.('change',canonicalize);
    addEventListener('resize',schedule,{passive:true});
    [80,180,400,900,1800,3500,7000,12000,22000,32000].forEach(ms=>setTimeout(canonicalize,ms));
  }
  if(document.readyState==='loading')document.addEventListener('DOMContentLoaded',boot,{once:true});else boot();
})();
