const BASE=(document.body.dataset.base||'/nueva').replace(/\/$/,'');
const STREAM=document.body.dataset.stream;
const radio=new Audio(STREAM);
radio.preload='none';
let currentTrack=null;
let currentTrackButton=null;
let currentAlbum=null;
let currentTrackIndex=-1;

const playBtn=document.querySelector('#radioPlay');
const panelPlay=document.querySelector('#radioPanelPlay');
const status=document.querySelector('#radioStatus');
const wave=document.querySelector('.wave');
const radioPanel=document.querySelector('#radioPanel');
function setRadioUI(on,text){
  [playBtn,panelPlay].forEach(b=>{if(b)b.textContent=on?'❚❚':'▶'});
  if(status)status.textContent=text||(on?'EN VIVO':'PAUSADO');
  if(wave)wave.classList.toggle('active',on);
  if(radioPanel)radioPanel.classList.toggle('playing',on);
}
function stopTrack(){
  if(currentTrack){currentTrack.pause();currentTrack.currentTime=0;currentTrack=null;}
  if(currentTrackButton)currentTrackButton.textContent='▶';
  currentTrackButton=null;
  currentTrackIndex=-1;
  document.querySelectorAll('.tracks tr').forEach(r=>r.classList.remove('active'));
  updateProgress(0,0);
}
async function toggleRadio(){
  if(!radio.paused){radio.pause();setRadioUI(false,'PAUSADO');return;}
  stopTrack();
  try{if(status)status.textContent='CONECTANDO…';radio.src=STREAM;await radio.play();setRadioUI(true,'EN VIVO');}
  catch(e){setRadioUI(false,'NO DISPONIBLE');}
}
[playBtn,panelPlay].forEach(b=>b&&b.addEventListener('click',toggleRadio));
radio.addEventListener('error',()=>setRadioUI(false,'NO DISPONIBLE'));
radio.addEventListener('pause',()=>{if(radio.currentTime!==0)setRadioUI(false,'PAUSADO')});

async function loadJson(path){const r=await fetch(`${BASE}/${path}`);if(!r.ok)throw new Error(`No se pudo cargar ${path}`);return r.json();}

let galleries=[];
let gallery=[];
let gIndex=0;
const box=document.querySelector('#lightbox');
const boxImg=box?.querySelector('img');
function showGallery(images,i=0){if(!images?.length||!box||!boxImg)return;gallery=images.map(x=>`${BASE}/${x}`);gIndex=i;boxImg.src=gallery[gIndex];box.classList.add('open');box.setAttribute('aria-hidden','false');}
function shiftGallery(n){if(!gallery.length||!boxImg)return;gIndex=(gIndex+n+gallery.length)%gallery.length;boxImg.src=gallery[gIndex];}
function closeGallery(){box?.classList.remove('open');box?.setAttribute('aria-hidden','true');}
document.querySelector('#lightboxClose')?.addEventListener('click',closeGallery);
document.querySelector('#lightboxPrev')?.addEventListener('click',()=>shiftGallery(-1));
document.querySelector('#lightboxNext')?.addEventListener('click',()=>shiftGallery(1));
box?.addEventListener('click',e=>{if(e.target===box)closeGallery();});
document.addEventListener('keydown',e=>{if(e.key==='Escape')closeGallery();if(box?.classList.contains('open')&&e.key==='ArrowLeft')shiftGallery(-1);if(box?.classList.contains('open')&&e.key==='ArrowRight')shiftGallery(1);});

