import {$,msg,dl,jsonDownload,readJson,safeName} from './v7-core.mjs';const MAX=10*1024*1024,TOTAL=50*1024*1024;let db;const req=r=>new Promise((ok,no)=>{r.onsuccess=()=>ok(r.result);r.onerror=()=>no(r.error)});async function open(){if(!window.indexedDB)throw Error('IndexedDB no disponible');const r=indexedDB.open('AppInitDevEmbedWorkspace',1);r.onupgradeneeded=()=>r.result.createObjectStore('files',{keyPath:'id',autoIncrement:true});db=await req(r)}async function all(){return req(db.transaction('files').objectStore('files').getAll())}async function txAction(fn){const t=db.transaction('files','readwrite');const done=new Promise((ok,no)=>{t.oncomplete=ok;t.onerror=()=>no(t.error);t.onabort=()=>no(t.error||Error('Transacción cancelada'))});fn(t.objectStore('files'));await done}async function add(files){const current=await all();let size=current.reduce((a,b)=>a+b.blob.size,0);if(current.length+files.length>100||files.some(f=>f.blob.size>MAX)||size+files.reduce((a,b)=>a+b.blob.size,0)>TOTAL)throw Error('Límites: 100 archivos, 10 MB por archivo, 50 MB total');await txAction(s=>files.forEach(f=>s.add(f)));await refresh()}async function refresh(){const list=await all();$('items').replaceChildren();for(const x of list){const c=document.createElement('article');c.className='card';const h=document.createElement('h2');h.textContent=x.name;const p=document.createElement('p');p.textContent=`${x.blob.size} bytes · ${x.date}`;const a=document.createElement('button');a.textContent='Descargar';a.onclick=()=>dl(x.blob,safeName(x.name));const b=document.createElement('button');b.textContent='Eliminar';b.onclick=async()=>{if(confirm('¿Eliminar este archivo local?'))try{await txAction(s=>s.delete(x.id));await refresh()}catch(e){msg(e.message)}};c.append(h,p,a,b);$('items').append(c)}msg(`${list.length} archivos · ${list.reduce((a,b)=>a+b.blob.size,0)} bytes`)}const attempt=fn=>async()=>{try{await fn()}catch(e){msg(e.message)}};$('save').onclick=attempt(async()=>{await add([...$('files').files].map(f=>({name:f.name,blob:f,date:new Date().toISOString()})));$('files').value=''});$('backup').onclick=attempt(async()=>{const data=[];for(const f of await all()){const u=new Uint8Array(await f.blob.arrayBuffer());let s='';for(let i=0;i{const b=await readJson($('restore').files[0],75*1024*1024);if(b.version!==1||!Array.isArray(b.files)||b.files.length>100)throw Error('Copia inválida');const files=b.files.map(f=>{if(typeof f.name!=='string'||typeof f.data!=='string'||f.data.length>14000000||! /^[A-Za-z0-9+/=]*$/.test(f.data))throw Error('Archivo inválido');return {name:f.name.slice(0,150),blob:new Blob([Uint8Array.from(atob(f.data),c=>c.charCodeAt(0))],{type:typeof f.type==='string'?f.type:'application/octet-stream'}),date:new Date().toISOString()}});await add(files)});try{await open();await refresh()}catch(e){msg(e.message);$('save').disabled=$('backup').disabled=$('restore').disabled=true}