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';}}}
asyncfunctionloadJobs({silent=false}={}){if(!silent){jobMessage('Loading jobs…');resetJobCounts();}try{constpayload=awaitjobsRequest('/api/v1/jobs');jobs=Array.isArray(payload)?payload:(payload.jobs||payload.items||[]);renderJobCounts(payload);renderJobsList();$('jobsUpdatedAt').textContent=`Updated ${newDate().toLocaleTimeString([],{hour:'2-digit',minute:'2-digit'})}`;jobMessage('');constactive=jobs.some(job=>['queued','running'].includes(jobStatus(job)));if(active&&!jobPollTimer)jobPollTimer=setInterval(()=>loadJobs({silent:true}),5000);if(!active&&jobPollTimer){clearInterval(jobPollTimer);jobPollTimer=null;}if(selectedJobId){constselected=jobs.find(job=>String(job.id)===String(selectedJobId));if(selected)awaitloadJobDetail(selectedJobId);}}catch(error){jobs=[];resetJobCounts();renderJobsList();if(error.message!=='unauthorized')jobMessage(error.message||'Unable to load jobs.',true);}}
asyncfunctionstartDemoJob(){if(!canManageJobs()){jobMessage('Your role is not permitted to start jobs.',true);return;}constbutton=$('startDemoJobBtn');button.disabled=true;jobMessage('Starting demo job…');try{constjob=awaitjobsRequest('/api/v1/jobs',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({type:'noop',payload:{},idempotency_key:`demo-${Date.now()}-${Math.random().toString(36).slice(2)}`})});awaitloadJobs({silent:true});if(job?.id)awaitloadJobDetail(job.id);jobMessage('Demo job started.');}catch(error){if(error.message!=='unauthorized')jobMessage(error.message||'Unable to start demo job.',true);}finally{button.disabled=!canManageJobs();}}
asyncfunctionjobAction(action){constjob=jobs.find(item=>String(item.id)===String(selectedJobId));if(!job||!canManageJobs())return;constendpointPath=action==='cancel'?`/api/v1/jobs/${encodeURIComponent(job.id)}/cancel`:`/api/v1/jobs/${encodeURIComponent(job.id)}/retry`;constlabel=action==='cancel'?'cancel':'retry';try{awaitjobsRequest(endpointPath,{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({})});jobMessage(`Job ${label} requested.`);awaitloadJobs({silent:true});awaitloadJobDetail(job.id);}catch(error){if(error.message!=='unauthorized')jobMessage(error.message||`Unable to ${label} job.`,true);}}
functionrenderSourceRecords(items){constlist=$('sourceRecordsList');if(!items.length){list.innerHTML='<div class="source-empty">No source records returned by the workspace.</div>';return;}list.innerHTML=`<div class="source-record-table"><table><thead><tr><th>Record</th><th>Source</th><th>Status</th><th>Observed</th></tr></thead><tbody>${items.slice(0,25).map(record=>`<tr><td>${esc(record.name||record.title||record.external_id||record.id||'Unnamed record')}</td><td>${esc(record.source_name||record.source||'Unknown source')}</td><td><span class="status">${esc(record.status||'Pending')}</span></td><td>${esc(record.observed_at||record.created_at||'Time unavailable')}</td></tr>`).join('')}</tbody></table></div>`;}
asyncfunctionloadSources(){sourceMessage('Loading sources…');$('sourcesList').innerHTML='<div class="detail-loading" aria-live="polite">Loading source registry…</div>';$('sourceRecordsList').innerHTML='<div class="detail-loading" aria-live="polite">Loading source records…</div>';try{const[sourcePayload,recordPayload]=awaitPromise.all([jsonRequest('/api/v1/sources'),jsonRequest('/api/v1/source-records?page_size=25')]);sources=sourceItems(sourcePayload);renderSources();renderSourceRecords(sourceItems(recordPayload));$('sourcesUpdatedAt').textContent=`Updated ${newDate().toLocaleTimeString([],{hour:'2-digit',minute:'2-digit'})}`;sourceMessage(sources.some(sourceState)?'':'No live source is enabled.');}catch(error){sources=[];renderSources();renderSourceRecords([]);if(error.message!=='unauthorized')sourceMessage(error.message||'Unable to load sources.',true);}}
asyncfunctionsaveSource(event){event.preventDefault();constform=event.currentTarget,fields=Object.fromEntries(newFormData(form).entries());if(fields.source_type==='csv'&&!fields.csv_content.trim()){message('sourceFormMessage','CSV content is required for a CSV source.',true);return;}constconfig={url:fields.url,terms_url:fields.terms_url,owner:fields.owner,rate_limit:fields.rate_limit};if(fields.source_type==='csv')config.csv=fields.csv_content;elseconfig.rows=[];try{awaitjsonRequest('/api/v1/sources',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({name:fields.name,kind:fields.source_type,config,enabled:false})});message('sourceFormMessage','Source saved. It remains disabled until explicitly enabled.');form.reset();$('sourceCsvField').hidden=true;awaitloadSources();}catch(error){if(error.message!=='unauthorized')message('sourceFormMessage',error.message||'Unable to save source.',true);}}
asyncfunctionsourceAction(id,action){constsource=sources.find(item=>String(item.id)===String(id));if(!source)return;try{if(action==='test'){awaitjsonRequest(`/api/v1/sources/${encodeURIComponent(id)}/test`,{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({})});sourceMessage('Source test completed.');}else{constenabled=sourceState(source);awaitjsonRequest(`/api/v1/sources/${encodeURIComponent(id)}`,{method:'PATCH',headers:{'Content-Type':'application/json'},body:JSON.stringify({enabled:!enabled})});sourceMessage(`Source ${enabled?'disabled':'enabled'} by the workspace.`);}awaitloadSources();}catch(error){if(error.message!=='unauthorized')sourceMessage(error.message||`Unable to ${action} source.`,true);}}
asyncfunctionrunDiscovery(dryRun){constform=$('discoveryForm'),data=Object.fromEntries(newFormData(form).entries());data.dry_run=Boolean(dryRun);if(!data.source_id||!data.query.trim()){message('discoveryMessage','Select a source and enter a query.',true);return;}constsource=sources.find(item=>String(item.id)===String(data.source_id));if(!dryRun&&!sourceState(source)){message('discoveryMessage','This source is disabled. Enable it only after review.',true);return;}constbutton=dryRun?$('discoveryDryRunBtn'):$('discoveryRunBtn');button.disabled=true;message('discoveryMessage',dryRun?'Validating query…':'Starting discovery…');try{constquery=awaitjsonRequest('/api/v1/discovery-queries',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({source_id:Number(data.source_id),name:data.query.trim().slice(0,80),query:{text:data.query.trim()},dry_run:data.dry_run})});if(!dryRun)awaitjsonRequest(`/api/v1/discovery-queries/${encodeURIComponent(query.id)}/run`,{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({})});message('discoveryMessage',dryRun?'Dry run completed; no discovery job was started.':'Discovery request accepted. Check Jobs for progress.');}catch(error){if(error.message!=='unauthorized')message('discoveryMessage',error.message||'Discovery request failed.',true);}finally{button.disabled=false;}}
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();awaitloadJobs();awaitloadSources();}catch(e){if(e.message!=='unauthorized')showLogin('Unable to connect to the workspace. Try again.');}}