
// pwa_customers.js - renders customer list and supports create/search
window.renderCustomers = window.renderCustomers || (async function(){
  const cont = document.getElementById('view_customers');
  if(!cont) return;
  cont.innerHTML = '<div class="card"><div style="display:flex;align-items:center;justify-content:space-between"><h3>Customers</h3><div><input id="cust_search" placeholder="Search..." style="padding:6px"/><button id="btn_new_customer">New</button></div></div></div><div id="cust_list" class="card"></div>';
  const listEl = document.getElementById('cust_list');
  const q = (new URLSearchParams(location.hash.split('?')[1]||'')).get('q') || '';
  if(q) document.getElementById('cust_search').value = q;

  async function load(page=1, per=50, query=''){
    listEl.innerHTML = '<div class="loading">Loading customers...</div>';
    const url = (window.API_BASE||'') + '/api/customers.php?action=list&page='+page+'&per='+per + (query ? '&q='+encodeURIComponent(query):'');
    try{
      const res = await fetch(url, { headers: Auth.authHeaders() });
      if(!res.ok){ listEl.innerHTML = '<div class="error">Load failed</div>'; return; }
      const j = await res.json();
      if(!j.status){ listEl.innerHTML = '<div class="error">Auth required</div>'; return; }
      const rows = j.data || [];
      if(!rows.length) { listEl.innerHTML = '<div class="loading">No customers</div>'; return; }
      listEl.innerHTML = '';
      rows.forEach(r=>{
        const el = document.createElement('div');
        el.className = 'card';
        el.innerHTML = '<div style="display:flex;justify-content:space-between;align-items:center"><div><strong>'+ (r.name||'--') +'</strong><div style="font-size:12px;color:#666">'+ (r.phone||'') +'</div></div><div><button class="btn_view" data-id="'+r.id+'">Open</button></div></div>';
        listEl.appendChild(el);
      });
      listEl.querySelectorAll('.btn_view').forEach(b=> b.addEventListener('click', ()=>{ const id=b.dataset.id; location.hash = '#customer?id='+id; }));
    }catch(err){
      console.warn('customers load error', err);
      listEl.innerHTML = '<div class="error">Network error — will show cached results if available</div>';
      // optionally load from cache if implemented
    }
  }

  document.getElementById('btn_new_customer').addEventListener('click', async function(){
    const name = prompt('Customer name');
    if(!name) return;
    const phone = prompt('Phone number');
    const payload = { name, phone };
    try{
      const res = await fetch((window.API_BASE||'') + '/api/customers.php?action=create', { method:'POST', headers: Object.assign({'Content-Type':'application/json'}, Auth.authHeaders()), body: JSON.stringify(payload) });
      if(!res.ok) throw new Error('create failed');
      const j = await res.json();
      if(j.status==1){ alert('Created'); load(); }
      else alert('Create error: '+(j.error||'unknown'));
    }catch(err){
      console.warn('create offline', err);
      // queue to outbox
      await Outbox.enqueue('POST', '/api/customers.php?action=create', payload);
      alert('You are offline — customer queued for sync');
      load();
    }
  });

  document.getElementById('cust_search').addEventListener('keydown', function(e){
    if(e.key === 'Enter'){ load(1,50,this.value); location.hash = '#customers?q='+encodeURIComponent(this.value); }
  });

  await load(1,50, q);
  return true;
});