const bioRail=document.querySelector('#bioRail');
loadJson('data/galleries.json').then(items=>{
  galleries=items;
  items.forEach(g=>{
    const el=document.querySelector(`[data-gallery="${g.id}"]`);
    if(el){el.style.backgroundImage=`url(${BASE}/${g.cover})`;el.addEventListener('click',()=>showGallery(g.images));}
  });
  if(bioRail){
    const railItems=items.flatMap(g=>g.images.slice(0,1).map((img,i)=>({g,img,i}))).slice(0,6);
    bioRail.innerHTML=railItems.map(({g,img,i})=>`<button type="button" class="bio-rail-item" style="background-image:url(${BASE}/${img})" data-gallery-id="${g.id}" data-image-index="${i}"><span class="bio-rail-label">${g.title}</span></button>`).join('');
    bioRail.querySelectorAll('.bio-rail-item').forEach(btn=>btn.addEventListener('click',()=>{const g=items.find(x=>x.id===btn.dataset.galleryId);if(g)showGallery(g.images,+btn.dataset.imageIndex||0);}));
  }
}).catch(()=>{});
document.querySelector('.bio-rail-prev')?.addEventListener('click',()=>bioRail?.scrollBy({left:-bioRail.clientWidth*.72,behavior:'smooth'}));
document.querySelector('.bio-rail-next')?.addEventListener('click',()=>bioRail?.scrollBy({left:bioRail.clientWidth*.72,behavior:'smooth'}));
const bioToggle=document.querySelector('#bioToggle');
const bioStory=document.querySelector('#bioStory');
bioToggle?.addEventListener('click',()=>{const opening=bioStory.hasAttribute('hidden');if(opening){bioStory.removeAttribute('hidden');bioToggle.textContent='Cerrar biografía ↑';bioStory.scrollIntoView({behavior:'smooth',block:'start'});}else{bioStory.setAttribute('hidden','');bioToggle.textContent='Leer biografía →';}bioToggle.setAttribute('aria-expanded',opening?'true':'false');});

const albumsEl=document.querySelector('#albums');
const panel=document.querySelector('#albumPanel');
let albums=[];
const fmt=s=>{if(!Number.isFinite(s)||s<0)return'0:00';const m=Math.floor(s/60);return`${m}:${String(Math.floor(s%60)).padStart(2,'0')}`;};
function updateProgress(current=0,duration=0){const seek=document.querySelector('#trackSeek'),elapsed=document.querySelector('#trackElapsed'),total=document.querySelector('#trackDuration');if(seek){seek.max=String(duration||0);seek.value=String(current||0)}if(elapsed)elapsed.textContent=fmt(current);if(total)total.textContent=fmt(duration);}
async function playTrack(index,button){
  if(!currentAlbum||!currentAlbum.tracks[index])return;
  radio.pause();setRadioUI(false,'PAUSADO');
  if(currentTrack&&currentTrackIndex===index&&!currentTrack.paused){currentTrack.pause();button.textContent='▶';return;}
  stopTrack();currentTrackIndex=index;currentTrackButton=button;currentTrack=new Audio(`${BASE}/${currentAlbum.tracks[index].file}`);currentTrack.preload='metadata';
  const row=button.closest('tr');row?.classList.add('active');
  currentTrack.addEventListener('loadedmetadata',()=>updateProgress(currentTrack.currentTime,currentTrack.duration));
  currentTrack.addEventListener('timeupdate',()=>updateProgress(currentTrack.currentTime,currentTrack.duration));
  currentTrack.addEventListener('ended',()=>{button.textContent='▶';if(index<currentAlbum.tracks.length-1){const next=document.querySelector(`.track-play[data-index="${index+1}"]`);if(next)playTrack(index+1,next);}else stopTrack();});
  try{await currentTrack.play();button.textContent='❚❚';}catch(e){button.textContent='!';}
}
function renderAlbum(a){
  if(!panel)return;currentAlbum=a;stopTrack();
  panel.innerHTML=`<div class="album-panel-top"><div class="album-cover-wrap"><img src="${BASE}/${a.cover}" alt="${a.title}"><div class="album-actions"><button id="playAll" class="btn gold" type="button">▶ Reproducir todo</button><button class="btn" type="button" disabled aria-disabled="true">Descargar disco ↓</button></div></div><div class="album-meta"><span class="label">Tavo Lamas y su Trompeta</span><h3>${a.title}</h3><p>${a.description||'Una selección musical interpretada con la elegancia y el buen sonido que siempre lo caracterizaron.'}</p><table class="tracks"><tbody>${a.tracks.map((t,i)=>`<tr><td>${String(t.number).padStart(2,'0')}</td><td>${t.title}</td><td>${t.duration||'--:--'}</td><td><button class="track-play" type="button" data-index="${i}" aria-label="Reproducir ${t.title}">▶</button></td></tr>`).join('')}</tbody></table></div></div><div class="album-progress"><span id="trackElapsed">0:00</span><input id="trackSeek" type="range" min="0" max="0" value="0" step="1" aria-label="Posición de reproducción"><span id="trackDuration">0:00</span></div>`;
  panel.hidden=false;
  panel.querySelectorAll('.track-play').forEach(btn=>btn.addEventListener('click',()=>playTrack(+btn.dataset.index,btn)));
  panel.querySelector('#playAll')?.addEventListener('click',()=>{const first=panel.querySelector('.track-play[data-index="0"]');if(first)playTrack(0,first);});
  panel.querySelector('#trackSeek')?.addEventListener('input',e=>{if(currentTrack)currentTrack.currentTime=+e.target.value;});
}
if(albumsEl){loadJson('data/albums.json').then(data=>{albums=data;albumsEl.innerHTML=data.map((a,i)=>`<button class="album-card${i===0?' active':''}" type="button" data-i="${i}"><img src="${BASE}/${a.cover}" alt="${a.title}"><strong>${a.title}</strong><small>Escuchar →</small></button>`).join('');albumsEl.querySelectorAll('.album-card').forEach(b=>b.addEventListener('click',()=>{albumsEl.querySelectorAll('.album-card').forEach(x=>x.classList.remove('active'));b.classList.add('active');renderAlbum(albums[+b.dataset.i]);}));if(albums[0])renderAlbum(albums[0]);}).catch(()=>{});}

