(() => {
  'use strict';
  const THEME_KEY='apu-ui-theme';
  const LANGUAGE_KEY='apu-ui-language';
  const supported=['id','en','ms','de','vi','zh','ja'];
  const ui={
    id:{light:'Terang',dark:'Gelap',theme:'Ganti tema',language:'Pilih bahasa',group:'Tema dan bahasa'},
    en:{light:'Light',dark:'Dark',theme:'Change theme',language:'Choose language',group:'Theme and language'},
    ms:{light:'Cerah',dark:'Gelap',theme:'Tukar tema',language:'Pilih bahasa',group:'Tema dan bahasa'},
    de:{light:'Hell',dark:'Dunkel',theme:'Design wechseln',language:'Sprache wählen',group:'Design und Sprache'},
    vi:{light:'Sáng',dark:'Tối',theme:'Đổi giao diện',language:'Chọn ngôn ngữ',group:'Giao diện và ngôn ngữ'},
    zh:{light:'浅色',dark:'深色',theme:'切换主题',language:'选择语言',group:'主题和语言'},
    ja:{light:'ライト',dark:'ダーク',theme:'テーマを変更',language:'言語を選択',group:'テーマと言語'}
  };
  const byId=id=>document.getElementById(id);
  const frame=byId('viewerFrame');
  const themeButton=byId('viewerThemeControl');
  const themeLabel=byId('viewerThemeLabel');
  const languageSelect=byId('viewerLanguageControl');
  const group=byId('viewerDisplayControls');
  if(!frame||!themeButton||!languageSelect)return;

  const read=(key,fallback)=>{try{return localStorage.getItem(key)||fallback;}catch(_){return fallback;}};
  let theme=['light','dark'].includes(read(THEME_KEY,''))?read(THEME_KEY,'light'):(matchMedia('(prefers-color-scheme: dark)').matches?'dark':'light');
  let language=supported.includes(read(LANGUAGE_KEY,''))?read(LANGUAGE_KEY,'id'):'id';
  const save=(key,value)=>{try{localStorage.setItem(key,value);}catch(_){}};

  function render(){
    const text=ui[language]||ui.id;
    themeButton.setAttribute('aria-pressed',String(theme==='dark'));
    themeButton.setAttribute('aria-label',`${text.theme}: ${text[theme]}`);
    themeButton.title=text.theme;
    themeLabel.textContent=text[theme];
    languageSelect.value=language;
    languageSelect.setAttribute('aria-label',text.language);
    languageSelect.title=text.language;
    group.setAttribute('aria-label',text.group);
  }
  function cleanupEmbeddedDock(){
    try{
      const doc=frame.contentDocument;
      if(!doc)return;
      doc.documentElement.dataset.apuEmbedded='true';
      ['apu-ui-dock-v62','apu-ui-toast-v62','apu-ui-dock-v60','apu-ui-toast-v60','apu-ui-dock-v59','apu-ui-toast-v59','apu-ui-dock-v58','apu-ui-toast-v58','apu-ui-dock-v57','apu-ui-toast-v57','apu-ui-dock-v56','apu-ui-toast-v56'].forEach(id=>doc.getElementById(id)?.remove());
      if(!doc.getElementById('apu-embedded-menu-only-v62')){
        const style=doc.createElement('style');
        style.id='apu-embedded-menu-only-v62';
        style.textContent='#apu-ui-dock-v62,#apu-ui-toast-v62,#apu-ui-dock-v60,#apu-ui-toast-v60,#apu-ui-dock-v59,#apu-ui-toast-v59,#apu-ui-dock-v58,#apu-ui-toast-v58,#apu-ui-dock-v57,#apu-ui-toast-v57,#apu-ui-dock-v56,#apu-ui-toast-v56{display:none!important}';
        doc.head?.appendChild(style);
      }
    }catch(_){}
  }
  function send(){
    cleanupEmbeddedDock();
    try{frame.contentWindow?.postMessage({type:'apu:viewer-settings',theme,language},location.origin);}catch(_){}
  }
  function broadcast(){
    send();
    setTimeout(send,80);
    setTimeout(send,420);
  }
  function setExternalTheme(next){if(!['light','dark'].includes(next))return;if(next!==theme){theme=next;save(THEME_KEY,theme);render();broadcast();}}
  function setExternalLanguage(next){if(!supported.includes(next))return;if(next!==language){language=next;save(LANGUAGE_KEY,language);render();broadcast();}}
  window.APUViewerControls={setTheme:setExternalTheme,setLanguage:setExternalLanguage,getTheme:()=>theme,getLanguage:()=>language};
  themeButton.addEventListener('click',()=>{
    theme=theme==='dark'?'light':'dark';
    save(THEME_KEY,theme);render();broadcast();window.dispatchEvent(new CustomEvent('apu:viewer-theme-change',{detail:{theme}}));
  });
  languageSelect.addEventListener('change',()=>{
    language=supported.includes(languageSelect.value)?languageSelect.value:'id';
    save(LANGUAGE_KEY,language);render();broadcast();window.dispatchEvent(new CustomEvent('apu:viewer-language-change',{detail:{language}}));
  });
  frame.addEventListener('load',broadcast);
  window.addEventListener('message',event=>{
    if(event.origin!==location.origin)return;
    if(event.data?.type==='apu:close-project'){
      document.getElementById('viewerClose')?.click();
      return;
    }
    if(event.data?.type==='apu:project-ready')broadcast();
  });
  window.addEventListener('storage',event=>{
    if(event.key===THEME_KEY&&['light','dark'].includes(event.newValue)){theme=event.newValue;render();broadcast();}
    if(event.key===LANGUAGE_KEY&&supported.includes(event.newValue)){language=event.newValue;render();broadcast();}
  });

  window.addEventListener('apu:front-theme-change',event=>setExternalTheme(event.detail?.theme));
  window.addEventListener('apu:front-language-change',event=>setExternalLanguage(event.detail?.language));
  render();
})();
