try{const[listRes,summaryRes]=awaitPromise.all([request('/api/v1/businesses'),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||[]);renderMetrics(summary);$('apiStatus').textContent='● API connected';$('apiStatus').classList.add('live');}catch(error){if(error.message==='unauthorized'){return;}prospects=[];renderMetrics(null);$('apiStatus').textContent='● API unavailable';}
asyncfunctionaddProspect(event){event.preventDefault();constdata=Object.fromEntries(newFormData(event.currentTarget).entries());constmsg=$('formMessage');try{constres=awaitrequest('/api/v1/businesses',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(data)});constbody=awaitres.json();if(!res.ok)thrownewError(body.error||'Could not add prospect');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,message=$('loginMessage');constdata=Object.fromEntries(newFormData(form).entries());message.textContent='Signing in…';message.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'){message.textContent=e.message;message.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.');}}