const DB = (function(){
  const DB_NAME = 'atulya_db_v1'; const DB_VERSION = 1; let db=null;
  function openDB(){ return new Promise((res,rej)=>{ if (db) return res(db); const r=indexedDB.open(DB_NAME,DB_VERSION); r.onupgradeneeded=function(e){ const idb=e.target.result; if (!idb.objectStoreNames.contains('outbox')) idb.createObjectStore('outbox',{keyPath:'id',autoIncrement:true}); if (!idb.objectStoreNames.contains('cache')) idb.createObjectStore('cache',{keyPath:'key'}); }; r.onsuccess=function(){ db=r.result; res(db); }; r.onerror=function(e){ rej(e); }; }); }
  async function addOutbox(item){ item.created_at=new Date().toISOString(); const d=await openDB(); return new Promise((res,rej)=>{ const tx=d.transaction('outbox','readwrite'); tx.objectStore('outbox').add(item).onsuccess=()=>res(true); tx.onerror=e=>rej(e); }); }
  async function allOutbox(){ const d=await openDB(); return new Promise((res,rej)=>{ const tx=d.transaction('outbox','readonly'); const req=tx.objectStore('outbox').getAll(); req.onsuccess=()=>res(req.result||[]); req.onerror=e=>rej(e); }); }
  async function clearOutbox(){ const d=await openDB(); return new Promise((res,rej)=>{ const tx=d.transaction('outbox','readwrite'); tx.objectStore('outbox').clear().onsuccess=()=>res(true); tx.onerror=e=>rej(e); }); }
  return { openDB, addOutbox, allOutbox, clearOutbox };
})(); window.DB = DB;