
// pwa_tasks.js - task list and simple editor
window.renderTasks = window.renderTasks || (async function(){
  const cont = document.getElementById('view_tasks'); if(!cont) return;
  cont.innerHTML = '<div class="card"><div style="display:flex;justify-content:space-between;align-items:center"><h3>Tasks</h3><button id="btn_new_task">New Task</button></div></div><div id="task_list" class="card"></div>';
  const listEl = document.getElementById('task_list');

  async function load(page=1, per=50){
    listEl.innerHTML = '<div class="loading">Loading tasks...</div>';
    try{
      const res = await fetch((window.API_BASE||'') + '/api/tasks.php?action=list&page='+page+'&per='+per, { headers: Auth.authHeaders() });
      const j = await res.json();
      if(!j.status){ listEl.innerHTML = '<div class="error">Auth</div>'; return; }
      if(!j.data.length){ listEl.innerHTML = '<div class="loading">No tasks</div>'; return; }
      listEl.innerHTML = ''; j.data.forEach(t=>{
        const el = document.createElement('div'); el.className='card'; el.innerHTML = '<div style="display:flex;justify-content:space-between"><div><strong>'+t.title+'</strong><div style="font-size:12px;color:#666">Cust: '+(t.customer_id||'')+'</div></div><div><button class="btn_task_view" data-id="'+t.id+'">Open</button></div></div>';
        listEl.appendChild(el);
      });
      listEl.querySelectorAll('.btn_task_view').forEach(b=> b.addEventListener('click', ()=>{ location.hash = '#task?id='+b.dataset.id; }));
    }catch(err){ listEl.innerHTML = '<div class="error">Network</div>'; }
  }

  document.getElementById('btn_new_task').addEventListener('click', async ()=>{
    const title = prompt('Task title'); if(!title) return;
    const cid = prompt('Customer ID'); if(!cid) return;
    const payload = { title, customer_id: cid };
    try{
      const res = await fetch((window.API_BASE||'') + '/api/tasks.php?action=create', { method:'POST', headers: Object.assign({'Content-Type':'application/json'}, Auth.authHeaders()), body: JSON.stringify(payload) });
      const j = await res.json();
      if(j.status==1){ alert('Task created'); load(); } else alert('Error: '+(j.error||'unknown'));
    }catch(err){
      await Outbox.enqueue('POST','/api/tasks.php?action=create', payload);
      alert('Offline — task queued');
      load();
    }
  });

  await load();
});