/* V6.19 — keep root and standalone theme attributes synchronized, then
   force native select labels to repaint after a theme or language change. */
(()=>{
  'use strict';
  const root=document.documentElement;
  let queued=false;
  const currentTheme=()=>root.dataset.frontTheme||root.dataset.apuTheme||
    (matchMedia('(prefers-color-scheme: dark)').matches?'dark':'light');
  const repaint=()=>{
    queued=false;
    const theme=currentTheme()==='dark'?'dark':'light';
    if(root.dataset.apuTheme!==theme) root.dataset.apuTheme=theme;
    document.querySelectorAll('select').forEach(select=>{
      select.style.setProperty('color',theme==='dark'?'#f8fafc':'#0e1726','important');
      select.style.setProperty('-webkit-text-fill-color',theme==='dark'?'#f8fafc':'#0e1726','important');
      select.style.setProperty('opacity','1','important');
    });
    document.querySelectorAll('#viewerThemeLabel,#frontThemeLabel,#frontThemeLabelMobile').forEach(label=>{
      label.style.setProperty('color',theme==='dark'?'#f8fafc':'#0e1726','important');
      label.style.setProperty('-webkit-text-fill-color',theme==='dark'?'#f8fafc':'#0e1726','important');
      label.style.setProperty('opacity','1','important');
    });
  };
  const schedule=()=>{if(!queued){queued=true;requestAnimationFrame(repaint)}};
  new MutationObserver(schedule).observe(root,{attributes:true,attributeFilter:['data-front-theme','data-apu-theme','class']});
  addEventListener('apu:front-theme-change',schedule);
  addEventListener('apu:viewer-theme-change',schedule);
  addEventListener('storage',schedule);
  addEventListener('load',()=>{schedule();setTimeout(schedule,120);setTimeout(schedule,700)},{once:true});
  document.addEventListener('change',event=>{if(event.target.matches('select'))schedule()});
  schedule();
})();
