
function getActiveLayoutPreviewUrl(){
  const key=activeLayoutKey();
  const img=[...document.querySelectorAll('.layout-tile')].find(b=>b.dataset.layout===key)?.querySelector('img');
  return img?.src || '';
}
function ensurePreviewLayer(id,cls){
  let el=document.getElementById(id);
  if(!el){
    el=document.createElement('div');
    el.id=id;
    el.className=cls;
    document.getElementById('preview').appendChild(el);
  }
  return el;
}
function updateLayoutGuide(){
  const src=getActiveLayoutPreviewUrl();
  const guide=ensurePreviewLayer('layoutGuide','layout-guide');
  const skin=ensurePreviewLayer('layoutStyleSkin','layout-style-skin');
  if(src){
    guide.style.backgroundImage=`url('${src}')`;
    skin.style.backgroundImage=`url('${src}')`;
  }
}
const $=s=>document.querySelector(s); const $$=s=>[...document.querySelectorAll(s)];
const state={layout:'auto_ads_layout_0',title:'',year:'',overview:'',poster:'',backdrop:'',logo:'',cast:[],tmdb:null,settings:{},autoItems:[],autoIndex:0,autoTimer:null,autoPage:1};
const imgBase='https://image.tmdb.org/t/p/original'; const csrf=$('#app').dataset.csrf; let lastDownload='';
function setVar(k,v){ $('#preview').style.setProperty(k,v); }
function setStatus(msg){ const el=$('#autoStatus'); if(el) el.textContent=msg; }
function rotationMs(){ const v=($('#rotation')?.value||'20 SECONDS').match(/\d+/); return (parseInt(v? v[0]:20,10)||20)*1000; }
function sourceMode(){ const src=($('#source')?.value||'').toLowerCase(); if(src.includes('animation')) return 'animation'; return 'tmdb'; }
function currentType(){ const v=$('#mediaType')?.value||'movie'; return v==='multi'?'movie':v; }

// ACTIVE LAYOUT: ogni foto/stile deve comandare il taglio del TMDB.
// La foto nella griglia resta solo riferimento: quando scegli un layout,
// il TMDB prende fonte immagine, posizione, zoom, poster/card in base a quel modello.
let manualTmdbAdjust=false;
function setInputValue(id,val){ const el=document.getElementById(id); if(el) el.value=val; }
function activeLayoutKey(){ return document.getElementById('layoutSelect')?.value || state.layout || 'auto_ads_layout_0'; }

