// @ts-check
(()=>{
  'use strict';
  const App=window.IUS_TEMPLATE,{state,utils}=App;
  const root=document.documentElement;
  const FIXED_PALETTE="signal-noir";
  const FIXED_APPEARANCE="dark";
  const THEME_COLOUR="#020304";
  function apply({persistState=false,announce=false}={}){
    App.setState({palette:FIXED_PALETTE,appearance:FIXED_APPEARANCE});
    root.dataset.palette=FIXED_PALETTE;
    root.dataset.appearance=FIXED_APPEARANCE;
    root.dataset.themeEdition=`${FIXED_PALETTE}-${FIXED_APPEARANCE}`;
    document.querySelector('meta[name="theme-color"]')?.setAttribute('content',THEME_COLOUR);
    root.style.colorScheme=FIXED_APPEARANCE;
    document.dispatchEvent(new CustomEvent('ius:themechange',{detail:{palette:FIXED_PALETTE,appearance:FIXED_APPEARANCE,locked:true,announce}}));
  }
  async function handleMotion(checked){
    let allowed=checked;
    if(checked&&typeof DeviceOrientationEvent!=='undefined'&&typeof DeviceOrientationEvent.requestPermission==='function'){
      try{allowed=(await DeviceOrientationEvent.requestPermission())==='granted'}catch(_){allowed=false}
    }
    App.setState({sensorMotion:allowed});
    const input=utils.$('[data-motion-toggle]');if(input)input.checked=allowed;
    try{localStorage.setItem('ius-template-motion-v1',allowed?'1':'0')}catch(_){}
    document.dispatchEvent(new CustomEvent('ius:motionchange',{detail:{enabled:allowed}}));
  }
  function init(){
    try{const m=localStorage.getItem('ius-template-motion-v1');if(m!==null)state.sensorMotion=m==='1'}catch(_){}
    const mt=utils.$('[data-motion-toggle]');if(mt){mt.checked=state.sensorMotion;mt.addEventListener('change',()=>handleMotion(mt.checked))}
    apply();requestAnimationFrame(()=>root.classList.add('theme-ready'));
  }
  App.modules.theme={init,apply,fixed:true,palette:FIXED_PALETTE,appearance:FIXED_APPEARANCE};
})();
