const qs = id => document.getElementById(id);
const params = new URLSearchParams(location.search), src = params.get('src'), searching=params.get('search')==='1', pageTitle = params.get('title') || 'Video', postImage=params.get('image')||'', postUrl=params.get('post')||'',contextId=params.get('context')||'',attemptId=params.get('attempt')||'';
const video = qs('video'), stage = qs('stage'), seek = qs('seek'), message = qs('message');
let hls = null, hideTimer, resumeChecked=false,seriesContext=null,sourceFailureReported=false,playbackConfirmed=false,retryData=null;

const playSessionId=crypto.randomUUID();let playStartReported=false;
function sourceHost(){try{return new URL(src||'').hostname;}catch{return '';}}
function refreshDownloadButton(){const button=qs('downloadVideo');const direct=Boolean(src&&/^https?:/i.test(src)&&!/\.m3u8(?:[?#]|$)/i.test(src)&&!/\.mpd(?:[?#]|$)/i.test(src));button.hidden=!direct;button.disabled=!direct;button.title=direct?'Descargar este archivo a tu PC':'Esta fuente usa transmisión por segmentos y no admite descarga directa.';}
refreshDownloadButton();
qs('downloadVideo').onclick=async()=>{if(!src)return;const button=qs('downloadVideo'),label=button.textContent;button.disabled=true;button.textContent='Preparando…';const response=await chrome.runtime.sendMessage({type:'DOWNLOAD_DIRECT_MEDIA',url:src,title:pageTitle,image:postImage,postUrl:postUrl||src}).catch(()=>null);button.disabled=false;button.textContent=response?.ok?'✓ Descargando':label;if(!response?.ok)fail(response?.error||'Esta fuente no permite descarga directa.');setTimeout(()=>{button.textContent=label;refreshDownloadButton();},2200);};
video.addEventListener('playing',()=>{if(playStartReported)return;playStartReported=true;const episode=seriesContext?.episodes?.[seriesContext.currentIndex||0];chrome.runtime.sendMessage({type:'REPORT_PLAY_START',payload:{play_id:playSessionId,content_url:postUrl||src,title:pageTitle,season:episode?.season||null,episode:episode?.episode||null,source_host:sourceHost()}}).catch(()=>{});});
qs('title').textContent = pageTitle; document.title = `${pageTitle} · HIRO PLAY`;

const format = value => { if (!Number.isFinite(value)) return '0:00'; const h=Math.floor(value/3600),m=Math.floor(value%3600/60),s=Math.floor(value%60); return `${h?`${h}:`:''}${h?String(m).padStart(2,'0'):m}:${String(s).padStart(2,'0')}`; };
function fail(text){message.textContent=attemptId?'Probando otra opción disponible…':text;message.style.display='block';stage.classList.remove('loading');if(attemptId&&!sourceFailureReported){sourceFailureReported=true;chrome.runtime.sendMessage({type:'SMART_SOURCE_FAILED',attemptTabId:attemptId}).catch(()=>{});}}
function toggle(){video.paused?video.play().catch(()=>{}):video.pause();}
function update(){const duration=video.duration||0,p=duration?video.currentTime/duration*100:0;seek.value=p*10;qs('progress').style.width=`${p}%`;qs('time').textContent=`${format(video.currentTime)} / ${format(duration)}`;qs('play').textContent=video.paused?'▶':'❚❚';stage.classList.toggle('paused',video.paused);stage.classList.toggle('playing',!video.paused);}
function tracks(){const box=qs('subtitles');[...video.textTracks].forEach((track,i)=>{const o=document.createElement('option');o.value=i;o.textContent=track.label||track.language||`CC ${i+1}`;box.append(o);});}
function qualities(){if(!hls)return;const box=qs('quality');box.innerHTML='<option value="-1">Auto</option>';hls.levels.forEach((level,i)=>{const o=document.createElement('option');o.value=i;o.textContent=level.height?`${level.height}p`:`Nivel ${i+1}`;box.append(o);});}

if(searching&&!src){stage.classList.add('loading');message.textContent='Buscando un reproductor disponible…';message.style.display='block';}
else if(!src||!/^https?:/i.test(src)) fail('Esta fuente no puede abrirse fuera de la página original.');
else if(/\.m3u8(?:[?#]|$)/i.test(src)){
 if(window.Hls?.isSupported()){hls=new Hls({enableWorker:false,lowLatencyMode:true});hls.loadSource(src);hls.attachMedia(video);hls.on(Hls.Events.MANIFEST_PARSED,()=>{qualities();video.play().catch(()=>{});});hls.on(Hls.Events.ERROR,(_,d)=>{if(d.fatal)fail('No se pudo abrir la transmisión. Puede requerir autorización del sitio original.');});}
 else if(video.canPlayType('application/vnd.apple.mpegurl'))video.src=src;else fail('Este navegador no admite esta transmisión HLS.');
}else video.src=src;

video.addEventListener('error',()=>fail('No se pudo reproducir esta fuente. Puede haber caducado o requerir autorización.'));
chrome.runtime.onMessage.addListener(messageData=>{if(messageData.type==='SMART_PLAYER_FAILED'){retryData=messageData.retry||null;message.textContent=messageData.text||'No encontramos un reproductor disponible que funcione en este momento.';message.style.display='block';stage.classList.remove('loading');qs('retrySource').hidden=!retryData;}if(messageData.type==='HIRO_ACCOUNT_DELETED'){video.pause();message.textContent='Su usuario fue eliminado. Abre HIRO PLAY para obtener ayuda.';message.style.display='block';stage.classList.remove('loading');}});
video.addEventListener('waiting',()=>stage.classList.add('loading'));video.addEventListener('playing',()=>{stage.classList.remove('loading');if(attemptId&&!playbackConfirmed){playbackConfirmed=true;chrome.runtime.sendMessage({type:'SMART_PLAYBACK_CONFIRMED',attemptTabId:attemptId,mediaUrl:src}).catch(()=>{});}});
['timeupdate','durationchange','play','pause','volumechange'].forEach(e=>video.addEventListener(e,update));
video.addEventListener('progress',()=>{if(video.buffered.length&&video.duration)qs('buffered').style.width=`${video.buffered.end(video.buffered.length-1)/video.duration*100}%`;});
video.addEventListener('loadedmetadata',async()=>{update();tracks();if(resumeChecked)return;resumeChecked=true;const{watchHistory=[]}=await chrome.storage.local.get({watchHistory:[]});const previous=watchHistory.find(x=>x.url===src);if(previous?.currentTime>10&&previous.currentTime<(video.duration||Infinity)-10){video.pause();qs('resumeText').textContent=`Te quedaste en ${format(previous.currentTime)}.`;qs('resumeModal').classList.add('open');qs('resumeYes').onclick=()=>{video.currentTime=previous.currentTime;qs('resumeModal').classList.remove('open');video.play().catch(()=>{});};qs('resumeNo').onclick=()=>{video.currentTime=0;qs('resumeModal').classList.remove('open');video.play().catch(()=>{});};}}); video.addEventListener('click',toggle); qs('centerPlay').onclick=toggle;qs('play').onclick=toggle;
qs('back').onclick=()=>video.currentTime=Math.max(0,video.currentTime-10);qs('forward').onclick=()=>video.currentTime=Math.min(video.duration||Infinity,video.currentTime+10);
seek.oninput=()=>{if(video.duration)video.currentTime=seek.value/1000*video.duration;};
qs('volume').oninput=e=>{video.volume=Number(e.target.value);video.muted=false;};qs('mute').onclick=()=>{video.muted=!video.muted;qs('mute').textContent=video.muted?'🔇':'🔊';};
qs('speed').onchange=e=>video.playbackRate=Number(e.target.value);qs('quality').onchange=e=>{if(hls)hls.currentLevel=Number(e.target.value);};
qs('subtitles').onchange=e=>[...video.textTracks].forEach((t,i)=>t.mode=String(i)===e.target.value?'showing':'disabled');
qs('fullscreen').onclick=()=>document.fullscreenElement?document.exitFullscreen():stage.requestFullscreen();
qs('pip').onclick=async()=>{try{document.pictureInPictureElement?await document.exitPictureInPicture():await video.requestPictureInPicture();}catch{fail('Picture-in-Picture no está disponible.');}};
qs('cast').onclick=async()=>{try{if(video.remote&&video.remote.prompt)await video.remote.prompt();else fail('No se encontró una función de transmisión compatible. Usa el menú Transmitir del navegador como alternativa.');}catch{fail('No se pudo iniciar la transmisión. Verifica que el televisor esté en la misma red.');}};
qs('help').onclick=()=>qs('helpPanel').classList.toggle('open');
qs('retrySource').onclick=()=>{if(!retryData)return;qs('retrySource').disabled=true;qs('retrySource').textContent='Reintentando…';chrome.runtime.sendMessage({type:'OPEN_SMART_PLAYER',urls:retryData.urls||[],title:retryData.title||pageTitle,image:retryData.image||postImage,postUrl:retryData.postUrl||postUrl,series:retryData.series||null,closeSourceTab:true}).catch(()=>{});};
function openEpisode(index){const episode=seriesContext?.episodes?.[index],options=episode?.options||[];if(!options.length)return;saveProgress();chrome.runtime.sendMessage({type:'OPEN_SMART_PLAYER',urls:options.map(option=>option.url),title:episode.label||`Capítulo ${episode.episode||index+1}`,image:episode.image||seriesContext.image||'',postUrl:episode.url,series:{...seriesContext,currentIndex:index},closeSourceTab:true});}
function renderSeries(series){if(!series?.episodes?.length)return;seriesContext=series;const current=Math.max(0,Number(series.currentIndex)||0),seasons=[...new Set(series.episodes.map(x=>x.season??1))],activeSeason=series.episodes[current]?.season||seasons[0];qs('episodesToggle').hidden=false;qs('seriesTitle').textContent=series.title||'Serie';qs('episodesToggle').onclick=()=>qs('seriesPanel').classList.toggle('open');qs('closeSeries').onclick=()=>qs('seriesPanel').classList.remove('open');const tabs=qs('seasonTabs'),list=qs('episodeList');tabs.textContent='';list.textContent='';const showSeason=season=>{tabs.querySelectorAll('button').forEach(x=>x.classList.toggle('active',Number(x.dataset.season)===season));list.querySelectorAll('[data-season]').forEach(x=>x.hidden=Number(x.dataset.season)!==season);};seasons.forEach(season=>{const button=document.createElement('button');button.dataset.season=season;button.textContent=`Temporada ${season}`;button.onclick=()=>showSeason(season);tabs.append(button);});series.episodes.forEach((episode,index)=>{const button=document.createElement('button');button.className=`player-episode${index===current?' current':''}`;button.dataset.season=episode.season??1;button.disabled=!episode.options?.length;button.innerHTML='<span></span><div><b></b><small></small></div><i>▶</i>';button.querySelector('span').textContent=episode.episode||index+1;button.querySelector('b').textContent=episode.label||`Capítulo ${episode.episode||index+1}`;button.querySelector('small').textContent=episode.options?.length?'Reproductor disponible':'No disponible';button.onclick=()=>openEpisode(index);list.append(button);});showSeason(activeSeason);qs('previousEpisode').disabled=current<=0||!series.episodes[current-1]?.options?.length;qs('nextEpisode').disabled=current>=series.episodes.length-1||!series.episodes[current+1]?.options?.length;qs('previousEpisode').onclick=()=>openEpisode(current-1);qs('nextEpisode').onclick=()=>openEpisode(current+1);video.addEventListener('ended',()=>{if(current<series.episodes.length-1){qs('seriesPanel').classList.add('open');qs('nextEpisode').focus();}},{once:true});}
function upgradePlayerSeasonMenu(){const tabs=qs('seasonTabs'),buttons=[...tabs.querySelectorAll(':scope > button')];if(buttons.length<2){tabs.hidden=true;return;}tabs.hidden=false;const details=document.createElement('details');details.className='player-season-menu';const summary=document.createElement('summary'),choices=document.createElement('div'),active=buttons.find(x=>x.classList.contains('active'))||buttons[0];summary.textContent=`Temporadas · ${active.textContent}`;buttons.forEach(button=>{const choose=button.onclick;button.onclick=event=>{choose?.call(button,event);summary.textContent=`Temporadas · ${button.textContent}`;choices.querySelectorAll('button').forEach(x=>x.classList.toggle('active',x===button));details.open=false;};choices.append(button);});details.append(summary,choices);tabs.append(details);}
if(contextId)chrome.runtime.sendMessage({type:'GET_PLAYER_CONTEXT',contextId},context=>{if(context?.series){renderSeries(context.series);upgradePlayerSeasonMenu();}});
async function refreshSaved(){const{savedCatalog=[]}=await chrome.storage.local.get({savedCatalog:[]});const saved=savedCatalog.some(x=>x.url===src);qs('saveVideo').classList.toggle('saved',saved);qs('saveVideo').textContent=saved?'♥ Guardado':'♡ Guardar video';return saved;}
qs('saveVideo').onclick=async()=>{if(!src)return;const data=await chrome.storage.local.get({savedCatalog:[]});const previous=data.savedCatalog.find(x=>x.url===src);const entry={url:src,title:pageTitle,image:postImage,postUrl,currentTime:video.currentTime||previous?.currentTime||0,duration:Number.isFinite(video.duration)?video.duration:(previous?.duration||0),savedAt:previous?.savedAt||Date.now(),updatedAt:Date.now(),seriesTitle:seriesContext?.title||'',season:seriesContext?.episodes?.[seriesContext.currentIndex||0]?.season||null,episode:seriesContext?.episodes?.[seriesContext.currentIndex||0]?.episode||null};await chrome.storage.local.set({savedCatalog:[entry,...data.savedCatalog.filter(x=>x.url!==src)].slice(0,100)});await refreshSaved();chrome.runtime.sendMessage({type:'OPEN_USER_CATALOG'});};refreshSaved();
async function saveProgress(){if(!src||!Number.isFinite(video.currentTime)||video.currentTime<1)return;const data=await chrome.storage.local.get({watchHistory:[]});const entry={url:src,title:pageTitle,image:postImage,postUrl,currentTime:video.currentTime,duration:Number.isFinite(video.duration)?video.duration:0,updatedAt:Date.now()};await chrome.storage.local.set({watchHistory:[entry,...data.watchHistory.filter(x=>x.url!==src)].slice(0,30)});}
setInterval(saveProgress,5000);window.addEventListener('beforeunload',saveProgress);video.addEventListener('pause',saveProgress);
setInterval(()=>{if(!src||video.paused||video.ended||video.readyState<2)return;const episode=seriesContext?.episodes?.[seriesContext.currentIndex||0];chrome.runtime.sendMessage({type:'REPORT_WATCH_SECONDS',payload:{event_id:crypto.randomUUID(),seconds:15,content_url:postUrl||src,title:pageTitle,season:episode?.season||null,episode:episode?.episode||null,position_seconds:Math.floor(video.currentTime||0)}}).catch(()=>{});},15000);
document.addEventListener('keydown',e=>{if(/INPUT|SELECT/.test(e.target.tagName))return;if(e.code==='Space'){e.preventDefault();toggle();}if(e.key==='ArrowLeft')video.currentTime-=10;if(e.key==='ArrowRight')video.currentTime+=10;if(e.key==='ArrowUp')video.volume=Math.min(1,video.volume+.1);if(e.key==='ArrowDown')video.volume=Math.max(0,video.volume-.1);if(e.key.toLowerCase()==='m')video.muted=!video.muted;if(e.key.toLowerCase()==='f')qs('fullscreen').click();});
