asyncfunctionrequest(path,options={}){constresponse=awaitfetch(endpoint(path),{...options,credentials:'include'});if(response.status===401){showLogin('Your session has expired. Please sign in again.');thrownewError('unauthorized');}returnresponse;}
asyncfunctionloadData(){$('apiStatus').textContent='● Connecting…';$('apiStatus').classList.remove('live');try{const[listRes,summaryRes]=awaitPromise.all([request(`/api/v1/businesses${listQuery()}`),request('/api/v1/dashboard/summary')]);if(!listRes.ok||!summaryRes.ok)thrownewError('API request failed');constlist=awaitlistRes.json(),summary=awaitsummaryRes.json();prospects=Array.isArray(list)?list:(list.businesses||list.items||[]);hasNextPage=Boolean(list.has_next??list.next_page??list.next??list.next_cursor);renderMetrics(summary);$('apiStatus').textContent='● API connected';$('apiStatus').classList.add('live');}catch(error){if(error.message==='unauthorized')return;prospects=[];hasNextPage=false;renderMetrics(null);$('apiStatus').textContent='● API unavailable';}renderRows();if(selectedId)loadDetail(selectedId);}
asyncfunctionsaveContact(form){constdata=Object.fromEntries(newFormData(form).entries());if(!data.email.trim()){message('contactMessage','Email is required.',true);return;}try{awaitjsonRequest(`/api/v1/businesses/${selectedId}/contacts`,{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(data)});message('contactMessage','Contact added.');awaitloadDetail(selectedId);}catch(e){if(e.message!=='unauthorized')message('contactMessage',e.message,true);}}
asyncfunctionsaveNote(form){constdata=Object.fromEntries(newFormData(form).entries());if(!data.body.trim()){message('noteMessage','Note cannot be empty.',true);return;}try{awaitjsonRequest(`/api/v1/businesses/${selectedId}/notes`,{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(data)});message('noteMessage','Note added.');awaitloadDetail(selectedId);}catch(e){if(e.message!=='unauthorized')message('noteMessage',e.message,true);}}
asyncfunctionsaveStage(form){conststage=newFormData(form).get('stage');if(!stage){message('pipelineMessage','Choose a pipeline stage.',true);return;}try{awaitjsonRequest(`/api/v1/businesses/${selectedId}/pipeline`,{method:'PATCH',headers:{'Content-Type':'application/json'},body:JSON.stringify({stage})});message('pipelineMessage','Pipeline stage updated.');awaitloadDetail(selectedId);awaitloadData();}catch(e){if(e.message!=='unauthorized')message('pipelineMessage',e.message,true);}}
asyncfunctionaddProspect(event){event.preventDefault();constdata=Object.fromEntries(newFormData(event.currentTarget).entries());constmsg=$('formMessage');try{constbody=awaitjsonRequest('/api/v1/businesses',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(data)});prospects.unshift(body);msg.textContent='Added to review queue.';event.currentTarget.reset();renderMetrics(null);renderRows();}catch(e){if(e.message!=='unauthorized'){msg.textContent=e.message;msg.className='form-message error';}}}
functionrenderCsv(rows){if(!rows.length){$('csvPreview').innerHTML='<span>⊞</span><p>No data rows found</p>';return;}consth=Object.keys(rows[0]);$('csvPreview').className='csv-table';$('csvPreview').innerHTML=`<table><thead><tr>${h.map(x=>`<th>${esc(x)}</th>`).join('')}</tr></thead><tbody>${rows.map(r=>`<tr>${h.map(x=>`<td>${esc(r[x])}</td>`).join('')}</tr>`).join('')}</tbody></table><small class="muted">Showing up to 10 rows · Preview only; nothing added yet.</small>`;}
asyncfunctionlogin(event){event.preventDefault();constform=event.currentTarget,messageEl=$('loginMessage'),data=Object.fromEntries(newFormData(form).entries());messageEl.textContent='Signing in…';messageEl.className='form-message';try{constres=awaitfetch(endpoint('/api/v1/auth/login'),{method:'POST',headers:{'Content-Type':'application/json'},credentials:'include',body:JSON.stringify(data)});constbody=awaitres.json().catch(()=>({}));if(!res.ok)thrownewError(body.error||'Invalid email or password.');awaitbootstrap();}catch(e){if(e.message!=='unauthorized'){messageEl.textContent=e.message;messageEl.className='form-message error';}}}
asyncfunctionlogout(){try{awaitfetch(endpoint('/api/v1/auth/logout'),{method:'POST',credentials:'include'});}finally{showLogin('You have been signed out.');$('loginForm').reset();}}
asyncfunctionbootstrap(){try{constres=awaitfetch(endpoint('/api/v1/auth/me'),{credentials:'include'});if(res.status===401){showLogin();return;}if(!res.ok)thrownewError('Could not verify session.');constuser=awaitres.json();showDashboard(user.user||user);awaitloadData();}catch(e){if(e.message!=='unauthorized')showLogin('Unable to connect to the workspace. Try again.');}}