import { Motion } from './motion.js';
import { ADS, DURATION, FPS, getFormat } from './config.js';
const $ = s => document.querySelector(s);
let motion, companion, ad='electro', time=0, playing=true, loop=true, comparing=false, last=0, lastFrame=-1;
const params=new URLSearchParams(location.search);
if(ADS[params.get('ad')])ad=params.get('ad');
const playIcon='<svg viewBox="0 0 24 24"><path d="m8 5 11 7-11 7Z"/></svg>';
const pauseIcon='<svg viewBox="0 0 24 24"><path d="M8 5v14M16 5v14"/></svg>';
function updatePlay(){ $('#play').innerHTML=(playing?pauseIcon:playIcon)+`<span>${playing?'Pauza':'Pokreni'}</span>`;$('#play').setAttribute('aria-label',playing?'Pauziraj':'Pokreni'); }
function layout(){
  const side=ad==='side',{width,height}=getFormat(ad);
  $('.stage').classList.toggle('side-panel',side);
  $('.stage').classList.toggle('comparison',side&&comparing);
  $('#side-options').hidden=!side;
  $('#companion').hidden=!(side&&comparing);
  $('#front-ad').hidden=!(side&&comparing);
  $('#compare').setAttribute('aria-pressed',String(comparing));
  $('#compare').innerHTML=comparing?'Prikaži samo bočnu <span>↗</span>':'Pogledaj uz prednju reklamu <span>↗</span>';
  $('#format-size').textContent=`${width} × ${height}`;
  $('.dimension').textContent=side&&comparing?'PREDNJA 320 × 512 + BOČNA 64 × 512':`${width} × ${height}`;
  $('#motion').setAttribute('aria-label',`${ADS[ad].title}, ${width} × ${height} piksela`);
}
function select(key){
  if(!ADS[key])return;
  ad=key;time=0;lastFrame=-1;playing=true;last=performance.now();updatePlay();
  document.querySelectorAll('.ad-tab').forEach(el=>{const active=el.dataset.ad===ad;el.classList.toggle('active',active);el.setAttribute('aria-selected',String(active));el.tabIndex=active?0:-1;});
  $('#film-label').textContent=`${ADS[ad].number} / ${ADS[ad].title.toUpperCase()}`;
  $('#download').href=`/output/${ADS[ad].file}`;
  history.replaceState(null,'',`?ad=${ad}`);layout();draw();
}
function draw(){
  if(!motion)return;
  const frame=Math.min(DURATION*FPS-1,Math.floor(time*FPS));
  if(frame!==lastFrame){
    motion.render(ad,frame/FPS);
    if(ad==='side'&&comparing)companion.render($('#front-ad').value,frame/FPS);
    lastFrame=frame;
  }
  $('#timeline').value=time;$('#timeline').style.setProperty('--progress',`${time/DURATION*100}%`);
  $('#current-time').textContent=`00:${String(Math.floor(time)).padStart(2,'0')}`;
  let scene=0;ADS[ad].times.forEach((at,i)=>{if(time>=at)scene=i;});$('#scene-label').textContent=ADS[ad].scenes[scene];
}
function tick(now){if(last&&playing&&!document.hidden){time+=(now-last)/1000;if(time>=DURATION){if(loop)time%=DURATION;else{time=DURATION;playing=false;updatePlay();}}}last=now;draw();requestAnimationFrame(tick);}
function toggle(){if(time>=DURATION)time=0;playing=!playing;last=performance.now();updatePlay();}
$('#play').onclick=toggle;
$('#restart').onclick=()=>{time=0;lastFrame=-1;playing=true;last=performance.now();updatePlay();draw();};
$('#loop').onclick=()=>{loop=!loop;$('#loop').setAttribute('aria-pressed',String(loop));$('#loop').classList.toggle('on',loop);$('#loop-value').textContent=loop?'ON':'OFF';};
$('#safe').onclick=()=>{const value=$('#safe').getAttribute('aria-pressed')!=='true';$('#safe').setAttribute('aria-pressed',String(value));$('#safe').classList.toggle('on',value);$('#safe-zone').classList.toggle('visible',value);};
$('#timeline').oninput=e=>{time=Number(e.target.value);playing=false;updatePlay();draw();};
$('#compare').onclick=()=>{comparing=!comparing;lastFrame=-1;layout();draw();};
$('#front-ad').onchange=()=>{lastFrame=-1;draw();};
const tabs=[...document.querySelectorAll('.ad-tab')];
tabs.forEach((el,i)=>{el.onclick=()=>select(el.dataset.ad);el.onkeydown=e=>{if(['ArrowDown','ArrowUp','ArrowRight','ArrowLeft','Home','End'].includes(e.key)){e.preventDefault();let next;if(e.key==='Home')next=0;else if(e.key==='End')next=tabs.length-1;else next=(i+(['ArrowDown','ArrowRight'].includes(e.key)?1:tabs.length-1))%tabs.length;tabs[next].focus();select(tabs[next].dataset.ad);}};});
document.addEventListener('keydown',e=>{if(e.code==='Space'&&e.target===document.body){e.preventDefault();toggle();}});
document.addEventListener('visibilitychange',()=>last=performance.now());
try{
  motion=await new Motion($('#motion')).init();
  companion=Object.assign(new Motion($('#companion')),{logo:motion.logo,lighting:motion.lighting,lift:motion.lift});
  $('#loading').classList.add('hidden');select(ad);
  window.preview={select,seek:(t)=>{time=Math.max(0,Math.min(DURATION,t));playing=false;updatePlay();draw();},get state(){return{ad,time,playing,loop,comparing};}};
  requestAnimationFrame(tick);
}catch(error){$('#loading').textContent='Film se nije učitao. Osvježi stranicu.';console.error(error);}
