const $=id=>document.getElementById(id);const formatBytes=bytes=>{const n=Number(bytes)||0;if(n>=1073741824)return`${(n/1073741824).toFixed(2)} GB`;if(n>=1048576)return`${(n/1048576).toFixed(1)} MB`;if(n>=1024)return`${(n/1024).toFixed(0)} KB`;return`${n} B`;};
async function records(){const{hiroPcDownloads=[]}=await chrome.storage.local.get({hiroPcDownloads:[]});const out=[];for(const meta of hiroPcDownloads){try{const found=await chrome.downloads.search({id:Number(meta.downloadId)});out.push({...meta,download:found[0]||null});}catch{out.push({...meta,download:null});}}return out.sort((a,b)=>(b.startedAt||0)-(a.startedAt||0));}
async function removeRecord(entry,deleteFile=false){if(deleteFile&&entry.download?.exists){try{await chrome.downloads.removeFile(Number(entry.downloadId));}catch{}}const{hiroPcDownloads=[]}=await chrome.storage.local.get({hiroPcDownloads:[]});await chrome.storage.local.set({hiroPcDownloads:hiroPcDownloads.filter(x=>String(x.downloadId)!==String(entry.downloadId))});render();}
async function render(){const items=await records();$("downloads").textContent="";$("count").textContent=`${items.length} archivo${items.length===1?'':'s'}`;let total=0;items.forEach(x=>total+=Number(x.download?.fileSize||x.download?.totalBytes||0));$("totalSize").textContent=formatBytes(total);$("summary").textContent=`${items.filter(x=>x.download?.state==='complete').length} completadas`;$("usageBar").style.width=items.length?`${Math.min(100,items.filter(x=>x.download?.state==='complete').length/items.length*100)}%`:'0%';if(!items.length){$("downloads").innerHTML='<div class="empty"><b>Aún no tienes descargas</b><span>Abre un contenido en HIRO PLAY y pulsa “Descargar” cuando la fuente permita guardar un archivo directo.</span></div>';return;}for(const entry of items){const d=entry.download,card=document.createElement('article'),poster=document.createElement('div');poster.className='poster';if(entry.image){const img=document.createElement('img');img.src=entry.image;img.alt='';img.onerror=()=>img.remove();poster.append(img);}const state=d?.state==='complete'?'LISTO':d?.state==='interrupted'?'ERROR':'DESCARGANDO';poster.insertAdjacentHTML('beforeend',`<span>↓ ${state}</span>`);const body=document.createElement('div');body.className='body';const title=document.createElement('h2');title.textContent=entry.title||d?.filename?.split(/[\\/]/).pop()||'Contenido';const meta=document.createElement('p');meta.textContent=`${formatBytes(d?.fileSize||d?.totalBytes||0)} · ${d?.state==='complete'?'Guardado en tu PC':d?.error||'En progreso'}`;const actions=document.createElement('div');actions.className='actions';const open=document.createElement('button');open.className='watch';open.textContent=d?.state==='complete'?'▶ Abrir archivo':'Ver descarga';open.onclick=()=>d?.state==='complete'?chrome.downloads.open(Number(entry.downloadId)):chrome.downloads.show(Number(entry.downloadId));const folder=document.createElement('button');folder.textContent='Carpeta';folder.onclick=()=>chrome.downloads.show(Number(entry.downloadId));const del=document.createElement('button');del.className='delete';del.textContent='Quitar';del.onclick=()=>removeRecord(entry,false);actions.append(open,folder,del);body.append(title,meta,actions);card.append(poster,body);$("downloads").append(card);}}
$("openCatalog").onclick=()=>chrome.runtime.sendMessage({type:'OPEN_USER_CATALOG'});render();chrome.downloads.onChanged.addListener(()=>render());chrome.storage.onChanged.addListener(changes=>{if(changes.hiroPcDownloads)render();});