// Preset reali per i 15 ACTIVE LAYOUT: non generico, ogni foto ha un suo taglio.
// bg = quale immagine TMDB usare come sfondo principale: backdrop oppure poster.
const ACTIVE_LAYOUT_TMDB_PRESETS={
  // ACTIVE LAYOUT precisi: ogni foto guida comanda crop, zoom, luce, poster e attori.
  auto_ads_layout_0:{bg:'backdrop',x:48,y:47,z:128,skin:14,guide:0,cast:false,mode:'hero-right',shade:'right-dark'},
  auto_ads_layout_1:{bg:'backdrop',x:61,y:47,z:132,skin:16,guide:0,cast:false,mode:'hero-left',shade:'left-dark'},
  auto_ads_layout_2:{bg:'backdrop',x:55,y:49,z:126,skin:13,guide:0,posterW:150,posterH:225,posterX:79,posterY:50,cast:false,mode:'box-right-poster',shade:'center-card'},
  auto_ads_layout_3:{bg:'backdrop',x:50,y:48,z:126,skin:10,guide:0,posterW:0,posterH:0,cast:false,mode:'clean',shade:'clean'},
  auto_ads_layout_4:{bg:'backdrop',x:50,y:50,z:112,skin:12,guide:0,posterW:0,posterH:0,cast:false,mode:'trailer',shade:'trailer'},
  auto_ads_layout_5:{bg:'backdrop',x:60,y:49,z:132,skin:16,guide:0,posterW:150,posterH:225,posterX:15,posterY:36,cast:true,castStyle:'theme-left bottom-right',mode:'poster-left-cast',shade:'left-card'},
  auto_ads_layout_6:{bg:'backdrop',x:60,y:50,z:130,skin:16,guide:0,posterW:104,posterH:156,posterX:14,posterY:32,cast:true,castStyle:'theme-card bottom-left',mode:'poster-left-cast',shade:'left-card'},
  auto_ads_layout_7:{bg:'poster',x:50,y:50,z:108,skin:18,guide:0,posterW:190,posterH:285,posterX:50,posterY:50,cast:false,mode:'poster-center',shade:'poster'},
  auto_ads_layout_8:{bg:'backdrop',x:48,y:49,z:127,skin:18,guide:0,posterW:0,posterH:0,cast:false,mode:'green-right',shade:'right-green'},
  auto_ads_layout_9:{bg:'backdrop',x:48,y:49,z:128,skin:18,guide:0,posterW:120,posterH:180,posterX:81,posterY:51,cast:false,mode:'green-center-poster',shade:'green-card'},
  auto_ads_layout_10:{bg:'backdrop',x:42,y:49,z:128,skin:10,guide:0,posterW:86,posterH:129,posterX:89,posterY:50,cast:false,mode:'split-right',shade:'split'},
  auto_ads_layout_11:{bg:'backdrop',x:50,y:45,z:122,skin:15,guide:0,posterW:118,posterH:177,posterX:36,posterY:48,cast:false,mode:'glass-center',shade:'glass'},
  auto_ads_layout_12:{bg:'backdrop',x:50,y:49,z:130,skin:18,guide:0,posterW:0,posterH:0,cast:true,castStyle:'theme-green inside-card',mode:'green-cast-right',shade:'right-green'},
  auto_ads_layout_13:{bg:'backdrop',x:49,y:48,z:128,skin:18,guide:0,posterW:0,posterH:0,cast:true,castStyle:'theme-orange bottom-card',mode:'orange-cast-right',shade:'orange'},
  auto_ads_layout_14:{bg:'backdrop',x:50,y:50,z:114,skin:12,guide:0,posterW:125,posterH:188,posterX:20,posterY:50,cast:false,mode:'big-horizontal',shade:'center-card'},
  special_layout_15:{bg:'backdrop',x:48,y:47,z:128,skin:14,guide:0,cast:false,mode:'hero-right',shade:'right-dark'},
  special_layout_16:{bg:'backdrop',x:50,y:50,z:114,skin:12,guide:0,posterW:125,posterH:188,posterX:20,posterY:50,cast:false,mode:'big-horizontal',shade:'center-card'},
  special_layout_17:{bg:'backdrop',x:50,y:45,z:122,skin:15,guide:0,posterW:118,posterH:177,posterX:36,posterY:48,cast:false,mode:'glass-center',shade:'glass'},
  special_layout_18:{bg:'backdrop',x:50,y:48,z:126,skin:10,guide:0,posterW:0,posterH:0,cast:false,mode:'clean',shade:'clean'},
  special_layout_19:{bg:'backdrop',x:61,y:47,z:132,skin:16,guide:0,cast:false,mode:'hero-left',shade:'left-dark'},
  special_layout_20:{bg:'backdrop',x:55,y:49,z:126,skin:13,guide:0,posterW:150,posterH:225,posterX:79,posterY:50,cast:false,mode:'box-right-poster',shade:'center-card'},
  special_layout_21:{bg:'backdrop',x:48,y:49,z:127,skin:18,guide:0,posterW:86,posterH:129,posterX:82,posterY:44,cast:false,mode:'green-right',shade:'right-green'},
  special_layout_22:{bg:'backdrop',x:60,y:49,z:132,skin:16,guide:0,posterW:150,posterH:225,posterX:15,posterY:36,cast:true,castStyle:'theme-left bottom-right',mode:'poster-left-cast',shade:'left-card'},
  special_layout_23:{bg:'backdrop',x:48,y:47,z:128,skin:14,guide:0,posterW:0,posterH:0,cast:false,mode:'hero-right',shade:'right-dark'},
  special_layout_24:{bg:'backdrop',x:49,y:48,z:128,skin:18,guide:0,posterW:0,posterH:0,cast:true,castStyle:'theme-orange bottom-card',mode:'orange-cast-right',shade:'orange'}
};


