function formatPhoneForE164(e){return e?String(e).split(/[,\/;]|\bor\b/i).map(e=>e.trim()).filter(e=>e).map(e=>{let t=e.replace(/[^\d+]/g,"");return t.length>0&&!t.startsWith("+")&&(t="+"+t),t}).join(", "):""}document.addEventListener("DOMContentLoaded",async()=>{const e=new URLSearchParams(window.location.search).get("id"),t=document.getElementById("loading"),n=document.getElementById("error-container"),o=document.getElementById("viewer-container");if(e)try{if(!window.agentDb)throw new Error("Database not initialized.");const n=await window.agentDb.artifacts.get(e);if(!n)return void showError("Artifact not found or has expired.");!function renderViewer(e){document.getElementById("artifact-title").textContent=e.name||"Exported Leads",document.getElementById("artifact-meta").textContent=`${e.leadCount||0} leads \u2022 Extracted ${new Date(e.createdAt).toLocaleString()}`;const{headers:n,rows:r}=function parseCSV(e){let t,n="",o=[""],r=[o],a=0,c=0,l=!0;for(t of e)'"'===t?(l&&t===n&&(o[a]+=t),l=!l):","===t&&l?t=o[++a]="":"\n"===t&&l?("\r"===n&&(o[a]=o[a].slice(0,-1)),o=r[++c]=[t=""],a=0):o[a]+=t,n=t;if(r.length>0&&1===r[r.length-1].length&&""===r[r.length-1][0]&&r.pop(),0===r.length)return{headers:[],rows:[]};return{headers:r[0],rows:r.slice(1)}}(e.csvText),a=n.findIndex(e=>"phone"===e.toLowerCase()||"telephone"===e.toLowerCase()||"contact"===e.toLowerCase()),c=n.findIndex(e=>"address"===e.toLowerCase()||"location"===e.toLowerCase()),l=document.getElementById("csv-thead"),d=document.createElement("tr"),s=document.createElement("th");s.textContent="#",s.style.width="40px",s.style.textAlign="center",d.appendChild(s),n.forEach(e=>{const t=document.createElement("th");t.textContent=e,d.appendChild(t)}),l.appendChild(d);const i=document.getElementById("csv-tbody"),m=document.createDocumentFragment();r.forEach((t,o)=>{const r=document.createElement("tr"),l=document.createElement("td");l.textContent=o+1,l.style.textAlign="center",l.style.color="#888",l.style.fontWeight="500",l.style.backgroundColor="#f9f9f9",l.contentEditable="false",r.appendChild(l),n.forEach((n,o)=>{const l=document.createElement("td");let d=t[o]||"";if(o===a&&d){const n=-1!==c?t[c]:"";d=formatPhoneForE164(d,n,e.name||"")}if(l.contentEditable="true",d.startsWith("http://")||d.startsWith("https://")){const e=document.createElement("a");e.href=d,e.target="_blank",e.rel="noopener noreferrer",e.textContent=d,e.contentEditable="false",l.appendChild(e),e.addEventListener("click",e=>{e.preventDefault(),window.open(d,"_blank")})}else l.textContent=d;l.addEventListener("blur",()=>{const t=l.textContent.trim();if(t!==d){if(o===a){const n=formatPhoneForE164(t,-1!==c?r.cells[c+1].textContent.trim():"",e.name||"");l.textContent=n,d=n}else d=t;!async function saveTableToDB(e){try{const t=document.querySelector("#csv-thead tr");if(!t)return;const n=Array.from(t.cells).slice(1).map(e=>e.textContent),o=n.findIndex(e=>"phone"===e.toLowerCase()||"telephone"===e.toLowerCase()||"contact"===e.toLowerCase()),r=n.findIndex(e=>"address"===e.toLowerCase()||"location"===e.toLowerCase()),a=document.querySelectorAll("#csv-tbody tr"),c=Array.from(a).map(t=>{const n=Array.from(t.cells).slice(1);return n.map((t,a)=>{let c=t.textContent.trim();return a===o&&c&&(c=formatPhoneForE164(c,-1!==r?n[r].textContent.trim():"",e.name||"")),c})}),escapeCell=e=>`"${String(e??"").replace(/"/g,'""')}"`,l=[n.map(e=>escapeCell(e)),...c.map(e=>e.map(e=>escapeCell(e)))],d=[];for(const e of l)for(let t=0;t<e.length;t++)(!d[t]||e[t].length>d[t])&&(d[t]=e[t].length);const s=l.map(e=>e.map((e,t)=>e.padEnd(d[t]," ")).join(",")).join("\n");e.csvText=s,await window.agentDb.artifacts.put(e)}catch(e){}}(e)}}),l.title=d,r.appendChild(l)}),m.appendChild(r)}),i.appendChild(m),document.getElementById("download-csv-btn").addEventListener("click",()=>{const t=new Blob([e.csvText],{type:"text/csv;charset=utf-8;"}),n=URL.createObjectURL(t),o=document.createElement("a");o.href=n,o.download=`${e.name||"leads"}.csv`,o.click(),URL.revokeObjectURL(n)}),document.getElementById("download-excel-btn").addEventListener("click",()=>{if(window.SimpleXLSX){const t=document.querySelector("#csv-thead tr"),n=Array.from(t.cells).slice(1).map(e=>e.textContent),o=document.querySelectorAll("#csv-tbody tr"),r=[n,...Array.from(o).map(e=>Array.from(e.cells).slice(1).map(e=>e.textContent.trim()))];window.SimpleXLSX.downloadXLSX(r,`${e.name||"leads"}.xlsx`)}}),t.style.display="none",o.style.display="flex"}(n)}catch(e){showError(e.message)}else showError("No Artifact ID provided.");function showError(e){t.style.display="none",o.style.display="none",n.style.display="flex";const r=document.getElementById("error-message");r&&(r.textContent=e)}});