const box=document.getElementById('catalog'),summary=document.getElementById('summary');
const format=value=>{if(!Number.isFinite(value)||value<0)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')}`;};
const unfinished=item=>item.currentTime>0&&(!item.duration||item.currentTime<item.duration-10);
async function data(){const{savedCatalog=[],watchHistory=[]}=await chrome.storage.local.get({savedCatalog:[],watchHistory:[]});const saved=new Map(savedCatalog.map(x=>[x.url,x]));const merged=new Map();for(const item of [...savedCatalog,...watchHistory.filter(unfinished)]){const prior=merged.get(item.url)||{};merged.set(item.url,{...prior,...item,saved:saved.has(item.url),unfinished:unfinished(item)});}return{items:[...merged.values()].sort((a,b)=>(b.updatedAt||b.savedAt||0)-(a.updatedAt||a.savedAt||0)),savedCatalog,watchHistory};}
async function render(){const state=await data();box.textContent='';summary.textContent=`${state.items.length} video${state.items.length===1?'':'s'} en tu catálogo`;if(!state.items.length){box.innerHTML='<div class="empty"><b>Tu catálogo está vacío</b>Guarda un video o comienza a reproducirlo para verlo aquí.</div>';return;}state.items.forEach(item=>{const card=document.createElement('article');card.className='card';const poster=document.createElement('div');poster.className='poster';if(item.image){const img=document.createElement('img');img.src=item.image;img.alt='';img.onerror=()=>{img.remove();poster.insertAdjacentHTML('beforeend','<div class="fallback">▶</div>');};poster.append(img);}else poster.innerHTML='<div class="fallback">▶</div>';const tag=document.createElement('span');tag.className='tag';tag.textContent=item.saved?'♥ Guardado':'▶ Sin terminar';poster.append(tag);const body=document.createElement('div');body.className='body';const title=document.createElement('h2');title.textContent=item.title||'Video';title.title=item.title||'Video';const meta=document.createElement('div');meta.className='meta';meta.textContent=item.currentTime?`${format(item.currentTime)} de ${format(item.duration)}`:'Listo para reproducir';const track=document.createElement('div');track.className='track';const progress=document.createElement('span');progress.style.width=`${item.duration?Math.min(100,item.currentTime/item.duration*100):0}%`;track.append(progress);const actions=document.createElement('div');actions.className='actions';const watch=document.createElement('button');watch.className='watch';watch.textContent=item.currentTime?'Continuar viendo':'Ver video';watch.onclick=()=>chrome.runtime.sendMessage({type:'OPEN_PLAYER',url:item.url,title:item.title,image:item.image,postUrl:item.postUrl});const remove=document.createElement('button');remove.className='remove';remove.textContent='Eliminar';remove.onclick=async()=>{const d=await chrome.storage.local.get({savedCatalog:[],watchHistory:[]});await chrome.storage.local.set({savedCatalog:d.savedCatalog.filter(x=>x.url!==item.url),watchHistory:d.watchHistory.filter(x=>x.url!==item.url)});render();};actions.append(watch,remove);body.append(title,meta,track,actions);card.append(poster,body);box.append(card);});}
document.getElementById('clearFinished').onclick=async()=>{const d=await chrome.storage.local.get({watchHistory:[]});await chrome.storage.local.set({watchHistory:d.watchHistory.filter(unfinished)});render();};render();chrome.storage.onChanged.addListener(render);