// === FIX REALE GENNY 2026-05-18 ===
// Ogni ACTIVE LAYOUT usa la sua foto come modello preciso:
// - il TMDB prende crop/zoom/posizione del modello
// - gli attori appaiono SOLO nei layout che nella foto hanno i cerchi/cast
// - gli attori prendono colore/posizione dal tema, non restano generici sopra la foto
Object.assign(ACTIVE_LAYOUT_TMDB_PRESETS, {
  auto_ads_layout_0:{bg:'backdrop',x:42,y:50,z:135,skin:0,guide:0,cast:false,mode:'lay0-title-right',shade:'soft-right'},
  auto_ads_layout_1:{bg:'backdrop',x:58,y:50,z:137,skin:0,guide:0,cast:false,mode:'lay1-title-left',shade:'soft-left'},
  auto_ads_layout_2:{bg:'backdrop',x:58,y:50,z:135,skin:0,guide:0,posterW:142,posterH:213,posterX:78,posterY:50,cast:false,mode:'lay2-center-glass-poster',shade:'center-glass'},
  auto_ads_layout_3:{bg:'backdrop',x:56,y:50,z:126,skin:0,guide:0,cast:false,mode:'lay3-clean-hero',shade:'none'},
  auto_ads_layout_4:{bg:'backdrop',x:50,y:50,z:112,skin:0,guide:0,cast:false,mode:'lay4-youtube-trailer',shade:'trailer-dark'},
  auto_ads_layout_5:{bg:'backdrop',x:60,y:50,z:136,skin:0,guide:0,posterW:132,posterH:198,posterX:18,posterY:24,cast:true,castCount:3,castStyle:'cast-under-poster theme-gold',mode:'lay5-poster-left',shade:'soft-left'},
  auto_ads_layout_6:{bg:'backdrop',x:46,y:50,z:125,skin:0,guide:0,posterW:96,posterH:144,posterX:12,posterY:31,cast:true,castCount:3,castStyle:'cast-under-poster-small theme-gold',mode:'lay6-small-card-left',shade:'warm-clean'},
  auto_ads_layout_7:{bg:'poster',x:50,y:50,z:116,skin:0,guide:0,posterW:210,posterH:315,posterX:50,posterY:52,cast:false,mode:'lay7-poster-premium',shade:'poster-dim'},
  auto_ads_layout_8:{bg:'backdrop',x:56,y:50,z:130,skin:0,guide:0,cast:false,mode:'lay8-green-card-right',shade:'green-right'},
  auto_ads_layout_9:{bg:'backdrop',x:55,y:50,z:132,skin:0,guide:0,posterW:112,posterH:168,posterX:77,posterY:52,cast:false,mode:'lay9-green-center',shade:'green-center'},
  auto_ads_layout_10:{bg:'backdrop',x:47,y:50,z:134,skin:0,guide:0,posterW:84,posterH:126,posterX:88,posterY:47,cast:false,mode:'lay10-split-black',shade:'split-black'},
  auto_ads_layout_11:{bg:'backdrop',x:50,y:50,z:145,skin:0,guide:0,posterW:110,posterH:165,posterX:36,posterY:49,cast:false,mode:'lay11-glass-box',shade:'blue-glass'},
  auto_ads_layout_12:{bg:'backdrop',x:56,y:50,z:132,skin:0,guide:0,cast:true,castCount:3,castStyle:'cast-inside-green theme-green',mode:'lay12-green-cast-card',shade:'green-right'},
  auto_ads_layout_13:{bg:'backdrop',x:42,y:50,z:135,skin:0,guide:0,cast:true,castCount:3,castStyle:'cast-bottom-orange theme-orange',mode:'lay13-orange-cast-card',shade:'soft-right'},
  auto_ads_layout_14:{bg:'backdrop',x:50,y:50,z:122,skin:0,guide:0,posterW:136,posterH:204,posterX:25,posterY:50,cast:false,mode:'lay14-wide-glass',shade:'wide-blur'},
  special_layout_15:{bg:'backdrop',x:42,y:50,z:135,skin:0,guide:0,cast:false,mode:'lay0-title-right',shade:'soft-right'},
  special_layout_16:{bg:'backdrop',x:50,y:50,z:122,skin:0,guide:0,posterW:136,posterH:204,posterX:25,posterY:50,cast:false,mode:'lay14-wide-glass',shade:'wide-blur'},
  special_layout_17:{bg:'backdrop',x:50,y:50,z:145,skin:0,guide:0,posterW:110,posterH:165,posterX:36,posterY:49,cast:false,mode:'lay11-glass-box',shade:'blue-glass'},
  special_layout_18:{bg:'backdrop',x:56,y:50,z:126,skin:0,guide:0,cast:false,mode:'lay3-clean-hero',shade:'none'},
  special_layout_19:{bg:'backdrop',x:58,y:50,z:137,skin:0,guide:0,cast:false,mode:'lay1-title-left',shade:'soft-left'},
  special_layout_20:{bg:'backdrop',x:58,y:50,z:135,skin:0,guide:0,posterW:142,posterH:213,posterX:78,posterY:50,cast:false,mode:'lay2-center-glass-poster',shade:'center-glass'},
  special_layout_21:{bg:'backdrop',x:56,y:50,z:130,skin:0,guide:0,posterW:88,posterH:132,posterX:76,posterY:50,cast:false,mode:'lay8-green-card-right',shade:'green-right'},
  special_layout_22:{bg:'backdrop',x:60,y:50,z:136,skin:0,guide:0,posterW:132,posterH:198,posterX:18,posterY:24,cast:true,castCount:3,castStyle:'cast-under-poster theme-gold',mode:'lay5-poster-left',shade:'soft-left'},
  special_layout_23:{bg:'backdrop',x:42,y:50,z:135,skin:0,guide:0,cast:false,mode:'lay0-title-right',shade:'soft-right'},
  special_layout_24:{bg:'backdrop',x:42,y:50,z:135,skin:0,guide:0,cast:true,castCount:3,castStyle:'cast-bottom-orange theme-orange',mode:'lay13-orange-cast-card',shade:'soft-right'}
});

