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,s=!0;for(t of e)'"'===t?(s&&t===n&&(o[a]+=t),s=!s):","===t&&s?t=o[++a]="":"\n"===t&&s?("\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()),s=document.getElementById("csv-thead"),l=document.createElement("tr"),d=document.createElement("th");d.textContent="#",d.style.width="40px",d.style.textAlign="center",l.appendChild(d),n.forEach(e=>{const t=document.createElement("th");t.textContent=e,l.appendChild(t)}),s.appendChild(l);const i=document.getElementById("csv-tbody"),m=document.createDocumentFragment();r.forEach((t,o)=>{const r=document.createElement("tr"),s=document.createElement("td");s.textContent=o+1,s.style.textAlign="center",s.style.color="#888",s.style.fontWeight="500",s.style.backgroundColor="#f9f9f9",s.contentEditable="false",r.appendChild(s),n.forEach((o,s)=>{const l=document.createElement("td");let d=t[s]||"";if(s===a&&d){const n=-1!==c?t[c]:"";d=formatPhoneForE164(d,n,e.name||"")}l.contentEditable="true";const i=(n[s]||"").toLowerCase(),m=["website","no ssl","instagram","facebook","twitter","linkedin","youtube","tiktok","linkedin url"].includes(i);if(d.startsWith("http://")||d.startsWith("https://")||d.startsWith("www.")||m&&d.includes(".")&&!d.includes(" ")){let e=d;e.startsWith("http://")||e.startsWith("https://")||(e="https://"+e);const t=document.createElement("a");t.href=e,t.target="_blank",t.rel="noopener noreferrer",t.textContent=e,t.contentEditable="false",t.style.cursor="pointer",l.appendChild(t),t.addEventListener("click",e=>{e.stopPropagation()})}else l.textContent=d;l.addEventListener("blur",()=>{const t=l.textContent.trim();if(t!==d){if(s===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,'""')}"`,s=[n.map(e=>escapeCell(e)),...c.map(e=>e.map(e=>escapeCell(e)))],l=[];for(const e of s)for(let t=0;t<e.length;t++)(!l[t]||e[t].length>l[t])&&(l[t]=e[t].length);const d=s.map(e=>e.map((e,t)=>e.padEnd(l[t]," ")).join(",")).join("\n");e.csvText=d,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)}});