(()=>{const base=document.documentElement.dataset.apiBase||'', $=id=>document.getElementById(id),form=$("payForm"),list=$("pairList"),tpl=$("pairTemplate"),jobs=$("jobs"),empty=$("emptyState"),submit=$("submitButton"),polls=new Map(),esc=v=>String(v??"").replace(/[&<>"']/g,c=>({"&":"&","<":"<",">":">",'"':""","'":"'"}[c]));function renumber(){[...list.children].forEach((r,i)=>r.querySelector(".pair-index").textContent=`${String(i+1).padStart(2,"0")} / ACCOUNT`)}function add(){if(list.children.length>=50)return;const n=tpl.content.firstElementChild.cloneNode(true);n.querySelector(".remove-pair").onclick=()=>{if(list.children.length>1){n.remove();renumber()}};list.appendChild(n);renumber()}function draw(x){let n=document.querySelector(`[data-job="${x.id}"]`);if(!n){n=document.createElement("article");n.className="job";n.dataset.job=x.id;jobs.prepend(n)}n.className=`job status-${x.status}`;const logs=(x.logs||[]).slice(-4).map(v=>`
${esc(v.time)} · ${esc(v.message)}
`).join(""),res=x.result&&Object.keys(x.result).length?`${esc(x.result.intent_status||x.result.status||x.stage||"Prepared")}
`:"",err=x.error?`${esc(x.error)}
`:"";n.innerHTML=`${esc((x.status||"queued").toUpperCase())}${esc(x.account_email||"AT account")}${esc(x.checkout_url||"")}
${esc(x.stage||"Waiting")}${Number(x.progress||0)}%
${logs||esc(x.message||"")}
${res}${err}`;empty.hidden=true}async function get(id){const r=await fetch(`${base}/api/protocol-pay/jobs/${id}`,{cache:"no-store"}),d=await r.json();if(!r.ok||!d.ok)throw new Error(d.error||`HTTP ${r.status}`);draw(d.job);return d.job}async function waitPrepared(ids){for(;;){const states=await Promise.all(ids.map(get));if(states.every(x=>["prepared","error","cancelled"].includes(x.status)))return states;await new Promise(r=>setTimeout(r,1000))}}function pollFinal(id){if(polls.has(id))return;const t=setInterval(async()=>{try{const x=await get(id);if(["ready","error","cancelled","verification_required"].includes(x.status)){clearInterval(t);polls.delete(id)}}catch{}},1200);polls.set(id,t)}async function create(item){const r=await fetch(`${base}/api/protocol-pay/jobs`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({access_token:item.at,checkout_url:item.url,defer_confirm:true})}),d=await r.json();if(!r.ok||!d.ok)throw new Error(d.error||`HTTP ${r.status}`);draw(d.job);return d.job.id}form.addEventListener("submit",async e=>{e.preventDefault();submit.disabled=true;try{const items=[...list.querySelectorAll(".pair-row")].map(r=>({at:r.querySelector(".pair-at").value.trim(),url:r.querySelector(".pair-url").value.trim()}));if(items.some(x=>!x.at||!x.url))throw new Error("AT and Checkout are required for every row");const ids=await Promise.all(items.map(create));const states=await waitPrepared(ids),ready=states.filter(x=>x.status==="prepared").map(x=>x.id);if(!ready.length)throw new Error("No task completed preparation");const r=await fetch(`${base}/api/protocol-pay/batch-confirm`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({job_ids:ready})}),d=await r.json();if(!r.ok||!d.ok)throw new Error(d.error||`HTTP ${r.status}`);ready.forEach(pollFinal)}catch(e){alert(e.message)}finally{submit.disabled=false}});$("addPair").onclick=add;$("clearButton").onclick=()=>{jobs.innerHTML="";empty.hidden=false};add()})();