function activeLayoutPreset(){
  return ACTIVE_LAYOUT_TMDB_PRESETS[activeLayoutKey()] || {bg:'backdrop',x:50,y:50,z:125,guide:0,posterW:135,posterH:203,posterX:27,posterY:55};
}
function activeBackgroundUrl(){
  const p=activeLayoutPreset();
  // Alcuni stili delle foto sono poster/montaggio: lì il TMDB deve usare il poster come immagine principale.
  if(p.bg==='poster' && state.poster) return state.poster;
  return state.backdrop || state.poster || '';
}
function paintActiveBackground(){
  const url=activeBackgroundUrl();
  const bd=document.getElementById('backdrop');
  const pv=document.getElementById('preview');
  if(bd && url){
    const cssUrl=`url('${String(url).replace(/'/g,"%27")}')`;
    bd.style.backgroundImage=cssUrl;
    if(pv) pv.style.setProperty('--activeBg',cssUrl);
  }
}
function resetTmdbToLayoutReference(force=false){
  if(force || !manualTmdbAdjust){
    const p=activeLayoutPreset();
    setInputValue('tmdbX',p.x);
    setInputValue('tmdbY',p.y);
    setInputValue('tmdbZoom',p.z);
    setInputValue('guideOpacity',p.guide);
    setInputValue('layoutSkinOpacity',p.skin||0);
    if('posterW' in p) setInputValue('posterW',p.posterW||0);
    if('posterH' in p) setInputValue('posterH',p.posterH||0);
    if('posterX' in p) setInputValue('posterX',p.posterX||50);
    if('posterY' in p) setInputValue('posterY',p.posterY||50);
  }
}
function applyLayoutImagePreset(force=false){ resetTmdbToLayoutReference(force); paintActiveBackground(); }
function ensureActorStrip(){
  let strip=document.getElementById('actorStrip');
  if(!strip){
    strip=document.createElement('div');
    strip.id='actorStrip';
    strip.className='actor-strip';
    document.getElementById('preview').appendChild(strip);
  }
  return strip;
}
function renderCast(){
  const p=activeLayoutPreset();
  const strip=ensureActorStrip();
  strip.className='actor-strip '+(p.castStyle||'');
  const max=p.castCount||3;
  const cast=(state.cast||[]).filter(a=>a && a.profile).slice(0,max);
  if(!p.cast || !cast.length){ strip.innerML=''; strip.style.display='none'; return; }
  strip.style.display='flex';
  strip.dataset.layout=activeLayoutKey();
  strip.innerML=cast.map((a,i)=>`<div class="actor actor-${i+1}"><img src="${a.profile}" alt="${a.name}"><span>${a.name}</span></div>`).join('');
}