const carousel=document.querySelector('#memoryCarousel');
const memPrev=document.querySelector('#memPrev');
const memNext=document.querySelector('#memNext');
function visibleMemoryCards(){
  if(window.innerWidth<=560)return 1;
  if(window.innerWidth<=900)return 2;
  return 3;
}
function memoryStep(){
  const card=carousel?.querySelector('.memory-card');
  if(!card)return 0;
  const styles=getComputedStyle(carousel);
  const gap=parseFloat(styles.columnGap||styles.gap||'0')||0;
  return card.getBoundingClientRect().width+gap;
}
function syncMemoryCarousel(){
  if(!carousel)return;
  const count=carousel.querySelectorAll('.memory-card').length;
  const visible=visibleMemoryCards();
  carousel.classList.toggle('is-centered',count<visible);
  const hideArrows=count<=visible;
  if(memPrev)memPrev.hidden=hideArrows;
  if(memNext)memNext.hidden=hideArrows;
}
memPrev?.addEventListener('click',()=>carousel?.scrollBy({left:-memoryStep(),behavior:'smooth'}));
memNext?.addEventListener('click',()=>carousel?.scrollBy({left:memoryStep(),behavior:'smooth'}));
window.addEventListener('resize',syncMemoryCarousel);
syncMemoryCarousel();

document.querySelectorAll('.upload-control input').forEach(input=>input.addEventListener('change',()=>{const label=input.closest('.upload-control')?.querySelector('span');if(label&&input.files?.[0])label.textContent=`✓ ${input.files[0].name}`;}));
const form=document.querySelector('#memoryForm');
if(form)form.addEventListener('submit',async e=>{e.preventDefault();const btn=form.querySelector('button[type=submit]'),notice=document.querySelector('#formNotice');btn.disabled=true;btn.textContent='ENVIANDO…';try{const r=await fetch(form.action,{method:'POST',body:new FormData(form),headers:{Accept:'application/json'}});const data=await r.json();if(!r.ok)throw new Error(data.message||'No fue posible enviar el recuerdo.');notice.textContent=data.message;notice.hidden=false;form.reset();document.querySelectorAll('.upload-control span').forEach((s,i)=>s.textContent=i===0?'＋ Avatar':'＋ Foto del recuerdo');}catch(err){notice.textContent=err.message;notice.hidden=false;}finally{btn.disabled=false;btn.textContent='ENVIAR RECUERDO';}});
