diff --git a/torrent/app.js b/torrent/app.js
index ac10efbd..a7fd30e5 100644
--- a/torrent/app.js
+++ b/torrent/app.js
@@ -214,8 +214,20 @@ export function createBeaconApp({
function setProcessing(flag) {
state.processing = Boolean(flag);
- if (elements.overlay) {
- elements.overlay.hidden = !state.processing;
+
+ if (!elements.overlay) {
+ return;
+ }
+
+ const isActive = state.processing;
+
+ elements.overlay.hidden = !isActive;
+ elements.overlay.setAttribute("aria-hidden", isActive ? "false" : "true");
+
+ if (isActive) {
+ elements.overlay.style.removeProperty("display");
+ } else {
+ elements.overlay.style.display = "none";
}
}
diff --git a/torrent/dist/beacon.js b/torrent/dist/beacon.js
index 8686d644..ad385566 100644
--- a/torrent/dist/beacon.js
+++ b/torrent/dist/beacon.js
@@ -1 +1 @@
-var O={info:"torrent-toast torrent-toast--info",success:"torrent-toast torrent-toast--success",error:"torrent-toast torrent-toast--error",warn:"torrent-toast torrent-toast--warn"},V="transition duration-200 ease-out",Y="beacon-toast-motion",q="data-beacon-motion";function J(e,t){let a=e?.defaultView;if(a&&typeof a.requestAnimationFrame=="function"){a.requestAnimationFrame(t);return}setTimeout(t,16)}function Q(e){let t=e||(typeof document<"u"?document:null);if(!t)return null;let a=t.getElementById("beacon-toast-container");if(!a){a=t.createElement("div"),a.id="beacon-toast-container",a.setAttribute("role","region"),a.setAttribute("aria-live","polite"),a.className=["pointer-events-none","fixed","inset-x-0","top-0","z-overlay-toast","flex","w-full","flex-col","items-center","gap-3","px-4","pt-6","sm:items-end","sm:px-6","sm:pt-8"].join(" ");let i=t.body||t.getElementsByTagName?.("body")?.[0];i&&i.appendChild(a)}return a}function X(e,t,a){let i=e.createElement("div");i.className=[V,a].join(" "),i.setAttribute("role","status"),i.setAttribute("tabindex","0"),i.textContent=t;let o=e.createElement("button");o.type="button",o.className=["notification-dismiss","focus-ring","absolute","right-3","top-3"].join(" "),o.setAttribute("aria-label","Dismiss notification"),o.innerHTML='';let d=e.createElement("div");return d.className=["relative","w-full",V,Y].join(" "),d.setAttribute(q,"exit"),d.appendChild(i),i.appendChild(o),{wrapper:d,toast:i,closeButton:o}}function Z(e,t=setTimeout,a=clearTimeout){return{show(i,o={}){if(!i)return;let d=o.type&&O[o.type]?o.type:"info",n=Q(e);if(!n)return;let{wrapper:m,toast:c,closeButton:T}=X(e,i,O[d]);n.appendChild(m),J(e,()=>{m.setAttribute(q,"enter")});let v=typeof o.duration=="number"?o.duration:3500,p=()=>{m.setAttribute(q,"exit");let N=t(()=>{m.parentNode&&m.parentNode.removeChild(m)},200);return T.removeEventListener("click",E),c.removeEventListener("keydown",h),T.removeEventListener("keydown",h),N},E=()=>p(),h=N=>{N.key==="Escape"&&(N.stopPropagation(),p())};T.addEventListener("click",E),c.addEventListener("keydown",h),T.addEventListener("keydown",h);let S=null;return o.sticky||(S=t(()=>{p()},v)),{dismiss(){S&&a(S),p()}}},set(i,o){return typeof o=="string"?this.show(i,{type:o}):this.show(i,o)},info(i,o={}){return this.show(i,{...o,type:"info"})},success(i,o={}){return this.show(i,{...o,type:"success"})},error(i,o={}){return this.show(i,{...o,type:"error"})},warn(i,o={}){return this.show(i,{...o,type:"warn"})}}}function R(e,t=setTimeout,a=clearTimeout){return Z(e,t,a)}var $=[{key:"name",label:"Name",headerClass:"w-full sm:w-1/3 text-left",cellClass:"font-medium text-text truncate"},{key:"progress",label:"Progress",headerClass:"w-24 text-right",cellClass:"tabular-nums text-right",formatter:"progress"},{key:"downloadSpeed",label:"\u2193 Speed",headerClass:"w-24 text-right",cellClass:"tabular-nums text-right",formatter:"bytesPerSecond"},{key:"uploadSpeed",label:"\u2191 Speed",headerClass:"w-24 text-right",cellClass:"tabular-nums text-right",formatter:"bytesPerSecond"},{key:"numPeers",label:"Peers",headerClass:"w-20 text-right",cellClass:"tabular-nums text-right",formatter:"integer"},{key:"ratio",label:"Ratio",headerClass:"w-20 text-right",cellClass:"tabular-nums text-right",formatter:"ratio"}];function ee(e){return e?e.infoHash||e.magnetURI||e.name||String(Math.random()):""}function te(e,t){return!e||!t?!1:e===t||e.magnetURI&&e.magnetURI===t.magnetURI||e.infoHash&&e.infoHash===t.infoHash}function ne(e){return typeof e!="number"||Number.isNaN(e)?"":`${(e*100).toFixed(1)}%`}function re(e){return typeof e!="number"||!Number.isFinite(e)?"0.00":e.toFixed(2)}function oe(e){return typeof e!="number"||!Number.isFinite(e)?"0":Math.max(0,Math.floor(e)).toString()}function ae(e,t){if(typeof t=="function")return t(e,!0)||"";if(typeof e!="number"||Number.isNaN(e)||e<1)return"";let a=["B","kB","MB","GB","TB"],i=Math.min(Math.floor(Math.log(e)/Math.log(1e3)),a.length-1);return`${(e/Math.pow(1e3,i)).toFixed(1)} ${a[i]}/s`}function se(e,t){let a=e.formatter;if(typeof a=="function")return a;let i=t?.[a];if(typeof i=="function")return i;switch(a){case"progress":return ne;case"ratio":return re;case"integer":return oe;case"bytesPerSecond":return o=>ae(o,t?.bytes);default:return o=>o}}function W({documentRef:e=typeof document<"u"?document:null,root:t,onSelect:a,formatters:i={}}={}){if(!e)throw new Error("createTorrentTable requires a document reference");if(!(t instanceof e.defaultView.HTMLElement))throw new Error("createTorrentTable requires a valid root element");let o=e;t.innerHTML="";let d=o.createElement("div");d.className="overflow-hidden rounded-xl border border-border-translucent bg-surface shadow-sm";let n=o.createElement("div");n.className="overflow-x-auto",d.appendChild(n);let m=o.createElement("table");m.className="min-w-full divide-y divide-border-translucent text-sm",n.appendChild(m);let c=o.createElement("thead");c.className="bg-surface-alt text-muted-strong";let T=o.createElement("tr");$.forEach(y=>{let x=o.createElement("th");x.setAttribute("scope","col"),x.className="px-4 py-3 text-left text-xs font-semibold uppercase tracking-wide",y.headerClass&&(x.className+=` ${y.headerClass}`),x.textContent=y.label,T.appendChild(x)}),c.appendChild(T),m.appendChild(c);let v=o.createElement("tbody");v.className="divide-y divide-border-translucent",m.appendChild(v);let p=o.createElement("tbody"),E=o.createElement("tr"),h=o.createElement("td");h.className="px-4 py-8 text-center text-sm text-muted",h.colSpan=$.length,h.textContent="No active torrents yet. Add a magnet link to get started.",E.appendChild(h),p.appendChild(E),m.appendChild(p),t.appendChild(d);function S(y=[],x=null){let k=Array.isArray(y)?y:[];if(v.innerHTML="",!k.length){v.hidden=!0,p.hidden=!1;return}v.hidden=!1,p.hidden=!0;for(let B of k){let w=o.createElement("tr");w.className=["group","align-middle","cursor-pointer","transition","hover:bg-panel-hover","focus-visible:outline","focus-visible:outline-2","focus-visible:outline-offset-2","focus-visible:outline-info"].join(" "),w.setAttribute("role","button"),w.setAttribute("tabindex","0"),w.dataset.torrentId=ee(B),te(x,B)?(w.classList.add("bg-info/10","text-text"),w.setAttribute("aria-pressed","true")):w.setAttribute("aria-pressed","false"),w.addEventListener("click",()=>{typeof a=="function"&&a(B)}),w.addEventListener("keydown",C=>{(C.key==="Enter"||C.key===" ")&&(C.preventDefault(),typeof a=="function"&&a(B))}),$.forEach(C=>{let A=o.createElement("td");A.className="px-4 py-3",C.cellClass&&(A.className+=` ${C.cellClass}`);let H=B?B[C.key]:void 0,r=se(C,i)(H,B,C),s=o.createElement("span");s.textContent=r==null?"":String(r),A.appendChild(s),w.appendChild(A)}),v.appendChild(w)}}function N(){t.innerHTML=""}return{render:S,destroy:N}}var ie="2.0",z=["wss://tracker.btorrent.xyz","wss://tracker.openwebtorrent.com"],j={announce:z},le={announce:z};function M(e,t=!1){if(typeof e!="number"||Number.isNaN(e))return"";if(e<1)return t?"":"0 B";let a=["B","kB","MB","GB","TB"],i=Math.min(Math.floor(Math.log(e)/Math.log(1e3)),a.length-1);return`${(e/Math.pow(1e3,i)).toFixed(1)} ${a[i]}${t?"/s":""}`}function ce(e){return typeof e!="number"||Number.isNaN(e)?"":`${(e*100).toFixed(1)}%`}function _(e){return typeof e!="number"||!Number.isFinite(e)?"0.00":e.toFixed(2)}function de(e,t){return!e||!t?!1:!!(e===t||e.infoHash&&t.infoHash&&e.infoHash===t.infoHash||e.magnetURI&&t.magnetURI&&e.magnetURI===t.magnetURI)}function ue(e){if(!(!e||!Array.isArray(e.files))&&(e.files.forEach(t=>{typeof t.priority!="string"&&(t.priority="0"),typeof t.getBlobURL=="function"&&t.getBlobURL((a,i)=>{a||!i||(t.url=i)})}),e.torrentFile&&typeof Blob=="function"&&typeof URL<"u"))try{let t=new Blob([e.torrentFile],{type:"application/x-bittorrent"});if(e.torrentFileBlobURL=URL.createObjectURL(t),!e.fileName){let a=e.name||"download";e.fileName=`${a}.torrent`}}catch(t){console.warn("[beacon] Failed to create torrent blob URL",t)}}function fe(e,t){if(!e)return;let a=typeof t=="string"?t:String(t??"0");if(e.priority=a,a==="-1"){typeof e.deselect=="function"&&e.deselect();return}let i=Number.parseInt(a,10);Number.isFinite(i)&&typeof e.select=="function"&&e.select(i)}function D(e,t){if(!Array.isArray(t)||t.length===0)return null;if(!e)return t[0];let a=t.find(i=>de(i,e));return a||t[0]}function G({documentRef:e=typeof document<"u"?document:null,WebTorrentCtor:t}={}){if(!e)throw new Error("createBeaconApp requires a document reference");let a=e.defaultView||globalThis,i=typeof t=="function"?t:typeof a?.WebTorrent=="function"?a.WebTorrent:null;if(!i)throw new Error("createBeaconApp requires a WebTorrent constructor");let o=R(e),d=new i({tracker:le}),n={form:e.querySelector('[data-beacon="magnet-form"]'),magnetInput:e.querySelector('[data-beacon="magnet-input"]'),seedButton:e.querySelector('[data-beacon="seed-button"]'),seedInput:e.querySelector('[data-beacon="seed-input"]'),tableRoot:e.querySelector('[data-beacon="torrent-table"]'),selectedSection:e.querySelector('[data-beacon="selected"]'),selectedName:e.querySelector('[data-beacon="selected-name"]'),pauseButton:e.querySelector('[data-beacon-action="pause"]'),resumeButton:e.querySelector('[data-beacon-action="resume"]'),downloadAllButton:e.querySelector('[data-beacon-action="download-all"]'),removeButton:e.querySelector('[data-beacon-action="remove"]'),copyMagnetButton:e.querySelector('[data-beacon-action="copy-magnet"]'),infoHashValue:e.querySelector('[data-beacon="info-hash"]'),fileList:e.querySelector('[data-beacon="file-list"]'),stats:e.querySelector('[data-beacon="client-stats"]'),overlay:e.querySelector('[data-beacon="processing-overlay"]')},m=n.tableRoot?W({documentRef:e,root:n.tableRoot,formatters:{bytes:(r,s=!1)=>M(r,s),progress:r=>ce(r),ratio:r=>_(r),integer:r=>typeof r=="number"&&Number.isFinite(r)?Math.floor(r).toString():"0",bytesPerSecond:r=>M(r,!0)},onSelect(r){c.selectedTorrent=r,y()}}):null,c={selectedTorrent:null,processing:!1},T=[],v=[];function p(r){T.push(r)}function E(r){c.processing=!!r,n.overlay&&(n.overlay.hidden=!c.processing)}function h(){return Array.isArray(d.torrents)?[...d.torrents]:[]}function S(){if(!n.stats)return;let r=M(d.downloadSpeed,!0)||"0 B/s",s=M(d.uploadSpeed,!0)||"0 B/s",f=_(d.ratio);n.stats.textContent=`Client stats: \u2193 ${r} \xB7 \u2191 ${s} \xB7 Ratio: ${f}`}function N(r){n.fileList&&(n.fileList.innerHTML="",!(!r||!Array.isArray(r.files)||!r.files.length)&&r.files.forEach((s,f)=>{let u=e.createElement("tr");u.className="align-top";let l=e.createElement("td");if(l.className="px-3 py-2",s.done&&s.url){let g=e.createElement("a");g.className="text-info hover:text-info-strong",g.href=s.url,g.download=s.name||`file-${f+1}`,g.textContent=s.name||`File ${f+1}`,l.appendChild(g)}else{let g=e.createElement("span");g.textContent=s.name||`File ${f+1}`,l.appendChild(g)}u.appendChild(l);let b=e.createElement("td");b.className="px-3 py-2 text-muted-strong",b.textContent=M(s.length)||"0 B",u.appendChild(b);let I=e.createElement("td");I.className="px-3 py-2";let L=e.createElement("select");L.className="select",L.name=`${s.name||`file-${f+1}`}-priority`,L.setAttribute("aria-label",`Set priority for ${s.name||`file ${f+1}`}`),[{value:"1",label:"High priority"},{value:"0",label:"Low priority"},{value:"-1",label:"Don't download"}].forEach(g=>{let U=e.createElement("option");U.value=g.value,U.textContent=g.label,g.value===s.priority&&(U.selected=!0),L.appendChild(U)}),L.value=s.priority??"0",L.addEventListener("change",g=>{fe(s,g.target.value)}),I.appendChild(L),u.appendChild(I),n.fileList.appendChild(u)}))}function y(){if(!n.selectedSection)return;let r=h();c.selectedTorrent=D(c.selectedTorrent,r);let s=c.selectedTorrent;n.selectedSection.hidden=!s,s&&(n.selectedName&&(n.selectedName.textContent=s.name||"Untitled torrent"),n.pauseButton&&(n.pauseButton.hidden=s.paused===!0,n.pauseButton.disabled=s.paused===!0),n.resumeButton&&(n.resumeButton.hidden=s.paused!==!0,n.resumeButton.disabled=s.paused!==!0),n.downloadAllButton&&(n.downloadAllButton.disabled=!(s.progress>=1)),n.infoHashValue&&(n.infoHashValue.textContent=s.infoHash||""),N(s))}function x(r,{isSeed:s=!1}={}){E(!1),ue(r),s||o.info(`Received ${r.name||"torrent"} metadata`),c.selectedTorrent||(c.selectedTorrent=r),y(),m?.render(h(),c.selectedTorrent)}function k(r){let s=typeof r=="string"?r.trim():"";s&&(E(!0),d.add(s,j,f=>{x(f,{isSeed:!1})}))}function B(r){!Array.isArray(r)||r.length===0||(E(!0),d.seed(r,j,s=>{x(s,{isSeed:!0}),o.success(`Seeding ${s.files.length} file(s)`)}))}function w(r){if(r){if(r.progress<1){o.warn("Torrent is not finished downloading yet.");return}r.files.forEach(s=>{typeof s.getBlob=="function"&&s.getBlob((f,u)=>{if(f||!u){console.error("[beacon] Failed to get blob for file",s?.name,f),o.error("Failed to prepare file for download.");return}let l=URL.createObjectURL(u),b=e.createElement("a");b.className="beacon-hidden-download",b.setAttribute("data-beacon-hidden-download","true"),b.href=l,b.download=s.name||"download",e.body.appendChild(b),b.click(),e.body.removeChild(b),URL.revokeObjectURL(l)})})}}function C(r){if(!r?.magnetURI)return;let s=r.magnetURI,f=a?.navigator?.clipboard;if(f&&typeof f.writeText=="function"){f.writeText(s).then(()=>{o.success("Magnet URI copied to clipboard!")}).catch(u=>{console.error("[beacon] Clipboard error",u),o.error("Failed to copy magnet URI")});return}try{let u=e.createElement("textarea");u.value=s,u.className="beacon-clipboard-offscreen",u.setAttribute("data-beacon-clipboard-state","offscreen"),e.body.appendChild(u),u.select(),e.execCommand?.("copy"),e.body.removeChild(u),o.success("Magnet URI copied (fallback)!")}catch(u){console.error("[beacon] Clipboard fallback error",u),o.error("Failed to copy magnet URI")}}function A(r){r&&r.destroy(s=>{s&&(console.error("[beacon] Failed to destroy torrent",s),o.error("Failed to remove torrent"));let f=h();c.selectedTorrent=D(null,f),m?.render(f,c.selectedTorrent),y()})}function H(){if(console.log(`[beacon] Starting beacon runtime v${ie}`),o||console.warn("[beacon] Toast service unavailable"),i.WEBRTC_SUPPORT||o?.error("Please use a browser with WebRTC support.",{sticky:!0}),n.form){let l=b=>{b.preventDefault(),k(n.magnetInput?.value||""),n.magnetInput&&(n.magnetInput.value="")};n.form.addEventListener("submit",l),p(()=>n.form.removeEventListener("submit",l))}if(n.seedButton&&n.seedInput){let l=()=>{n.seedInput.click()},b=()=>{let I=Array.from(n.seedInput.files||[]);n.seedInput.value="",B(I)};n.seedButton.addEventListener("click",l),n.seedInput.addEventListener("change",b),p(()=>{n.seedButton.removeEventListener("click",l),n.seedInput.removeEventListener("change",b)})}if(n.pauseButton){let l=()=>{c.selectedTorrent&&typeof c.selectedTorrent.pause=="function"&&(c.selectedTorrent.pause(),y())};n.pauseButton.addEventListener("click",l),p(()=>n.pauseButton.removeEventListener("click",l))}if(n.resumeButton){let l=()=>{c.selectedTorrent&&typeof c.selectedTorrent.resume=="function"&&(c.selectedTorrent.resume(),y())};n.resumeButton.addEventListener("click",l),p(()=>n.resumeButton.removeEventListener("click",l))}if(n.downloadAllButton){let l=()=>w(c.selectedTorrent);n.downloadAllButton.addEventListener("click",l),p(()=>n.downloadAllButton.removeEventListener("click",l))}if(n.removeButton){let l=()=>A(c.selectedTorrent);n.removeButton.addEventListener("click",l),p(()=>n.removeButton.removeEventListener("click",l))}if(n.copyMagnetButton){let l=()=>C(c.selectedTorrent);n.copyMagnetButton.addEventListener("click",l),p(()=>n.copyMagnetButton.removeEventListener("click",l))}let r=l=>{console.error("[beacon] Torrent client error",l),o?.error(l?.message||String(l)),E(!1)};d.on("error",r),p(()=>d.removeListener("error",r));let s=l=>{if(d.torrents&&d.torrents.length>0)return l.preventDefault(),l.returnValue="Transfers are in progress. Are you sure you want to leave or refresh?",l.returnValue};a&&typeof a.addEventListener=="function"&&(a.addEventListener("beforeunload",s),p(()=>a.removeEventListener("beforeunload",s))),m?.render(h(),c.selectedTorrent),y(),S(),E(!1);let f=a.setInterval(()=>{m?.render(h(),c.selectedTorrent),y(),S()},1e3);v.push(f);let u=a?.location?.hash;typeof u=="string"&&u.length>1&&k(u.slice(1))}function P(){v.forEach(r=>a.clearInterval(r)),v.length=0,T.forEach(r=>{try{r()}catch(s){console.warn("[beacon] Cleanup task failed",s)}}),T.length=0,m?.destroy();try{d.destroy()}catch(r){console.warn("[beacon] Failed to destroy client",r)}}return{mount:H,destroy:P}}function pe(){return typeof window<"u"&&window||typeof globalThis<"u"&&globalThis||null}function me(){let e=pe();if(e&&typeof e.WebTorrent=="function")return e.WebTorrent;throw new Error("WebTorrent runtime is not available on the global scope")}var F=null;function K(){if(F)return F;if(typeof document>"u")throw new Error("Beacon runtime requires a document environment");let e=me();return F=G({documentRef:document,WebTorrentCtor:e}),F.mount(),F}if(typeof document<"u")if(document.readyState==="loading")document.addEventListener("DOMContentLoaded",()=>{try{K()}catch(e){console.error("[beacon] Failed to mount app",e)}});else try{K()}catch(e){console.error("[beacon] Failed to mount app",e)}export{G as createBeaconApp,K as mountBeaconApp};
+var O={info:"torrent-toast torrent-toast--info",success:"torrent-toast torrent-toast--success",error:"torrent-toast torrent-toast--error",warn:"torrent-toast torrent-toast--warn"},V="transition duration-200 ease-out",Y="beacon-toast-motion",q="data-beacon-motion";function J(e,t){let s=e?.defaultView;if(s&&typeof s.requestAnimationFrame=="function"){s.requestAnimationFrame(t);return}setTimeout(t,16)}function Q(e){let t=e||(typeof document<"u"?document:null);if(!t)return null;let s=t.getElementById("beacon-toast-container");if(!s){s=t.createElement("div"),s.id="beacon-toast-container",s.setAttribute("role","region"),s.setAttribute("aria-live","polite"),s.className=["pointer-events-none","fixed","inset-x-0","top-0","z-overlay-toast","flex","w-full","flex-col","items-center","gap-3","px-4","pt-6","sm:items-end","sm:px-6","sm:pt-8"].join(" ");let i=t.body||t.getElementsByTagName?.("body")?.[0];i&&i.appendChild(s)}return s}function X(e,t,s){let i=e.createElement("div");i.className=[V,s].join(" "),i.setAttribute("role","status"),i.setAttribute("tabindex","0"),i.textContent=t;let o=e.createElement("button");o.type="button",o.className=["notification-dismiss","focus-ring","absolute","right-3","top-3"].join(" "),o.setAttribute("aria-label","Dismiss notification"),o.innerHTML='';let d=e.createElement("div");return d.className=["relative","w-full",V,Y].join(" "),d.setAttribute(q,"exit"),d.appendChild(i),i.appendChild(o),{wrapper:d,toast:i,closeButton:o}}function Z(e,t=setTimeout,s=clearTimeout){return{show(i,o={}){if(!i)return;let d=o.type&&O[o.type]?o.type:"info",r=Q(e);if(!r)return;let{wrapper:m,toast:c,closeButton:T}=X(e,i,O[d]);r.appendChild(m),J(e,()=>{m.setAttribute(q,"enter")});let w=typeof o.duration=="number"?o.duration:3500,p=()=>{m.setAttribute(q,"exit");let N=t(()=>{m.parentNode&&m.parentNode.removeChild(m)},200);return T.removeEventListener("click",E),c.removeEventListener("keydown",y),T.removeEventListener("keydown",y),N},E=()=>p(),y=N=>{N.key==="Escape"&&(N.stopPropagation(),p())};T.addEventListener("click",E),c.addEventListener("keydown",y),T.addEventListener("keydown",y);let S=null;return o.sticky||(S=t(()=>{p()},w)),{dismiss(){S&&s(S),p()}}},set(i,o){return typeof o=="string"?this.show(i,{type:o}):this.show(i,o)},info(i,o={}){return this.show(i,{...o,type:"info"})},success(i,o={}){return this.show(i,{...o,type:"success"})},error(i,o={}){return this.show(i,{...o,type:"error"})},warn(i,o={}){return this.show(i,{...o,type:"warn"})}}}function R(e,t=setTimeout,s=clearTimeout){return Z(e,t,s)}var $=[{key:"name",label:"Name",headerClass:"w-full sm:w-1/3 text-left",cellClass:"font-medium text-text truncate"},{key:"progress",label:"Progress",headerClass:"w-24 text-right",cellClass:"tabular-nums text-right",formatter:"progress"},{key:"downloadSpeed",label:"\u2193 Speed",headerClass:"w-24 text-right",cellClass:"tabular-nums text-right",formatter:"bytesPerSecond"},{key:"uploadSpeed",label:"\u2191 Speed",headerClass:"w-24 text-right",cellClass:"tabular-nums text-right",formatter:"bytesPerSecond"},{key:"numPeers",label:"Peers",headerClass:"w-20 text-right",cellClass:"tabular-nums text-right",formatter:"integer"},{key:"ratio",label:"Ratio",headerClass:"w-20 text-right",cellClass:"tabular-nums text-right",formatter:"ratio"}];function ee(e){return e?e.infoHash||e.magnetURI||e.name||String(Math.random()):""}function te(e,t){return!e||!t?!1:e===t||e.magnetURI&&e.magnetURI===t.magnetURI||e.infoHash&&e.infoHash===t.infoHash}function re(e){return typeof e!="number"||Number.isNaN(e)?"":`${(e*100).toFixed(1)}%`}function ne(e){return typeof e!="number"||!Number.isFinite(e)?"0.00":e.toFixed(2)}function oe(e){return typeof e!="number"||!Number.isFinite(e)?"0":Math.max(0,Math.floor(e)).toString()}function ae(e,t){if(typeof t=="function")return t(e,!0)||"";if(typeof e!="number"||Number.isNaN(e)||e<1)return"";let s=["B","kB","MB","GB","TB"],i=Math.min(Math.floor(Math.log(e)/Math.log(1e3)),s.length-1);return`${(e/Math.pow(1e3,i)).toFixed(1)} ${s[i]}/s`}function se(e,t){let s=e.formatter;if(typeof s=="function")return s;let i=t?.[s];if(typeof i=="function")return i;switch(s){case"progress":return re;case"ratio":return ne;case"integer":return oe;case"bytesPerSecond":return o=>ae(o,t?.bytes);default:return o=>o}}function W({documentRef:e=typeof document<"u"?document:null,root:t,onSelect:s,formatters:i={}}={}){if(!e)throw new Error("createTorrentTable requires a document reference");if(!(t instanceof e.defaultView.HTMLElement))throw new Error("createTorrentTable requires a valid root element");let o=e;t.innerHTML="";let d=o.createElement("div");d.className="overflow-hidden rounded-xl border border-border-translucent bg-surface shadow-sm";let r=o.createElement("div");r.className="overflow-x-auto",d.appendChild(r);let m=o.createElement("table");m.className="min-w-full divide-y divide-border-translucent text-sm",r.appendChild(m);let c=o.createElement("thead");c.className="bg-surface-alt text-muted-strong";let T=o.createElement("tr");$.forEach(h=>{let x=o.createElement("th");x.setAttribute("scope","col"),x.className="px-4 py-3 text-left text-xs font-semibold uppercase tracking-wide",h.headerClass&&(x.className+=` ${h.headerClass}`),x.textContent=h.label,T.appendChild(x)}),c.appendChild(T),m.appendChild(c);let w=o.createElement("tbody");w.className="divide-y divide-border-translucent",m.appendChild(w);let p=o.createElement("tbody"),E=o.createElement("tr"),y=o.createElement("td");y.className="px-4 py-8 text-center text-sm text-muted",y.colSpan=$.length,y.textContent="No active torrents yet. Add a magnet link to get started.",E.appendChild(y),p.appendChild(E),m.appendChild(p),t.appendChild(d);function S(h=[],x=null){let k=Array.isArray(h)?h:[];if(w.innerHTML="",!k.length){w.hidden=!0,p.hidden=!1;return}w.hidden=!1,p.hidden=!0;for(let B of k){let v=o.createElement("tr");v.className=["group","align-middle","cursor-pointer","transition","hover:bg-panel-hover","focus-visible:outline","focus-visible:outline-2","focus-visible:outline-offset-2","focus-visible:outline-info"].join(" "),v.setAttribute("role","button"),v.setAttribute("tabindex","0"),v.dataset.torrentId=ee(B),te(x,B)?(v.classList.add("bg-info/10","text-text"),v.setAttribute("aria-pressed","true")):v.setAttribute("aria-pressed","false"),v.addEventListener("click",()=>{typeof s=="function"&&s(B)}),v.addEventListener("keydown",C=>{(C.key==="Enter"||C.key===" ")&&(C.preventDefault(),typeof s=="function"&&s(B))}),$.forEach(C=>{let A=o.createElement("td");A.className="px-4 py-3",C.cellClass&&(A.className+=` ${C.cellClass}`);let H=B?B[C.key]:void 0,n=se(C,i)(H,B,C),a=o.createElement("span");a.textContent=n==null?"":String(n),A.appendChild(a),v.appendChild(A)}),w.appendChild(v)}}function N(){t.innerHTML=""}return{render:S,destroy:N}}var ie="2.0",z=["wss://tracker.btorrent.xyz","wss://tracker.openwebtorrent.com"],j={announce:z},le={announce:z};function M(e,t=!1){if(typeof e!="number"||Number.isNaN(e))return"";if(e<1)return t?"":"0 B";let s=["B","kB","MB","GB","TB"],i=Math.min(Math.floor(Math.log(e)/Math.log(1e3)),s.length-1);return`${(e/Math.pow(1e3,i)).toFixed(1)} ${s[i]}${t?"/s":""}`}function ce(e){return typeof e!="number"||Number.isNaN(e)?"":`${(e*100).toFixed(1)}%`}function _(e){return typeof e!="number"||!Number.isFinite(e)?"0.00":e.toFixed(2)}function de(e,t){return!e||!t?!1:!!(e===t||e.infoHash&&t.infoHash&&e.infoHash===t.infoHash||e.magnetURI&&t.magnetURI&&e.magnetURI===t.magnetURI)}function ue(e){if(!(!e||!Array.isArray(e.files))&&(e.files.forEach(t=>{typeof t.priority!="string"&&(t.priority="0"),typeof t.getBlobURL=="function"&&t.getBlobURL((s,i)=>{s||!i||(t.url=i)})}),e.torrentFile&&typeof Blob=="function"&&typeof URL<"u"))try{let t=new Blob([e.torrentFile],{type:"application/x-bittorrent"});if(e.torrentFileBlobURL=URL.createObjectURL(t),!e.fileName){let s=e.name||"download";e.fileName=`${s}.torrent`}}catch(t){console.warn("[beacon] Failed to create torrent blob URL",t)}}function fe(e,t){if(!e)return;let s=typeof t=="string"?t:String(t??"0");if(e.priority=s,s==="-1"){typeof e.deselect=="function"&&e.deselect();return}let i=Number.parseInt(s,10);Number.isFinite(i)&&typeof e.select=="function"&&e.select(i)}function D(e,t){if(!Array.isArray(t)||t.length===0)return null;if(!e)return t[0];let s=t.find(i=>de(i,e));return s||t[0]}function G({documentRef:e=typeof document<"u"?document:null,WebTorrentCtor:t}={}){if(!e)throw new Error("createBeaconApp requires a document reference");let s=e.defaultView||globalThis,i=typeof t=="function"?t:typeof s?.WebTorrent=="function"?s.WebTorrent:null;if(!i)throw new Error("createBeaconApp requires a WebTorrent constructor");let o=R(e),d=new i({tracker:le}),r={form:e.querySelector('[data-beacon="magnet-form"]'),magnetInput:e.querySelector('[data-beacon="magnet-input"]'),seedButton:e.querySelector('[data-beacon="seed-button"]'),seedInput:e.querySelector('[data-beacon="seed-input"]'),tableRoot:e.querySelector('[data-beacon="torrent-table"]'),selectedSection:e.querySelector('[data-beacon="selected"]'),selectedName:e.querySelector('[data-beacon="selected-name"]'),pauseButton:e.querySelector('[data-beacon-action="pause"]'),resumeButton:e.querySelector('[data-beacon-action="resume"]'),downloadAllButton:e.querySelector('[data-beacon-action="download-all"]'),removeButton:e.querySelector('[data-beacon-action="remove"]'),copyMagnetButton:e.querySelector('[data-beacon-action="copy-magnet"]'),infoHashValue:e.querySelector('[data-beacon="info-hash"]'),fileList:e.querySelector('[data-beacon="file-list"]'),stats:e.querySelector('[data-beacon="client-stats"]'),overlay:e.querySelector('[data-beacon="processing-overlay"]')},m=r.tableRoot?W({documentRef:e,root:r.tableRoot,formatters:{bytes:(n,a=!1)=>M(n,a),progress:n=>ce(n),ratio:n=>_(n),integer:n=>typeof n=="number"&&Number.isFinite(n)?Math.floor(n).toString():"0",bytesPerSecond:n=>M(n,!0)},onSelect(n){c.selectedTorrent=n,h()}}):null,c={selectedTorrent:null,processing:!1},T=[],w=[];function p(n){T.push(n)}function E(n){if(c.processing=!!n,!r.overlay)return;let a=c.processing;r.overlay.hidden=!a,r.overlay.setAttribute("aria-hidden",a?"false":"true"),a?r.overlay.style.removeProperty("display"):r.overlay.style.display="none"}function y(){return Array.isArray(d.torrents)?[...d.torrents]:[]}function S(){if(!r.stats)return;let n=M(d.downloadSpeed,!0)||"0 B/s",a=M(d.uploadSpeed,!0)||"0 B/s",f=_(d.ratio);r.stats.textContent=`Client stats: \u2193 ${n} \xB7 \u2191 ${a} \xB7 Ratio: ${f}`}function N(n){r.fileList&&(r.fileList.innerHTML="",!(!n||!Array.isArray(n.files)||!n.files.length)&&n.files.forEach((a,f)=>{let u=e.createElement("tr");u.className="align-top";let l=e.createElement("td");if(l.className="px-3 py-2",a.done&&a.url){let g=e.createElement("a");g.className="text-info hover:text-info-strong",g.href=a.url,g.download=a.name||`file-${f+1}`,g.textContent=a.name||`File ${f+1}`,l.appendChild(g)}else{let g=e.createElement("span");g.textContent=a.name||`File ${f+1}`,l.appendChild(g)}u.appendChild(l);let b=e.createElement("td");b.className="px-3 py-2 text-muted-strong",b.textContent=M(a.length)||"0 B",u.appendChild(b);let I=e.createElement("td");I.className="px-3 py-2";let L=e.createElement("select");L.className="select",L.name=`${a.name||`file-${f+1}`}-priority`,L.setAttribute("aria-label",`Set priority for ${a.name||`file ${f+1}`}`),[{value:"1",label:"High priority"},{value:"0",label:"Low priority"},{value:"-1",label:"Don't download"}].forEach(g=>{let U=e.createElement("option");U.value=g.value,U.textContent=g.label,g.value===a.priority&&(U.selected=!0),L.appendChild(U)}),L.value=a.priority??"0",L.addEventListener("change",g=>{fe(a,g.target.value)}),I.appendChild(L),u.appendChild(I),r.fileList.appendChild(u)}))}function h(){if(!r.selectedSection)return;let n=y();c.selectedTorrent=D(c.selectedTorrent,n);let a=c.selectedTorrent;r.selectedSection.hidden=!a,a&&(r.selectedName&&(r.selectedName.textContent=a.name||"Untitled torrent"),r.pauseButton&&(r.pauseButton.hidden=a.paused===!0,r.pauseButton.disabled=a.paused===!0),r.resumeButton&&(r.resumeButton.hidden=a.paused!==!0,r.resumeButton.disabled=a.paused!==!0),r.downloadAllButton&&(r.downloadAllButton.disabled=!(a.progress>=1)),r.infoHashValue&&(r.infoHashValue.textContent=a.infoHash||""),N(a))}function x(n,{isSeed:a=!1}={}){E(!1),ue(n),a||o.info(`Received ${n.name||"torrent"} metadata`),c.selectedTorrent||(c.selectedTorrent=n),h(),m?.render(y(),c.selectedTorrent)}function k(n){let a=typeof n=="string"?n.trim():"";a&&(E(!0),d.add(a,j,f=>{x(f,{isSeed:!1})}))}function B(n){!Array.isArray(n)||n.length===0||(E(!0),d.seed(n,j,a=>{x(a,{isSeed:!0}),o.success(`Seeding ${a.files.length} file(s)`)}))}function v(n){if(n){if(n.progress<1){o.warn("Torrent is not finished downloading yet.");return}n.files.forEach(a=>{typeof a.getBlob=="function"&&a.getBlob((f,u)=>{if(f||!u){console.error("[beacon] Failed to get blob for file",a?.name,f),o.error("Failed to prepare file for download.");return}let l=URL.createObjectURL(u),b=e.createElement("a");b.className="beacon-hidden-download",b.setAttribute("data-beacon-hidden-download","true"),b.href=l,b.download=a.name||"download",e.body.appendChild(b),b.click(),e.body.removeChild(b),URL.revokeObjectURL(l)})})}}function C(n){if(!n?.magnetURI)return;let a=n.magnetURI,f=s?.navigator?.clipboard;if(f&&typeof f.writeText=="function"){f.writeText(a).then(()=>{o.success("Magnet URI copied to clipboard!")}).catch(u=>{console.error("[beacon] Clipboard error",u),o.error("Failed to copy magnet URI")});return}try{let u=e.createElement("textarea");u.value=a,u.className="beacon-clipboard-offscreen",u.setAttribute("data-beacon-clipboard-state","offscreen"),e.body.appendChild(u),u.select(),e.execCommand?.("copy"),e.body.removeChild(u),o.success("Magnet URI copied (fallback)!")}catch(u){console.error("[beacon] Clipboard fallback error",u),o.error("Failed to copy magnet URI")}}function A(n){n&&n.destroy(a=>{a&&(console.error("[beacon] Failed to destroy torrent",a),o.error("Failed to remove torrent"));let f=y();c.selectedTorrent=D(null,f),m?.render(f,c.selectedTorrent),h()})}function H(){if(console.log(`[beacon] Starting beacon runtime v${ie}`),o||console.warn("[beacon] Toast service unavailable"),i.WEBRTC_SUPPORT||o?.error("Please use a browser with WebRTC support.",{sticky:!0}),r.form){let l=b=>{b.preventDefault(),k(r.magnetInput?.value||""),r.magnetInput&&(r.magnetInput.value="")};r.form.addEventListener("submit",l),p(()=>r.form.removeEventListener("submit",l))}if(r.seedButton&&r.seedInput){let l=()=>{r.seedInput.click()},b=()=>{let I=Array.from(r.seedInput.files||[]);r.seedInput.value="",B(I)};r.seedButton.addEventListener("click",l),r.seedInput.addEventListener("change",b),p(()=>{r.seedButton.removeEventListener("click",l),r.seedInput.removeEventListener("change",b)})}if(r.pauseButton){let l=()=>{c.selectedTorrent&&typeof c.selectedTorrent.pause=="function"&&(c.selectedTorrent.pause(),h())};r.pauseButton.addEventListener("click",l),p(()=>r.pauseButton.removeEventListener("click",l))}if(r.resumeButton){let l=()=>{c.selectedTorrent&&typeof c.selectedTorrent.resume=="function"&&(c.selectedTorrent.resume(),h())};r.resumeButton.addEventListener("click",l),p(()=>r.resumeButton.removeEventListener("click",l))}if(r.downloadAllButton){let l=()=>v(c.selectedTorrent);r.downloadAllButton.addEventListener("click",l),p(()=>r.downloadAllButton.removeEventListener("click",l))}if(r.removeButton){let l=()=>A(c.selectedTorrent);r.removeButton.addEventListener("click",l),p(()=>r.removeButton.removeEventListener("click",l))}if(r.copyMagnetButton){let l=()=>C(c.selectedTorrent);r.copyMagnetButton.addEventListener("click",l),p(()=>r.copyMagnetButton.removeEventListener("click",l))}let n=l=>{console.error("[beacon] Torrent client error",l),o?.error(l?.message||String(l)),E(!1)};d.on("error",n),p(()=>d.removeListener("error",n));let a=l=>{if(d.torrents&&d.torrents.length>0)return l.preventDefault(),l.returnValue="Transfers are in progress. Are you sure you want to leave or refresh?",l.returnValue};s&&typeof s.addEventListener=="function"&&(s.addEventListener("beforeunload",a),p(()=>s.removeEventListener("beforeunload",a))),m?.render(y(),c.selectedTorrent),h(),S(),E(!1);let f=s.setInterval(()=>{m?.render(y(),c.selectedTorrent),h(),S()},1e3);w.push(f);let u=s?.location?.hash;typeof u=="string"&&u.length>1&&k(u.slice(1))}function P(){w.forEach(n=>s.clearInterval(n)),w.length=0,T.forEach(n=>{try{n()}catch(a){console.warn("[beacon] Cleanup task failed",a)}}),T.length=0,m?.destroy();try{d.destroy()}catch(n){console.warn("[beacon] Failed to destroy client",n)}}return{mount:H,destroy:P}}function pe(){return typeof window<"u"&&window||typeof globalThis<"u"&&globalThis||null}function me(){let e=pe();if(e&&typeof e.WebTorrent=="function")return e.WebTorrent;throw new Error("WebTorrent runtime is not available on the global scope")}var F=null;function K(){if(F)return F;if(typeof document>"u")throw new Error("Beacon runtime requires a document environment");let e=me();return F=G({documentRef:document,WebTorrentCtor:e}),F.mount(),F}if(typeof document<"u")if(document.readyState==="loading")document.addEventListener("DOMContentLoaded",()=>{try{K()}catch(e){console.error("[beacon] Failed to mount app",e)}});else try{K()}catch(e){console.error("[beacon] Failed to mount app",e)}export{G as createBeaconApp,K as mountBeaconApp};