function refresh(){
  applyLayoutImagePreset(false);
  $('#pvTitle').textContent=$('#title').value||'Titolo'; $('#pvYear').textContent=$('#year').value||''; $('#pvOverview').textContent=$('#overview').value||'';
  state.title=$('#title').value; state.year=$('#year').value; state.overview=$('#overview').value;
  setVar('--neon',$('#cNeon').value); setVar('--title',$('#cTitle').value); setVar('--year',$('#cYear').value); setVar('--desc',$('#cDesc').value); setVar('--brightness',$('#brightness').value+'%');
  setVar('--tmdbX',(document.getElementById('tmdbX')?.value||50)+'%');
  setVar('--tmdbY',(document.getElementById('tmdbY')?.value||50)+'%');
  setVar('--tmdbZoom',(document.getElementById('tmdbZoom')?.value||100)+'%');
  setVar('--guideOpacity',(document.getElementById('guideOpacity')?.value||0));
  setVar('--layoutSkinOpacity',(document.getElementById('layoutSkinOpacity')?.value||activeLayoutPreset().skin||0));
  setVar('--posterW',$('#posterW').value+'px'); setVar('--posterH',$('#posterH').value+'px'); setVar('--posterX',$('#posterX').value+'%'); setVar('--posterY',$('#posterY').value+'%'); setVar('--logoW',$('#logoW').value+'px'); setVar('--cardW',$('#cardW').value+'%'); setVar('--cardH',$('#cardH').value+'vh'); setVar('--glow',$('#glow').value+'px');
  const p=$('#preview'); const ap=activeLayoutPreset();
  p.className='preview '+$('#layoutSelect').value+' mode-'+(ap.mode||'standard')+' shade-'+(ap.shade||'standard')+((ap.cast && (state.cast||[]).some(a=>a&&a.profile))?' has-cast':'')+(($('#posterStripes')&&$('#posterStripes').checked)?' stripes-on':'');
  state.layout=$('#layoutSelect').value;
  paintActiveBackground();
  updateLayoutGuide();
  renderCast();
}


function applyMedia(d,type){
  if(!d) return;
  state.tmdb=d;
  const title=d.title||d.name||'Titolo'; const year=(d.release_date||d.first_air_date||d.year||'').slice(0,4); const overview=d.overview||'Trama non disponibile su TMDB per questo contenuto.';
  $('#title').value=title; $('#year').value=year; $('#overview').value=overview;
  const posterPath=d.poster_path||''; const backdropPath=d.backdrop_path||'';
  if(posterPath){ state.poster=posterPath.startsWith('http')?posterPath:imgBase+posterPath; $('#poster').src=state.poster; updateStripes(state.poster); }
  if(backdropPath){ state.backdrop=backdropPath.startsWith('http')?backdropPath:imgBase+backdropPath; $('#backdrop').style.backgroundImage=`url('${state.backdrop}')`; }
  const logo=(d.images?.logos||[]).find(x=>x.iso_639_1==='it')||(d.images?.logos||[]).find(x=>x.iso_639_1==='en')||(d.images?.logos||[])[0];
  if(logo?.file_path){ state.logo=imgBase+logo.file_path; $('#logo').src=state.logo; $('#logo').style.display='block'; }
  else { $('#logo').style.display=state.logo?'block':'none'; }
  state.cast=(d.credits?.cast||[]).filter(a=>a.profile_path).slice(0,6).map(a=>({name:a.name||'',character:a.character||'',profile:imgBase+a.profile_path}));
  const rating=d.vote_average?Number(d.vote_average).toFixed(1):''; const star=$('.stars'); if(star) star.textContent=rating?'★★★★★ '+rating+'/10':'★★★★★';
  refresh();
}
function updateStripes(posterUrl){
  $$('#miniStack div').forEach((el,i)=>{ if(posterUrl){ el.style.backgroundImage=`linear-gradient(90deg,rgba(0,0,0,.15),rgba(255,255,255,.18)), url('${posterUrl}')`; el.style.backgroundPosition=`${35+i*15}% center`; } else { el.style.backgroundImage='none'; }});
}
function loadLayouts(){ fetch('api.php?action=layouts').then(r=>r.json()).then(j=>{let s=$('#layoutSelect'); s.innerML=''; Object.entries(j.layouts).forEach(([k,v],i)=>{let o=document.createElement('option'); o.value=k; o.textContent=(i+1).toString().padStart(2,'0')+' - '+v.name; s.appendChild(o)}); let g=$('#layoutGrid'); if(g){g.innerML=''; Object.entries(j.layouts).forEach(([k,v],i)=>{let b=document.createElement('button'); b.type='button'; b.className='layout-tile'; b.dataset.layout=k; b.innerML=(v.preview?'<img src="'+v.preview+'" alt="'+v.name+'">':'')+'<b>'+String(i+1).padStart(2,'0')+'</b><span>'+v.name+'</span>'; b.onclick=()=>{s.value=k; manualTmdbAdjust=false; resetTmdbToLayoutReference(true); refresh(); updateLayoutGuide();}; g.appendChild(b);});} s.onchange=()=>{manualTmdbAdjust=false; resetTmdbToLayoutReference(true); refresh(); updateLayoutGuide();}; resetTmdbToLayoutReference(true); refresh(); updateLayoutGuide();});}
function loadAutoFeed(){
  if(!$('#autoTmdb')?.checked){ setStatus('AUTO TMDB spento. Attivalo se vuoi cambio automatico.'); return; }
  setStatus('Caricamento automatico TMDB...');
  fetch('api.php?action=auto_feed&type='+encodeURIComponent(currentType())+'&source='+encodeURIComponent(sourceMode())+'&page='+state.autoPage)
    .then(r=>r.json()).then(j=>{
      if(!j.ok){ setStatus('AUTO TMDB errore: '+(j.error||'controlla API KEY')); return; }
      state.autoItems=j.items||[]; state.autoIndex=0;
      if(!state.autoItems.length){ setStatus('AUTO TMDB: nessun contenuto trovato.'); return; }
      setStatus('AUTO TMDB attivo: immagini cambiano da sole.');
      playAutoItem(true); startAutoRotation();
    }).catch(()=>setStatus('AUTO TMDB: errore connessione. Controlla API KEY o server.'));
}
function playAutoItem(instant=false){
  if(!state.autoItems.length) return;
  const item=state.autoItems[state.autoIndex % state.autoItems.length]; state.autoIndex++;
  applyMedia(item,item.type||currentType());
  // Carica dettagli completi e logo in automatico, senza cercare manualmente.
  if(item.id){ fetch('api.php?action=details&type='+(item.type||currentType())+'&id='+item.id).then(r=>r.json()).then(j=>{ if(j.ok&&j.data) applyMedia(j.data,item.type||currentType()); }); }
  if(state.autoIndex>=state.autoItems.length){ state.autoPage=state.autoPage>=10?1:state.autoPage+1; }
}
function startAutoRotation(){ clearInterval(state.autoTimer); state.autoTimer=setInterval(()=>{ if($('#autoTmdb')?.checked) playAutoItem(); }, rotationMs()); }
$$('input,select,textarea').forEach(el=>el.addEventListener('input',()=>{ if(['tmdbX','tmdbY','tmdbZoom'].includes(el.id)) manualTmdbAdjust=true; refresh(); if(['mediaType','source'].includes(el.id)){state.autoPage=1; loadAutoFeed();} if(el.id==='rotation') startAutoRotation();}));
$$('.tab').forEach(b=>b.onclick=()=>{$$('.tab,.tabpane').forEach(x=>x.classList.remove('active')); b.classList.add('active'); $('#'+b.dataset.tab).classList.add('active');});
$('#searchBtn').onclick=()=>{let q=$('#searchQ').value.trim(); if(!q) return; fetch('api.php?action=search&type='+$('#mediaType').value+'&q='+encodeURIComponent(q)).then(r=>r.json()).then(j=>{let box=$('#results'); box.innerML=''; (j.data?.results||[]).slice(0,20).forEach(it=>{let d=document.createElement('div'); d.className='result'; let type=it.media_type||$('#mediaType').value; if(type==='multi') type=it.title?'movie':'tv'; d.textContent=(it.title||it.name)+' '+((it.release_date||it.first_air_date||'').slice(0,4)); d.onclick=()=>selectTmdb(type,it.id); box.appendChild(d)});});};
function selectTmdb(type,id){ fetch('api.php?action=details&type='+type+'&id='+id).then(r=>r.json()).then(j=>{if(j.ok) applyMedia(j.data,type);});}
$('#uploadForm').onsubmit=e=>{e.preventDefault(); let fd=new FormData(e.target); fd.append('action','upload_assets'); fetch('api.php',{method:'POST',body:fd}).then(r=>r.json()).then(j=>{if(j.poster){state.poster=j.poster; $('#poster').src=j.poster; updateStripes(j.poster)} if(j.backdrop){state.backdrop=j.backdrop; $('#backdrop').style.backgroundImage=`url('${j.backdrop}')`} if(j.logo){state.logo=j.logo; $('#logo').src=j.logo; $('#logo').style.display='block'} refresh(); alert('Immagini caricate');});};
$('#applyCss').onclick=()=>{let id='liveCustomCss'; let st=document.getElementById(id)||document.createElement('style'); st.id=id; st.textContent=$('#cssEditor').value; document.head.appendChild(st);};
function buildProject(){refresh(); return {title:state.title,year:state.year,overview:state.overview,layout:state.layout,poster:state.poster,backdrop:state.backdrop,logo:state.logo,cast:state.cast,settings:{neon:$('#cNeon').value,titleColor:$('#cTitle').value,yearColor:$('#cYear').value,descColor:$('#cDesc').value,brightness:$('#brightness').value,tmdbX:$('#tmdbX')?.value||50,tmdbY:$('#tmdbY')?.value||50,tmdbZoom:$('#tmdbZoom')?.value||100,guideOpacity:$('#guideOpacity')?.value||0,layoutSkinOpacity:$('#layoutSkinOpacity')?.value||activeLayoutPreset().skin||0,posterW:$('#posterW').value,posterH:$('#posterH').value,posterX:$('#posterX').value,posterY:$('#posterY').value,logoW:$('#logoW').value,cardW:$('#cardW').value,cardH:$('#cardH').value,glow:$('#glow').value,rotation:$('#rotation').value,autoTmdb:$('#autoTmdb')?.checked||false,posterStripes:$('#posterStripes')?.checked||false},tmdb:state.tmdb,developer:' FATO CON IL ❤️'};}
$('#exportJson').onclick=()=>{$('#exportBox').textContent=JSON.stringify(buildProject(),null,2);};
$('#saveProject').onclick=()=>{let fd=new FormData(); fd.append('action','save_project'); fd.append('csrf',csrf); fd.append('project',JSON.stringify(buildProject())); fetch('api.php',{method:'POST',body:fd}).then(r=>r.json()).then(j=>{if(j.ok){lastDownload=j.download; $('#exportBox').textContent='Salvato: '+j.file+'\n'+j.download;}else alert(j.error);});};
$('#downloadZip').onclick=()=>{ if(lastDownload) location.href=lastDownload; else alert('Prima salva il progetto'); };
$('#saveSettings').onclick=()=>{localStorage.setItem('genny_tmdb_panel_settings',JSON.stringify(buildProject().settings)); alert('Impostazioni salvate nel browser');};
$('#autoTmdb')?.addEventListener('change',()=>{refresh(); if($('#autoTmdb').checked) loadAutoFeed(); else {clearInterval(state.autoTimer); setStatus('AUTO TMDB spento.');}});
$('#posterStripes')?.addEventListener('change',refresh);
$('#cssEditor').value=`.info-card{\n  border-radius:18px;\n}\n.text h1{\n  letter-spacing:1px;\n}\n.poster{\n  transform:perspective(700px) rotateY(12deg);\n}`;
loadLayouts(); refresh(); loadAutoFeed();
