import{a as e,n as t,r as n}from"./rolldown-runtime-BEU_UCik.js";import{$a as s,$i as r,$l as a,$n as o,$r as i,$t as c,A as l,Aa as u,Ai as d,Al as f,An as m,Ao as p,Au as h,B as g,Ba as y,Bc as b,Bi as w,Bl as v,Br as x,Bs as k,C as N,Ca as j,Cc as S,Ci as C,Cl as E,Cn as M,Co as I,Cs as A,Cu as P,Da as T,Dc as R,Di as U,Dl as $,Dn as D,Do as L,Ds as B,E as z,Ea as F,Ec as _,Ei as O,El as W,En as V,Eo as q,Es as J,F as H,Fa as K,Fc as G,Fi as Y,Fl as X,Fn as Z,Fu as Q,G as ee,Ga as te,Gc as ne,Gi as se,Gl as re,Gn as ae,Go as oe,Gr as ie,Ha as ce,Hi as le,Hl as ue,Hn as de,Ho as fe,Hr as me,Hs as pe,I as he,Ia as ge,Ic as ye,Ii as be,Io as we,Is as ve,Jc as xe,Ji as ke,Jl as Ne,Jn as je,Jo as Se,Jr as Ce,K as Ee,Ka as Me,Kc as Ie,Ki as Ae,Ko as Pe,Kr as Te,L as Re,La as Ue,Lc as $e,Lo as De,Ls as Le,Lu as Be,M as ze,Ma as Fe,Mi as _e,Ml as Oe,Mn as We,N as Ve,Na as qe,Ni as Je,Nl as He,Nn as Ke,Oa as Ge,Oc as Ye,Oi as Xe,Ol as Ze,On as Qe,Oo as et,Ou as tt,P as nt,Pa as st,Pc as rt,Pi as at,Pl as ot,Pn as it,Qa as ct,Qi as lt,Ql as ut,Qn as dt,Qt as ft,R as mt,Ra as pt,Rc as ht,Ri as gt,Rl as yt,Ro as bt,Rs as wt,S as vt,Sa as xt,Sc as kt,Si as Nt,Sl as jt,Sn as St,So as Ct,Ss as Et,T as Mt,Ta as It,Tc as At,Ti as Pt,Tl as Tt,Tn as Rt,To as Ut,Ts as $t,Ua as Dt,Ui as Lt,Ul as Bt,Un as zt,Uo as Ft,Ur as _t,Us as Ot,Va as Wt,Vc as Vt,Vi as qt,Vl as Jt,Vn as Ht,Vr as Kt,Vs as Gt,Wa as Yt,Wc as Xt,Wi as Zt,Wl as Qt,Wn as en,Wo as tn,Wr as nn,Ws as sn,Xa as rn,Xc as an,Xi as on,Xl as cn,Xn as ln,Xr as un,Yc as dn,Yi as fn,Yl as mn,Yn as pn,Yo as hn,Yr as gn,Za as yn,Zc as bn,Zi as wn,Zl as vn,Zn as xn,Zt as kn,_a as Nn,_i as jn,_l as Sn,_n as Cn,_t as En,_u as Mn,a as In,aa as An,ai as Pn,al as Tn,an as Rn,ar as Un,au as $n,b as Dn,bl as Ln,bn as Bn,bs as zn,ci as Fn,cl as _n,cn as On,co as Wn,cr as Vn,cs as qn,cu as Jn,da as Hn,di as Kn,dl as Gn,dn as Yn,do as Xn,ds as Zn,du as Qn,ea as es,ei as ts,en as ns,eo as ss,er as rs,eu as as,fa as os,fl as is,fn as cs,fu as ls,g as us,ga as ds,gi as fs,gl as ms,gn as ps,gu as hs,h as gs,ha as ys,hi as bs,hl as ws,hn as vs,ho as xs,hs as ks,i as Ns,ii as js,il as Ss,in as Cs,ir as Es,iu as Ms,j as Is,ja as As,jc as Ps,ji as Ts,jl as Rs,jn as Us,jo as $s,k as Ds,ka as Ls,kc as Bs,ki as zs,kl as Fs,kn as _s,ko as Os,ku as Ws,l as Vs,la as qs,li as Js,ll as Hs,ln as Ks,lo as Gs,lr as Ys,ls as Xs,lu as Zs,m as Qs,ma as er,mi as tr,ml as nr,mn as sr,mo as rr,ms as ar,n as or,na as ir,ni as cr,nl as lr,nn as ur,nr as dr,ns as fr,nu as mr,oa as pr,oi as hr,ol as gr,on as yr,oo as br,or as wr,p as vr,pa as xr,pi as kr,pl as Nr,pn as jr,pu as Sr,qa as Cr,qc as Er,qi as Mr,qo as Ir,qr as Ar,r as Pr,ri as Tr,rl as Rr,rn as Ur,rr as $r,rs as Dr,ru as Lr,si as Br,sl as zr,sn as Fr,so as _r,sr as Or,t as Wr,ta as Vr,ti as qr,tn as Jr,tr as Hr,tu as Kr,u as Gr,ua as Yr,ui as Xr,ul as Zr,un as Qr,uo as ea,us as ta,uu as na,va as sa,vi as ra,vn as aa,vs as oa,vu as ia,w as ca,wa as la,wc as ua,wi as da,wl as fa,wn as ma,ws as pa,x as ha,xl as ga,xn as ya,xo as ba,y as wa,ya as va,yi as xa,yn as ka,ys as Na,yu as ja,z as Sa,za as Ca,zc as Ea,zi as Ma,zl as Ia,zo as Aa,zr as Pa,zs as Ta}from"./vendor-hi7xyrZU.js";function Ra(e){return Da.find(t=>t.id===e)||$a}function Ua(e,t){const n=document.documentElement,s="dark"===t?e.colors.dark:e.colors.light;n.style.setProperty("--background",s.background),n.style.setProperty("--foreground",s.foreground),n.style.setProperty("--card",s.card),n.style.setProperty("--card-foreground",s.cardForeground),n.style.setProperty("--popover",s.popover),n.style.setProperty("--popover-foreground",s.popoverForeground),n.style.setProperty("--primary",s.primary),n.style.setProperty("--primary-foreground",s.primaryForeground),n.style.setProperty("--secondary",s.secondary),n.style.setProperty("--secondary-foreground",s.secondaryForeground),n.style.setProperty("--muted",s.muted),n.style.setProperty("--muted-foreground",s.mutedForeground),n.style.setProperty("--accent",s.accent),n.style.setProperty("--accent-foreground",s.accentForeground),n.style.setProperty("--destructive",s.destructive),n.style.setProperty("--border",s.border),n.style.setProperty("--input",s.input),n.style.setProperty("--ring",s.ring)}var $a,Da,La,Ba,za,Fa,_a,Oa,Wa,Va,qa,Ja,Ha,Ka,Ga,Ya,Xa,Za,Qa,eo,to,no,so,ro,ao,oo,io,co,lo,uo,fo,mo,po,ho,go,yo,bo,wo,vo,xo,ko,No,jo,So,Co,Eo,Mo,Io,Ao,Po,To,Ro,Uo,$o,Do,Lo,Bo,zo,Fo,_o,Oo,Wo,Vo,qo,Jo,Ho,Ko,Go,Yo,Xo,Zo,Qo,ei,ti,ni,si,ri,ai,oi,ii,ci,li,ui,di,fi,mi,pi,hi,gi,yi,bi,wi,vi,xi,ki,Ni,ji,Si,Ci,Ei,Mi,Ii,Ai,Pi,Ti,Ri,Ui,$i,Di,Li,Bi,zi,Fi,_i,Oi,Wi,Vi,qi,Ji,Hi,Ki,Gi,Yi,Xi,Zi,Qi,ec,tc,nc,sc,rc,ac,oc,ic,cc,lc,uc,dc,fc,mc,pc,hc,gc,yc,bc,wc,vc,xc,kc,Nc,jc,Sc,Cc,Ec,Mc,Ic,Ac,Pc,Tc,Rc,Uc,$c,Dc,Lc,Bc,zc,Fc,_c,Oc,Wc,Vc,qc,Jc,Hc,Kc,Gc,Yc,Xc,Zc;function Qc(){return(Qc=t(()=>{Da=[$a={id:"nostube",name:"Nostube",appTitle:{text:"nostube",imageUrl:"/nostube.svg"},colors:{light:{background:"oklch(1 0 0)",foreground:"oklch(0.141 0.005 285.823)",card:"oklch(1 0 0)",cardForeground:"oklch(0.141 0.005 285.823)",popover:"oklch(1 0 0)",popoverForeground:"oklch(0.141 0.005 285.823)",primary:"oklch(0.606 0.25 292.717)",primaryForeground:"oklch(0.969 0.016 293.756)",secondary:"oklch(0.967 0.001 286.375)",secondaryForeground:"oklch(0.21 0.006 285.885)",muted:"oklch(0.967 0.001 286.375)",mutedForeground:"oklch(0.552 0.016 285.938)",accent:"oklch(0.967 0.001 286.375)",accentForeground:"oklch(0.21 0.006 285.885)",destructive:"oklch(0.577 0.245 27.325)",border:"oklch(0.92 0.004 286.32)",input:"oklch(0.92 0.004 286.32)",ring:"oklch(0.606 0.25 292.717)"},dark:{background:"oklch(0.18 0.005 285.823)",foreground:"oklch(0.985 0 0)",card:"oklch(0.21 0.006 285.885)",cardForeground:"oklch(0.985 0 0)",popover:"oklch(0.21 0.006 285.885)",popoverForeground:"oklch(0.985 0 0)",primary:"oklch(0.541 0.281 293.009)",primaryForeground:"oklch(0.969 0.016 293.756)",secondary:"oklch(0.274 0.006 286.033)",secondaryForeground:"oklch(0.985 0 0)",muted:"oklch(0.274 0.006 286.033)",mutedForeground:"oklch(0.705 0.015 286.067)",accent:"oklch(0.274 0.006 286.033)",accentForeground:"oklch(0.985 0 0)",destructive:"oklch(0.704 0.191 22.216)",border:"oklch(1 0 0 / 10%)",input:"oklch(1 0 0 / 15%)",ring:"oklch(0.541 0.281 293.009)"}}},{id:"red",name:"Red",appTitle:{text:"NosTube",imageUrl:"/red.svg"},colors:{light:{background:"oklch(0.99 0 0)",foreground:"oklch(0.15 0 0)",card:"oklch(1 0 0)",cardForeground:"oklch(0.15 0 0)",popover:"oklch(1 0 0)",popoverForeground:"oklch(0.15 0 0)",primary:"oklch(0.55 0.22 29)",primaryForeground:"oklch(0.98 0 0)",secondary:"oklch(0.96 0 0)",secondaryForeground:"oklch(0.2 0 0)",muted:"oklch(0.96 0 0)",mutedForeground:"oklch(0.5 0 0)",accent:"oklch(0.96 0 0)",accentForeground:"oklch(0.2 0 0)",destructive:"oklch(0.55 0.22 25)",border:"oklch(0.91 0 0)",input:"oklch(0.91 0 0)",ring:"oklch(0.55 0.22 29)"},dark:{background:"oklch(0.14 0 0)",foreground:"oklch(0.98 0 0)",card:"oklch(0.17 0 0)",cardForeground:"oklch(0.98 0 0)",popover:"oklch(0.17 0 0)",popoverForeground:"oklch(0.98 0 0)",primary:"oklch(0.60 0.24 29)",primaryForeground:"oklch(0.98 0 0)",secondary:"oklch(0.22 0 0)",secondaryForeground:"oklch(0.98 0 0)",muted:"oklch(0.22 0 0)",mutedForeground:"oklch(0.68 0 0)",accent:"oklch(0.22 0 0)",accentForeground:"oklch(0.98 0 0)",destructive:"oklch(0.65 0.20 25)",border:"oklch(1 0 0 / 8%)",input:"oklch(1 0 0 / 12%)",ring:"oklch(0.60 0.24 29)"}}},{id:"ocean",name:"Ocean",colors:{light:{background:"oklch(0.99 0.005 220)",foreground:"oklch(0.15 0.01 220)",card:"oklch(1 0 0)",cardForeground:"oklch(0.15 0.01 220)",popover:"oklch(1 0 0)",popoverForeground:"oklch(0.15 0.01 220)",primary:"oklch(0.55 0.18 220)",primaryForeground:"oklch(0.98 0.01 220)",secondary:"oklch(0.96 0.01 220)",secondaryForeground:"oklch(0.2 0.01 220)",muted:"oklch(0.96 0.01 220)",mutedForeground:"oklch(0.5 0.02 220)",accent:"oklch(0.96 0.01 220)",accentForeground:"oklch(0.2 0.01 220)",destructive:"oklch(0.55 0.22 25)",border:"oklch(0.91 0.01 220)",input:"oklch(0.91 0.01 220)",ring:"oklch(0.55 0.18 220)"},dark:{background:"oklch(0.15 0.02 220)",foreground:"oklch(0.98 0.01 220)",card:"oklch(0.18 0.02 220)",cardForeground:"oklch(0.98 0.01 220)",popover:"oklch(0.18 0.02 220)",popoverForeground:"oklch(0.98 0.01 220)",primary:"oklch(0.60 0.20 200)",primaryForeground:"oklch(0.98 0.01 220)",secondary:"oklch(0.25 0.02 220)",secondaryForeground:"oklch(0.98 0.01 220)",muted:"oklch(0.25 0.02 220)",mutedForeground:"oklch(0.65 0.02 220)",accent:"oklch(0.25 0.02 220)",accentForeground:"oklch(0.98 0.01 220)",destructive:"oklch(0.65 0.20 25)",border:"oklch(1 0 0 / 10%)",input:"oklch(1 0 0 / 15%)",ring:"oklch(0.60 0.20 200)"}}},{id:"forest",name:"Forest",colors:{light:{background:"oklch(0.99 0.005 150)",foreground:"oklch(0.15 0.01 150)",card:"oklch(1 0 0)",cardForeground:"oklch(0.15 0.01 150)",popover:"oklch(1 0 0)",popoverForeground:"oklch(0.15 0.01 150)",primary:"oklch(0.55 0.15 145)",primaryForeground:"oklch(0.98 0.01 150)",secondary:"oklch(0.96 0.01 150)",secondaryForeground:"oklch(0.2 0.01 150)",muted:"oklch(0.96 0.01 150)",mutedForeground:"oklch(0.5 0.02 150)",accent:"oklch(0.96 0.01 150)",accentForeground:"oklch(0.2 0.01 150)",destructive:"oklch(0.55 0.22 25)",border:"oklch(0.91 0.01 150)",input:"oklch(0.91 0.01 150)",ring:"oklch(0.55 0.15 145)"},dark:{background:"oklch(0.15 0.02 150)",foreground:"oklch(0.98 0.01 150)",card:"oklch(0.18 0.02 150)",cardForeground:"oklch(0.98 0.01 150)",popover:"oklch(0.18 0.02 150)",popoverForeground:"oklch(0.98 0.01 150)",primary:"oklch(0.60 0.18 145)",primaryForeground:"oklch(0.98 0.01 150)",secondary:"oklch(0.25 0.02 150)",secondaryForeground:"oklch(0.98 0.01 150)",muted:"oklch(0.25 0.02 150)",mutedForeground:"oklch(0.65 0.02 150)",accent:"oklch(0.25 0.02 150)",accentForeground:"oklch(0.98 0.01 150)",destructive:"oklch(0.65 0.20 25)",border:"oklch(1 0 0 / 10%)",input:"oklch(1 0 0 / 15%)",ring:"oklch(0.60 0.18 145)"}}},{id:"sunset",name:"Sunset",colors:{light:{background:"oklch(0.99 0.005 30)",foreground:"oklch(0.15 0.01 30)",card:"oklch(1 0 0)",cardForeground:"oklch(0.15 0.01 30)",popover:"oklch(1 0 0)",popoverForeground:"oklch(0.15 0.01 30)",primary:"oklch(0.60 0.20 40)",primaryForeground:"oklch(0.98 0.01 30)",secondary:"oklch(0.96 0.01 30)",secondaryForeground:"oklch(0.2 0.01 30)",muted:"oklch(0.96 0.01 30)",mutedForeground:"oklch(0.5 0.02 30)",accent:"oklch(0.96 0.01 30)",accentForeground:"oklch(0.2 0.01 30)",destructive:"oklch(0.55 0.22 25)",border:"oklch(0.91 0.01 30)",input:"oklch(0.91 0.01 30)",ring:"oklch(0.60 0.20 40)"},dark:{background:"oklch(0.15 0.02 30)",foreground:"oklch(0.98 0.01 30)",card:"oklch(0.18 0.02 30)",cardForeground:"oklch(0.98 0.01 30)",popover:"oklch(0.18 0.02 30)",popoverForeground:"oklch(0.98 0.01 30)",primary:"oklch(0.65 0.22 35)",primaryForeground:"oklch(0.98 0.01 30)",secondary:"oklch(0.25 0.02 30)",secondaryForeground:"oklch(0.98 0.01 30)",muted:"oklch(0.25 0.02 30)",mutedForeground:"oklch(0.65 0.02 30)",accent:"oklch(0.25 0.02 30)",accentForeground:"oklch(0.98 0.01 30)",destructive:"oklch(0.65 0.20 25)",border:"oklch(1 0 0 / 10%)",input:"oklch(1 0 0 / 15%)",ring:"oklch(0.65 0.22 35)"}}},{id:"monochrome",name:"Monochrome",colors:{light:{background:"oklch(0.99 0 0)",foreground:"oklch(0.15 0 0)",card:"oklch(1 0 0)",cardForeground:"oklch(0.15 0 0)",popover:"oklch(1 0 0)",popoverForeground:"oklch(0.15 0 0)",primary:"oklch(0.30 0 0)",primaryForeground:"oklch(0.98 0 0)",secondary:"oklch(0.96 0 0)",secondaryForeground:"oklch(0.2 0 0)",muted:"oklch(0.96 0 0)",mutedForeground:"oklch(0.5 0 0)",accent:"oklch(0.96 0 0)",accentForeground:"oklch(0.2 0 0)",destructive:"oklch(0.55 0.22 25)",border:"oklch(0.91 0 0)",input:"oklch(0.91 0 0)",ring:"oklch(0.30 0 0)"},dark:{background:"oklch(0.15 0 0)",foreground:"oklch(0.98 0 0)",card:"oklch(0.18 0 0)",cardForeground:"oklch(0.98 0 0)",popover:"oklch(0.18 0 0)",popoverForeground:"oklch(0.98 0 0)",primary:"oklch(0.70 0 0)",primaryForeground:"oklch(0.15 0 0)",secondary:"oklch(0.25 0 0)",secondaryForeground:"oklch(0.98 0 0)",muted:"oklch(0.25 0 0)",mutedForeground:"oklch(0.65 0 0)",accent:"oklch(0.25 0 0)",accentForeground:"oklch(0.98 0 0)",destructive:"oklch(0.65 0.20 25)",border:"oklch(1 0 0 / 10%)",input:"oklch(1 0 0 / 15%)",ring:"oklch(0.70 0 0)"}}}]}))()}function el({children:e,defaultTheme:t="system",storageKey:n="vite-ui-theme",colorThemeStorageKey:s="nostube-color-theme",...r}){const[a,o]=(0,La.useState)(()=>localStorage.getItem(n)||t),[i,c]=(0,La.useState)(()=>localStorage.getItem(s)||"nostube"),l=(0,La.useCallback)(()=>"system"===a?window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light":a,[a]);(0,La.useEffect)(()=>{const e=window.document.documentElement,t=l();e.classList.remove("light","dark"),e.classList.add(t);Ua(Ra(i),t)},[a,i,l]),(0,La.useEffect)(()=>{if("system"!==a)return;const e=window.matchMedia("(prefers-color-scheme: dark)"),t=()=>{const t=e.matches?"dark":"light";Ua(Ra(i),t)};return e.addEventListener("change",t),()=>e.removeEventListener("change",t)},[a,i]);const u={theme:a,setTheme:e=>{localStorage.setItem(n,e),o(e)},colorTheme:i,setColorTheme:e=>{localStorage.setItem(s,e),c(e)}};return(0,Ba.jsx)(za.Provider,{...r,value:u,children:e})}function tl(){return(tl=t(()=>{La=Be(),Qc(),Ba=Q(),za=(0,La.createContext)({theme:"system",setTheme:()=>null,colorTheme:"nostube",setColorTheme:()=>null}),Fa=()=>{const e=(0,La.useContext)(za);if(void 0===e)throw new Error("useTheme must be used within a ThemeProvider");return e}}))()}function nl(...e){return _(R(e))}function sl(e){const t=e.trim();if(!t)return[];const n=(t.match(/wss:\/\//g)||[]).length,s=(t.match(/ws:\/\//g)||[]).length,r=n>1||s>1||n+s>1,a=t.includes("%20")||t.includes("avatar")||/\s/.test(t);return r||a?[]:[rl(t)]}function rl(e){const t=e.trim();if(!t)return t;let n=t;return n.includes("://")||(n=`wss://${n}`),n=n.replace(/\/+$/,""),n}function al(e){const t=new Set,n=[];for(const s of e)for(const e of s){const s=rl(e);s&&!t.has(s)&&(t.add(s),n.push(s))}return n}function ol(){return Math.floor(Date.now()/1e3)}function il(e,t,n){const s=e||"video/mp4";if(/codecs\s*=/.test(s))return s;const r=[];if(t&&r.push(t),n&&r.push(n),0===r.length)return s.replace(/;\s*$/,"").trim();const a=`codecs="${r.join(",")}"`;return`${s.replace(/;\s*$/,"").trim()}; ${a}`}function cl(e){if(!e)return"";const[t,n]=e.split(/[-_]/),s=_a.default.where("1",t)||_a.default.where("2",t)||_a.default.where("2T",t)||_a.default.where("2B",t)||_a.default.where("3",t);if(!s)return e;let r=s.name;if(n)try{if("undefined"!=typeof Intl&&"function"==typeof Intl.DisplayNames){const e=new Intl.DisplayNames(["en"],{type:"region"}).of(n.toUpperCase());e&&e!==n.toUpperCase()?r+=` (${e})`:r+=` (${n.toUpperCase()})`}else r+=` (${n.toUpperCase()})`}catch{r+=` (${n.toUpperCase()})`}return r}function ll(e,t){if(!e||!t)return e;const n=new URL(e),s=n.pathname;if(/\.\w+$/.test(s))return e;const r={"image/jpeg":".jpg","image/jpg":".jpg","image/png":".png","image/webp":".webp","image/gif":".gif","video/mp4":".mp4","video/webm":".webm","video/quicktime":".mov"}[t.toLowerCase()];return r?(n.pathname+=r,n.toString()):e}function ul(e){return function(e){let t=BigInt(0);for(let n=0;n{Ye(),At(),_a=e(ua(),1),Oa=e=>e.replace("https://","").replace("http://","").replace(/\/.*$/,"")}))()}function fl(){return(fl=t(()=>{S(),Wa=kt("inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",{variants:{variant:{default:"bg-primary text-primary-foreground hover:bg-primary/90",destructive:"bg-destructive text-destructive-foreground hover:bg-destructive/90",outline:"border border-input bg-background hover:bg-accent hover:text-accent-foreground",secondary:"bg-secondary text-secondary-foreground hover:bg-secondary/80",ghost:"hover:bg-accent hover:text-accent-foreground",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-10 px-4 py-2",sm:"h-9 rounded-md px-3",lg:"h-11 rounded-md px-8",icon:"h-10 w-10"}},defaultVariants:{variant:"default",size:"default"}})}))()}function ml(){return(ml=t(()=>{Va=e(Be(),1),Ps(),dl(),fl(),qa=Q(),(Ja=Va.forwardRef(({className:e,variant:t,size:n,asChild:s=!1,...r},a)=>(0,qa.jsx)(s?Bs:"button",{className:nl(Wa({variant:t,size:n,className:e}),"cursor-pointer"),ref:a,...r}))).displayName="Button"}))()}function pl(){return(pl=t(()=>{Ha=e(Be(),1),dl(),Ka=Q(),(Ga=Ha.forwardRef(({className:e,type:t,...n},s)=>(0,Ka.jsx)("input",{type:t,className:nl("flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-base ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",e),ref:s,...n}))).displayName="Input"}))()}function hl(){return(hl=t(()=>{Ya=e(Be(),1),sn(),$e(),dl(),Xa=Q(),Za=ve,Qa=Ot,eo=Gt,(to=Ya.forwardRef(({className:e,...t},n)=>(0,Xa.jsx)(k,{ref:n,className:nl("fixed inset-0 z-70 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",e),...t}))).displayName=k.displayName,(no=Ya.forwardRef(({className:e,children:t,hideCloseButton:n,...s},r)=>(0,Xa.jsxs)(eo,{children:[(0,Xa.jsx)(to,{}),(0,Xa.jsxs)(wt,{ref:r,className:nl("fixed left-[50%] top-[50%] z-70 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",e),...s,children:[t,!n&&(0,Xa.jsxs)(Le,{className:"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground",children:[(0,Xa.jsx)(ye,{className:"h-4 w-4"}),(0,Xa.jsx)("span",{className:"sr-only",children:"Close"})]})]})]}))).displayName=wt.displayName,(so=({className:e,...t})=>(0,Xa.jsx)("div",{className:nl("flex flex-col space-y-1.5 text-center sm:text-left",e),...t})).displayName="DialogHeader",(ro=({className:e,...t})=>(0,Xa.jsx)("div",{className:nl("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",e),...t})).displayName="DialogFooter",(ao=Ya.forwardRef(({className:e,...t},n)=>(0,Xa.jsx)(pe,{ref:n,className:nl("text-lg font-semibold leading-none tracking-tight",e),...t}))).displayName=pe.displayName,(oo=Ya.forwardRef(({className:e,...t},n)=>(0,Xa.jsx)(Ta,{ref:n,className:nl("text-sm text-muted-foreground",e),...t}))).displayName=Ta.displayName}))()}function gl(){return(gl=t(()=>{io=e(Be(),1),B(),dl(),co=Q(),lo=$t,(uo=io.forwardRef(({className:e,...t},n)=>(0,co.jsx)(pa,{ref:n,className:nl("inline-flex h-10 items-center justify-center rounded-md bg-muted p-1 text-muted-foreground",e),...t}))).displayName=pa.displayName,(fo=io.forwardRef(({className:e,...t},n)=>(0,co.jsx)(J,{ref:n,className:nl("inline-flex items-center justify-center whitespace-nowrap rounded-sm px-3 py-1.5 text-sm font-medium ring-offset-background transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-background data-[state=active]:text-foreground data-[state=active]:shadow-sm",e),...t}))).displayName=J.displayName,(mo=io.forwardRef(({className:e,...t},n)=>(0,co.jsx)(A,{ref:n,className:nl("mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",e),...t}))).displayName=A.displayName}))()}function yl(){return(yl=t(()=>{po=e(Be(),1),S(),dl(),ho=Q(),go=kt("relative w-full rounded-lg border p-4 [&>svg~*]:pl-7 [&>svg+div]:translate-y-[-3px] [&>svg]:absolute [&>svg]:left-4 [&>svg]:top-4 [&>svg]:text-foreground",{variants:{variant:{default:"bg-background text-foreground",destructive:"border-destructive/50 text-destructive dark:border-destructive [&>svg]:text-destructive"}},defaultVariants:{variant:"default"}}),(yo=po.forwardRef(({className:e,variant:t,...n},s)=>(0,ho.jsx)("div",{ref:s,role:"alert",className:nl(go({variant:t}),e),...n}))).displayName="Alert",(bo=po.forwardRef(({className:e,...t},n)=>(0,ho.jsx)("h5",{ref:n,className:nl("mb-1 font-medium leading-none tracking-tight",e),...t}))).displayName="AlertTitle",(wo=po.forwardRef(({className:e,...t},n)=>(0,ho.jsx)("div",{ref:n,className:nl("text-sm [&_p]:leading-relaxed",e),...t}))).displayName="AlertDescription"}))()}function bl(){try{const e=sessionStorage.getItem(ko);if(!e)return{};const t=JSON.parse(e);return t&&"object"==typeof t&&!Array.isArray(t)?t:{}}catch{return sessionStorage.removeItem(ko),{}}}function wl(e){try{const t=bl();delete t[e],sessionStorage.setItem(ko,JSON.stringify(t))}catch(t){}}function vl(e,t,n){try{const s=xl(),r=s.findIndex(t=>t.pubkey===e.pubkey),a={pubkey:e.pubkey,method:t,data:"nsec"===t?void 0:n,createdAt:r>=0?s[r].createdAt:Date.now()};"bunker"===t&&e.signer instanceof Ls&&(a.clientKey=Nn(e.signer.signer.key)),"nsec"===t&&n&&function(e,t){try{const n=bl();n[e]=t.trim(),sessionStorage.setItem(ko,JSON.stringify(n))}catch(n){}}(e.pubkey,n),r>=0?s[r]=a:s.push(a),localStorage.setItem(vo,JSON.stringify(s))}catch(s){s instanceof DOMException&&s.name}}function xl(){try{const e=localStorage.getItem(vo);if(!e)return[];const t=JSON.parse(e);return Array.isArray(t)?t:[]}catch(e){return localStorage.removeItem(vo),[]}}function kl(e){try{e?localStorage.setItem(xo,e):localStorage.removeItem(xo)}catch(t){}}function Nl(){try{return localStorage.getItem(xo)}catch(e){return null}}function jl(e){try{const t=xl().filter(t=>t.pubkey!==e);localStorage.setItem(vo,JSON.stringify(t)),wl(e),Nl()===e&&kl(null)}catch(t){}}function Sl(){return"undefined"!=typeof window&&"nostr"in window&&void 0!==window.nostr}function Cl(e=3e3){return new Promise(t=>{if(Sl())return void t(!0);const n=Date.now(),s=()=>{Sl()?t(!0):Date.now()-n>=e?t(!1):setTimeout(s,100)};s()})}async function El(e,t=!1){try{switch(e.method){case"extension":{if(t||Sl()){if(t&&!Sl())return null}else if(!(await Cl(3e3)))return null;const n=new Ue,s=await n.getPublicKey();return s!==e.pubkey?null:new K(s,n)}case"nsec":{const t=function(e){return bl()[e]}(e.pubkey);if(!t)return null;const n=er.decode(t);if("nsec"!==n.type)return wl(e.pubkey),null;const s=new T(n.data),r=await s.getPublicKey();return r!==e.pubkey?(wl(e.pubkey),null):new xt(r,s)}case"bunker":if(!e.data)return null;try{const t={};e.clientKey&&(t.signer=qe.fromKey(e.clientKey));const n=await Ls.fromBunkerURI(e.data,t),s=await n.getPublicKey();return s!==e.pubkey?null:new la(s,n)}catch(n){return null}default:return null}}catch(n){return null}}async function Ml(e){const t=xl(),n=Nl();if(0===t.length)return;t.some(e=>"extension"===e.method)&&await Cl(3e3);const s=[];for(const r of t){const t=await El(r,!0);t?(s.push(t),e.addAccount(t)):"nsec"!==r.method&&jl(r.pubkey)}if(n){const t=s.find(e=>e.pubkey===n);t?e.setActive(t):kl(null)}}function Il(e){let t=!1;const n=e.active$.subscribe(n=>{if(n||t)return;const s=window.nostr;"function"==typeof s?.peekPublicKey&&(t=!0,s.peekPublicKey().then(t=>{if(!/^[0-9a-f]{64}$/.test(t||"")||e.active)return;let n=e.accounts.find(e=>e.pubkey===t&&"extension"===e.type);n||(n=new K(t,new Ue),e.addAccount(n),vl(n,"extension")),e.setActive(n),kl(n.pubkey)}).catch(()=>{}).finally(()=>{t=!1}))});return()=>n.unsubscribe()}function Al(){return(Al=t(()=>{va(),F(),os(),qs(),vo="nostr:accounts",xo="nostr:active-account",ko="nostr:session-nsec-keys"}))()}function Pl(e){return!e.startsWith("bunker://")&&((e.includes("@")||e.includes("."))&&No.test(e))}function Tl(){return(Tl=t(()=>{No=/^(?:([^@]+)@)?([^\s]+)$/}))()}async function Rl(e,t,n){return await pr(function(e){return(new TextEncoder).encode(e.normalize("NFKC"))}(e),t,{N:2**n,r:8,p:1,dkLen:32,maxmem:2**n*128*8+1048576})}function Ul(e){return e.trim().toLowerCase().startsWith("ncryptsec1")}async function $l(e,t,n={}){if(!t)throw new Error("Password is required to create an encrypted backup");const s=function(e){const t=er.decode(e.trim());if("nsec"!==t.type)throw new Error("Expected an nsec private key");return t.data}(e),r=n.logN??16,a=crypto.getRandomValues(new Uint8Array(So)),o=crypto.getRandomValues(new Uint8Array(Co)),i=Io[n.keySecurity??"secure"],c=Uint8Array.of(i),l=await Rl(t,a,r);try{const e=ds(l,o,c).encrypt(s),t=new Uint8Array(Eo);let n=0;return t[n++]=jo,t[n++]=r,t.set(a,n),n+=So,t.set(o,n),n+=Co,t[n++]=i,t.set(e,n),As.encode("ncryptsec",As.toWords(t),!1)}finally{l.fill(0)}}function Dl(){return(Dl=t(()=>{ys(),An(),Fe(),os(),jo=2,So=16,Co=24,Eo=91,Mo="show my raw key",Io={insecure:0,secure:1,unknown:2}}))()}function Ll(){const e=(0,Ao.useContext)(zn);if(!e)throw new Error("useLoginActions must be used within AccountsProvider");return{async nsec(t){try{if(!t.trim())throw new Error("Nsec cannot be empty");let n;try{const e=er.decode(t);if("nsec"!==e.type)throw new Error("Invalid nsec format");n=e.data}catch{throw new Error("Failed to decode nsec. Please check the format.")}const s=new T(n),r=await s.getPublicKey(),a=new xt(r,s);await e.addAccount(a),e.setActive(a),vl(a,"nsec",t),kl(r)}catch(n){throw n}},async ncryptsec(t,n){try{if(!t.trim())throw new Error("Encrypted key cannot be empty");const{privateKey:s,nsec:r}=await async function(e,t){if(!t)throw new Error("Password is required to unlock this key");const n=As.decodeToBytes(e.trim());if("ncryptsec"!==n.prefix)throw new Error("Expected an ncryptsec encrypted key");const s=n.bytes;if(s.length!==Eo)throw new Error("Invalid ncryptsec payload length");let r=0;if(s[r++]!==jo)throw new Error("Unsupported ncryptsec version");const a=s[r++],o=s.slice(r,r+So);r+=So;const i=s.slice(r,r+Co);r+=Co;const c=s[r++],l=s.slice(r),u=await Rl(t,o,a);try{const e=ds(u,i,Uint8Array.of(c)).decrypt(l);return{privateKey:e,nsec:er.nsecEncode(e),logN:a,keySecurity:(d=c,0===d?"insecure":1===d?"secure":"unknown")}}catch{throw new Error("Failed to unlock encrypted key. Check the password and try again.")}finally{u.fill(0)}var d}(t,n),a=new T(s),o=await a.getPublicKey(),i=new xt(o,a);await e.addAccount(i),e.setActive(i),vl(i,"nsec",r),kl(o)}catch(s){throw s}},async bunker(t,n){try{if(!t.trim())throw new Error("Bunker URI cannot be empty");let s;if(Pl(t))s=(await async function(e){const t=e.match(No);if(!t)throw new Error("Invalid NIP-05 address format");const n=t[1]||"_",s=t[2],r=`https://${s}/.well-known/nostr.json?name=${encodeURIComponent(n)}`;let a,o;try{a=await fetch(r,{headers:{Accept:"application/json"}})}catch{throw new Error(`Failed to reach ${s} for NIP-05 lookup`)}if(!a.ok)throw new Error(`NIP-05 lookup failed: ${a.status} from ${s}`);try{o=await a.json()}catch{throw new Error(`Invalid JSON response from ${s}`)}const i=o.names?.[n];if(!i)throw new Error(`User "${n}" not found on ${s}`);let c=[];if(o.nip46?.relays&&o.nip46.relays.length>0?c=o.nip46.relays:o.relays?.[i]&&o.relays[i].length>0&&(c=o.relays[i]),0===c.length)throw new Error(`No relays found for bunker connection on ${s}`);const l=`bunker://${i}?${c.map(e=>`relay=${encodeURIComponent(e)}`).join("&")}`;return{pubkey:i,relays:c,bunkerUri:l}}(t)).bunkerUri;else{if(!t.startsWith("bunker://"))throw new Error("Enter a bunker:// URI or NIP-05 address (user@domain)");s=t}const r=await Ls.fromBunkerURI(s,{onAuth:n?.onAuth}),a=await r.getPublicKey(),o=new la(a,r);await e.addAccount(o),e.setActive(o),vl(o,"bunker",s),kl(a)}catch(s){throw s}},async extension(){try{if(!("nostr"in window)||!window.nostr)throw new Error("Nostr extension not found. Please install a NIP-07 extension.");const t=new Ue,n=await t.getPublicKey(),s=new K(n,t);await e.addAccount(s),e.setActive(s),vl(s,"extension"),kl(n)}catch(t){throw t}},async logout(){e.clearActive(),kl(null)}}}function Bl(){return(Bl=t(()=>{Ao=Be(),Ca(),va(),F(),os(),Al(),Tl(),Dl()}))()}function zl(e){return e.replace(/^https?:\/\//,"").replace(/\/$/,"")}function Fl(){return(Fl=t(()=>{Po=[{url:"https://almond.slidestr.net",name:"almond.slidestr.net",status:"ok",supportsMirror:!0,payment:"free",notes:"Supports chunked upload"},{url:"https://blossom.primal.net",name:"blossom.primal.net",status:"ok",cdnProvider:"Bunny Net",supportsMirror:!1,payment:"free"},{url:"https://24242.io",name:"24242.io",status:"ok",cdnProvider:"Bunny Net",supportsMirror:!1,maxFileSize:"100MB",retention:"60 days",payment:"free"},{url:"https://blossom.band",name:"blossom.band",status:"ok",cdnProvider:"Cloudflare",supportsMirror:!0,payment:"paid",price:"$0.05/GB/Month",notes:"Lightning payment"},{url:"https://cdn.satellite.earth",name:"cdn.satellite.earth",status:"ok",cdnProvider:"Cloudflare",supportsMirror:!0,payment:"paid",price:"$0.05/GB/Month",notes:"Lightning payment"},{url:"https://nostr.download",name:"nostr.download",status:"ok",supportsMirror:!0,payment:"free",notes:""},{url:"https://blossom-01.uid.ovh",name:"blossom-01.uid.ovh",supportsMirror:!0,status:"ok",payment:"free",notes:""},{url:"https://blossom-02.uid.ovh",name:"blossom-02.uid.ovh",supportsMirror:!0,status:"ok",payment:"free",notes:""},{url:"https://blossom.yakihonne.com",name:"blossom.yakihonne.com",supportsMirror:!0,status:"ok",payment:"free",notes:""},{url:"https://loratu.bitcointxoko.com",name:"loratu.bitcointxoko.com",supportsMirror:!0,status:"ok",payment:"free",notes:""},{url:"https://nostrmedia.com",name:"nostrmedia.com",supportsMirror:!0,status:"ok",payment:"paid",notes:"Subscriptions at https://nostrmedia.com/#plan",price:"from $2.99/month"}],To=["https://blossom.primal.net","https://nostr.download","https://almond.slidestr.net"],Ro=[]}))()}function _l(e){const t=e.toLowerCase();return $o.some(e=>t.includes(e.toLowerCase()))}function Ol(e){if(e.startsWith("data:"))return{};if(function(e){try{const t=new URL(e).host.toLowerCase();return Uo.some(e=>t.includes(e.toLowerCase()))}catch{return!1}}(e))return{};try{const t=new URL(e).pathname,n=t.match(/^\/([a-f0-9]{64})\.([^.]+)$/i);if(n)return{sha256:n[1].toLowerCase(),ext:n[2]};const s=t.match(/^\/([a-f0-9]{64})$/i);return s?{sha256:s[1].toLowerCase()}:{}}catch{return{}}}function Wl(e){const{sha256:t}=Ol(e);return Boolean(t)}function Vl(e){const{sha256:t,ext:n}=Ol(e);if(!t)return{isBlossomUrl:!1};try{const s=new URL(e);return{isBlossomUrl:!0,sha256:t,ext:n,server:`${s.protocol}//${s.host}`,host:s.host}}catch{return{isBlossomUrl:!1}}}function ql(){return(ql=t(()=>{Uo=["video.nostr.build","image.nostr.build","cdn.nostrcheck.me"],$o=["cdn.nostrcheck.me"]}))()}function Jl(){return(Jl=t(()=>{Fl(),ql(),Do=[{url:"wss://relay.divine.video",name:"relay.divine.video",tags:["read"]},{url:"wss://relay.primal.net",name:"relay.primal.net",tags:["read"]},{url:"wss://nos.lol",name:"nos.lol",tags:["read"]}],Lo="wss://purplepag.es",Bo=["wss://index.hzrd149.com","wss://relay.noswhere.com","wss://relay.snort.social"],zo=["wss://relay.primal.net","wss://nos.lol"],Fo=["wss://relay.divine.video"],_o=[...To.map(e=>({url:e,name:zl(e),tags:["initial upload"]})),...Ro.map(e=>({url:e,name:zl(e),tags:["mirror"]}))],Oo=[]}))()}function Hl(){return(Hl=t(()=>{Wo=new Map}))()}async function Kl(){return qo||(qo=await Y()),qo}function Gl(e){return e.filter(e=>!e.kinds?.includes(5)).map(e=>({kinds:[5],authors:e.authors,since:e.since,until:e.until,limit:e.limit}))}function Yl(e){return e.tags.filter(e=>"a"===e[0]&&e[1]).map(e=>{const[t,n,...s]=e[1].split(":"),r=Number(t),a=s.join(":");if(Number.isInteger(r)&&n)return{kind:r,pubkey:n,identifier:a}}).filter(e=>void 0!==e)}async function Xl(e,t){await async function(e,t){const n=t.filter(e=>5===e.kind);if(0!==n.length){await d(e,n);for(const t of n){const n=t.tags.filter(e=>"e"===e[0]&&e[1]).map(e=>e[1]);await Promise.all(n.map(t=>U(e,t)));const s=Yl(t);await Promise.all(s.map(t=>Xe(e,t.pubkey,t.kind,t.identifier)))}}}(e,t);const n=t.filter(e=>5!==e.kind);n.length>0&&await d(e,n)}async function Zl(e){await Xl(await Kl(),e)}function Ql(){Ho.removeByFilters({}),Wo.clear();for(const e of[...Ko.relays.keys()])Ko.remove(e);qo?.close(),qo=void 0}async function eu(e){try{const t=await Kl(),n=await _e(t,[...e,...Gl(e)]),s=Math.floor(Date.now()/1e3)-Jo;return n.filter(e=>e.created_at>=s&&"sig"in e&&"string"==typeof e.sig)}catch(t){return[]}}function tu(e,t,n=Vo,s){const r=[t,...Gl([t])],a=Object.fromEntries(n.map(e=>[e,r])),o=t.limit??100,i=new ta({}),c=i.pipe(Lt(Ko,a,{limit:o})),l=s?.skipCache?qn:i.pipe(le(eu,t,{limit:o})),u=Ft(l,c).pipe(L(e=>{5===e.kind&&Zl([e])}),yn(Ho),$s());return e=>new ar(t=>{const n=u.subscribe(t);return"object"==typeof e&&void 0!==e?i.next(e):i.next({since:e??-1/0}),()=>n.unsubscribe()})}function nu(){return(nu=t(()=>{rn(),on(),be(),O(),br(),F(),Zn(),ks(),fe(),p(),Xs(),Aa(),q(),ct(),Jl(),Hl(),Vo=Do.map(e=>e.url),Kl(),Jo=14400,Ho=new s,Ko=new wn,Go=8e3,Yo=Ko.request.bind(Ko),Ko.request=(e,t,n)=>{const s=Array.isArray(e)?e:[e];return r=Yo(e,t,n),JSON.stringify(s),new ar(e=>{let t=null,n=null;const s=()=>{t&&(clearTimeout(t),t=null)},a=()=>{s(),t=setTimeout(()=>{n?.unsubscribe(),e.complete()},Go)};return a(),n=r.subscribe({next:t=>{a(),e.next(t)},error:t=>{s(),e.error(t)},complete:()=>{s(),e.complete()}}),()=>{s(),n?.unsubscribe()}});var r},gt(Ho,Ko,{cacheRequest:eu,lookupRelays:Vo,bufferTime:0,followRelayHints:!0}),Xn(Ho,Zl),Xo=(e,t)=>Ko.subscription(e,t).pipe(bt(e=>"string"!=typeof e&&"kind"in e)),Zo=async(e,t)=>await Ko.publish(e,t),Ls.subscriptionMethod=Xo,Ls.publishMethod=Zo}))()}function su({onLogin:e,onError:t}){const{t:n}=ir(),s=(0,Qo.useContext)(zn),[a,o]=(0,Qo.useState)(null),[i,c]=(0,Qo.useState)(!1),l=(0,Qo.useRef)(null),u=(0,Qo.useRef)(null);if(!s)throw new Error("QRCodeLogin must be used within AccountsProvider");const d=(0,Qo.useCallback)(async()=>{u.current&&u.current.abort();try{const t=new Ls({relays:ti,subscriptionMethod:Xo,publishMethod:Zo});l.current=t;const n=t.getNostrConnectURI({name:"nostube",url:window.location.origin,image:new URL("/apple-touch-icon.png",window.location.origin).toString(),permissions:Ls.buildSigningPermissions([0,1,3,7,10002])});o(n);const r=new AbortController;u.current=r,await t.waitForSigner(r.signal);const a=await t.getPublicKey(),i=new la(a,t);await s.addAccount(i),s.setActive(i);const c=t.remote;if(!c)throw new Error("Failed to get remote signer pubkey");const d=function(e,t,n){const s=new URLSearchParams;return t.forEach(e=>s.append("relay",e)),n&&s.append("secret",n),`bunker://${e}?${s.toString()}`}(c,ti,t.secret);vl(i,"bunker",d),kl(a),e()}catch(n){if(n instanceof Error&&("AbortError"===n.name||n.message.toLowerCase().includes("aborted")||n.message.toLowerCase().includes("abort")))return;t(n instanceof Error?n.message:"Connection failed")}},[s,e,t]);(0,Qo.useEffect)(()=>(d(),()=>{u.current&&u.current.abort()}),[d]);return(0,ei.jsxs)("div",{className:"flex flex-col items-center space-y-4",children:[(0,ei.jsxs)("div",{className:"text-center",children:[(0,ei.jsx)(lr,{className:"w-10 h-10 mx-auto mb-2 text-primary"}),(0,ei.jsx)("p",{className:"text-sm text-muted-foreground",children:n("auth.login.qrDescription","Scan with your Nostr signer app")}),(0,ei.jsx)("p",{className:"text-xs text-muted-foreground mt-1",children:n("auth.login.qrApps","Amber, Nostrudel, or other NIP-46 signers")})]}),(0,ei.jsx)("div",{className:"p-4 bg-white rounded-xl",children:a?(0,ei.jsx)(r,{value:a,size:200,level:"M",includeMargin:!1}):(0,ei.jsx)("div",{className:"w-[200px] h-[200px] flex items-center justify-center",children:(0,ei.jsx)(Ze,{className:"w-8 h-8 animate-spin text-muted-foreground"})})}),(0,ei.jsxs)("div",{className:"flex flex-wrap items-center justify-center gap-2",children:[(0,ei.jsx)(Ja,{variant:"ghost",size:"sm",onClick:async()=>{if(a)try{await navigator.clipboard.writeText(a),c(!0),setTimeout(()=>c(!1),2e3)}catch(e){}},disabled:!a,className:"text-muted-foreground","aria-label":i?n("common.copied","Copied!"):n("common.copy","Copy"),title:i?n("common.copied","Copied!"):n("common.copy","Copy"),children:i?(0,ei.jsx)(na,{className:"w-4 h-4"}):(0,ei.jsx)(ue,{className:"w-4 h-4"})}),a?(0,ei.jsx)(Ja,{asChild:!0,variant:"default",size:"sm",children:(0,ei.jsxs)("a",{href:a,children:[(0,ei.jsx)(yt,{className:"w-4 h-4 mr-2"}),n("auth.login.qrOpen","Use Signer")]})}):(0,ei.jsxs)(Ja,{variant:"default",size:"sm",disabled:!0,children:[(0,ei.jsx)(yt,{className:"w-4 h-4 mr-2"}),n("auth.login.qrOpen","Use Signer")]}),(0,ei.jsx)(Ja,{variant:"ghost",size:"icon",onClick:()=>{o(null),c(!1),d()},className:"h-8 w-8 shrink-0 text-muted-foreground","aria-label":n("auth.login.qrRefresh","New Code"),title:n("auth.login.qrRefresh","New Code"),children:(0,ei.jsx)(Zr,{className:"w-4 h-4"})})]})]})}function ru(){return(ru=t(()=>{Qo=Be(),es(),Fs(),Rr(),Gn(),Bt(),Qn(),Ia(),F(),va(),Ca(),ml(),Al(),Jl(),nu(),Vr(),ei=Q(),ti=Do.map(e=>e.url)}))()}function au(){return(au=t(()=>{ni=e(Be(),1),Tn(),dn(),Kr(),ws(),Ia(),ml(),pl(),hl(),gl(),yl(),Bl(),Vr(),ru(),Tl(),Dl(),si=Q(),ri="undefined"!=typeof navigator&&"undefined"!=typeof window&&(Boolean(window.matchMedia?.("(pointer: coarse)")?.matches)||/Android|iPhone|iPad|iPod/i.test(navigator.userAgent)),ai=({isOpen:e,onClose:t,onLogin:n,onSignup:s})=>{const{t:r}=ir(),[a,o]=(0,ni.useState)(!1),[i,c]=(0,ni.useState)(null),[l,u]=(0,ni.useState)(""),[d,f]=(0,ni.useState)(""),[m,p]=(0,ni.useState)(()=>localStorage.getItem("nostube:last-bunker")||""),[h,g]=(0,ni.useState)(null),[y,b]=(0,ni.useState)(!1),w=(0,ni.useRef)(null),v=Ll(),x=Ul(l),k=y&&!ri;(0,ni.useEffect)(()=>{if(!e)return;const t=()=>{const e="undefined"!=typeof window?window.nostr:void 0;b(!!e&&"function"==typeof e.getPublicKey&&"function"==typeof e.signEvent)};t();const n=[window.setTimeout(t,100),window.setTimeout(t,500)];return()=>{n.forEach(window.clearTimeout)}},[e]);const N=(0,ni.useCallback)(async e=>{/iPad|iPhone|iPod/.test(navigator.userAgent)||window.open(e,"_blank","noopener,noreferrer"),g(e)},[]),j=e=>{const t=e.trim();return t.startsWith("bunker://")||Pl(t)};return(0,si.jsx)(Za,{open:e,onOpenChange:t,children:(0,si.jsxs)(no,{className:"max-h-[90vh] overflow-y-auto sm:max-w-lg p-0 rounded-2xl",children:[(0,si.jsxs)(so,{className:"px-6 pt-6 pb-0 relative",children:[(0,si.jsx)(ao,{className:"text-xl font-semibold text-center",children:r("auth.login.title")}),(0,si.jsx)(oo,{className:"text-center text-muted-foreground mt-2",children:r("auth.login.subtitle")})]}),(0,si.jsxs)("div",{className:"px-6 py-8 space-y-6",children:[i&&(0,si.jsxs)(yo,{variant:"destructive",children:[(0,si.jsx)(as,{className:"h-4 w-4"}),(0,si.jsx)(wo,{children:i})]}),(0,si.jsxs)(lo,{defaultValue:"qr",className:"w-full",onValueChange:()=>c(null),children:[(0,si.jsxs)(uo,{className:"grid h-auto mb-6 "+(k?"grid-cols-2 sm:grid-cols-4":"grid-cols-3"),children:[(0,si.jsxs)(fo,{value:"qr",className:"min-w-0 gap-1 text-xs sm:text-sm",children:[(0,si.jsx)(nr,{className:"w-4 h-4 shrink-0"}),(0,si.jsx)("span",{className:"truncate",children:r("auth.login.qr","QR")})]}),k&&(0,si.jsx)(fo,{value:"extension",className:"min-w-0 text-xs sm:text-sm",children:(0,si.jsx)("span",{className:"truncate",children:r("auth.login.extension")})}),(0,si.jsx)(fo,{value:"protected",className:"min-w-0 text-xs sm:text-sm",children:(0,si.jsx)("span",{className:"truncate",children:r("auth.login.protectedKey","Secret Key")})}),(0,si.jsx)(fo,{value:"bunker",className:"min-w-0 text-xs sm:text-sm",children:(0,si.jsx)("span",{className:"truncate",children:r("auth.login.bunker")})})]}),(0,si.jsx)(mo,{value:"qr",className:"space-y-4",children:(0,si.jsx)(su,{onLogin:()=>{n(),t()},onError:c})}),k&&(0,si.jsx)(mo,{value:"extension",className:"space-y-4",children:(0,si.jsxs)("div",{className:"text-center p-4 rounded-lg bg-card",children:[(0,si.jsx)(Ss,{className:"w-12 h-12 mx-auto mb-3 text-primary"}),(0,si.jsx)("p",{className:"text-sm mb-4",children:r("auth.login.extensionDescription")}),(0,si.jsx)(Ja,{className:"w-full rounded-full py-6",onClick:async()=>{o(!0),c(null);try{await v.extension(),n(),t()}catch(i){const t=i instanceof Error?i.message:"Extension login failed. Please try again.";c(t)}finally{o(!1)}},disabled:a,children:r(a?"auth.login.loggingIn":"auth.login.loginWithExtension")})]})}),(0,si.jsx)(mo,{value:"protected",className:"space-y-4",children:(0,si.jsxs)("div",{className:"space-y-4",children:[(0,si.jsxs)("div",{className:"space-y-2",children:[(0,si.jsx)("label",{htmlFor:"nostr-key",className:"text-sm font-medium text-gray-700 dark:text-gray-400",children:r("auth.login.enterProtectedKey","Nostr key")}),(0,si.jsx)(Ga,{id:"nostr-key",value:l,onChange:e=>u(e.target.value),className:"rounded-lg focus-visible:ring-primary",placeholder:r("auth.login.keyPlaceholder","ncryptsec1... or nsec1...")})]}),x&&(0,si.jsxs)("div",{className:"space-y-2",children:[(0,si.jsx)("label",{htmlFor:"ncryptsec-password",className:"text-sm font-medium text-gray-700 dark:text-gray-400",children:r("auth.login.protectedKeyPassword","Backup password")}),(0,si.jsx)(Ga,{id:"ncryptsec-password",type:"password",value:d,onChange:e=>f(e.target.value),className:"rounded-lg focus-visible:ring-primary",placeholder:r("auth.login.protectedKeyPassword","Backup password")})]}),(0,si.jsxs)("div",{className:"text-center",children:[(0,si.jsx)("p",{className:"text-sm mb-2",children:r("auth.login.uploadKeyFile")}),(0,si.jsx)("input",{type:"file",accept:".txt",className:"hidden",ref:w,onChange:e=>{const t=e.target.files?.[0];if(!t)return;const n=new FileReader;n.onload=e=>{const t=e.target?.result;u(t.trim())},n.readAsText(t)}}),(0,si.jsxs)(Ja,{variant:"secondary",className:"w-full",onClick:()=>w.current?.click(),children:[(0,si.jsx)(xe,{className:"w-4 h-4 mr-2"}),r("auth.login.uploadProtectedKeyFile","Upload key file")]})]}),(0,si.jsx)(Ja,{className:"w-full rounded-full py-6 mt-4",onClick:async()=>{const e=l.trim();if(e){o(!0),c(null);try{Ul(e)?await v.ncryptsec(e,d):await v.nsec(e),u(""),f(""),n(),t()}catch(i){const t=i instanceof Error?i.message:"Key login failed. Please check your key and try again.";c(t)}finally{o(!1)}}else c("Please enter your Nostr key")},disabled:a||!l.trim()||x&&!d,children:a?r("auth.login.verifying"):r("auth.login.loginWithProtectedKey","Continue with key")})]})}),(0,si.jsxs)(mo,{value:"bunker",className:"space-y-4",children:[(0,si.jsxs)("div",{className:"space-y-2",children:[(0,si.jsx)("label",{htmlFor:"bunkerUri",className:"text-sm font-medium text-gray-700 dark:text-gray-400",children:r("auth.login.bunkerInputLabel")}),(0,si.jsx)(Ga,{id:"bunkerUri",value:m,onChange:e=>p(e.target.value),className:"rounded-lg border-gray-300 dark:border-gray-700 focus-visible:ring-primary",placeholder:r("auth.login.bunkerPlaceholder")}),m&&!j(m)&&(0,si.jsx)("p",{className:"text-red-500 text-xs",children:r("auth.login.bunkerInputError")})]}),h&&(0,si.jsxs)(yo,{children:[(0,si.jsx)(yt,{className:"h-4 w-4"}),(0,si.jsxs)(wo,{className:"space-y-2",children:[(0,si.jsx)("p",{children:r("auth.login.authRequired","Authorization required. Tap below to approve the connection:")}),(0,si.jsx)("a",{href:h,target:"_blank",rel:"noopener noreferrer",className:"block",children:(0,si.jsxs)(Ja,{type:"button",variant:"secondary",className:"w-full",children:[(0,si.jsx)(yt,{className:"w-4 h-4 mr-2"}),r("auth.login.openAuth","Open Authorization")]})})]})]}),(0,si.jsx)(Ja,{className:"w-full rounded-full py-6",onClick:async()=>{if(m.trim())if(j(m)){o(!0),c(null),g(null);try{await v.bunker(m,{onAuth:N}),localStorage.setItem("nostube:last-bunker",m.trim()),g(null),n(),t()}catch(i){const t=i instanceof Error?i.message:"Bunker login failed. Please check your input and try again.";c(t),g(null)}finally{o(!1)}}else c(r("auth.login.bunkerInputError"));else c("Please enter a bunker URI or NIP-05 address")},disabled:a||!m.trim()||!j(m),children:r(a?"auth.login.connecting":"auth.login.loginWithBunker")})]})]}),(0,si.jsx)("div",{className:"text-center text-sm",children:(0,si.jsxs)("p",{className:"text-gray-600 dark:text-gray-400",children:[r("auth.login.noAccount")," ",(0,si.jsx)("button",{onClick:()=>{t(),s&&s()},className:"text-primary hover:underline font-medium",children:r("auth.login.signUp")})]})})]})]})})}}))()}function ou(){return(ou=t(()=>{oi=Be(),ii=(0,oi.createContext)(void 0)}))()}function iu(){const e=(0,ci.useContext)(ii);if(void 0===e)throw new Error("useAppContext must be used within an AppProvider");return e}function cu(){return(0,ci.useContext)(ii)}function lu(){return(lu=t(()=>{ci=Be(),ou()}))()}function uu(){const{config:e}=iu();return(0,li.useMemo)(()=>e.relays.filter(e=>e.tags.includes("read")).map(e=>e.url),[e.relays])}function du(){return(du=t(()=>{li=Be(),lu()}))()}function fu(){const e=Cr(),{pool:t}=iu(),n=uu(),s=(0,ui.useRef)(!1);(0,ui.useEffect)(()=>{if(s.current)return;s.current=!0;const r=()=>{fi&&clearTimeout(fi),fi=setTimeout(()=>{(()=>{if(0===mi.size)return;const s=Array.from(mi).filter(t=>!e.hasReplaceable(xr.Metadata,t));mi.clear(),0!==s.length&&w(t,[...n,Lo,"wss://index.hzrd149.com"],{kinds:[xr.Metadata],authors:s},{eventStore:e,limit:s.length})().subscribe({next:e=>{},error:e=>{}})})(),fi=null},di)};return window.__requestProfile=e=>{e&&""!==e.trim()&&(mi.add(e),r())},()=>{fi&&clearTimeout(fi),s.current=!1}},[e,t,n])}function mu(){return(mu=t(()=>{ui=Be(),Wt(),be(),os(),lu(),du(),Jl(),di=100,fi=null,mi=new Set}))()}function pu(e,t,n){return t?s=>Ft(tn(()=>(s.hasReplaceable(xr.Metadata,t)||(n&&n.length>0?w(e,n,{kinds:[xr.Metadata],authors:[t]},{eventStore:s,limit:1})().subscribe({error:e=>{}}):function(e){const t=window;"undefined"!=typeof window&&t.__requestProfile&&t.__requestProfile(e)}(t)),qn)),s.profile(t)):()=>Dr(void 0)}function hu(e){const t=Cr(),{pool:n}=iu(),s=e?.pubkey&&""!==e.pubkey.trim()?e.pubkey:void 0,r=e?.relays?.length?e.relays.join(","):void 0;return Dt(()=>{const e=r?r.split(","):void 0;return t.model(pu,n,s,e)},[t,n,s,r])}function gu(){return(gu=t(()=>{os(),Wt(),oe(),Xs(),fe(),fr(),mu(),lu(),be(),pu.getKey=(e,t,n)=>`${t??""}|${n?.join(",")??""}`}))()}function yu(){const e=Na(!1),t=Ct(),n=t?{pubkey:t.pubkey,signer:t.signer}:void 0;return{user:n,users:e?.accounts.map(e=>({pubkey:e.pubkey,signer:e.signer}))||[],loginWithExtension:async()=>{if(!e)throw new Error("Account manager not available");const t=new Ue,n=await t.getPublicKey(),s=new K(n,t);await e.addAccount(s),e.setActive(s),vl(s,"extension"),kl(n)},loginWithNsec:async t=>{if(!e)throw new Error("Account manager not available");const n=T.fromKey(t),s=await n.getPublicKey(),r=new xt(s,n);await e.addAccount(r),e.setActive(r),vl(r,"nsec",t),kl(s)},loginWithBunker:async(t,n)=>{if(!e)throw new Error("Account manager not available");const s=await Ls.fromBunkerURI(t,{onAuth:n?.onAuth}),r=await s.getPublicKey(),a=new la(r,s);await e.addAccount(a),e.setActive(a),vl(a,"bunker",t),kl(r)},logout:()=>{t&&e&&(e.removeAccount(t.pubkey),kl(null))},...hu(n?.pubkey?{pubkey:n.pubkey}:void 0)}}function bu(){return(bu=t(()=>{Wt(),va(),F(),gu(),Al()}))()}function wu(){return(wu=t(()=>{Wt()}))()}function vu(){const{user:e}=yu(),t=Cr(),n=hu(e?.pubkey?{pubkey:e.pubkey}:void 0);if(!e?.pubkey)return{hasProfile:!1,loaded:!1};const s=t.hasReplaceable(xr.Metadata,e.pubkey);return{hasProfile:!!(n?.display_name||n?.name||n?.picture),loaded:s||void 0!==n}}function xu(){return(xu=t(()=>{os(),Wt(),bu(),gu()}))()}function ku(){const{user:e}=yu(),{config:t}=iu(),n=Cr(),[s,r]=(0,pi.useState)(!1),[a,o]=(0,pi.useState)(null);return{publish:async s=>{if(!e)throw new Error("User is not logged in");r(!0),o(null);try{const r=s.event.tags??[];r.some(e=>"client"===e[0])||r.push(["client","nostube"]);const o={kind:s.event.kind,content:s.event.content??"",tags:r,created_at:s.event.created_at??ol()},i=await e.signer.signEvent(o),c=s.relays||t.relays.map(e=>e.url);await Ko.publish(c,i);const l=n.getReplaceable(10002,e.pubkey);if(l)try{await Ko.publish(c,l)}catch(a){}return i}catch(a){const e=a instanceof Error?a:new Error("Failed to publish event");throw o(e),e}finally{r(!1)}},isPending:s,error:a}}function Nu(){return(Nu=t(()=>{pi=Be(),bu(),lu(),Wt(),dl(),nu()}))()}function ju(){const e=Cr(),{publish:t,isPending:n}=ku();return{publishProfile:async n=>{const s=await t({event:{kind:0,content:JSON.stringify(n),tags:[],created_at:Math.floor(Date.now()/1e3)}});return e.add(s),s},isPending:n}}function Su(){return(Su=t(()=>{Wt(),Nu()}))()}function Cu(e){try{const t=localStorage.getItem(e);if(!t)return[];const n=JSON.parse(t);return Array.isArray(n)?n.filter(e=>"string"==typeof e):[]}catch(t){return[]}}function Eu(e,t){localStorage.setItem(e,JSON.stringify(t)),window.dispatchEvent(new CustomEvent(yi,{detail:{key:e,pubkeys:t}}))}function Mu(){const{user:e}=yu(),t=(0,hi.useMemo)(()=>{return t=e?.pubkey,t?`${gi}:${t}`:`${gi}:anonymous`;var t},[e?.pubkey]),[n,s]=(0,hi.useState)(()=>Cu(t));return(0,hi.useEffect)(()=>{s(Cu(t))},[t]),(0,hi.useEffect)(()=>{const e=e=>{e.key===t&&s(Cu(t))},n=e=>{const n=e.detail;n?.key===t&&s(n.pubkeys)};return window.addEventListener("storage",e),window.addEventListener(yi,n),()=>{window.removeEventListener("storage",e),window.removeEventListener(yi,n)}},[t]),{mutedPubkeys:n,mutePubkey:(0,hi.useCallback)(e=>{s(n=>{if(n.includes(e))return n;const s=[...n,e];return Eu(t,s),s})},[t]),unmutePubkey:(0,hi.useCallback)(e=>{s(n=>{const s=n.filter(t=>t!==e);return Eu(t,s),s})},[t])}}function Iu(){return(Iu=t(()=>{hi=Be(),bu(),gi="nostube_muted_pubkeys",yi="nostube:muted-pubkeys-changed"}))()}function Au(e){try{const t=localStorage.getItem(xi);if(!t)return ki;const n=JSON.parse(t);if("object"!=typeof n||null===n)return ki;const s=n[e];return Array.isArray(s)?s.filter(e=>"string"==typeof e):ki}catch{return ki}}function Pu({children:e}){const{user:t}=yu(),{pool:n,config:s}=iu(),r=Cr(),[a,o]=(0,bi.useState)(null),[i,c]=(0,bi.useState)(null),[l,u]=(0,bi.useState)(!1),d=t?.pubkey,f=(0,bi.useMemo)(()=>[...s.relays.filter(e=>e.tags.includes("read")).map(e=>e.url),Lo],[s.relays]);(0,bi.useEffect)(()=>{if(!d)return;u(!1);const e=ke(n,{bufferTime:0})({kind:vi,pubkey:d,relays:f}).subscribe({next:e=>r.add(e),complete:()=>u(!0)});return()=>e.unsubscribe()},[d,r,n,f]),(0,bi.useEffect)(()=>{if(!d||r.hasReplaceable(xr.Contacts,d))return;const e=ke(n,{bufferTime:0})({kind:xr.Contacts,pubkey:d,relays:f}).subscribe(e=>r.add(e));return()=>e.unsubscribe()},[d,r,n,f]),(0,bi.useEffect)(()=>{if(!d)return void o(null);const e=r.replaceable(vi,d).subscribe(e=>o(e??null));return()=>e.unsubscribe()},[d,r]),(0,bi.useEffect)(()=>{if(!d)return void c(null);const e=r.replaceable(xr.Contacts,d).subscribe(e=>c(e??null));return()=>e.unsubscribe()},[d,r]);const m=(0,bi.useMemo)(()=>a?a.tags.filter(e=>"p"===e[0]&&e[1]).map(e=>e[1]):ki,[a]),[p,h]=(0,bi.useState)(()=>d?Au(d):ki);(0,bi.useEffect)(()=>{h(d?Au(d):ki)},[d]),(0,bi.useEffect)(()=>{d&&a&&function(e,t){try{const n=localStorage.getItem(xi),s=n?JSON.parse(n):{},r="object"==typeof s&&null!==s?s:{};localStorage.setItem(xi,JSON.stringify({...r,[e]:t}))}catch{}}(d,m)},[d,a,m]);const g=(0,bi.useMemo)(()=>({followSetEvent:a,kind3Event:i,followSetLoaded:l,followedPubkeys:m,optimisticFollowedPubkeys:a?m:p}),[a,i,l,m,p]);return(0,wi.jsx)(Ni.Provider,{value:g,children:e})}function Tu(){return(0,bi.useContext)(Ni)}function Ru(){return(Ru=t(()=>{bi=Be(),Wt(),be(),os(),bu(),lu(),Jl(),wi=Q(),vi=10020,xi="nostr:follow-set-cache",ki=[],Ni=(0,bi.createContext)({followSetEvent:null,kind3Event:null,followSetLoaded:!1,followedPubkeys:ki,optimisticFollowedPubkeys:ki})}))()}function Uu(e){switch(e){case"shorts":return[34236,22];case"videos":return[34235,21];default:return[34235,34236,21,22]}}function $u(e){switch(e){case 21:case 34235:return"videos";case 22:case 34236:return"shorts";default:return"all"}}function Du(){return(Du=t(()=>{}))()}function Lu(){const{user:e}=yu(),{pool:t,config:n}=iu(),s=Cr(),{publish:r}=ku(),{followSetEvent:a,kind3Event:o,followSetLoaded:i,followedPubkeys:c}=Tu(),[l,u]=(0,ji.useState)(!1),[d,f]=(0,ji.useState)({phase:"idle",checked:0,total:0,withVideos:0}),m=(0,ji.useRef)(!1),p=(0,ji.useMemo)(()=>n.relays.filter(e=>e.tags.includes("read")).map(e=>e.url),[n.relays]),h=(0,ji.useMemo)(()=>n.relays.filter(e=>e.tags.includes("write")).map(e=>e.url),[n.relays]),g=!!a,y=!(!o||!o.tags.some(e=>"p"===e[0])),b=(0,ji.useMemo)(()=>o?o.tags.filter(e=>"p"===e[0]&&e[1]).length:0,[o]),w=(0,ji.useCallback)(async(t,n)=>{if(e?.pubkey){u(!0);try{const o=a,i=[];if(o){const e=o.tags.filter(e=>"p"===e[0]&&e[1]!==t);i.push(...e)}o?.tags.some(t=>"p"===t[0]&&t[1]===e.pubkey)||t===e.pubkey||i.push(["p",e.pubkey]),i.push(n?["p",t,n]:["p",t]);const c=await r({event:{kind:vi,created_at:ol(),content:"",tags:i},relays:h});s.add(c)}catch(o){throw o}finally{u(!1)}}},[e?.pubkey,a,r,h,s]),v=(0,ji.useCallback)(async t=>{if(e?.pubkey&&a){u(!0);try{const e=a.tags.filter(e=>"p"===e[0]&&e[1]!==t),n=await r({event:{kind:vi,created_at:ol(),content:"",tags:e},relays:h});s.add(n)}catch(n){throw n}finally{u(!1)}}},[e?.pubkey,a,r,h,s]),x=(0,ji.useCallback)(()=>{m.current=!0},[]);return{followedPubkeys:c,isLoading:l,addFollow:w,removeFollow:v,importFromKind3:(0,ji.useCallback)(async()=>{if(!e?.pubkey||!o)return!1;u(!0),m.current=!1;try{const n=o.tags.filter(e=>"p"===e[0]&&e[1]),i=n.map(e=>e[1]);if(0===i.length)return!1;f({phase:"checking",checked:0,total:i.length,withVideos:0});const l=[],u=Uu("all");for(let e=0;e({...e,phase:"idle"})),!1;const n=i.slice(e,e+Si),s=await new Promise(e=>{const s=[],r=new Set,a=t.req(p,{kinds:u,authors:n,limit:n.length}).subscribe({next:t=>{if("EOSE"===t.type)return a.unsubscribe(),void e(s);if("EVENT"!==t.type)return;const n=t.event;r.has(n.pubkey)||(r.add(n.pubkey),s.push(n))},error:()=>{a.unsubscribe(),e(s)}});setTimeout(()=>{a.unsubscribe(),e(s)},1e4)}),r=new Set(s.map(e=>e.pubkey));n.forEach(e=>{r.has(e)&&l.push(e)}),f({phase:"checking",checked:Math.min(e+Si,i.length),total:i.length,withVideos:l.length})}if(m.current)return f(e=>({...e,phase:"idle"})),!1;if(l.includes(e.pubkey)||l.push(e.pubkey),0===l.length)return f({phase:"done",checked:i.length,total:i.length,withVideos:0}),!0;f(e=>({...e,phase:"importing"}));const d=new Set(c),g=a?a.tags.filter(e=>"p"===e[0]&&e[1]):[];l.forEach(e=>{if(!d.has(e)){const t=n.find(t=>t[1]===e)?.[2];g.push(t?["p",e,t]:["p",e])}});const y=await r({event:{kind:vi,created_at:ol(),content:"",tags:g},relays:h});return s.add(y),f({phase:"done",checked:i.length,total:i.length,withVideos:l.length}),!0}catch(n){return f(e=>({...e,phase:"idle"})),!1}finally{u(!1)}},[e?.pubkey,o,a,c,r,h,s,t,p]),hasFollowSet:g,followSetLoaded:i,hasKind3Contacts:y,kind3PubkeyCount:b,importProgress:d,cancelImport:x}}function Bu(){return(Bu=t(()=>{Wt(),bu(),ji=Be(),lu(),Ru(),Nu(),dl(),Si=50}))()}function zu(){const{user:e}=yu(),{isLoading:t}=Lu(),{optimisticFollowedPubkeys:n}=Tu();return{data:(0,Ci.useMemo)(()=>n.map(e=>({pubkey:e})),[n]),isLoading:e&&t,enabled:!!e?.pubkey}}function Fu(){return(Fu=t(()=>{bu(),Ci=Be(),Bu(),Ru()}))()}function _u(e,t=[]){const{pool:n}=iu(),s=Cr(),[r,a]=(0,Ei.useState)(null),[o,i]=(0,Ei.useState)(!1),c=(0,Ei.useMemo)(()=>{const e=new Set([...t,Lo]);return Array.from(e)},[t]);return(0,Ei.useEffect)(()=>{if(!e)return;const t=ke(n)({kind:Mi,pubkey:e,relays:c}).subscribe({next:e=>{s.add(e)},complete:()=>{i(!0)}});return()=>t.unsubscribe()},[e,s,n,c]),(0,Ei.useEffect)(()=>{if(!e)return;const t=s.replaceable(Mi,e).subscribe(e=>{a(e??null)});return()=>t.unsubscribe()},[e,s]),{followedPubkeys:(0,Ei.useMemo)(()=>r?r.tags.filter(e=>"p"===e[0]&&e[1]).map(e=>e[1]):[],[r]),isLoading:!o&&!r,followSetEvent:r}}function Ou(){return(Ou=t(()=>{Ei=Be(),Wt(),be(),lu(),Jl(),Mi=10020}))()}function Wu(e){return!!e&&!(!e.lud16&&!e.lud06)}async function Vu(e){return fs(e)}function qu(e){const{recipientPubkey:t,amount:n,comment:s,relays:r,event:a,timestamp:o}=e,i=1e3*n;let c;return c=ra(a?{event:a,amount:i,comment:s,relays:r}:{pubkey:t,amount:i,comment:s,relays:r}),void 0!==o&&o>=0&&(c.tags=[...c.tags,["timestamp",Math.floor(o).toString()]]),c}async function Ju(e,t,n){const s=1e3*t,r=new URL(e);r.searchParams.set("amount",s.toString()),r.searchParams.set("nostr",JSON.stringify(n));const a=await fetch(r.toString());if(!a.ok)throw new Error(`LNURL request failed: ${a.status}`);const o=await a.json();if("ERROR"===o.status)throw new Error(o.reason||"LNURL request failed");if(!o.pr)throw new Error("No invoice returned from LNURL");return o.pr}function Hu(e){return bs(e)}function Ku(e){return e>=1e6?`${(e/1e6).toFixed(1).replace(/\.0$/,"")}M`:e>=1e3?`${(e/1e3).toFixed(1).replace(/\.0$/,"")}k`:e.toString()}function Gu(){return(Gu=t(()=>{jn()}))()}function Yu(e){try{return JSON.parse(localStorage.getItem(Ii)||"{}")[e]||[]}catch{return[]}}function Xu(e,t){try{const n=JSON.parse(localStorage.getItem(Ii)||"{}"),s=n[e]||[];s.includes(t)||(s.push(t),n[e]=s,localStorage.setItem(Ii,JSON.stringify(n)))}catch{}}function Zu(){return(Zu=t(()=>{Ii="nostube:replaced-event-ids"}))()}function Qu(e,t,n,s,r){Di.set(e,{totalSats:t,zapCount:n,upvoteCount:s,downvoteCount:r,timestamp:Date.now()}),function(){try{const e={};Di.forEach((t,n)=>{e[n]=t}),localStorage.setItem(Ui,JSON.stringify(e))}catch{}}()}function ed({eventId:e,authorPubkey:t,kind:n,relays:s=[],identifier:r}){const a=Cr(),{pool:o,config:i}=iu(),[c]=(0,Ai.useState)(()=>function(e){const t=Di.get(e);return t&&Date.now()-t.timestamp<$i?t:null}(e)),l=34235===n||34236===n,u=(0,Ai.useMemo)(()=>l&&r?`${n}:${t}:${r}`:null,[l,n,t,r]),d=(0,Ai.useMemo)(()=>a.getEvent(e),[a,e]),f=(0,Ai.useMemo)(()=>{if(!d)return[];const e=rr(d);return e?Array.from(e):[]},[d]),m=(0,Ai.useMemo)(()=>({id:e,pubkey:t,created_at:0,kind:n,tags:[],content:"",sig:""}),[e,t,n]),p=d??m,h=(0,Ai.useMemo)(()=>{const e=i.relays.filter(e=>e.tags.includes("read")).map(e=>e.url);return al([s,f,e])},[s,f,i.relays]),g=(0,Ai.useMemo)(()=>{const t=[e];if(u)for(const e of Yu(u))t.includes(e)||t.push(e);return t},[e,u]);(0,Ai.useEffect)(()=>{if(!e)return;const t=[{kinds:[9735],"#e":g}];u&&t.push({kinds:[9735],"#a":[u]});const n=o.subscription(zo,t).subscribe({next:e=>{"string"!=typeof e&&"kind"in e&&a.add(e)},error:e=>{}});return()=>n.unsubscribe()},[e,g,u,o,a]);const y=Dt(()=>a.timeline({kinds:[9735],"#e":g}),[a,g]),b=Dt(()=>u?a.timeline({kinds:[9735],"#a":[u]}):void 0,[a,u]),w=(0,Ai.useMemo)(()=>{const e=y||[],t=b||[],n=new Set,s=[];for(const r of[...e,...t])n.has(r.id)||(n.add(r.id),s.push(r));return s},[y,b]),{totalSats:v,zapCount:x}=(0,Ai.useMemo)(()=>{if(!w||0===w.length)return{totalSats:0,zapCount:0};let e=0;const t=new Set;for(const n of w){const s=n.tags.find(e=>"bolt11"===e[0])?.[1];if(s&&!t.has(s)){t.add(s);try{e+=Hu(s)}catch{}}}return{totalSats:e,zapCount:t.size}},[w]),k=te(Nt,[p]),N=(0,Ai.useMemo)(()=>k||[],[k]);(0,Ai.useEffect)(()=>{if(!e||0===h.length)return;const t=Zt(o,{eventStore:a,useSeenRelays:!0})(p,h).subscribe({next:()=>{},error:e=>{}});return()=>t.unsubscribe()},[e,o,a,p,h]);const{upvoteCount:j,downvoteCount:S}=(0,Ai.useMemo)(()=>{const e=new Set,t=new Set;for(const n of N)Ti(n.content)?t.add(n.pubkey):e.add(n.pubkey);return{upvoteCount:e.size,downvoteCount:t.size}},[N]);(0,Ai.useEffect)(()=>{e&&(v>0||x>0||j>0||S>0)&&Qu(e,v,x,j,S)},[e,v,x,j,S]);const C=w&&w.length>0,E=N&&N.length>0,M=C||E;return{totalSats:C?v:c?.totalSats??0,zapCount:C?x:c?.zapCount??0,upvoteCount:E?j:c?.upvoteCount??0,downvoteCount:E?S:c?.downvoteCount??0,hasUpvoted:!1,hasDownvoted:!1,zaps:w||[],reactions:N||[],isLoading:!M&&!c}}function td(e,t){return(0,Ai.useMemo)(()=>{if(!t)return{hasUpvoted:!1,hasDownvoted:!1};let n=!1,s=!1;for(const r of e)r.pubkey===t&&(Ti(r.content)?s=!0:n=!0);return{hasUpvoted:n,hasDownvoted:s}},[e,t])}function nd(){return(nd=t(()=>{Ai=Be(),Wt(),xa(),xs(),Gu(),lu(),be(),dl(),Zu(),Jl(),Pi=new Set(["-","👎","💩","❌","🚫","📉","🤮","🗑️","💀"]),Ti=e=>Pi.has(e),Ri=e=>!Pi.has(e),Ui="event-stats-cache",$i=36e5,Di=new Map,function(){try{const e=localStorage.getItem(Ui);if(e){const t=JSON.parse(e),n=Date.now();for(const[e,s]of Object.entries(t))n-s.timestamp<$i&&Di.set(e,s)}}catch{}}()}))()}function sd(){const{user:e}=yu(),t=Cr(),{pool:n,config:s}=iu(),[r,a]=(0,Li.useState)(null),o=(0,Li.useMemo)(()=>s.relays.filter(e=>e.tags.includes("read")).map(e=>e.url),[s.relays]),i=Dt(()=>t.timeline([{kinds:[7],authors:e?.pubkey?[e.pubkey]:[]}]),[t,e?.pubkey]),c=(0,Li.useMemo)(()=>i??[],[i]);(0,Li.useEffect)(()=>{if(!e?.pubkey||r===e.pubkey)return;const s={kinds:[7],authors:[e.pubkey]},i=w(n,o,s,{eventStore:t,limit:500})().subscribe({next:e=>{t.add(e)},complete:()=>{a(e.pubkey)},error:t=>{a(e.pubkey)}});return()=>{i.unsubscribe()}},[e?.pubkey,n,o,t,r]);const{likedEventIds:l,likedAddresses:u}=(0,Li.useMemo)(()=>{if(!e||0===c.length)return{likedEventIds:[],likedAddresses:[]};const t=[...c].filter(e=>Ri(e.content)).sort((e,t)=>t.created_at-e.created_at),n=[],s=[];for(const e of t){const t=e.tags.find(e=>"e"===e[0]);t?.[1]&&n.push(t[1]);const r=e.tags.find(e=>"a"===e[0]);r?.[1]&&s.push(r[1])}return{likedEventIds:Array.from(new Set(n)),likedAddresses:Array.from(new Set(s))}},[e,c]),d=Boolean(e?.pubkey&&r===e.pubkey);return{data:l,likedAddresses:u,isLoading:Boolean(e&&0===c.length&&!d),enabled:!!e}}function rd(){return(rd=t(()=>{bu(),Wt(),Li=Be(),lu(),be(),nd()}))()}function ad(){const e=uu().join(",");return(0,Bi.useMemo)(()=>e?e.split(","):[],[e])}function od(){return(od=t(()=>{Bi=Be(),du()}))()}function id(e){const t=Cr(),{pool:n}=iu(),s=ad(),[r,a]=(0,zi.useState)(null),o=Dt(()=>t.timeline([{kinds:[7],authors:e?[e]:[]}]),[t,e]),i=(0,zi.useMemo)(()=>o??[],[o]),c=Dt(()=>t.timeline([{kinds:[9734],authors:e?[e]:[]}]),[t,e]),l=(0,zi.useMemo)(()=>c??[],[c]);(0,zi.useEffect)(()=>{if(!e||r===e)return;const o=w(n,s,{kinds:[7],authors:[e]},{eventStore:t,limit:200}),i=w(n,s,{kinds:[9734],authors:[e]},{eventStore:t,limit:200});let c=0;const l=()=>{c++,2===c&&a(e)},u=o().subscribe({next:e=>t.add(e),complete:l,error:()=>l()}),d=i().subscribe({next:e=>t.add(e),complete:l,error:()=>l()});return()=>{u.unsubscribe(),d.unsubscribe()}},[e,n,s,t,r]);const u=e=>{const t=e.tags.find(e=>"k"===e[0]);if(t?.[1]){const e=parseInt(t[1],10);if(Fi.has(e))return!0}const n=e.tags.find(e=>"a"===e[0]);if(n?.[1]){const e=n[1].split(":");if(e.length>=1){const t=parseInt(e[0],10);if(Fi.has(t))return!0}}return!1},d=(0,zi.useMemo)(()=>{if(!e)return[];const t=new Set;for(const e of i)if(Ri(e.content)&&u(e)){const n=e.tags.find(e=>"e"===e[0]);n?.[1]&&t.add(n[1])}for(const e of l)if(u(e)){const n=e.tags.find(e=>"e"===e[0]);n?.[1]&&t.add(n[1])}return Array.from(t)},[e,i,l]);return{eventIds:d,isLoading:Boolean(e&&!Boolean(e&&r===e)),count:d.length}}function cd(){return(cd=t(()=>{Wt(),zi=Be(),lu(),be(),od(),nd(),Fi=new Set(Uu("all"))}))()}function ld({videoId:e}){const t=Cr();return Dt(()=>t.timeline([{kinds:[1],"#e":[e]},{kinds:[1111],"#E":[e]}]).pipe(hn(e=>e.length)),[t,e])??0}function ud(){return(ud=t(()=>{Wt(),Se()}))()}function dd(){return(dd=t(()=>{Wt(),_i=Be(),Oi=({p:e,e:t,x:n}={})=>{const s=Cr(),r=(0,_i.useMemo)(()=>{const s={kinds:[1984]};return e&&(s["#p"]=[e]),t&&(s["#e"]=[t]),n&&(s["#x"]=[n]),s},[e,t,n]),a=Dt(()=>s.timeline([r]),[s,r]),o=(0,_i.useMemo)(()=>a??[],[a]);return{data:(0,_i.useMemo)(()=>o.map(e=>{const t={justification:e.content},n=e.tags.find(e=>"p"===e[0]&&e[1]);n&&(t.pubkey=n[1],t.pubkeyReason=n[2]);const s=e.tags.find(e=>"e"===e[0]&&e[1]);s&&(t.eventId=s[1],t.eventReason=s[2]);const r=e.tags.find(e=>"x"===e[0]&&e[1]);return r&&(t.hash=r[1],t.hashReason=r[2]),t}),[o]),isLoading:0===o.length}}}))()}function fd(){return(fd=t(()=>{Wi="b7c6f6915cfa9a62fff6a1f02604de88c23c6c6c6d1b8f62c7cc10749f307e81",Vi=30078,qi="nostube-presets",Ji={defaultRelays:[],defaultBlossomProxy:void 0,blockedPubkeys:[],nsfwPubkeys:[],blockedEvents:[]}}))()}function md(e,t={}){const n=Cr(),s=uu(),{relays:r=s,enabled:a=!0}=t,[o,i]=(0,Hi.useState)(!0),c=(0,Hi.useMemo)(()=>e?Array.isArray(e)?e:[e]:null,[e]),l=Dt(()=>c&&a?n.timeline(c):Dr([]),[n,c,a]),u=(0,Hi.useMemo)(()=>l??[],[l]),d=(0,Hi.useMemo)(()=>r.slice().sort().join(","),[r]),f=(0,Hi.useRef)(r);return(0,Hi.useEffect)(()=>{f.current=r}),(0,Hi.useEffect)(()=>{if(!c||!a||0===f.current.length)return void i(!1);i(!0);let e=c.length;const t=()=>{e--,0===e&&i(!1)},s=c.map(e=>{String(ul({filter:e,relays:d}));return tu(0,e,f.current)().subscribe({next:e=>n.add(e),complete:t,error:t})});return()=>s.forEach(e=>e.unsubscribe())},[c,a,d,n]),{events:u,isLoading:o}}function pd(){return(pd=t(()=>{Wt(),Hi=Be(),fr(),nu(),du(),dl()}))()}function hd(e){try{const t=e.tags.find(e=>"name"===e[0]),n=e.tags.find(e=>"description"===e[0]);let s;try{s=JSON.parse(e.content)}catch{s=Ji}return{name:t?.[1]||"Unnamed Preset",description:n?.[1],pubkey:e.pubkey,createdAt:e.created_at,defaultRelays:s.defaultRelays||[],defaultBlossomProxy:s.defaultBlossomProxy,blockedPubkeys:s.blockedPubkeys||[],nsfwPubkeys:s.nsfwPubkeys||[],blockedEvents:s.blockedEvents||[]}}catch(t){return null}}function gd(){const{config:e}=iu(),t=(0,Ki.useMemo)(()=>{const t=new Set;return e.relays.forEach(e=>t.add(e.url)),Do.forEach(e=>t.add(e.url)),t.add(Lo),Array.from(t)},[e.relays]),{events:n,isLoading:s}=md(Gi,{relays:t});return{presets:(0,Ki.useMemo)(()=>{const e=new Map;for(const t of n){const n=hd(t);if(n){const t=e.get(n.pubkey);(!t||n.createdAt>t.createdAt)&&e.set(n.pubkey,n)}}return Array.from(e.values()).sort((e,t)=>t.createdAt-e.createdAt)},[n]),isLoading:s}}function yd(){return(yd=t(()=>{Ki=Be(),lu(),Jl(),fd(),pd(),Gi={kinds:[Vi],"#d":[qi],limit:100}}))()}function bd(){return(bd=t(()=>{Yi="nostube_preset_cache",Xi=36e5,Zi=1e4}))()}function wd({children:e}){const t=Cr(),{pool:n,config:s,updateConfig:r}=iu(),a=s.selectedPresetPubkey??"b7c6f6915cfa9a62fff6a1f02604de88c23c6c6c6d1b8f62c7cc10749f307e81",[o]=(0,Qi.useState)(()=>function(e){try{const t=localStorage.getItem(Yi);if(!t)return null;const n=JSON.parse(t);if(n.pubkey!==e)return localStorage.removeItem(Yi),null;const s=Date.now()-n.cachedAt>Xi;return{preset:n.preset,stale:s}}catch{return null}}(a)),i=o?.preset??null,[c,l]=(0,Qi.useState)(()=>i?"loaded":"loading"),[u,d]=(0,Qi.useState)(0),f=Dt(()=>t.replaceable(Vi,a,qi).pipe(hn(e=>e??void 0)),[t,a]),m=(0,Qi.useMemo)(()=>{const e=new Set;return s.relays.forEach(t=>e.add(t.url)),Do.forEach(t=>e.add(t.url)),e.add(Lo),Array.from(e)},[s.relays]);(0,Qi.useEffect)(()=>{if(!a||0===m.length)return;let e=!1;const s=ke(n,{eventStore:t,bufferTime:0})({kind:Vi,pubkey:a,identifier:qi,relays:m}).subscribe({next:n=>{n&&(e=!0,t.add(n),l("loaded"))},error:e=>{}}),r=setTimeout(()=>{e||i||l("error")},Zi);return()=>{s.unsubscribe(),clearTimeout(r)}},[a,m,n,t,u,i]);const p=(0,Qi.useMemo)(()=>{if(f){const e=hd(f);if(e)return function(e,t){try{const n={preset:e,pubkey:t,cachedAt:Date.now()};localStorage.setItem(Yi,JSON.stringify(n))}catch{}}(e,a),e}return i||null},[f,i,a]),h=(0,Qi.useCallback)(e=>{r(t=>({...t,selectedPresetPubkey:e})),localStorage.removeItem(Yi),l("loading")},[r]),g=(0,Qi.useCallback)(()=>{l("loading"),d(e=>e+1)},[]),y=p||Ji,b=(0,Qi.useMemo)(()=>({preset:p,presetContent:y,selectedPubkey:a,setSelectedPreset:h}),[p,y,a,h]);return"loading"!==c||i?"error"!==c||p?(0,ec.jsx)(tc.Provider,{value:b,children:e}):(0,ec.jsxs)("div",{className:"flex min-h-screen flex-col items-center justify-center gap-4 bg-background text-foreground",children:[(0,ec.jsx)(as,{className:"h-12 w-12 text-destructive"}),(0,ec.jsxs)("div",{className:"text-center",children:[(0,ec.jsx)("h2",{className:"text-lg font-semibold",children:"Failed to load configuration"}),(0,ec.jsx)("p",{className:"mt-1 text-sm text-muted-foreground",children:"Could not connect to Nostr relays to load app preset."})]}),(0,ec.jsxs)(Ja,{onClick:g,variant:"outline",className:"mt-2",children:[(0,ec.jsx)(Zr,{className:"mr-2 h-4 w-4"}),"Retry"]})]}):(0,ec.jsxs)("div",{className:"flex min-h-screen flex-col items-center justify-center gap-4 bg-background text-foreground",children:[(0,ec.jsx)(Ze,{className:"h-8 w-8 animate-spin text-muted-foreground"}),(0,ec.jsx)("p",{className:"text-muted-foreground",children:"Loading app configuration..."})]})}function vd(){const e=(0,Qi.useContext)(tc);if(!e)throw new Error("usePresetContext must be used within a PresetProvider");return e}function xd(){return(xd=t(()=>{Qi=Be(),Wt(),Se(),be(),lu(),Jl(),fd(),yd(),Fs(),Kr(),Gn(),ml(),bd(),ec=Q(),tc=(0,Qi.createContext)(null)}))()}function kd(){return(kd=t(()=>{xd()}))()}function Nd(){return(Nd=t(()=>{nc=Be(),dd(),kd(),Iu(),sc=()=>{const{data:e}=Oi({}),{presetContent:t}=vd(),{mutedPubkeys:n}=Mu();return(0,nc.useMemo)(()=>{const s=t.blockedPubkeys.reduce((e,t)=>({...e,[t]:!0}),{}),r=n.reduce((e,t)=>({...e,[t]:!0}),{});if(!e)return{...s,...r};const a=e.filter(e=>!!e.pubkey&&("illegal"===e.pubkeyReason||"illegal"===e.eventReason)).reduce((e,t)=>(t.pubkey&&!e[t.pubkey]&&(e[t.pubkey]=t),e),{});return{...s,...r,...a}},[e,t.blockedPubkeys,n])}}))()}function jd(e){const t=e.components?.validators;if(!t||"object"!=typeof t)return null;const n=[];for(const[s,r]of Object.entries(t)){const e=s.includes(":")?s.slice(s.indexOf(":")+1):s;ic.has(e)&&n.push(r.score)}return 0===n.length?null:n.reduce((e,t)=>e+t,0)/n.length}async function Sd(e){if(cc)return cc;const t=new Fn(e),n=new Xr(ac),s=new hr({serverPubkey:oc,signer:t,relayHandler:n,isStateless:!0}),r=new kr({name:"nostube",version:"1.0.0"});try{await r.connect(s)}catch(a){throw a}return cc=r,lc=s,uc=n,r}async function Cd(e,t){if(0===t.length)return[];try{return function(e){if(!e)return[];if(e.structuredContent){const t=Ed(e.structuredContent);if(t.length>0)return t}try{const t=function(e){if(!e)return null;if("content"in e&&Array.isArray(e.content)){const t=e.content.find(e=>"text"===e.type);if(t?.text)return t.text}return null}(e);return t?Ed(JSON.parse(t)):[]}catch{return[]}}(await e.callTool({name:"calculate_trust_scores",arguments:{targetPubkeys:t}}))}catch(n){return[]}}function Ed(e){return e?Array.isArray(e)?e:Array.isArray(e.trustScores)?e.trustScores:e.trustScore?[e.trustScore]:[]:[]}function Md(){return(Md=t(()=>{tr(),Br(),Js(),Kn(),os(),rc="npub16w48u4xvtlp7ywgfsjlud74tlgdfx9s33scdlafmgl3a40n9tthsu6ty8g",ac=["wss://relay2.contextvm.org","wss://relay.contextvm.org","wss://relay.nostu.be"],oc=er.decode(rc).data,ic=new Set(["video_creator_activity","video_viewer_engagement","video_creator_comments"]),cc=null,lc=null,uc=null}))()}function Id(){return hc||(hc=new Promise((e,t)=>{const n=indexedDB.open(dc,fc);n.onupgradeneeded=()=>{const e=n.result;e.objectStoreNames.contains(mc)||e.createObjectStore(mc,{keyPath:"pubkey"})},n.onsuccess=()=>e(n.result),n.onerror=()=>{hc=null,t(n.error)}}))}async function Ad(e){if(0!==e.length)try{const t=await Id(),n=Date.now();return new Promise((s,r)=>{const a=t.transaction(mc,"readwrite"),o=a.objectStore(mc);for(const t of e){const e={pubkey:t.targetPubkey,result:t,timestamp:n};o.put(e)}a.oncomplete=()=>s(),a.onerror=()=>r(a.error)})}catch{}}function Pd(){return(Pd=t(()=>{dc="nostube-trust-scores",fc=1,mc="scores",pc=864e5,hc=null}))()}function Td(e){return yc.get(e)??null}function Rd(e){for(const t of e)yc.set(t.targetPubkey,t)}function Ud(e){return bc.add(e),()=>bc.delete(e)}function $d(){bc.forEach(e=>e())}function Dd(e){return new Promise(t=>setTimeout(t,e))}function Ld(e){const t=[];let n=!1;for(const s of e){const e=(Cc.get(s)??0)+1;Cc.set(s,e),e{for(const e of t)jc.add(e);zd()},xc)}function Bd(e){e&&""!==e.trim()&&(Td(e)||jc.has(e)||(jc.add(e),function(){Nc&&clearTimeout(Nc);Nc=setTimeout(()=>{Nc=null,async function(){if(0===jc.size)return;const e=Array.from(jc);jc.clear();try{const{results:t,stale:n}=await async function(e){const t=new Map,n=new Set;if(0===e.length)return{results:t,stale:n};try{const s=await Id(),r=Date.now();return new Promise((a,o)=>{const i=s.transaction(mc,"readonly").objectStore(mc);let c=0;for(const s of e){const l=i.get(s);l.onsuccess=()=>{const o=l.result;o?(t.set(s,o.result),r-o.timestamp>=pc&&n.add(s)):t.set(s,null),c++,c===e.length&&a({results:t,stale:n})},l.onerror=()=>o(l.error)}})}catch{for(const n of e)t.set(n,null);return{results:t,stale:n}}}(e),s=[];for(const[e,a]of t)a?yc.set(e,a):s.push(e);t.size>s.length&&$d();const r=[...s,...n];if(r.length>0){for(const e of r)jc.add(e);zd()}}catch{for(const t of e)jc.add(t);zd()}}()},wc)}()))}async function zd(){if(0!==jc.size&&Ec&&!Mc){Mc=!0;try{for(;jc.size>0&&Ec;){const t=Array.from(jc);jc.clear();const n=[];for(let e=0;e0&&await Dd(xc);try{const e=(await Cd(s,a)).filter(e=>e&&"number"==typeof e.score&&"string"==typeof e.targetPubkey);Rd(e);for(const n of e)Sc.delete(n.targetPubkey),Cc.delete(n.targetPubkey);await Ad(e);const t=new Set(e.map(e=>e.targetPubkey));Ld(a.filter(e=>!t.has(e))),$d()}catch(e){Ld(a)}}}}catch(e){}finally{Mc=!1}}}function Fd(){const e=sessionStorage.getItem(Ic);if(e)return e;const t=Hn(),n=Nn(t);return sessionStorage.setItem(Ic,n),n}function _d(){const{user:e}=yu(),t=e?.pubkey,n=(0,gc.useRef)(void 0);(0,gc.useEffect)(()=>{const s=n.current;n.current=t,s&&t&&s!==t&&(yc.clear(),jc.clear(),Sc.clear(),Cc.clear(),async function(){try{const e=await Id();return new Promise((t,n)=>{const s=e.transaction(mc,"readwrite");s.objectStore(mc).clear(),s.oncomplete=()=>t(),s.onerror=()=>n(s.error)})}catch{}}(),$d()),Ec=e&&e.signer instanceof qe?Nn(e.signer.key):Fd(),async function(){if(cc){try{await cc.close()}catch{}cc=null}if(lc){try{await lc.close()}catch{}lc=null}if(uc){try{await uc.disconnect()}catch{}uc=null}}(),jc.size>0&&zd(),async function(){const e=7*pc;try{const t=await Id(),n=Date.now();return new Promise((s,r)=>{const a=t.transaction(mc,"readwrite"),o=a.objectStore(mc).openCursor();o.onsuccess=()=>{const t=o.result;if(t){const s=t.value;n-s.timestamp>=e&&t.delete(),t.continue()}},a.oncomplete=()=>s(),a.onerror=()=>r(a.error)})}catch{}}()},[t])}function Od(e){const[,t]=(0,gc.useState)(0);(0,gc.useEffect)(()=>Ud(()=>t(e=>e+1)),[]),(0,gc.useEffect)(()=>{e&&Bd(e)},[e]);const n=e?Td(e):null,s=!!e&&(!n&&!Sc.has(e));return{score:n?.score??null,globalScore:n?jd(n):null,isLoading:s}}function Wd(e){const[,t]=(0,gc.useState)(0);(0,gc.useEffect)(()=>Ud(()=>t(e=>e+1)),[]),(0,gc.useEffect)(()=>{e&&(Td(e)||async function(e){try{const t=await Id();return new Promise((n,s)=>{const r=t.transaction(mc,"readonly").objectStore(mc).get(e);r.onsuccess=()=>{const e=r.result;n(e?e.result:null)},r.onerror=()=>s(r.error)})}catch{return null}}(e).then(t=>{t?(yc.set(e,t),$d()):Bd(e)}))},[e]);const n=e?Td(e):null;return{result:n,isLoading:!!e&&(!n&&!!Ec)}}function Vd(e){const[t,n]=(0,gc.useState)(0);(0,gc.useEffect)(()=>Ud(()=>n(e=>e+1)),[]);const s=e.join(",");return(0,gc.useEffect)(()=>{for(const t of e)Bd(t)},[s]),(0,gc.useMemo)(()=>{const t=new Map;for(const n of e){const e=Td(n);t.set(n,e?.score??null)}return t},[s,t])}function qd(e){const[t,n]=(0,gc.useState)(0);(0,gc.useEffect)(()=>Ud(()=>n(e=>e+1)),[]);const s=e.join(",");return(0,gc.useEffect)(()=>{for(const t of e)Bd(t)},[s]),(0,gc.useMemo)(()=>{const t=new Map;for(const n of e){const e=Td(n);t.set(n,e?jd(e):null)}return t},[s,t])}function Jd(){return(Jd=t(()=>{gc=Be(),qs(),os(),F(),bu(),Md(),Pd(),yc=new Map,bc=new Set,wc=300,vc=20,xc=1e4,kc=3,Nc=null,jc=new Set,Sc=new Set,Cc=new Map,Ec=null,Mc=!1,Ic="trust-score-ephemeral-key"}))()}function Hd(e,t,n){const s=n?.serialize||JSON.stringify,r=n?.deserialize||JSON.parse,[a,o]=(0,Ac.useState)(()=>{try{const n=localStorage.getItem(e);return n?r(n):t}catch(n){return t}});return(0,Ac.useEffect)(()=>{const t=t=>{if(t.key===e&&null!==t.newValue)try{o(r(t.newValue))}catch(n){}};return window.addEventListener("storage",t),()=>window.removeEventListener("storage",t)},[e,r]),[a,t=>{try{const n=t instanceof Function?t(a):t;o(n),localStorage.setItem(e,s(n))}catch(n){}}]}function Kd(){return(Kd=t(()=>{Ac=Be()}))()}function Gd(e){zc=Lc(zc,e),Bc.forEach(e=>{e(zc)})}function Yd({...e}){const t=(Uc=(Uc+1)%Number.MAX_SAFE_INTEGER).toString(),n=()=>Gd({type:"DISMISS_TOAST",toastId:t});return Gd({type:"ADD_TOAST",toast:{...e,id:t,open:!0,onOpenChange:e=>{e||n()}}}),{id:t,dismiss:n,update:e=>Gd({type:"UPDATE_TOAST",toast:{...e,id:t}})}}function Xd(){const[e,t]=Pc.useState(zc);return Pc.useEffect(()=>(Bc.push(t),()=>{const e=Bc.indexOf(t);e>-1&&Bc.splice(e,1)}),[e]),{...e,toast:Yd,dismiss:e=>Gd({type:"DISMISS_TOAST",toastId:e})}}function Zd(){return(Zd=t(()=>{Pc=e(Be(),1),Tc=1,Rc=1e6,Uc=0,$c=new Map,Dc=e=>{if($c.has(e))return;const t=setTimeout(()=>{$c.delete(e),Gd({type:"REMOVE_TOAST",toastId:e})},Rc);$c.set(e,t)},Lc=(e,t)=>{switch(t.type){case"ADD_TOAST":return{...e,toasts:[t.toast,...e.toasts].slice(0,Tc)};case"UPDATE_TOAST":return{...e,toasts:e.toasts.map(e=>e.id===t.toast.id?{...e,...t.toast}:e)};case"DISMISS_TOAST":{const{toastId:n}=t;return n?Dc(n):e.toasts.forEach(e=>{Dc(e.id)}),{...e,toasts:e.toasts.map(e=>e.id===n||void 0===n?{...e,open:!1}:e)}}case"REMOVE_TOAST":return void 0===t.toastId?{...e,toasts:[]}:{...e,toasts:e.toasts.filter(e=>e.id!==t.toastId)}}},Bc=[],zc={toasts:[]}}))()}function Qd(){const[e,t]=Hd(_c,{}),{toast:n}=Xd();return{markVideoAsMissing:(0,Fc.useCallback)((s,r)=>{const a=Date.now(),o=e[s],i=o?o.attemptCount+1:1,c=Math.min(i-1,Wc.length-1),l=a+Wc[c];t(e=>({...e,[s]:{failedAt:a,urls:r,retryAfter:l,attemptCount:i}})),n({title:"Video unavailable",description:"This video could not be loaded from any source. It will be filtered from your feed.",variant:"destructive"})},[e,t,n]),isVideoMissing:(0,Fc.useCallback)(t=>{const n=e[t];if(!n)return!1;const s=Date.now();return s-n.failedAt>Vc||!(n.retryAfter&&s>=n.retryAfter)},[e]),clearMissingVideo:(0,Fc.useCallback)(e=>{t(t=>{const n={...t};return delete n[e],n}),n({title:"Video restored",description:"The video has been removed from the missing list."})},[t,n]),getAllMissingVideos:(0,Fc.useCallback)(()=>e,[e]),clearAllMissing:(0,Fc.useCallback)(()=>{t({}),n({title:"List cleared",description:"All missing videos have been removed from the list."})},[t,n]),getMissingCount:(0,Fc.useCallback)(()=>{const t=Date.now();return Object.entries(e).filter(([e,n])=>t-n.failedAt>Vc||!(n.retryAfter&&t>=n.retryAfter)).length},[e]),getVideosReadyForRetry:(0,Fc.useCallback)(()=>{const t=Date.now();return Object.entries(e).filter(([e,n])=>n.retryAfter&&t>=n.retryAfter).map(([e])=>e)},[e])}}function ef(){return(ef=t(()=>{Fc=Be(),Kd(),Zd(),_c="missing-videos",Wc=[1*(Oc=36e5),6*Oc,24*Oc],Vc=7*(24*Oc)}))()}function tf(e,t){if(5!==e.kind)return!1;if(e.pubkey!==t.pubkey)return!1;if(e.created_at"e"===e[0]).map(e=>e[1]).includes(t.id))return!0;if(t.kind>=3e4&&t.kind<4e4){const n=t.tags.find(e=>"d"===e[0])?.[1]||"",s=`${t.kind}:${t.pubkey}:${n}`;if(e.tags.filter(e=>"a"===e[0]).map(e=>e[1]).includes(s))return!0}return!1}function nf(e,t){return t.filter(t=>!function(e,t){const n=e.getByFilters({kinds:[5],authors:[t.pubkey]});for(const s of n)if(tf(s,t))return!0;return!1}(e,t))}function sf(){return(sf=t(()=>{}))()}function rf(e){if(e)try{return function(e,t,n){const s=function(e,t,n){const s=String.fromCharCode(120,1),r=[],a=String.fromCharCode(137,80,78,71,13,10,26,10),o=String.fromCharCode(0);let i,c,l;for(i=0;i<256;i++){for(c=i,l=0;l<8;l++)1&c?c=3988292384^c>>>1:c>>>=1;r[i]=c}function u(e){const t=65535;let n,s="";for(let r=0;r>>8),s+=String.fromCharCode(255&~n,(65280&~n)>>>8),s+=e.substring(r,r+n)}return s}function d(e){const t=65521;let n=1,s=0;for(let r=0;r>>8;return s}function m(e){return 4294967295^f(4294967295,e)}function p(e){return String.fromCharCode((4278190080&e)>>>24,(16711680&e)>>>16,(65280&e)>>>8,255&e)}function h(e,t,n){const s=m(t+n);return p(e)+t+n+p(s)}function g(e,t){return h(13,"IHDR",p(e)+p(t)+String.fromCharCode(8)+String.fromCharCode(6)+String.fromCharCode(0)+String.fromCharCode(0)+String.fromCharCode(0))}const y=h(0,"IEND",""),b=g(e,t);let w,v="";for(let N=0;NString.fromCharCode(e)).join(""));return"data:image/png;base64,"+("undefined"!=typeof Buffer?Buffer.from(function(e){const t=new Uint8Array(e.length);for(let n=0;n{js()}))()}function of(e){try{const t=er.decode(e);return"nevent"===t.type?t.data:"note"===t.type?{id:t.data,relays:[]}:null}catch(t){return null}}function cf(e){try{const t=er.decode(e);if("nevent"===t.type||"note"===t.type){const t=of(e);return t?{type:"event",data:t}:null}if("naddr"===t.type){const t=uf(e);return t?{type:"address",data:t}:null}return null}catch(t){return null}}function lf(e){try{const t=er.decode(e);return"nprofile"===t.type?t.data:"npub"===t.type?{pubkey:t.data,relays:[]}:null}catch(t){return null}}function uf(e){try{const t=er.decode(e);return"naddr"===t.type?t.data:null}catch(t){return null}}function df(){return(df=t(()=>{os()}))()}function ff(e){const t=e.split(".");if(4!==t.length||t.some(e=>!/^\d+$/.test(e)))return null;const n=t.map(Number);return n.every(e=>e>=0&&e<=255)?n:null}function mf(e){const[t,n]=e;return 127===t?"blocked-loopback":10===t||0===t||172===t&&n>=16&&n<=31||192===t&&168===n||169===t&&254===n||100===t&&n>=64&&n<=127||t>=224?"blocked-private-network":null}function pf(e,t){let n;try{n=new URL(e)}catch{return"blocked-invalid"}if("http:"!==n.protocol&&"https:"!==n.protocol)return"blocked-unsupported-scheme";if(n.username||n.password)return"blocked-credentials";if("configured-service"===t)return"allowed";const s=n.hostname.toLowerCase();return"localhost"===s||s.endsWith(".localhost")?"blocked-loopback":function(e){const t=ff(e);if(t)return mf(t);const n=e.replace(/^\[|\]$/g,"").toLowerCase();if(!n.includes(":"))return null;if("::1"===n)return"blocked-loopback";if(n.startsWith("::ffff:")){const e=ff(n.slice(7));return e?mf(e):"blocked-private-network"}return/^(?:fc|fd)[0-9a-f]{0,2}(?::|$)/.test(n)||/^fe[89ab][0-9a-f]?(?::|$)/.test(n)||"::"===n||n.startsWith("::ffff:0:")?"blocked-private-network":null}(s)??"allowed"}function hf(e){return"allowed"===pf(e,"event")}function gf(e){return"allowed"===pf(e,"configured-service")}function yf(e){return hf(e)}function bf(){return(bf=t(()=>{}))()}function wf(e){return e&&hf(e)?e:void 0}function vf(e){const t=e.find(e=>"origin"===e[0]);if(t)return`${t[1]}:${t[2]}`;const n=e.find(e=>"e"===e[0]);if(n)return`nostr:${n[1]}`;const s=e.find(e=>"a"===e[0]);if(s)return`nostr:${s[1]}`;const r=e.find(e=>"p"===e[0]);if(r)return`nostr:${r[1]}`;const a=e.find(e=>"r"===e[0]);return a?a[1]:""}function xf(e){const t=e.find(e=>"origin"===e[0]);return t?t[1]:e.find(e=>["e","p","a"].includes(e[0]))?"nostr":"web"}function kf(e){const t=Jc.find(t=>t.name===e);return t?t.color:"nostr"===e?"bg-purple-600 text-white":"bg-gray-500 text-white"}function Nf(e){const t=e.trim();if(!t)return null;const n=[];for(const r of Jc){const e=t.match(r.regex);if(e&&e[1])return n.push(["r",t]),n.push(["origin",r.name,e[1],t]),n}const s=t.match(Hc);if(s&&s[1]){const e=s[1];try{if(64===e.length&&/^[a-f0-9]{64}$/i.test(e))return n.push(["e",e]),n;const t=function(e){try{return er.decode(e)}catch(t){return null}}(e);if(!t)return null;switch(t.type){case"npub":n.push(["p",t.data]);break;case"nprofile":n.push(["p",t.data.pubkey]),t.data.relays?.[0]&&n[0].push(t.data.relays[0]);break;case"note":n.push(["e",t.data]);break;case"nevent":n.push(["e",t.data.id]),t.data.relays?.[0]&&n[0].push(t.data.relays[0]);break;case"naddr":n.push(["a",`${t.data.kind}:${t.data.pubkey}:${t.data.identifier}`]),t.data.relays?.[0]&&n[0].push(t.data.relays[0])}if(n.length>0)return n}catch{}}return Kc.test(t)?(n.push(["r",t]),n):null}function jf(){return(jf=t(()=>{df(),Jc=[{name:"youtube",color:"bg-[#FF0000] text-white",regex:qc=/(?:youtube\.com\/(?:[^/]+\/.+\/|(?:v|e(?:mbed)?)\/|.*[?&]v=)|youtu\.be\/|youtube\.com\/shorts\/)([^"&?/\s]{11})/i},{name:"tiktok",color:"bg-[#000000] text-white",regex:/tiktok\.com\/.*\/video\/(\d+)/i},{name:"instagram",color:"bg-[#E1306C] text-white",regex:/instagram\.com\/(?:p|reels|reel)\/([a-zA-Z0-9_-]+)/i},{name:"twitter",color:"bg-[#1DA1F2] text-white",regex:/(?:twitter\.com|x\.com)\/\w+\/status\/(\d+)/i},{name:"twitch",color:"bg-[#9146FF] text-white",regex:/twitch\.tv\/videos\/(\d+)/i}],Hc=/(?:nostr:|https?:\/\/(?:njump\.me|primal\.net)\/[ep]\/)?((?:nevent|note|naddr|npub|nprofile)1[023456789acdefghjklmnpqrstuvwxyz]+|[a-f0-9]{64})/i,Kc=/^https?:\/\/[^\s/$.?#].[^\s]*$/i}))()}function Sf(e){return btoa(JSON.stringify(e))}function Cf(e){try{return new URL(e).hostname.toLowerCase()}catch{return e.replace(/^https?:\/\//,"").replace(/[:/].*$/,"").toLowerCase()}}function Ef(e){if(!e||0===e)return"size unknown";const t=e/1048576;return t<1024?`${t.toFixed(1)} MB`:`${(t/1024).toFixed(2)} GB`}function Mf(e){try{const t=new URL(e);return`${t.protocol}//${t.host.toLowerCase()}`}catch{return e.replace(/\/$/,"")}}function If(){return(If=t(()=>{ow()}))()}function Af(e,t){const n=[],s=[],{sha256:r,ext:a}=Ol(e);if(!r)return{urls:n,metadata:s};for(const o of t){if(!gf(o.url))continue;const e=Mf(o.url),t=a?`${e}/${r}.${a}`:`${e}/${r}`;n.push(t),s.push({source:"mirror",serverUrl:o.url})}return{urls:n,metadata:s}}function Pf(e,t,n,s,r=[],a){const o=[],i=[];if(!n?.enabled)return{urls:o,metadata:i};const{sha256:c,ext:l}=Ol(e);if(!c)return{urls:o,metadata:i};let u;try{u=new URL(e).origin}catch{return{urls:o,metadata:i}}for(const d of t){if(!gf(d.url))continue;const f=Mf(d.url);let m;try{m=new URL(f).origin}catch{continue}if(u===m)continue;let p=l?`${f}/${c}.${l}`:`${f}/${c}`;const h=!yf(f),g=new URLSearchParams,y=new Set;for(const e of t){if(!gf(e.url))continue;const t=Mf(e.url);if(h||yf(t))try{if(new URL(t).origin===m)continue;const e=new URL(t).hostname;y.has(e)||(g.append("xs",e),y.add(e))}catch{continue}}for(const e of r){if(!gf(e.url))continue;const t=e.url.replace(/\/$/,"");if(h||yf(t))try{if(new URL(t).origin===m)continue;const e=new URL(t).hostname;y.has(e)||(g.append("xs",e),y.add(e))}catch{continue}}if(u&&u!==m&&hf(e))try{const t=new URL(e).hostname;y.has(t)||(g.append("xs",t),y.add(t))}catch{}s&&g.set("as",s.toLowerCase()),n.maxSize&&a&&["image","video"].includes(a)&&(n.maxSize.width&&g.set("width",n.maxSize.width.toString()),n.maxSize.height&&g.set("height",n.maxSize.height.toString())),g.toString()&&(p+=`?${g.toString()}`),o.push(p),i.push({source:"proxy",serverUrl:d.url})}return{urls:o,metadata:i}}function Tf(e){const{urls:t,blossomServers:n,cachingServers:s=[],proxyConfig:r,authorPubkey:a,mediaType:o}=e,i=[],c=[],l=n.filter(e=>e.tags.includes("mirror"));for(const m of t){const e=hf(m),t=Wl(m);if(!e){const{urls:e,metadata:t}=Pf(m,s,r,a,l,o);i.push(...e),c.push(...t);const{urls:n,metadata:u}=Af(m,l);i.push(...n),c.push(...u);continue}if(s.length>0){const{urls:e,metadata:t}=Pf(m,s,r,a,l,o);i.push(...e),c.push(...t)}if(t&&(i.push(m),c.push({source:"original"})),l.length>0){const{urls:e,metadata:t}=Af(m,l);i.push(...e),c.push(...t)}t||(i.push(m),c.push({source:"original"}))}const u=[],d=[],f=new Set;for(let m=0;m{If(),ql()}))()}function Uf(e,t=[]){return!!e&&t.includes(e)}function $f(){return($f=t(()=>{}))()}function Df(){return(Df=t(()=>{Gc=["xhamster","porntubeai","pmvhaven"],Yc=["porntubeai","pmvhaven"]}))()}function Lf(e){if(!e)return!0;const t=e.toLowerCase();if("application/vnd.apple.mpegurl"===t||"application/x-mpegurl"===t)return!0;if(function(){if("undefined"==typeof navigator)return!1;const e=navigator.userAgent||navigator.vendor||window.opera||"";return/iPad|iPhone|iPod/.test(e)||"MacIntel"===navigator.platform&&navigator.maxTouchPoints>1}())for(const n of Xc)if(t.includes(n))return!1;if(["hvc1","hev1"].some(e=>t.includes(e)))return!0;if("undefined"!=typeof document){const t=document.createElement("video");if(t.canPlayType&&""===t.canPlayType(e))return!1}return!0}function Bf(e){const t=e.filter(e=>Lf(e.mimeType));return 0===t.length?e:t}function zf(){return(zf=t(()=>{Xc=["hevc","h265","vp9","av01","av1"]}))()}function Ff(e={}){return{...e,includeYouTube:e.includeYouTube??!0,includeAudio:e.includeAudio??!0}}function _f(e,t,n={}){return s=function(e,t={}){const n=Ff(t),s=n.reportedEventIds?.length?new Set(n.reportedEventIds):void 0;return e.filter(e=>(n.includeYouTube||!Kb(e))&&(n.includeAudio||!Yb(e))&&"requires-hash-resolution"!==e.mediaSourceStatus&&"unavailable"!==e.mediaSourceStatus&&(!n.blockPubkeys||!n.blockPubkeys[e.pubkey])&&(!n.missingVideoIds||!n.missingVideoIds.has(e.id))&&(!s||!s.has(e.id)))}(function(e,t,n={}){const{blossomServers:s,nsfwPubkeys:r}=n,a=[];for(const o of e){const e=rr(o)?.size??0,n=Zc.get(o);let i;void 0!==n&&n.relays===t&&n.blossomServers===s&&n.nsfwPubkeys===r&&n.seenRelayCount===e?i=n.result:(i=aw(o,t,s,r),Zc.set(o,{relays:t,blossomServers:s,nsfwPubkeys:r,seenRelayCount:e,result:i})),void 0!==i&&i.id&&a.push(i)}return a}(function(e){return e.filter(e=>void 0!==e)}(e),t,n),n),sw(s);var s}function Of(e,t,n,s,r,a,o,i){return _f(e,t,function(e,t,n,s,r,a){return(o=e)&&("includeYouTube"in o||"includeAudio"in o||"blockPubkeys"in o||"blossomServers"in o||"missingVideoIds"in o||"nsfwPubkeys"in o||"reportedEventIds"in o)?Ff(e):Ff({...a,blockPubkeys:e,blossomServers:t,missingVideoIds:n,nsfwPubkeys:s,reportedEventIds:r});var o}(n,s,r,a,o,i))}function Wf(){return(Wf=t(()=>{xs(),ow(),Zc=new WeakMap}))()}var Vf,qf,Jf,Hf,Kf,Gf,Yf,Xf,Zf,Qf,em,tm,nm,sm,rm,am,om,im,cm,lm,um,dm,fm,mm,pm,hm,gm,ym,bm,wm,vm,xm,km,Nm,jm,Sm,Cm,Em,Mm,Im,Am,Pm,Tm,Rm,Um,$m,Dm,Lm,Bm,zm,Fm,_m,Om,Wm,Vm,qm,Jm,Hm,Km,Gm,Ym,Xm,Zm,Qm,ep,tp,np,sp,rp,ap,op,ip,cp,lp,up,dp,fp,mp,pp,hp,gp,yp,bp,wp,vp,xp,kp,Np,jp,Sp,Cp,Ep,Mp,Ip,Ap,Pp,Tp,Rp,Up,$p,Dp,Lp,Bp,zp,Fp,_p,Op,Wp,Vp,qp,Jp,Hp,Kp,Gp,Yp,Xp,Zp,Qp,eh,th,nh,sh,rh,ah,oh,ih,ch,lh,uh,dh,fh,mh,ph,hh,gh,yh,bh,wh,vh,xh,kh,Nh,jh,Sh,Ch,Eh,Mh,Ih,Ah,Ph,Th,Rh,Uh,$h,Dh,Lh,Bh,zh,Fh,_h,Oh,Wh,Vh,qh,Jh,Hh,Kh,Gh,Yh,Xh,Zh,Qh,eg,tg,ng,sg,rg,ag,og,ig,cg,lg,ug,dg,fg,mg,pg,hg,gg,yg,bg,wg,vg,xg,kg,Ng,jg,Sg,Cg,Eg,Mg,Ig,Ag,Pg,Tg,Rg,Ug,$g,Dg,Lg,Bg,zg,Fg,_g,Og,Wg,Vg,qg,Jg,Hg,Kg,Gg,Yg,Xg,Zg,Qg,ey,ty,ny,sy,ry,ay,oy,iy,cy,ly,uy,dy,fy,my,py,hy,gy,yy,by,wy,vy,xy,ky,Ny,jy,Sy,Cy,Ey,My,Iy,Ay,Py,Ty,Ry,Uy,$y,Dy,Ly,By,zy,Fy,_y,Oy,Wy,Vy,qy,Jy,Hy,Ky,Gy,Yy,Xy,Zy,Qy,eb,tb,nb,sb,rb,ab,ob,ib,cb,lb,ub,db,fb,mb,pb,hb,gb,yb,bb,wb,vb,xb,kb,Nb,jb,Sb,Cb,Eb,Mb,Ib,Ab,Pb,Tb,Rb,Ub,$b,Db,Lb,Bb,zb=n({processEvents:()=>Of});function Fb(e){return e.published_at??e.created_at}function _b(e){return`${e.title} ${e.description} ${e.tags.join(" ")}`.toLowerCase()}function Ob(e){return e?.split(";")[0]?.trim().toLowerCase()??""}function Wb(e){try{return new URL(e).pathname.toLowerCase()}catch{return e.toLowerCase().split("?")[0]}}function Vb(e){const t=Ob(e);return t.startsWith("audio/")||qf.has(t)}function qb(e){if(!e)return!1;const t=Wb(e);return Vf.some(e=>t.endsWith(e))}function Jb(e){if(!e)return;const t=parseFloat(e);return Number.isFinite(t)?Math.floor(t):void 0}function Hb(e){return"video/mp4"===Ob(e.mimeType)||Wb(e.url).endsWith(".mp4")}function Kb(e){return(e.sourceUrls??e.urls).some(e=>qc.test(e))}function Gb(e){for(const t of e){const e=t.match(qc);if(e?.[1])return{platform:"youtube",externalId:e[1],originalUrl:t}}}function Yb(e){return"audio"===e.mediaType}function Xb(e,t){return Vb(e)||qb(t)?"audio":Ob(e).startsWith("image/")?"image":"video"}function Zb(e){try{const t=(new URL(e).pathname.split("/").pop()||"").match(/^([a-f0-9]{64})(?:\.([^.]+))?$/i);return t?{sha256:t[1],ext:t[2]}:{}}catch{return{}}}function Qb(e){return e.sort((e,t)=>{const n=e=>{if(e.quality){const t=e.quality.match(/(\d+)/);if(t)return parseInt(t[1])}if(e.dimensions){const t=e.dimensions.match(/x(\d+)/);if(t)return parseInt(t[1])}return 0},s=n(e);return n(t)-s})}function ew(e,t,n){return 34235!==e.kind&&34236!==e.kind||!t?er.neventEncode({kind:e.kind,id:e.id,author:e.pubkey,relays:n}):er.naddrEncode({kind:e.kind,pubkey:e.pubkey,identifier:t,relays:n})}function tw(e,t){const n=rr(e),s=[...n?Array.from(n):[],...t];return[...new Set(s.flatMap(e=>sl(e)))].slice(0,3)}function nw(e){return 34235===e||34236===e}function sw(e){const t=new Map;for(const n of e){if(!n.identifier){t.set(n.id,n);continue}const e=`${n.pubkey}:${n.identifier}`,s=t.get(e);if(!s){t.set(e,n);continue}const r=nw(s.kind),a=nw(n.kind);if(a&&!r)t.set(e,n);else{if(!a&&r)continue;n.created_at>s.created_at&&t.set(e,n)}}return Array.from(t.values())}function rw(e){const t=[e.url,...e.fallbackUrls].filter(hf);return 0===t.length?null:{...e,url:t[0],fallbackUrls:t.slice(1)}}function aw(e,t,n,s){const r=rr(e),a=[...r?Array.from(r):[],...t],o=[...new Set(a.flatMap(e=>sl(e)))].slice(0,3),i=e.tags.filter(e=>"imeta"===e[0]),c=function(e){const t=e.find(([e])=>"content-warning"===e)?.[1];return t?.trim()?t:void 0}(e.tags)??(Uf(e.pubkey,s)||e.tags.some(([e,t])=>{if("string"!=typeof t)return!1;const n=t.trim().toLowerCase();return"d"===e?Gc.some(e=>n.startsWith(e)):"source"===e?"xhamster"===n:"client"===e&&Yc.includes(n)})?"NSFW":void 0);const l=e.tags.find(e=>"published_at"===e[0])?.[1],u=l?parseInt(l,10):void 0;if(i.length>0){const t=i.map(e=>function(e){const t=new Map;for(let f=1;fu.push(e)),t.get("mirror")?.forEach(e=>u.push(e)),r){const e=r.match(/x(\d+)/);e&&(d=`${e[1]}p`)}return{url:n,hash:i,size:a,duration:o,dimensions:r,mimeType:s,mediaType:l,quality:d,fallbackUrls:u,blurhash:c}}(e)).filter(e=>null!==e),s=t.flatMap(e=>[e.url,...e.fallbackUrls]),r=t.map(rw).filter(e=>null!==e),a=[];for(const e of i){const t=[];for(let n=1;n0){const e=rw({url:t[0],fallbackUrls:t.slice(1),mimeType:"image/jpeg"});e&&a.push(e)}}const l=Qb(r.filter(e=>e.mimeType?.startsWith("video/")||function(e){if(!e)return!1;const t=Wb(e);return t.endsWith(".mp4")||t.endsWith(".m4v")||t.endsWith(".webm")||t.endsWith(".mov")}(e.url)||Vb(e.mimeType)||qb(e.url)||"application/vnd.apple.mpegurl"===e.mimeType||e.url?.endsWith(".m3u8")||function(e){return"application/dash+xml"===Ob(e)}(e.mimeType)||function(e){return!!e&&Wb(e).endsWith(".mpd")}(e.url))),d=Qb(Bf(l)),f=[...r.filter(e=>e.mimeType?.startsWith("image/")),...a],m=i[0],p=new Map;for(let e=1;eb.push(e)),p.get("mirror")?.forEach(e=>b.push(e));const w=p.get("alt")?.[0]||e.content||"",v=p.get("blurhash")?.[0],x=p.get("x")?.[0],k=e.tags.filter(e=>"t"===e[0]).map(e=>e[1]),N=Jb(e.tags.find(e=>"duration"===e[0])?.[1]),j=e.tags.find(e=>"d"===e[0])?.[1],S=e.tags.filter(e=>"origin"===e[0]).map(e=>({platform:e[1],externalId:e[2],originalUrl:e[3],metadata:e[4]}));if(0===S.length){const t=Gb([...i.flatMap(e=>e.slice(1).filter(e=>e.startsWith("url ")).map(e=>e.slice(4))),...e.tags.filter(e=>"r"===e[0]).map(e=>e[1]).filter(Boolean)]);t&&S.push(t)}const C=S[0],E=[],M=e.tags.filter(e=>"text-track"===e[0]);M.forEach(e=>{let t=e[1];if(!t||!hf(t))return;const s=e[2];if(t&&n&&n.length>0){const e=n.filter(e=>e.tags.includes("mirror"));if(e.length>0){const{urls:n}=Tf({urls:[t],mediaType:"vtt",blossomServers:e});n.length>0&&(t=n[0])}}E.push({url:t,lang:s})}),h&&h.includes(" ")&&(h=h.split(" ")[0]);const I=[];for(const e of d)I.push(e.url),I.push(...e.fallbackUrls);const A=d[0],P=A?.mimeType||g,T="audio"===A?.mediaType?"audio":"video",R=A?.dimensions,U=A?.duration??l.find(e=>void 0!==e.duration)?.duration??N??0,$=A?.url??(h&&hf(h)?h:void 0),D=v?rf(v):void 0,L="audio"===T?[]:$?[$]:D?[D]:[],B=[...s,...p.get("image")??[],...M.flatMap(e=>e[1]?[e[1]]:[])].filter(e=>!hf(e)).length,z=I.length>0?"safe-declared-source":x?"requires-hash-resolution":"unavailable",F={id:e.id,kind:e.kind,identifier:j,title:e.tags.find(e=>"title"===e[0])?.[1]||w,description:e.content||"",images:y.length>0?y:L,pubkey:e.pubkey,created_at:e.created_at,published_at:u,duration:U,x:A?.hash||x,tags:k,searchText:"",urls:I,sourceUrls:s,mediaSourceStatus:z,blockedEventMediaUrlCount:B,mimeType:P,mediaType:T,dimensions:R,textTracks:E,link:ew(e,j,o),type:$u(e.kind),contentWarning:c,origin:C,origins:S,videoVariants:d,thumbnailVariants:f,allVideoVariants:l};return F.searchText=_b(F),F}{const t=e.tags.find(e=>"title"===e[0])?.[1]||"",n=e.tags.find(e=>"description"===e[0])?.[1]||e.content||"",s=e.tags.find(e=>"thumb"===e[0])?.[1],r=Jb(e.tags.find(e=>"duration"===e[0])?.[1])??0,a=e.tags.find(e=>"d"===e[0])?.[1]||"",i=e.tags.filter(e=>"t"===e[0]).map(e=>e[1]);let l=e.tags.find(e=>"url"===e[0])?.[1]||"";const d=e.tags.find(e=>"m"===e[0])?.[1]||"",f=e.tags.filter(e=>"origin"===e[0]).map(e=>({platform:e[1],externalId:e[2],originalUrl:e[3],metadata:e[4]}));if(l.includes(" ")&&(l=l.split(" ")[0]),0===f.length){const t=Gb([l,...e.tags.filter(e=>"r"===e[0]).map(e=>e[1]).filter(Boolean)]);t&&f.push(t)}const m=f[0],p=l?[l]:[],h=hf(l)?l:"",g=s&&hf(s)?s:"",y=h?[h]:[],b=e.tags.find(e=>"dim"===e[0])?.[1],w=parseInt(e.tags.find(e=>"size"===e[0])?.[1]||"0"),v=e.tags.find(e=>"x"===e[0])?.[1],x=h?[{url:h,hash:v,size:w||void 0,dimensions:b,mimeType:d,mediaType:Xb(d,h),fallbackUrls:[]}]:[],k=g?[{url:g,fallbackUrls:[]}]:[],N={id:e.id,kind:e.kind,identifier:a,title:t,description:n,images:[g||h].filter(Boolean),pubkey:e.pubkey,created_at:e.created_at,published_at:u,duration:r,tags:i,searchText:"",urls:y,sourceUrls:p,mediaSourceStatus:y.length>0?"safe-declared-source":v?"requires-hash-resolution":"unavailable",blockedEventMediaUrlCount:[l,s].filter(e=>Boolean(e)).filter(e=>!hf(e)).length,textTracks:[],mimeType:d,mediaType:"audio"===Xb(d,l)?"audio":"video",dimensions:b,size:w||void 0,x:v,link:ew(e,a,o),type:$u(e.kind),contentWarning:c,origin:m,origins:f,videoVariants:x,thumbnailVariants:k,allVideoVariants:x};return N.searchText=_b(N),N}}function ow(){return(ow=t(()=>{af(),os(),jf(),xs(),Rf(),Df(),zf(),dl(),Wf(),Vf=[".mp3",".ogg",".oga",".opus",".m4a",".aac",".wav",".flac"],qf=new Set(["application/ogg","application/x-ogg","application/opus"])}))()}function iw(e,t={}){const n=sc(),{config:s}=iu(),{getAllMissingVideos:r}=Qd(),{presetContent:a}=vd(),o=Cr(),{relays:i=[],loader:c,directMode:l=!1,includeAudio:u,enabled:d=!0,skipCache:f=!1,cacheKey:m,staleTimeMs:p,firstEventTimeoutMs:h=Hf,pageSettleMs:g=Kf,firstUsefulTimeoutMs:y=Gf}=t,b=(0,Jf.useMemo)(()=>{if(c||!function(e){return!!e&&!Array.isArray(e)}(e))return;m??String(ul({filters:e,relays:[...i].sort(),skipCache:f}));const t=tu(0,e,i,{skipCache:f});return()=>t},[m,e,c,i,f]),w=c??b,v=(0,Jf.useMemo)(()=>m||(e?String(ul({filters:e,relays:[...i].sort(),skipCache:f})):void 0),[m,e,i,f]),[x,k]=(0,Jf.useState)([]),[N,j]=(0,Jf.useState)([]),[S,C]=(0,Jf.useState)("idle"),[E,M]=(0,Jf.useState)(!1),[I,A]=(0,Jf.useState)(!1),P=(0,Jf.useRef)(null),T=(0,Jf.useRef)(null),R=(0,Jf.useRef)(null),U=(0,Jf.useRef)(null),$=(0,Jf.useRef)(!1),D=(0,Jf.useRef)(E),L=(0,Jf.useRef)([]),B=(0,Jf.useRef)(!0);D.current=E;const z=(0,Jf.useCallback)(e=>"function"!=typeof o.hasEvent||o.hasEvent(e.id),[o]),F=(0,Jf.useCallback)(()=>{T.current&&(clearTimeout(T.current),T.current=null),R.current&&(clearTimeout(R.current),R.current=null),U.current&&(clearTimeout(U.current),U.current=null)},[]);(0,Jf.useEffect)(()=>()=>{P.current?.unsubscribe(),F()},[F]);const _=(0,Jf.useMemo)(()=>{const e=r();return new Set(Object.keys(e))},[r]),O=Dt(()=>l||!e?Dr([]):o.timeline(e).pipe(we(100)),[o,e,l]),W=(0,Jf.useCallback)(t=>{if(!d||!w||$.current||D.current)return;if("initial"===t&&void 0!==p&&v){const e=Wo.get(v);if(void 0!==e&&Date.now()-e<=p)return B.current=!1,void C("ready")}B.current=!1,P.current?.unsubscribe(),F(),$.current=!0,A(!0),C("prefetch"===t?"prefetching":e=>"idle"===e||"initial"===t?"loading-initial":"loading-more");let n=!1,s=!1,r=!1;const a=()=>{r||"prefetch"===t||(r=!0,C("ready"))},i=e=>{s||(s=!0,$.current=!1,A(!1),F(),"initial"===t&&v&&Wo.set(v,Date.now()),C(e))};T.current=setTimeout(()=>{P.current?.unsubscribe(),M(!0),i("exhausted")},h),"prefetch"!==t&&(U.current=setTimeout(()=>{n&&a()},y));const c=L.current,u=c.length>0?Math.min(...c.map(e=>e.created_at)):void 0,f="initial"===t||void 0===u?void 0:{until:u-1},m=w();P.current=m(f).subscribe({next:t=>{!n&&T.current&&(clearTimeout(T.current),T.current=null),n=!0,a(),R.current&&clearTimeout(R.current),R.current=setTimeout(()=>{P.current?.unsubscribe(),i("ready")},g),5!==t.kind?l?z(t)&&k(e=>Array.from(Yr(e,t))):e?o.add(t):z(t)&&j(e=>Array.from(Yr(e,t))):l?k(e=>e.filter(e=>!tf(t,e))):e||j(e=>e.filter(e=>!tf(t,e)))},complete:()=>{if(!n)return M(!0),void i("exhausted");i("ready")},error:e=>{i(n?"ready":"error")}})},[F,l,d,o,e,h,y,w,g,z,p,v]),V=(0,Jf.useCallback)(()=>W("load-more"),[W]),q=(0,Jf.useCallback)(()=>W("prefetch"),[W]),J=(0,Jf.useMemo)(()=>l?x:e?O??[]:N,[l,x,e,O,N]);(0,Jf.useEffect)(()=>{L.current=J},[J]);const H=(0,Jf.useMemo)(()=>Of(J,i,{blockPubkeys:n,blossomServers:s.blossomServers,missingVideoIds:_,nsfwPubkeys:a.nsfwPubkeys,reportedEventIds:s.reportedEventIds,includeYouTube:s.showYouTubeContent??!0,includeAudio:u??s.showAudioContent??!0}).sort((e,t)=>Fb(t)-Fb(e)),[J,i,n,s.blossomServers,_,a.nsfwPubkeys,s.reportedEventIds,s.showYouTubeContent,s.showAudioContent,u]),K=(0,Jf.useCallback)(()=>{P.current?.unsubscribe(),P.current=null,F(),$.current=!1,A(!1),k([]),j([]),L.current=[],M(!1),C("idle"),B.current=!0},[F]);(0,Jf.useEffect)(()=>{d&&w&&B.current&&queueMicrotask(()=>W("initial"))},[d,w,W]);const G=(0,Jf.useRef)(w);return(0,Jf.useEffect)(()=>{if(void 0!==G.current){if(G.current!==w){G.current=w;let e=!1;return(async()=>{await Promise.resolve(),e||(K(),queueMicrotask(()=>{e||W("initial")}))})(),()=>{e=!0}}}else G.current=w},[w,K,W]),{videos:H,events:J,loading:"loading-initial"===S||"loading-more"===S,isInitialLoading:"loading-initial"===S,isLoadingMore:"loading-more"===S,isPrefetching:"prefetching"===S,subscriptionActive:I,exhausted:E,hasMore:!E,phase:S,loadMore:V,prefetchMore:q,reset:K}}function cw(){return(cw=t(()=>{lu(),ef(),Nd(),kd(),Hl(),dl(),ow(),nu(),Wt(),qs(),De(),fr(),Jf=Be(),Hf=1e4,Kf=5e3,Gf=900}))()}function lw(){return(lw=t(()=>{Be(),du(),dl(),cw()}))()}function uw(){return Qf||(Qf=new Promise((e,t)=>{const n=indexedDB.open(Yf,Xf);n.onupgradeneeded=()=>{const e=n.result;if(!e.objectStoreNames.contains(Zf)){const t=e.createObjectStore(Zf,{keyPath:"key"});t.createIndex("pubkey","pubkey",{unique:!1}),t.createIndex("lastPlayedAt","lastPlayedAt",{unique:!1}),t.createIndex("pubkey_lastPlayedAt",["pubkey","lastPlayedAt"],{unique:!1})}},n.onsuccess=()=>e(n.result),n.onerror=()=>{Qf=null,t(n.error)}}),Qf)}async function dw(e,t,n,s=Date.now()){try{const r=await uw();return new Promise((a,o)=>{const i=r.transaction(Zf,"readwrite"),c=i.objectStore(Zf),l={key:`${e}:${t}`,pubkey:e,videoId:t,time:n.time,duration:n.duration,lastPlayedAt:s};c.put(l),i.oncomplete=()=>a(),i.onerror=()=>o(i.error)})}catch{}}function fw(){return(fw=t(()=>{Yf="nostube-play-positions",Xf=1,Zf="positions",Qf=null}))()}async function mw(){try{const e=[];for(let t=0;t{const t=e.slice(8),n=t.indexOf(":");if(-1===n)return;const s=t.slice(0,n),r=t.slice(n+1);if(!s||!r)return;const a=function(e){if(!e)return null;if(e.startsWith("{"))try{const t=JSON.parse(e);if("number"==typeof t.time&&!isNaN(t.time)&&t.time>0)return{time:t.time,duration:"number"==typeof t.duration?t.duration:0}}catch{}const t=parseFloat(e);return!isNaN(t)&&t>0?{time:t,duration:0}:null}(localStorage.getItem(e));a&&await dw(s,r,a),localStorage.removeItem(e)}))}catch{}}async function pw(e,t){const n=`${e}:${t}`;if(em.has(n))return em.get(n)??null;const s=await async function(e,t){try{const n=await uw();return new Promise((s,r)=>{const a=n.transaction(Zf,"readonly").objectStore(Zf).get(`${e}:${t}`);a.onsuccess=()=>{const e=a.result;if(!e)return s(null);s({time:e.time,duration:e.duration})},a.onerror=()=>r(a.error)})}catch{return null}}(e,t);return em.set(n,s),s}function hw(){return(hw=t(()=>{fw(),em=new Map}))()}function gw(e){if(!e)return 0;if(/^\d+$/.test(e))return parseInt(e,10);const t=e.split(":").map(Number);return t.some(isNaN)?0:2===t.length?60*t[0]+t[1]:3===t.length?3600*t[0]+60*t[1]+t[2]:0}function yw({user:e,videoId:t,videoDuration:n,locationSearch:s}){const[r,a]=(0,tm.useState)(0),[o,i]=(0,tm.useState)(0),c=(0,tm.useRef)(null),l=(0,tm.useRef)(0),u=(0,tm.useRef)(null),d=(0,tm.useRef)(0),[f,m]=(0,tm.useState)(!1);return(0,tm.useEffect)(()=>{const e=u.current;if(!e)return;const t=()=>{e.duration&&isFinite(e.duration)&&(d.current=e.duration)};return t(),e.addEventListener("durationchange",t),e.addEventListener("loadedmetadata",t),()=>{e.removeEventListener("durationchange",t),e.removeEventListener("loadedmetadata",t)}},[f]),(0,tm.useEffect)(()=>{let r=!1;return async function(){const a=new URLSearchParams(s),o=gw(a.get("t"));if(o>0)return void(r||i(o));if("true"===a.get("autoplay"))return void(r||i(0));if(!e||!t)return void(r||i(0));const c=await pw(e.pubkey,t);if(!r){if(c&&c.time>0){const e=c.duration||n||0;return e>0?e-c.time>5&&c.time{r=!0}},[e,t,n,s]),(0,tm.useEffect)(()=>{if(!e||!t)return;if(r<5)return;const s=Date.now(),a=d.current||n||0,o=()=>{!async function(e,t,n){const s=`${e}:${t}`;em.set(s,n),await dw(e,t,n)}(e.pubkey,t,{time:r,duration:a}),l.current=Date.now(),function(e,t){e&&t?em.delete(`${t}:${e}`):em.clear()}(t,e.pubkey)};return s-l.current>3e3?(o(),c.current&&(clearTimeout(c.current),c.current=null)):(c.current&&clearTimeout(c.current),c.current=setTimeout(()=>{o(),c.current=null},2e3)),()=>{c.current&&(clearTimeout(c.current),c.current=null)}},[r,e,t,n]),(0,tm.useEffect)(()=>{if("undefined"!=typeof window&&u.current){const e=gw(new URLSearchParams(s).get("t"));e>0&&Math.abs(u.current.currentTime-e)>1&&(u.current.currentTime=e)}},[s]),(0,tm.useEffect)(()=>{if("undefined"==typeof window)return;const e=e=>{const t=e.detail?.time,n=u.current;"number"==typeof t&&n&&(n.currentTime=t,a(t))};return window.addEventListener("nostube:seek-to",e),()=>window.removeEventListener("nostube:seek-to",e)},[]),{currentPlayPos:r,setCurrentPlayPos:a,initialPlayPos:o,videoElementRef:u,setVideoElement:e=>{u.current=e,m(!!e)}}}function bw(){return(bw=t(()=>{tm=Be(),hw()}))()}function ww({videoElement:e,toggleCinemaMode:t,onPreviousVideo:n,onNextVideo:s,isPlaylistMode:r}){const a=(0,nm.useRef)(null);(0,nm.useEffect)(()=>{a.current=e},[e]),(0,nm.useEffect)(()=>{const e=e=>{const o=e.target;if("INPUT"===o.tagName||"TEXTAREA"===o.tagName||"SELECT"===o.tagName||o.isContentEditable)return;const i=a.current,c=e.key;if("t"===c||"T"===c)return e.preventDefault(),void t();if(","!==c&&"."!==c);else{if(e.preventDefault(),r)return void(","===c&&n?n():"."===c&&s&&s());if(i&&i.paused){const e=1/30;if("."===c){const t=i.currentTime+e;i.currentTime=Number.isFinite(i.duration)?Math.min(i.duration,t):t}else i.currentTime=Math.max(0,i.currentTime-e)}}};return window.addEventListener("keydown",e),()=>{window.removeEventListener("keydown",e)}},[t,n,s,r])}function vw(){return(vw=t(()=>{nm=Be()}))()}function xw(){const[e,t]=Hd("video-history",[]);return{history:e,addToHistory:(0,sm.useCallback)(e=>{t(t=>{const n=t.filter(t=>t.eventId!==e.id);return[{eventId:e.id,timestamp:Date.now(),event:e},...n].slice(0,rm)})},[t]),clearHistory:(0,sm.useCallback)(()=>{t([])},[t]),removeFromHistory:(0,sm.useCallback)(e=>{t(t=>t.filter(t=>t.eventId!==e))},[t]),getHistory:(0,sm.useCallback)(()=>e,[e])}}function kw(){return(kw=t(()=>{sm=Be(),Kd(),rm=100}))()}function Nw(e,t){return Number.isFinite(e)?Math.max(0,"floor"===t?Math.floor(e):Math.ceil(e)):0}function jw({videoId:e,videoKind:t,videoPubkey:n,videoIdentifier:s,relayHint:r,viewerPubkey:a,segments:o,source:i="unknown",sourceDetail:c,loopCount:l,createdAt:u}){if(!a||a===n)return null;const d=function(e){return e.filter(e=>e.end>e.start&&e.end-e.start>=1).map(e=>({start:Nw(e.start,"floor"),end:Nw(e.end,"ceil")})).filter(e=>e.end>e.start)}(o);if(0===d.length)return null;const f=r??"",m=[];m.push(["a",`${t}:${n}:${s??e}`,f]),m.push(["e",e,f]);for(const p of d)m.push(["viewed",String(p.start),String(p.end)]);return c?m.push(["source",i,c]):m.push(["source",i]),l&&l>0&&m.push(["loops",String(Math.floor(l))]),m.push(["client","nostube"]),{event:{kind:am,content:"",tags:m,created_at:u??Math.floor(Date.now()/1e3)},normalizedSegments:d}}function Sw(){return(Sw=t(()=>{am=22236}))()}function Cw(){if(lm)return lm;const{promise:e,resolve:t,reject:n}=Promise.withResolvers();lm=e;const s=indexedDB.open(om,im);return s.onupgradeneeded=()=>{const e=s.result;if(!e.objectStoreNames.contains(cm)){const t=e.createObjectStore(cm,{keyPath:"id"});t.createIndex("viewerPubkey_status",["viewerPubkey","status"],{unique:!1}),t.createIndex("createdAt","createdAt",{unique:!1}),t.createIndex("videoId","videoId",{unique:!1})}},s.onsuccess=()=>t(s.result),s.onerror=()=>{lm=null,n(s.error??new Error("IDB open failed"))},e}function Ew(e,t){const{promise:n,resolve:s,reject:r}=Promise.withResolvers(),a=e.transaction(cm,t);return a.oncomplete=()=>s(),a.onerror=()=>r(a.error??new Error("IDB transaction error")),a.onabort=()=>r(a.error??new Error("IDB transaction aborted")),{store:a.objectStore(cm),done:n}}async function Mw(e){try{const{store:t,done:n}=Ew(await Cw(),"readwrite"),s=t.get(e);s.onsuccess=()=>{if(s.result){const e={...s.result,status:"publishing",updatedAt:Date.now()};t.put(e)}},await n}catch(t){}}async function Iw(e,t){try{const{store:t,done:n}=Ew(await Cw(),"readwrite"),s=t.get(e);s.onsuccess=()=>{if(s.result){const e=s.result,n={...e,status:"failed",retryCount:e.retryCount+1,updatedAt:Date.now()};t.put(n)}},await n}catch(n){}}async function Aw(e){try{const{store:t,done:n}=Ew(await Cw(),"readwrite");t.delete(e),await n}catch(t){}}function Pw(){return(Pw=t(()=>{om="nostube-view-event-outbox",im=1,cm="viewEvents",lm=null}))()}function Tw({video:e,mediaElement:t,active:n=!0,source:s,sourceDetail:r,relayHint:a}){const{user:o}=yu(),{config:i}=iu(),c=(0,um.useRef)([]),l=(0,um.useRef)(null),u=(0,um.useRef)(null),d=(0,um.useRef)(0),f=(0,um.useRef)(null),m=(0,um.useCallback)(()=>{c.current=[],l.current=null,u.current=null,d.current=0},[]),p=(0,um.useCallback)(e=>{const t=l.current;null!==t&&Number.isFinite(e)&&(e>t&&c.current.push({start:t,end:e}),l.current=null)},[]),h=(0,um.useCallback)(e=>{Number.isFinite(e)&&(null===l.current&&(l.current=Math.max(0,e)),u.current=e)},[]),g=(0,um.useCallback)(()=>{if(!e||!o||!0!==i.viewTrackingEnabled)return void m();const n=t?.currentTime;"number"==typeof n&&p(n);const l=function(e,t){return t||("tags"in e?Array.from(rr(e)??[])[0]:void 0)}(e,a),u=function(e){return"identifier"in e?e.identifier:"tags"in e?e.tags.find(e=>"d"===e[0])?.[1]:void 0}(e),h=jw({videoId:e.id,videoKind:e.kind,videoPubkey:e.pubkey,videoIdentifier:u,relayHint:l,viewerPubkey:o.pubkey,segments:c.current,source:s,sourceDetail:r,loopCount:d.current});if(!h)return void m();const g=`${e.id}:${h.event.created_at}:${JSON.stringify(h.normalizedSegments)}`;f.current!==g&&(f.current=g,o.signer.signEvent(h.event).then(t=>async function(e){try{const t=await Cw(),n=Date.now(),s={id:e.event.id,viewerPubkey:e.viewerPubkey,videoId:e.videoId,videoKind:e.videoKind,videoPubkey:e.videoPubkey,videoIdentifier:e.videoIdentifier,relayHint:e.relayHint,source:e.source,sourceDetail:e.sourceDetail,segments:e.segments,loopCount:e.loopCount??0,event:e.event,status:"pending",retryCount:0,createdAt:n,updatedAt:n},{store:r,done:a}=Ew(t,"readwrite");r.put(s),await a}catch(t){}}({viewerPubkey:o.pubkey,videoId:e.id,videoKind:e.kind,videoPubkey:e.pubkey,videoIdentifier:u,relayHint:l,source:s,sourceDetail:r,segments:h.normalizedSegments,loopCount:d.current,event:t})).catch(e=>{}),m())},[p,i,t,a,m,s,r,o,e]);(0,um.useEffect)(()=>{m(),f.current=null},[m,e?.id]),(0,um.useEffect)(()=>{if(!t||!n)return;const e=()=>{h(t.currentTime)},s=()=>{if(t.paused||t.seeking)return;const e=t.currentTime,n=u.current;null!==n&&(e+.5dm&&(p(n),l.current=e)),h(e)},r=()=>{p(t.currentTime)},a=()=>{const e=u.current??t.currentTime;p(e),u.current=null},o=()=>{p(t.currentTime),g()};return t.addEventListener("play",e),t.addEventListener("playing",e),t.addEventListener("timeupdate",s),t.addEventListener("pause",r),t.addEventListener("seeking",a),t.addEventListener("ended",o),t.paused||h(t.currentTime),()=>{t.removeEventListener("play",e),t.removeEventListener("playing",e),t.removeEventListener("timeupdate",s),t.removeEventListener("pause",r),t.removeEventListener("seeking",a),t.removeEventListener("ended",o)}},[n,p,h,g,t]),(0,um.useEffect)(()=>{n||g()},[n,g]),(0,um.useEffect)(()=>{const e=()=>{"hidden"===document.visibilityState&&g()};return window.addEventListener("pagehide",g),document.addEventListener("visibilitychange",e),()=>{window.removeEventListener("pagehide",g),document.removeEventListener("visibilitychange",e),g()}},[g])}function Rw(){return(Rw=t(()=>{um=Be(),xs(),bu(),lu(),Sw(),Pw(),dm=2.5}))()}function Uw(e){return Math.min(fm*Math.pow(pm,e),mm)}async function $w(e,t){if(0===t.length)return;const n=await async function(e){try{const{store:t,done:n}=Ew(await Cw(),"readonly"),s=[],r=IDBKeyRange.bound([e,""],[e,"￿"]),a=t.index("viewerPubkey_status").openCursor(r);return a.onsuccess=()=>{const e=a.result;if(e){const t=e.value;"pending"!==t.status&&"failed"!==t.status||s.push(t),e.continue()}},await n,s.sort((e,t)=>e.createdAt-t.createdAt)}catch{return[]}}(e);for(const r of n)if(r.retryCount>=5)await Aw(r.id);else if(!("failed"===r.status&&Date.now()-r.updatedAt{nu(),Pw(),fm=2e3,mm=3e5,pm=2}))()}function Lw(){const{user:e}=yu(),{config:t}=iu(),n=t.viewTrackingRelays&&t.viewTrackingRelays.length>0?t.viewTrackingRelays:Fo,s=!0===t.viewTrackingEnabled,r=(0,hm.useCallback)(()=>{e&&s&&$w(e.pubkey,n).catch(e=>{})},[e,s,n]);(0,hm.useEffect)(()=>{e&&s&&async function(e){try{const{store:t,done:n}=Ew(await Cw(),"readwrite"),s=IDBKeyRange.only([e,"publishing"]),r=t.index("viewerPubkey_status").openCursor(s);r.onsuccess=()=>{const e=r.result;if(e){const t={...e.value,status:"pending",updatedAt:Date.now()};e.update(t),e.continue()}},await n}catch(t){}}(e.pubkey).then(r).catch(e=>{})},[e?.pubkey,s]),(0,hm.useEffect)(()=>{const e=()=>{"visible"===document.visibilityState&&r()};return document.addEventListener("visibilitychange",e),()=>document.removeEventListener("visibilitychange",e)},[r])}function Bw(){return(Bw=t(()=>{hm=Be(),bu(),lu(),Jl(),Dw()}))()}function zw(){const{pool:e}=iu(),t=uu(),n=Cr(),{user:s}=yu(),[r,a]=(0,gm.useState)([]),[o,i]=(0,gm.useState)(!0);return(0,gm.useEffect)(()=>{if(!e||!t||0===t.length||!s?.pubkey)return;const r=new Set;let o=null,c=null;const l=[],u=s?.pubkey?w(e,t,[{kinds:[21,22,34235,34236],authors:[s.pubkey],limit:500}],{eventStore:n}):null,d=w(e,t,[{kinds:[1],authors:[s.pubkey],limit:100}],{eventStore:n});u&&(o=u().subscribe({next:e=>{e.tags.filter(e=>"imeta"===e[0]).forEach(e=>{for(let t=1;t"url"===e[0]);t?.[1]&&r.add(t[1])},error:e=>{}})),c=d().subscribe({next:e=>{l.push(e)},error:e=>{}});const f=setTimeout(()=>{const e=l.map(e=>{const t=function(e,t){const n=[],s=e.match(ym)||[];n.push(...s),t.filter(e=>"imeta"===e[0]).forEach(e=>{for(let t=1;t{const t=e.toLowerCase();if(r.some(e=>t.includes(e)))return!0;try{const t=new URL(e).pathname;return a.test(t)}catch{return!1}})}(e.content,e.tags);if(0===t.length)return null;const n=e.tags.filter(e=>"imeta"===e[0]),s=t.map(e=>Zb(e).sha256).filter(e=>!!e);let a,o;if(n.length>0){const e=n[0];for(let t=1;t0&&(o=e)}}}!a&&t[0]&&(a=t[0]);const i=function(e,t){const n=new Map,s=(e,t)=>{const s=n.get(e);s?t.forEach(e=>s.add(e)):n.set(e,new Set(t))};for(const a of t)"p"===a[0]&&a[1]&&s(a[1],a[2]?[a[2]]:[]);const r=e.matchAll(bm);for(const a of r)try{const e=er.decode(a[1]);"npub"===e.type?s(e.data,[]):"nprofile"===e.type&&s(e.data.pubkey,e.data.relays??[])}catch{}return Array.from(n.entries()).map(([e,t])=>({pubkey:e,relays:Array.from(t)}))}(e.content,e.tags),c=t.some(e=>r.has(e));return{id:e.id,content:e.content,created_at:e.created_at,videoUrls:t,imetaTags:n,blossomHashes:s,thumbnailUrl:a,sizeBytes:o,pubkeys:i,isReposted:c}}).filter(e=>null!==e).sort((e,t)=>t.created_at-e.created_at);a(e),i(!1)},3e3);return()=>{clearTimeout(f),o&&o.unsubscribe(),c&&c.unsubscribe()}},[e,t,n,s?.pubkey]),{notes:r,loading:o}}function Fw(){return(Fw=t(()=>{gm=Be(),KN(),bu(),Wt(),be(),ow(),os(),ym=/https?:\/\/[^\s]+/g,bm=/nostr:(npub1[a-z0-9]+|nprofile1[a-z0-9]+)/g}))()}function _w({videoDimensions:e,videoId:t,persistedCinemaMode:n}){const[s,r]=(0,wm.useState)(null),[a,o]=(0,wm.useState)(!1),i=(0,wm.useCallback)((e,t)=>{r(e/t)},[]),c=(0,wm.useMemo)(()=>{if(e){const t=e.match(/(\d+)x(\d+)/);if(t){const e=parseInt(t[1],10),n=parseInt(t[2],10);if(n>0)return e/n}}return null},[e])??s,l=(0,wm.useMemo)(()=>null!==c&&c>xm,[c]),u=(0,wm.useMemo)(()=>null!==c&&c{let e=!1;return(async()=>{await Promise.resolve(),e||(r(null),o(!1))})(),()=>{e=!0}},[t]),(0,wm.useEffect)(()=>{if(null===s||!l||n)return;let e=!1;return(async()=>{await Promise.resolve(),e||o(!0)})(),()=>{e=!0}},[l,s,n]),{isUltraWide:l,isPortrait:u,effectiveAspectRatio:c,tempCinemaModeForWideVideo:a,setTempCinemaModeForWideVideo:o,handleVideoDimensionsLoaded:i}}function Ow(){return(Ow=t(()=>{wm=Be(),xm=1.1*(vm=16/9),km=.95*vm}))()}function Ww(){const[e,t]=Hd("cinemaMode",!1);return{cinemaMode:e,setCinemaMode:t,toggleCinemaMode:()=>{t(!e)}}}function Vw(){return(Vw=t(()=>{Kd()}))()}function qw({videoId:e,videoAddress:t,authorPubkey:n,kind:s,relays:r,enabled:a}){const o=Cr(),{pool:i}=iu();(0,Nm.useEffect)(()=>{if(!a||!e&&!t||0===r.length)return;const n=[];e&&n.push({kinds:[1,7],"#e":[e],limit:100},{kinds:[1111],"#E":[e],limit:100}),t&&n.push({kinds:[1],"#a":[t],limit:100},{kinds:[1111],"#A":[t],limit:100});const s=w(i,r,n,{eventStore:o,limit:100})().subscribe({next:e=>{o.add(e)},error:e=>{}});return()=>{s.unsubscribe()}},[e,t,n,s,r,a,o,i])}function Jw(){return(Jw=t(()=>{Nm=Be(),Wt(),lu(),be()}))()}function Hw(){return(Hw=t(()=>{ql(),Rf(),zf(),jm=class{options;_urls;_metadata;_index=0;_error=null;failed=new Set;listeners=new Set;constructor(e){this.options=e;const t=this.generate(this.sourceUrls(e),e.sha256);this._urls=t.urls,this._metadata=t.metadata}get urls(){return this._urls}get metadata(){return this._metadata}get currentIndex(){return this._index}get currentUrl(){return this._urls[this._index]??null}get hasMore(){return-1!==this.findNextIndex(this._index+1)}get error(){return this._error}get failedUrls(){return[...this.failed]}isFailed(e){return this.failed.has(e)}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}tryNext(){const e=this.currentUrl;return e&&this.failed.add(e),this.advance()}onError(e=this.currentUrl??void 0,t){if(!e)return!1;const n=e===this.currentUrl;this.failed.add(e);const s=!!n&&this.advance();return this.notify(),s}reset(){const e=this.findNextIndex(0);this._index=-1===e?this._urls.length:e,this._error=null,this.notify()}refresh(e){this.options=e;const t=this.generate(this.sourceUrls(e),e.sha256),n=this.appendNew(t.urls,e=>t.metadata[e]);return n&&this.notify(),n}merge(e,t="discovered"){const n=this.appendNew(e,()=>({source:t}));return n&&this.notify(),n}promote(e){const t=this.currentUrl,n=new Set(e.filter(e=>this._urls.includes(e)&&!this.failed.has(e)));if(0===n.size)return;const s=[...this._urls.flatMap((e,t)=>n.has(e)?[t]:[]),...this._urls.flatMap((e,t)=>n.has(e)?[]:[t])];this._urls=s.map(e=>this._urls[e]),this._metadata=s.map(e=>this._metadata[e]),this._index=t?this._urls.indexOf(t):this.findNextIndex(0),this.notify()}candidatesFor(e){const{sha256:t}=Ol(e);return(t?this.generate([e],t).urls:[e]).filter(e=>!this.failed.has(e))}sourceUrls(e){return e.variants?Bf(e.variants).map(e=>e.url):e.urls}generate(e,t){if(0===e.length)return{urls:[],metadata:[]};try{const n=Tf({urls:e,blossomServers:this.options.blossomServers,cachingServers:this.options.cachingServers,sha256:t,kind:this.options.kind,mediaType:this.options.mediaType,authorPubkey:this.options.authorPubkey,proxyConfig:this.options.proxyConfig});return this._error=null,n}catch(n){return this._error=n instanceof Error?n:new Error("Media URL generation failed"),{urls:[],metadata:[]}}}advance(){const e=this.findNextIndex(this._index+1);return-1!==e&&(this._index=e,this.notify(),!0)}findNextIndex(e){for(let t=e;t{n.has(e)||(n.add(e),s.push(e),r.push(t(a)))}),0!==s.length&&(this._urls=[...this._urls,...s],this._metadata=[...this._metadata,...r],!0)}notify(){this.listeners.forEach(e=>e())}}}))()}function Kw(e){try{const t=new URL(e);return`${t.protocol}//${t.hostname}`}catch{return null}}function Gw(e){return e.sort((e,t)=>t.timestamp-e.timestamp)}async function Yw(e){const{sha256:t}=e,n=Sm.get(t);if(n&&Date.now()-n.timestamp{const a=[],o=new Set,i=Ko.subscription(n,[{kinds:[1063],"#x":[t],limit:r}]).pipe(bt(e=>"string"!=typeof e&&"kind"in e)).subscribe({next:t=>{const n=function(e){const t=[],n=e.tags.find(e=>"url"===e[0]);n?.[1]&&t.push(n[1]);for(const s of e.tags)"fallback"===s[0]&&s[1]&&t.push(s[1]);return t}(t);if(0!==n.length)for(const s of n){if(o.has(s))continue;const n=Kw(s);if(n&&(o.add(s),a.push({url:s,serverUrl:n,pubkey:t.pubkey,timestamp:t.created_at}),a.length>=r))return clearTimeout(c),i.unsubscribe(),void e(Gw(a))}},error:t=>{clearTimeout(c),i.unsubscribe(),e(Gw(a))}}),c=window.setTimeout(()=>{i.unsubscribe(),e(Gw(a))},s)}):[]}(e);return s.length>0&&Sm.set(t,{urls:s,timestamp:Date.now()}),s}function Xw(){return(Xw=t(()=>{nu(),Aa(),Sm=new Map,Cm=36e5}))()}function Zw(e,t){const n=function(e){try{const t=new URL(e),n=t.pathname.match(/\/([a-f0-9]{64})(?:\.[a-z0-9]+)?$/i);if(n)return n[1];return t.searchParams.get("hash")||null}catch{return null}}(e);if(!n||0===t.length)return[];const s=e.match(/\.([a-z0-9]+)(?:\?|$)/i)?.[1]||"";return t.map(e=>{const t=e.endsWith("/")?e.slice(0,-1):e;return s?`${t}/${n}.${s}`:`${t}/${n}`})}async function Qw(e,t=5e3,n){try{const s=new AbortController,r=setTimeout(()=>s.abort(),t),a=await fetch(e,{method:"HEAD",signal:s.signal,redirect:"manual"});clearTimeout(r);const o=a.headers.get("content-type")||void 0,i=a.headers.get("content-length"),c=i?parseInt(i,10):void 0;let l=a.status>=200&&a.status<400;return l&&n?.expectedContentType&&o&&(n.expectedContentType.some(e=>o.toLowerCase().includes(e.toLowerCase()))||(l=!1)),l&&void 0!==c&&(n?.minSize&&cn.maxSize&&(l=!1)),{url:e,isValid:l,statusCode:a.status,contentType:o,contentLength:c}}catch(s){return{url:e,isValid:!1}}}async function ev(e,t){if(e.startsWith("data:"))return!0;const n=Date.now(),s=await Qw(e,t?.timeout||5e3,t),r=Date.now()-n,a="video";return Am[a].totalRequests++,Am[a].validationTimes.push(r),Am[a].validationTimes.length>100&&(Am[a].validationTimes=Am[a].validationTimes.slice(-100)),s.isValid}async function tv(e){const{urls:t,blossomServers:n=[],timeout:s=5e3,cache:r=!0,resourceType:a="video"}=e;if(0===t.length)return null;const o=t[0];if(o?.startsWith("data:"))return o;const i=a,c=Em[i];if(Am[i].totalRequests++,r){const e=t[0],n=c.get(e);if(n&&Date.now()-n.timestamp0&&t.length>0){const e=Zw(t[0],n);l.push(...e)}const u=Date.now();for(const f of l)if((await Qw(f,s)).isValid){r&&(c.set(t[0],{url:f,timestamp:Date.now()}),Im.delete(t[0]));const e=Date.now()-u;return Am[i].validationTimes.push(e),Am[i].validationTimes.length>100&&(Am[i].validationTimes=Am[i].validationTimes.slice(-100)),f}const d=Date.now()-u;return Am[i].validationTimes.push(d),Am[i].validationTimes.length>100&&(Am[i].validationTimes=Am[i].validationTimes.slice(-100)),r&&Im.set(t[0],Date.now()),t[0]||null}function nv(){return(nv=t(()=>{Em={video:new Map,image:new Map,vtt:new Map,audio:new Map},Mm=3e5,Im=new Map,Am={video:{totalRequests:0,cacheHits:0,cacheMisses:0,validationTimes:[]},image:{totalRequests:0,cacheHits:0,cacheMisses:0,validationTimes:[]},vtt:{totalRequests:0,cacheHits:0,cacheMisses:0,validationTimes:[]},audio:{totalRequests:0,cacheHits:0,cacheMisses:0,validationTimes:[]}}}))()}function sv(e){const{urls:t,variants:n,mediaType:s,sha256:r,kind:a,proxyConfig:o,authorPubkey:i,enabled:c=!0,discoveryEnabled:l,discoveryRelays:u,discoveryTimeout:d,preValidate:f,validationOptions:m}=e,p=cu()?.config,h=(0,Pm.useMemo)(()=>p?.blossomServers??[],[p?.blossomServers]),g=(0,Pm.useMemo)(()=>p?.cachingServers??[],[p?.cachingServers]),y=p?.media,[b,w]=(0,Pm.useState)(!1),[,v]=(0,Pm.useReducer)(e=>e+1,0),x=(0,Pm.useMemo)(()=>[c,s,r??"",a??"",i??"",...t,...(n??[]).flatMap(e=>[e.url,e.mimeType??""])].join("\0"),[i,c,a,s,r,t,n]),k=(0,Pm.useMemo)(()=>({urls:c?t:[],variants:c?n:void 0,blossomServers:h,cachingServers:g,sha256:r,kind:a,mediaType:s,authorPubkey:i,proxyConfig:o}),[i,h,g,c,a,s,o,r,t,n]),N=(0,Pm.useMemo)(()=>[x,o?.enabled,o?.maxSize?.width??"",o?.maxSize?.height??"",...h.map(e=>`${e.url}:${e.tags.join(",")}`),...g.map(e=>e.url)].join("\0"),[h,g,o,x]),j=(0,Pm.useRef)(null);j.current?.sourceKey!==x&&(j.current={sourceKey:x,ladder:new jm(k)});const S=j.current.ladder,C=(0,Pm.useRef)(k);C.current=k;const E=(0,Pm.useRef)({ladder:S,key:N});E.current.ladder!==S&&(E.current={ladder:S,key:N});const M=l??y?.failover.discovery.enabled??Boolean(r),I=(0,Pm.useMemo)(()=>[...new Set([...u??p?.relays.map(e=>e.url)??[],...Bo])],[p?.relays,u]),A=d??y?.failover.discovery.timeout??1e4,P=f??y?.failover.validation.enabled??!1,T=(0,Pm.useMemo)(()=>m??{timeout:y?.failover.validation.timeout??5e3},[y?.failover.validation.timeout,m]),R=S.urls.join("\0");return(0,Pm.useEffect)(()=>S.subscribe(v),[S]),(0,Pm.useEffect)(()=>{E.current.key!==N&&(E.current={ladder:S,key:N},S.refresh(C.current))},[S,N]),(0,Pm.useEffect)(()=>{if(!c||!M||!r||0===I.length)return;let e=!1;return w(!0),Yw({sha256:r,relays:I,timeout:A,maxResults:20}).then(t=>{e||S.merge(t.map(e=>e.url).filter(hf))}).catch(()=>{}).finally(()=>{e||w(!1)}),()=>{e=!0}},[c,M,I,A,S,r]),(0,Pm.useEffect)(()=>{if(!c||!P||0===S.urls.length)return;let e=!1;const t=S.urls.slice(0,5);return Promise.all(t.map(async e=>({url:e,isValid:await ev(e,T).catch(()=>!1)}))).then(t=>{e||S.promote(t.filter(e=>e.isValid).map(e=>e.url))}),()=>{e=!0}},[c,P,T,S,R]),{ladder:S,isLoading:b,error:S.error}}function rv(){return(rv=t(()=>{Pm=Be(),Hw(),Xw(),nv(),lu(),Jl()}))()}function av(...e){!function(){if("undefined"==typeof window)return!1;try{return"true"===window.localStorage.getItem(Tm)}catch{return!1}}()}function ov(e){return e.sha256?`sha256:${e.sha256}`:`url:${e.url}`}function iv(e){try{return new URL(e).origin}catch{return null}}function cv(e){const t=Lm.get(ov(e));if(t)return t.lastAccess=Date.now(),t.blob}function lv(e){const t=ov(e),n=Lm.get(t);if(n)return void(n.lastAccess=Date.now());const s=iv(e.url);if(s&&Fm.has(s))return void av(e.url);if(function(){if("undefined"==typeof navigator)return!1;const e=navigator.connection;if(!e)return!1;if(e.saveData)return!0;const t=e.effectiveType;return"slow-2g"===t||"2g"===t}())return void av();const r=Bm.get(t);r?r.priority=Math.min(r.priority,e.priority):(zm.set(t,{key:t,url:e.url,priority:e.priority}),uv())}function uv(){for(;Bm.size0;){let e;for(const t of zm.values())(!e||t.priorityDm)return void av();if(!t.body){const e=await t.blob();return e.size<=Dm?e:void 0}const r=t.body.getReader(),a=[];let o=0;for(;;){const{done:e,value:t}=await r.read();if(e)break;if(t){if(o+=t.byteLength,o>Dm)return await r.cancel(),void av();a.push(t)}}return new Blob(a,{type:n})}(e.url).then(t=>{t&&function(e,t){const n=t.size,s=Lm.get(e);s&&(_m-=s.bytes);Lm.set(e,{key:e,blob:t,bytes:n,lastAccess:Date.now()}),_m+=n,av((n/1024/1024).toFixed(1),Lm.size),function(){for(;Lm.size>$m||_m>Um;){let e;for(const t of Lm.values())(!e||t.lastAccess{!function(e,t){if(t instanceof DOMException&&"AbortError"===t.name)return;if(t instanceof TypeError){const t=iv(e);return void(t&&!Fm.has(t)&&(Fm.add(t),av()))}av()}(e.url,t)}).finally(()=>{Bm.get(e.key)===t&&Bm.delete(e.key),uv()})}function fv(){return(fv=t(()=>{Tm="nostube:prefetch-debug",Rm=2,Um=268435456,$m=6,Dm=100663296,Lm=new Map,Bm=new Map,zm=new Map,Fm=new Set,_m=0}))()}function mv({video:e,enabled:t,priority:n=1}){const{ladder:s}=sv({urls:e?.urls??[],mediaType:"video",sha256:e?.x,kind:e?.kind,authorPubkey:e?.pubkey,proxyConfig:Wm,enabled:t&&!!e}),r=s.currentUrl,a=e?.x;(0,Om.useEffect)(()=>{if(t&&r)return lv({sha256:a,url:r,priority:n}),()=>{!function(e){const t=ov(e);zm.delete(t)&&av(e.url)}({sha256:a,url:r})}},[t,r,a,n])}function pv(){return(pv=t(()=>{Om=Be(),rv(),fv(),Wm={enabled:!0}}))()}function hv(e){const{videoUrls:t,videoHash:n,videoExt:s,configServers:r,userServers:a}=e,o=(0,Vm.useMemo)(()=>function(e,t,n){const s=new Map;for(const r of e)if(!r.includes("?origin=")&&!r.includes("?xs="))try{const e=new URL(r),{sha256:t}=Zb(r);if(t){const t=Mf(e.origin);s.has(t)||s.set(t,{url:t,name:new URL(t).hostname,source:"video-url"})}}catch{}if(n&&n.length>0)for(const r of n){const e=Mf(r);s.has(e)||s.set(e,{url:e,name:new URL(e).hostname,source:"user"})}if(t&&t.length>0)for(const r of t){const e=Mf(r.url);s.has(e)||s.set(e,{url:e,name:r.name||new URL(e).hostname,source:"config"})}return Array.from(s.values()).sort((e,t)=>"video-url"===e.source&&"video-url"!==t.source?-1:"video-url"!==e.source&&"video-url"===t.source?1:e.name.localeCompare(t.name))}(t,r,a),[t,r,a]),[i,c]=(0,Vm.useState)(new Map),[l,u]=(0,Vm.useState)(!1),d=(0,Vm.useMemo)(()=>{const e=new Map;return o.forEach(t=>{const n=i.get(t.url);e.set(t.url,{...t,status:n?.status||"unknown",statusCode:n?.statusCode,contentLength:n?.contentLength,lastChecked:n?.lastChecked})}),e},[o,i]),f=(0,Vm.useRef)(null),m=(0,Vm.useRef)(i);(0,Vm.useEffect)(()=>{m.current=i},[i]);const p=n,h=(0,Vm.useMemo)(()=>{if(s)return s;for(const e of t){const{ext:t}=Zb(e);if(t)return t}return"mp4"},[t,s]),g=(0,Vm.useMemo)(()=>{if(p)return p;for(const e of t){const{sha256:t}=Zb(e);if(t)return t}},[p,t]),y=p||g;return{serverList:o,serverAvailability:d,checkAvailability:(0,Vm.useCallback)(async()=>{if(!y||!h)return;f.current&&f.current.abort(),f.current=new AbortController,u(!0);const e=Date.now(),t=3e5;c(n=>{const s=new Map(n);return o.forEach(r=>{const a=n.get(r.url);a?.lastChecked&&e-a.lastChecked{const s=m.current.get(n.url);if(s?.lastChecked&&e-s.lastChecked{const t=new Map(e);return t.set(n.url,r),t})});await Promise.allSettled(n),u(!1),f.current=null},[y,h,o]),isChecking:l}}function gv(){return(gv=t(()=>{Vm=Be(),ow(),If()}))()}function yv(e){return e?e instanceof Set?e:0===e.length?qm:new Set(e):qm}function bv(e,t,n){if(0===e.length)return{hasUnsafe:!1,unresolved:[]};const s=yv(n.nsfwPubkeys),r=yv(n.blockedPubkeys),a=yv(n.blockedEvents),o=yv(n.reportedEventIds),i=[];for(const c of e){if(o.has(c.id)||a.has(c.id))return{hasUnsafe:!0,unresolved:[]};if(c.pubkey&&(s.has(c.pubkey)||r.has(c.pubkey)))return{hasUnsafe:!0,unresolved:[]};if(c.address){const[e,n,...a]=c.address.split(":"),o=Number.parseInt(e??"",10);if(Number.isNaN(o)||!n)continue;const l=a.join(":"),u=t.getReplaceable(o,n,l);if(u){if(s.has(u.pubkey)||r.has(u.pubkey)||u.tags.some(e=>"content-warning"===e[0]))return{hasUnsafe:!0,unresolved:[]};continue}i.push({id:c.address,isAddress:!0,address:{kind:o,pubkey:n,identifier:l},relayHint:c.relayHint});continue}const e=t.getEvent(c.id);if(e){if(s.has(e.pubkey)||r.has(e.pubkey)||e.tags.some(e=>"content-warning"===e[0]))return{hasUnsafe:!0,unresolved:[]}}else i.push({id:c.id,isAddress:!1,relayHint:c.relayHint})}return{hasUnsafe:!1,unresolved:i}}function wv(){return(wv=t(()=>{qm=new Set}))()}function vv(){return Xm||(Xm=new Promise((e,t)=>{if("undefined"==typeof indexedDB)return void t(new Error("IndexedDB is not available in this environment"));const n=indexedDB.open(Jm,Hm);n.onupgradeneeded=()=>{const e=n.result;e.objectStoreNames.contains(Km)||e.createObjectStore(Km,{keyPath:"address"})},n.onsuccess=()=>e(n.result),n.onerror=()=>{Xm=null,t(n.error)}}))}function xv(e,t){const n="clean"===e.status?Gm:Ym;return t-e.ts{const a=t.transaction(Km,"readwrite"),o=a.objectStore(Km);for(const{address:t,eventId:i,status:c}of e){const e={address:t,eventId:i,status:c,ts:n};o.put(e)}a.oncomplete=()=>s(),a.onerror=()=>r(a.error)})}catch{}}function Nv(){return(Nv=t(()=>{Jm="nostube-playlist-validation",Hm=1,Km="validations",Gm=6048e5,Ym=2592e6,Xm=null}))()}function jv(e){const t=[];for(const n of e.tags)if("e"===n[0]){let s;for(let e=3;e=3){const r=Number.parseInt(s[0]??"",10);if(Number.isNaN(r))continue;const a=s[1],o=s.slice(2).join(":");t.push({id:`${r}:${a}:${o}`,kind:r,added_at:e.created_at,relayHint:n[2],pubkey:a,address:n[1]})}}return t}function Sv(e){const t=e.tags.find(e=>"d"===e[0])?.[1];return t?`${e.kind}:${e.pubkey}:${t}`:null}function Cv(e,t){const{enabled:n,sources:s,relays:r,videosByEventId:a,loadTimeoutMs:o=15e3}=t,i=Cr(),{pool:c}=iu(),l=(0,Zm.useMemo)(()=>function(e,t){const n=[];for(const s of e){const e=Sv(s);e&&n.push({event:s,address:e,videos:[...t?.get(s.id)??jv(s)]})}return n}(e,a),[e,a]),u=(0,Zm.useRef)(s);u.current=s;const[d,f]=(0,Zm.useState)(()=>new Map);return(0,Zm.useEffect)(()=>{n||f(e=>{if(0===e.size&&0===l.length)return e;const t=new Map;for(const n of l)t.set(n.event.id,"clean");return t})},[n,l]),(0,Zm.useEffect)(()=>{if(!n)return;let e=!1;const t=[];let s=null;const a=new Map;for(const n of l)a.set(n.event.id,n);const d=t=>{0===t.length||e||f(e=>{let n=!1;const s=new Map(e);for(const[r,a]of t)s.get(r)!==a&&(s.set(r,a),n=!0);return n?s:e})};d(l.map(e=>[e.event.id,"pending"]));const m=new Map,p=[],h=[],g=i;for(const n of l){const e=bv(n.videos,g,u.current);m.set(n.event.id,e),e.hasUnsafe?(p.push([n.event.id,"unsafe"]),h.push({address:n.address,eventId:n.event.id,status:"unsafe"}),a.delete(n.event.id)):0===e.unresolved.length&&(p.push([n.event.id,"clean"]),h.push({address:n.address,eventId:n.event.id,status:"clean"}),a.delete(n.event.id))}return d(p),h.length>0&&kv(h),(async()=>{if(e||0===a.size)return;const n=[];for(const e of a.values())n.push({address:e.address,eventId:e.event.id});const l=await async function(e){const t=new Map;if(0===e.length)return t;try{const n=await vv(),s=Date.now();return await new Promise((r,a)=>{const o=n.transaction(Km,"readonly").objectStore(Km);let i=e.length;if(0!==i)for(const{address:n,eventId:c}of e){const e=o.get(n);e.onsuccess=()=>{const a=e.result;a&&a.eventId===c&&xv(a,s)&&t.set(n,{eventId:a.eventId,status:a.status,ts:a.ts}),0===--i&&r(t)},e.onerror=()=>a(e.error)}else r(t)})}catch{return t}}(n);if(e)return;const f=[];for(const[,e]of[...a]){const t=l.get(e.address);t&&(f.push([e.event.id,t.status]),a.delete(e.event.id))}if(d(f),e||0===a.size)return;const p=new Map,h=new Map,y=new Map;for(const e of a.values()){const t=m.get(e.event.id);if(t)for(const n of t.unresolved){let t=y.get(n.id);t||(t=new Set,y.set(n.id,t)),t.add(e.event.id),n.isAddress&&n.address?h.has(n.id)||h.set(n.id,{address:n.id,pointer:n.address,relayHint:n.relayHint}):n.isAddress||p.has(n.id)||p.set(n.id,{id:n.id,relayHint:n.relayHint})}}const b=t=>{const n=new Set,s=y.get(t.id);if(s)for(const e of s)n.add(e);const r=t.tags.find(e=>"d"===e[0])?.[1];if(r){const e=y.get(`${t.kind}:${t.pubkey}:${r}`);if(e)for(const t of e)n.add(t)}n.size>0&&(t=>{if(e)return;const n=[],s=[];for(const e of t){const t=a.get(e);if(!t)continue;const r=bv(t.videos,g,u.current);r.hasUnsafe?(n.push([e,"unsafe"]),s.push({address:t.address,eventId:t.event.id,status:"unsafe"}),a.delete(e)):0===r.unresolved.length&&(n.push([e,"clean"]),s.push({address:t.address,eventId:t.event.id,status:"clean"}),a.delete(e))}d(n),s.length>0&&kv(s)})(n)};if(p.size>0){const n=[...p.keys()],s=function(e,t,n){const s=new Set(t);for(const r of e){r.relayHint&&s.add(r.relayHint);const e=n.getEvent(r.id);if(e){const t=rr(e);if(t)for(const e of t)s.add(e)}}return[...s]}(p.values(),r,i),a=w(c,s,{ids:n},{eventStore:i});if(e)return;t.push(a().subscribe({next:t=>{e||(i.add(t),b(t))},error:e=>{}}))}if(h.size>0){const n=ke(c,{eventStore:i,extraRelays:r});for(const s of h.values()){if(e)return;t.push(n(s.pointer).subscribe({next:t=>{!e&&t&&(i.add(t),b(t))},error:e=>{}}))}}s=window.setTimeout(()=>{for(const e of t)e.unsubscribe();t.length=0},o)})(),()=>{e=!0,null!==s&&window.clearTimeout(s);for(const e of t)e.unsubscribe()}},[l,n,i,c,r,o]),d}function Ev(){return(Ev=t(()=>{Zm=Be(),Wt(),be(),xs(),wv(),Nv(),lu(),Qm=/^[0-9a-f]{64}$/i}))()}function Mv(e){const t=e.map(rl).filter(e=>{try{const t=new URL(e);return"wss:"===t.protocol||"ws:"===t.protocol}catch{return!1}});return Array.from(new Set(t))}function Iv(){return(Iv=t(()=>{dl(),ep=10013}))()}function Av(e){const{config:t}=iu(),n=(0,tp.useMemo)(()=>e?{kinds:[10002],authors:[e],limit:1}:null,[e]),s=(0,tp.useMemo)(()=>{const e=new Set;return t.relays.forEach(t=>e.add(t.url)),Do.forEach(t=>e.add(t.url)),e.add(Lo),Bo.forEach(t=>e.add(t)),Array.from(e)},[t.relays]),{event:r,isLoading:a}=function(e,t){const{events:n,isLoading:s}=md(e,t);return{event:(0,Hi.useMemo)(()=>n[0]??null,[n]),isLoading:s}}(n,{relays:s});return{data:(0,tp.useMemo)(()=>{if(!e||!r)return[];const t=r,n=[];for(const e of t.tags)if("r"===e[0]&&e[1]){const t=e[1],s="read"===e[2]||void 0===e[2],r="write"===e[2]||void 0===e[2];n.push({url:t,read:s,write:r})}return n},[e,r]),isLoading:!!e&&a,enabled:!!e}}function Pv(){return(Pv=t(()=>{tp=Be(),lu(),Jl(),pd()}))()}function Tv({children:e}){const{user:t}=yu(),{data:n}=Av(t?.pubkey),s=(0,np.useMemo)(()=>{if(!t||!n||0===n.length)return{relays:null,readRelays:null,writeRelays:null};const e=n.filter(e=>e.read).map(e=>e.url),s=n.filter(e=>e.write).map(e=>e.url);return{relays:n,readRelays:e.length>0?e:null,writeRelays:s.length>0?s:null}},[n,t]);return(0,sp.jsx)(rp.Provider,{value:s,children:e})}function Rv(){return(0,np.useContext)(rp)}function Uv(){return(Uv=t(()=>{np=Be(),bu(),Pv(),sp=Q(),rp=(0,np.createContext)({relays:null,readRelays:null,writeRelays:null})}))()}function $v({children:e}){const{pool:t}=iu(),{user:n}=yu(),{writeRelays:s}=Rv(),r=Cr(),[a,o]=(0,ap.useState)([]),[i,c]=(0,ap.useState)(!1),[l,u]=(0,ap.useState)(null),[d,f]=(0,ap.useState)({}),m=n?.signer;(0,ap.useEffect)(()=>{let e=!1;if(o([]),u(null),!n?.pubkey||!m?.nip44||!s?.length)return void c(!1);c(!0);let a=-1;const i=async t=>{if(!(t.created_atArray.isArray(e)&&"relay"===e[0]&&"string"==typeof e[1]?[e[1]]:[]))}(m,n.pubkey,t);e||(o(s),u(null))}catch(s){e||u(s instanceof Error?s:new Error("Failed to decrypt private relay list"))}}},l=r.getReplaceable(ep,n.pubkey);l&&i(l);const d=t.request(s,{kinds:[ep],authors:[n.pubkey],limit:1}).subscribe({next:e=>{r.add(e);const t=r.getReplaceable(ep,n.pubkey);t&&i(t)},error:t=>{e||(u(t instanceof Error?t:new Error("Failed to load private relay list")),c(!1))},complete:()=>{e||c(!1)}});return()=>{e=!0,d.unsubscribe()}},[r,t,m,n?.pubkey,s]),(0,ap.useEffect)(()=>{if(f(Object.fromEntries(a.map(e=>[e,"disconnected"]))),m&&n?.pubkey)return function(e,t,n,s,r){const a=Mv(t).flatMap(t=>{const a=e.relay(t);let o;return[a.connected$.subscribe(e=>{r(t,e?a.authenticatedAs===s?"authenticated":"connected":"disconnected")}),a.authenticatedAs$.subscribe(e=>{e===s&&r(t,"authenticated")}),a.challenge$.subscribe(e=>{e&&a.authenticatedAs!==s&&!o&&(r(t,"authenticating"),o=a.authenticate(n).then(e=>{if(!e.ok)throw new Error(e.message||"Relay rejected authentication");r(t,"authenticated")}).catch(e=>{r(t,"error",e instanceof Error?e:new Error("Relay authentication failed"))}).finally(()=>{o=void 0}))})]});return()=>a.forEach(e=>e.unsubscribe())}(t,a,m,n.pubkey,(e,t,n)=>{f(n=>({...n,[e]:t}))})},[t,a,m,n?.pubkey]);const p=(0,ap.useCallback)(async e=>{if(!n?.pubkey||!m?.nip44)throw new Error("A NIP-44 capable signer is required to configure private relays");if(!s?.length)throw new Error("Publish a NIP-65 write relay list before configuring private relays");const a=Mv(e),i=await async function(e,t,n){if(!e.nip44)throw new Error("Signer does not support NIP-44 encryption");const s=Mv(n).map(e=>["relay",e]),r=await e.nip44.encrypt(t,JSON.stringify(s)),a={kind:ep,created_at:ol(),tags:[],content:r};return e.signEvent(a)}(m,n.pubkey,a);if(!(await t.publish(s,i)).some(e=>e.ok))throw new Error("The private relay list was rejected by every NIP-65 write relay");r.add(i),o(a),u(null)},[r,t,m,n?.pubkey,s]),h=(0,ap.useCallback)(async e=>{if(!m)throw new Error("User is not logged in");const n=await m.signEvent(e);return await async function(e,t,n){const s=Mv(t);if(0===s.length)throw new Error("Configure at least one private relay before publishing private content");const r=await e.publish(s,n);if(!r.some(e=>e.ok)){const e=r.map(e=>e.message).filter(Boolean).join("; ");throw new Error(e||"All private relays rejected the event")}}(t,a,n),r.add(n),n},[r,t,a,m]),g=(0,ap.useMemo)(()=>({relays:a,isLoading:i,error:l,canConfigure:Boolean(n?.pubkey&&m?.nip44&&s?.length),statuses:d,configure:p,publish:h}),[p,l,i,h,a,m?.nip44,d,n?.pubkey,s?.length]);return(0,op.jsx)(ip.Provider,{value:g,children:e})}function Dv(){const e=(0,ap.useContext)(ip);if(!e)throw new Error("usePrivateRelays must be used within PrivateRelaysProvider");return e}function Lv(){return(Lv=t(()=>{ap=Be(),Wt(),lu(),bu(),Iv(),Uv(),op=Q(),ip=(0,ap.createContext)(void 0)}))()}function Bv(e,t,n){const s=[],r=/^[0-9a-f]{64}$/i;for(const a of e)if("e"===a[0]){const e=n.getEvent(a[1]),o=e?rr(e):void 0,i=a[2]||(o?Array.from(o)[0]:void 0);let c=e?.pubkey;if(!c)for(let t=3;t=3){const n=parseInt(e[0]),r=e[1],o=e.slice(2).join(":"),i=a[2]||void 0;s.push({id:`${n}:${r}:${o}`,kind:n,title:void 0,added_at:t,relayHint:i,pubkey:r,address:a[1]})}}return s}function zv(){const e=Cr(),{user:t}=yu(),{publish:n}=ku(),{config:s,pool:r}=iu(),{presetContent:a}=vd(),{relays:o,publish:i}=Dv(),[c,l]=(0,cp.useState)(!1),u=(0,cp.useRef)(!1),d=(0,cp.useMemo)(()=>s.relays.filter(e=>e.tags.includes("read")).map(e=>e.url),[s.relays]),f=(0,cp.useMemo)(()=>Array.from(new Set([...d,...o])),[o,d]),m=(0,cp.useMemo)(()=>[up(t?.pubkey)],[t?.pubkey]),p=(0,cp.useMemo)(()=>[{kinds:[5],authors:t?.pubkey?[t.pubkey]:[]}],[t?.pubkey]),h=(0,cp.useMemo)(()=>w(r,f,[...m,...p],{eventStore:e}),[r,f,m,p,e]),g=Dt(()=>e.timeline(m),[e,m]),y=(0,cp.useMemo)(()=>g??[],[g]),b=(0,cp.useMemo)(()=>nf(e,y),[e,y]);(0,cp.useEffect)(()=>{if(!t?.pubkey||u.current)return;u.current=!0,l(!0);const n=h();let s=!1;const r=setTimeout(()=>{l(!1)},1e3),a=setTimeout(()=>{l(!1)},1e4),o=n.subscribe({next:t=>{e.add(t),s||(s=!0)},complete:()=>{clearTimeout(r),clearTimeout(a),l(!1)},error:e=>{clearTimeout(r),clearTimeout(a),l(!1)}});return()=>{clearTimeout(r),clearTimeout(a),o.unsubscribe()}},[t?.pubkey,e,h]);const[v,x]=(0,cp.useState)([]);(0,cp.useEffect)(()=>{let n=!1;const s=t=>{const n=t.tags.find(e=>"title"===e[0]),s=t.tags.find(e=>"description"===e[0]),r=n?n[1]:"Untitled Playlist",a=s?s[1]:void 0,o=t.tags.some(e=>"encrypted"===e[0])||""!==t.content,i=Bv(t.tags,t.created_at,e),c=t.tags.find(e=>"content-warning"===e[0]),l=c?c[1]||"NSFW":void 0;return{identifier:t.tags.find(e=>"d"===e[0])?.[1]||"",name:o?r||"Private Playlist":r,description:a,videos:i,eventId:t.id,isPrivate:o,contentWarning:l}};return(async()=>{const r=[];for(const n of b){const o=s(n);if(o.isPrivate&&t?.signer?.nip44)try{const s=await t.signer.nip44.decrypt(t.pubkey,n.content),r=JSON.parse(s),a=r.find(e=>"title"===e[0]),i=r.find(e=>"description"===e[0]);a&&(o.name=a[1]),i&&(o.description=i[1]),o.videos=Bv(r,n.created_at,e)}catch(a){}r.push(o)}n||x(r)})(),()=>{n=!0}},[b,t?.pubkey,t?.signer,e]);const k="show"!==(s.nsfwFilter??"hide"),N=(0,cp.useMemo)(()=>({nsfwPubkeys:a.nsfwPubkeys,blockedPubkeys:a.blockedPubkeys,blockedEvents:a.blockedEvents,reportedEventIds:s.reportedEventIds??[]}),[a.nsfwPubkeys,a.blockedPubkeys,a.blockedEvents,s.reportedEventIds]),j=(0,cp.useMemo)(()=>{const e=new Map;for(const t of v)t.eventId&&e.set(t.eventId,t.videos);return e},[v]),S=Cv((0,cp.useMemo)(()=>b.filter(e=>!e.tags.some(e=>"content-warning"===e[0])),[b]),{enabled:k,sources:N,relays:d,videosByEventId:j}),C=(0,cp.useMemo)(()=>v.map(e=>{const t=k&&e.eventId?e.contentWarning?"unsafe":S.get(e.eventId)??"pending":"clean";return{...e,safetyState:t}}),[v,k,S]),E=(0,cp.useCallback)(async r=>{if(!t?.pubkey)throw new Error("User not logged in");l(!0);try{const a=r.videos.map(t=>{if(t.address){const e=["a",t.address];return t.relayHint&&e.push(t.relayHint),e}const n=e.getEvent(t.id),s=n?rr(n):void 0,r=t.relayHint||(s?Array.from(s)[0]:void 0),a=["e",t.id];return r&&a.push(r),a});let o,c="";const l=r.contentWarning?[["content-warning",r.contentWarning]]:[];if(r.isPrivate){if(!t.signer?.nip44)throw new Error("Signer does not support NIP-44 encryption");o=[["d",r.identifier],["encrypted",""],...l,["client","nostube"]];const e=[["title",r.name],["description",r.description||""],...a];c=await t.signer.nip44.encrypt(t.pubkey,JSON.stringify(e))}else o=[["d",r.identifier],["title",r.name],["description",r.description||""],...l,...a,["client","nostube"]];const u={kind:lp,created_at:ol(),tags:o,content:c},d=r.isPrivate?await i(u):await n({event:u,relays:s.relays.filter(e=>e.tags.includes("write")).map(e=>e.url)});return e.add(d),r}finally{l(!1)}},[t?.pubkey,t?.signer,n,i,s.relays,e]),M=(0,cp.useCallback)(async(e,t,n)=>{const s={eventId:void 0,identifier:"nostube-"+crypto.randomUUID(),name:e,description:t,videos:[],isPrivate:n||!1};await E(s)},[E]),I=(0,cp.useCallback)(async(t,n,s,r,a,o)=>{const i=v.find(e=>e.identifier===t);if(!i)throw new Error("Playlist not found");const c=(34235===s||34236===s)&&o&&a?`${s}:${a}:${o}`:void 0;if(i.videos.some(e=>e.id===n||c&&e.address===c))return;const l=e.getEvent(n),u=l?rr(l):void 0,d=u?Array.from(u)[0]:void 0,f={...i,videos:[...i.videos,{id:n,kind:s||0,title:r,added_at:ol(),relayHint:d,address:c}]};await E(f)},[v,E,e]),A=(0,cp.useCallback)(async(e,t)=>{const n=v.find(t=>t.identifier===e);if(!n)throw new Error("Playlist not found");const s={...n,videos:n.videos.filter(e=>e.id!==t&&e.address!==t)};await E(s)},[v,E]),P=(0,cp.useCallback)(async r=>{if(!t?.pubkey)throw new Error("User not logged in");const a={kind:5,created_at:ol(),tags:[["e",r],["k",lp.toString()]],content:"Deleted by author"},o=v.find(e=>e.eventId===r)?.isPrivate?await i(a):await n({event:a,relays:s.relays.filter(e=>e.tags.includes("write")).map(e=>e.url)});e.add(o)},[t?.pubkey,v,n,i,s.relays,e]);(0,cp.useEffect)(()=>{if(!t?.pubkey)return;const n=new Set,s=new Map;for(const t of v)if(!t.isPrivate&&!t.contentWarning)for(const r of t.videos)if(r.address){if(s.has(r.address))continue;const[t,n,...a]=r.address.split(":"),o=Number.parseInt(t??"",10);if(Number.isNaN(o)||!n)continue;const i=a.join(":");if(e.getReplaceable(o,n,i))continue;s.set(r.address,{kind:o,pubkey:n,identifier:i})}else{if(e.hasEvent(r.id))continue;n.add(r.id)}if(0===n.size&&0===s.size)return;const a=[];if(n.size>0){const t=w(r,d,{ids:Array.from(n)},{eventStore:e});a.push(t().subscribe({next:t=>{t&&e.add(t)},error:e=>{}}))}if(s.size>0){const t=ke(r,{eventStore:e,extraRelays:d});for(const n of s.values())a.push(t(n).subscribe({next:t=>{t&&e.add(t)},error:e=>{}}))}return()=>{for(const e of a)e.unsubscribe()}},[v,e,r,d,t?.pubkey]);const T=(0,cp.useRef)(new Set);return(0,cp.useEffect)(()=>{if(!t?.pubkey)return;const n={nsfwPubkeys:a.nsfwPubkeys,blockedPubkeys:a.blockedPubkeys,blockedEvents:a.blockedEvents,reportedEventIds:s.reportedEventIds??[]},r=t=>{if(t.isPrivate)return;if(t.contentWarning)return;if(!t.eventId)return;if(T.current.has(t.eventId))return;if(!function(e,t,n){if(0===e.length)return!1;const s=yv(n.nsfwPubkeys),r=yv(n.blockedPubkeys),a=yv(n.blockedEvents),o=yv(n.reportedEventIds);for(const i of e){if(o.has(i.id)||a.has(i.id))return!0;if(i.pubkey&&(s.has(i.pubkey)||r.has(i.pubkey)))return!0;if(i.address){const[e,n,...a]=i.address.split(":"),o=Number.parseInt(e??"",10);if(!Number.isNaN(o)&&n){const e=t.getReplaceable(o,n,a.join(":"));if(e&&(s.has(e.pubkey)||r.has(e.pubkey)||e.tags.some(e=>"content-warning"===e[0])))return!0}continue}const e=t.getEvent(i.id);if(e&&(s.has(e.pubkey)||r.has(e.pubkey)||e.tags.some(e=>"content-warning"===e[0])))return!0}return!1}(t.videos,e,n))return;const s=t.eventId;T.current.add(s),E({...t,contentWarning:"NSFW"}).catch(e=>{T.current.delete(s)})};for(const e of v)r(e);const o=new Set,i=new Set;for(const e of v)if(!e.isPrivate&&!e.contentWarning)for(const t of e.videos)t.address?i.add(t.address):o.add(t.id);if(0===o.size&&0===i.size)return;const c=e=>{let t=!1;if(o.has(e.id))t=!0;else{const n=e.tags.find(e=>"d"===e[0])?.[1];n&&i.has(`${e.kind}:${e.pubkey}:${n}`)&&(t=!0)}if(t)for(const n of v)r(n)},l=e.insert$.subscribe(c),u=e.update$.subscribe(c);return()=>{l.unsubscribe(),u.unsubscribe()}},[v,e,t?.pubkey,a.nsfwPubkeys,a.blockedPubkeys,a.blockedEvents,s.reportedEventIds,E]),{playlists:C,isLoading:c,createPlaylist:M,addVideo:I,removeVideo:A,deletePlaylist:P,updatePlaylist:E}}function Fv(e,t){const n=Cr(),{pool:s,config:r}=iu(),{presetContent:a}=vd(),o=(0,cp.useMemo)(()=>r.relays.filter(e=>e.tags.includes("read")).map(e=>e.url),[r.relays]),i=t||o,c=(0,cp.useMemo)(()=>[up(e)],[e]),l=(0,cp.useMemo)(()=>[{kinds:[5],authors:e?[e]:[]}],[e]),u=Dt(()=>n.timeline(c),[n,c]),d=(0,cp.useMemo)(()=>u??[],[u]),f=(0,cp.useMemo)(()=>nf(n,d),[n,d]),m=(0,cp.useRef)(!1),[p,h]=(0,cp.useState)(!1),g=(0,cp.useMemo)(()=>w(s,i,[...c,...l],{eventStore:n}),[s,i,c,l,n]);(0,cp.useEffect)(()=>{m.current=!1},[i]),(0,cp.useEffect)(()=>{if(!e){const e=setTimeout(()=>h(!1),0);return()=>clearTimeout(e)}if(m.current)return;m.current=!0;const t=setTimeout(()=>h(!0),0),s=g(),r=setTimeout(()=>{h(!1)},1e3),a=setTimeout(()=>{h(!1)},1e4),o=s.subscribe({next:e=>n.add(e),complete:()=>{clearTimeout(r),clearTimeout(a),h(!1)},error:()=>{clearTimeout(r),clearTimeout(a),h(!1)}});return()=>{clearTimeout(t),clearTimeout(r),clearTimeout(a),o.unsubscribe()}},[e,g,n]);const y=(0,cp.useMemo)(()=>f?.filter(e=>!e.content)??[],[f]),b=r.nsfwFilter??"hide",v="hide"===b,x="show"!==b,k=r.reportedEventIds,N=(0,cp.useMemo)(()=>y.filter(e=>{const t=e.tags.find(e=>"content-warning"===e[0]);return!v||!t}),[y,v]),j=(0,cp.useMemo)(()=>N.filter(e=>!e.tags.some(e=>"content-warning"===e[0])),[N]),S=(0,cp.useMemo)(()=>({nsfwPubkeys:a.nsfwPubkeys,blockedPubkeys:a.blockedPubkeys,blockedEvents:a.blockedEvents,reportedEventIds:k??[]}),[a.nsfwPubkeys,a.blockedPubkeys,a.blockedEvents,k]),C=Cv(j,{enabled:x,sources:S,relays:i});return{data:(0,cp.useMemo)(()=>{const e=[];for(const t of N){const s=t.tags.find(e=>"content-warning"===e[0]),r=s?s[1]||"NSFW":void 0,a=x?r?"unsafe":C.get(t.id)??"pending":"clean";if(v&&"clean"!==a)continue;const o=t.tags.find(e=>"title"===e[0]),i=t.tags.find(e=>"description"===e[0]),c=Bv(t.tags,t.created_at,n);e.push({identifier:t.tags.find(e=>"d"===e[0])?.[1]||"",name:o?o[1]:"Untitled Playlist",description:i?i[1]:void 0,videos:c,eventId:t.id,isPrivate:!1,contentWarning:r,safetyState:a})}return e},[N,n,v,x,C]),isLoading:p,enabled:!!e}}function _v(){return(_v=t(()=>{Wt(),bu(),Nu(),kd(),dl(),lu(),cp=Be(),be(),xs(),wv(),Ev(),Lv(),lp=30005,up=e=>({kinds:[lp],authors:e?[e]:[]})}))()}function Ov(e){const t=[];for(const n of e)if("e"===n[0]){let e;for(let t=3;t=3){const s=parseInt(e[0]),r=e[1],a=e.slice(2).join(":");t.push({id:`${s}:${r}:${a}`,kind:s,added_at:0,relayHint:n[2],pubkey:r,address:n[1]})}}return t}function Wv(){const e=Cr(),{pool:t,config:n}=iu(),s=(0,dp.useMemo)(()=>n.relays.filter(e=>e.tags.includes("read")).map(e=>e.url),[n.relays]),r=(0,dp.useMemo)(()=>[fp],[]),a=Dt(()=>e.timeline(r),[e,r]),o=(0,dp.useMemo)(()=>a??[],[a]),[i,c]=(0,dp.useState)(!1),l=(0,dp.useRef)(!1),u=(0,dp.useMemo)(()=>w(t,s,r,{eventStore:e}),[t,s,r,e]);(0,dp.useEffect)(()=>{if(l.current)return;l.current=!0;const t=setTimeout(()=>c(!0),0),n=u(),s=setTimeout(()=>c(!1),2e3),r=setTimeout(()=>c(!1),15e3),a=n.subscribe({next:t=>e.add(t),complete:()=>{clearTimeout(s),clearTimeout(r),c(!1)},error:()=>{clearTimeout(s),clearTimeout(r),c(!1)}});return()=>{clearTimeout(t),clearTimeout(s),clearTimeout(r),a.unsubscribe()}},[u,e]);const d=n.nsfwFilter??"hide",f="hide"===d,m="show"!==d,{presetContent:p}=vd(),h=n.reportedEventIds,g=(0,dp.useMemo)(()=>o.filter(e=>{if(e.content)return!1;const t=e.tags.find(e=>"content-warning"===e[0]);return!f||!t}),[o,f]),y=(0,dp.useMemo)(()=>g.filter(e=>!e.tags.some(e=>"content-warning"===e[0])),[g]),b=(0,dp.useMemo)(()=>({nsfwPubkeys:p.nsfwPubkeys,blockedPubkeys:p.blockedPubkeys,blockedEvents:p.blockedEvents,reportedEventIds:h??[]}),[p.nsfwPubkeys,p.blockedPubkeys,p.blockedEvents,h]),v=Cv(y,{enabled:m,sources:b,relays:s});return{playlists:(0,dp.useMemo)(()=>{const e=[];for(const t of g){const n=t.tags.find(e=>"content-warning"===e[0]),s=n?n[1]||"NSFW":void 0,r=m?s?"unsafe":v.get(t.id)??"pending":"clean";if(f&&"clean"!==r)continue;const a=Ov(t.tags);if(0===a.length)continue;const o=t.tags.find(e=>"title"===e[0]),i=t.tags.find(e=>"description"===e[0]),c=t.tags.find(e=>"d"===e[0])?.[1]||"";e.push({eventId:t.id,pubkey:t.pubkey,identifier:c,name:o?.[1]||"Untitled Playlist",description:i?.[1],contentWarning:s,safetyState:r,videos:a})}return e},[g,f,m,v]),isLoading:i}}function Vv(){return(Vv=t(()=>{Wt(),lu(),dp=Be(),be(),kd(),Ev(),fp={kinds:[30005]},mp=/^[0-9a-f]{64}$/i}))()}function qv(e){return"object"==typeof e&&null!==e&&"id"in e}function Jv(e){return"object"==typeof e&&null!==e&&"identifier"in e&&"pubkey"in e&&"kind"in e}function Hv(e,t){const n=Cr(),{config:s,pool:r}=iu(),{presetContent:a}=vd(),{user:o}=yu(),i=uu(),{relays:c}=Dv(),[l,u]=(0,pp.useState)(new Set),[d,f]=(0,pp.useState)(new Set),[m,p]=(0,pp.useState)(null),[h,g]=(0,pp.useState)(!1),y=(0,pp.useMemo)(()=>{if(!e)return null;const t=uf(e);return t||of(e)},[e]),b=(0,pp.useMemo)(()=>y?qv(y)?`event:${y.id}`:`addr:${y.kind}:${y.pubkey}:${y.identifier}`:"",[y]);(0,pp.useEffect)(()=>{let e=!1;return(async()=>{await Promise.resolve(),e||(u(new Set),f(new Set))})(),()=>{e=!0}},[b]);const v=(0,pp.useMemo)(()=>s.relays.map(e=>e.url),[s.relays]),x=(0,pp.useMemo)(()=>al([t||[],y?.relays||[],c,v,zo]),[y,c,v,t]),k=(0,pp.useMemo)(()=>Ae(r,{eventStore:n,extraRelays:x}),[r,n,x]),N=(0,pp.useMemo)(()=>ke(r,{eventStore:n,extraRelays:x}),[r,n,x]),j=(0,pp.useMemo)(()=>y?qv(y)?n.event(y.id).pipe(hn(e=>e??void 0)):Jv(y)?n.replaceable(y.kind,y.pubkey,y.identifier).pipe(hn(e=>e??void 0)):Dr(void 0):Dr(void 0),[y,n]),S=Dt(()=>j,[j]),C=Boolean(y)&&!S;(0,pp.useEffect)(()=>{if(!y)return;let e;return qv(y)?e=k(y).subscribe({next:e=>{e&&n.add(e)},error:e=>{}}):Jv(y)&&(e=N(y).subscribe({next:e=>{e&&n.add(e)},error:e=>{}})),()=>{e&&e.unsubscribe()}},[y,n,k,N]);const E=S?.tags.some(e=>"encrypted"===e[0])||Boolean(S?.content);(0,pp.useEffect)(()=>{let e=!1;return S&&S.content?o?.pubkey&&S.pubkey===o.pubkey&&o.signer?.nip44?((async()=>{try{const t=await o.signer.nip44.decrypt(o.pubkey,S.content),n=JSON.parse(t);e||(p(n),g(!1))}catch(t){e||(p(null),g(!0))}})(),()=>{e=!0}):((async()=>{await Promise.resolve(),e||(p(null),g(!0))})(),()=>{e=!0}):((async()=>{await Promise.resolve(),e||(p(null),g(!1))})(),()=>{e=!0})},[S,o?.pubkey,o?.signer]);const{playlistTitle:M,playlistDescription:I,videoRefs:A}=(0,pp.useMemo)(()=>{if(!S)return{playlistTitle:"",playlistDescription:"",videoRefs:[]};const e=m?[...S.tags,...m]:S.tags,t=e.find(e=>"title"===e[0])?.[1]||(E?"Private Playlist":"Untitled Playlist"),s=e.find(e=>"description"===e[0])?.[1]||"",r=[];for(const a of e)if("e"===a[0]){const e=a[2]||"",t=e?[e]:[],s=n.getEvent(a[1]),o=s?rr(s):void 0,i=al([t,o?Array.from(o):[]]);r.push({id:a[1],kind:0,relayHints:i})}else if("a"===a[0]){const e=a[1]?.split(":");if(e&&e.length>=3){const t=parseInt(e[0]),s=e[1],o=e.slice(2).join(":"),i=a[2]?[a[2]]:[],c=n.getReplaceable(t,s,o)?.id;r.push({id:c||a[1],kind:t,relayHints:i,address:a[1]})}}return{playlistTitle:t,playlistDescription:s,videoRefs:r}},[S,n,m,E]);(0,pp.useEffect)(()=>{if(!S||0===A.length)return;const e=A.filter(e=>e.address),t=A.filter(e=>!e.address),s=e.filter(e=>{const t=e.address.split(":");return t.length<3||!n.getReplaceable(parseInt(t[0]),t[1],t.slice(2).join(":"))}),a=t.filter(e=>!n.hasEvent(e.id));if(0===s.length&&0===a.length)return;let o=!1;const i=[...a.map(e=>e.id),...s.map(e=>e.id)];(async()=>{await Promise.resolve(),o||f(new Set(i))})();const c=rr(S),l=c?Array.from(c):[],d=al([[...a,...s].flatMap(e=>e.relayHints||[]),l,x]),m=new Set,p=[],h=setTimeout(()=>{o||(i.forEach(e=>{m.has(e)||u(t=>new Set([...t,e]))}),f(new Set))},1e4),g=e=>{m.add(e),f(t=>{const n=new Set(t);return n.delete(e),n}),u(t=>{const n=new Set(t);return n.delete(e),n})};if(a.length>0){const e=a.map(e=>e.id),t=w(r,d,{ids:e},{eventStore:n});p.push(t().subscribe({next:t=>{!o&&t&&e.includes(t.id)&&(n.add(t),g(t.id))},complete:()=>{o||a.forEach(e=>{m.has(e.id)||n.hasEvent(e.id)||(u(t=>new Set([...t,e.id])),f(t=>{const n=new Set(t);return n.delete(e.id),n}))})},error:e=>{o||a.forEach(e=>{u(t=>new Set([...t,e.id]))})}}))}for(const r of s){const e=r.address.split(":");if(e.length<3)continue;const t=parseInt(e[0]),s=e[1],a=e.slice(2).join(":");p.push(N({kind:t,pubkey:s,identifier:a}).subscribe({next:e=>{!o&&e&&(n.add(e),g(r.id))},error:e=>{o||(u(e=>new Set([...e,r.id])),f(e=>{const t=new Set(e);return t.delete(r.id),t}))}}))}return()=>{o=!0,clearTimeout(h),p.forEach(e=>e.unsubscribe())}},[A,n,r,x,S,N]);const P=(0,pp.useMemo)(()=>{if(0===A.length)return Dr([]);const e=A.map(e=>{if(e.address){const t=e.address.split(":");if(t.length>=3){const e=parseInt(t[0]),s=t[1],r=t.slice(2).join(":");return n.replaceable(e,s,r).pipe(Os(e=>Dr(e)))}}return n.event(e.id).pipe(Os(e=>Dr(e)))});return Pe(e).pipe(Os(e=>{const t=e.filter(e=>Boolean(e));return Dr(Of(t,i,{blossomServers:s.blossomServers,nsfwPubkeys:a.nsfwPubkeys,reportedEventIds:s.reportedEventIds,includeYouTube:s.showYouTubeContent??!0,includeAudio:s.showAudioContent??!0}))}))},[A,n,i,s.blossomServers,a.nsfwPubkeys,s.reportedEventIds,s.showYouTubeContent,s.showAudioContent]),T=Dt(()=>P,[P])??[];return{playlistPointer:y,playlistEvent:S,playlistTitle:M,playlistDescription:I,videoRefs:A,videoEvents:T,isPrivate:E,decryptionFailed:h,readRelays:i,isLoadingPlaylist:C,isLoadingVideos:Boolean(S)&&A.length>0&&0===T.length,failedVideoIds:l,loadingVideoIds:d}}function Kv(){return(Kv=t(()=>{pp=Be(),fr(),Ir(),et(),Se(),Wt(),be(),xs(),df(),dl(),ow(),lu(),bu(),du(),kd(),Lv(),Jl()}))()}function Gv(e,t="video"){return"shorts"===t?`/short/${e}`:`/v/${e}`}function Yv(e,t="video",n){const s=Gv(e,t);if(!n)return s;const r=new URLSearchParams;n.playlist&&r.set("playlist",n.playlist),n.timestamp&&n.timestamp>0&&r.set("t",String(Math.floor(n.timestamp))),n.comment&&r.set("comment",n.comment),n.autoplay&&r.set("autoplay","true");const a=r.toString();return a?`${s}?${a}`:s}function Xv(e,t){return Yv(e,"video",t).replace(`/v/${e}`,`/desktop/player/${e}`)}function Zv(e){return[34236,22].includes(e??0)}function Qv(e,t,n,s,r="video"){const a=Gv(t,r),o=n?Math.floor(s):0;return o>0?`${e}${a}?t=${o}`:`${e}${a}`}function ex(e,t,n,s){const r=encodeURIComponent,a=r(e),o=r(t),i=r(n);return{mailto:`mailto:?body=${a}`,whatsapp:`https://api.whatsapp.com/send/?text=${i}%20${a}`,x:`https://x.com/intent/tweet?url=${a}&text=${i}`,reddit:`https://www.reddit.com/submit?url=${o}&title=${i}`,facebook:`https://www.facebook.com/share_channel/?type=reshare&link=${o}&display=popup`,pinterest:`https://www.pinterest.com/pin/create/button/?url=${o}&description=${i}&is_video=true&media=${r(s)}`}}function tx(){return(tx=t(()=>{0}))()}function nx({playlistParam:e,currentVideoId:t,playlistVideos:n,shouldLoop:s,onPlayPosReset:r}){const a=h(),o=Ws().pathname.startsWith("/desktop/player/"),i=(0,hp.useMemo)(()=>e&&t?n.findIndex(e=>e.id===t):-1,[e,t,n]),c=(0,hp.useMemo)(()=>{if(-1!==i)return n[i+1]},[i,n]),l=(0,hp.useMemo)(()=>{if(-1!==i&&0!==i)return n[i-1]},[i,n]);return{currentPlaylistIndex:i,nextPlaylistVideo:c,prevPlaylistVideo:l,navigateToPrevious:(0,hp.useCallback)(()=>{if(!e||!l)return;r();const t=o?Xv(l.link,{playlist:e}):Yv(l.link,"video",{playlist:e});a(t)},[e,l,a,r,o]),navigateToNext:(0,hp.useCallback)(()=>{if(!e||!c)return;r();const t=o?Xv(c.link,{playlist:e}):Yv(c.link,"video",{playlist:e});a(t)},[e,c,a,r,o]),handlePlaylistVideoEnd:(0,hp.useCallback)(()=>{e&&!s&&c&&(r(),a(o?Xv(c.link,{playlist:e,autoplay:!0}):Yv(c.link,"video",{playlist:e,autoplay:!0})))},[e,s,c,a,r,o])}}function sx(){return(sx=t(()=>{hp=Be(),tt(),tx()}))()}function rx(){return(rx=t(()=>{gp="nwc-connection",yp="wallet-type",bp="cashu-mint-url",wp="default-zap-amount"}))()}function ax({children:e}){const t=(0,vp.useContext)(I),n=yu().user?.pubkey,[s,r]=(0,vp.useState)(()=>localStorage.getItem("wallet-type")||null),[a,o]=(0,vp.useState)(null),[c,l]=(0,vp.useState)(!1),[u,d]=(0,vp.useState)(!1),[f,m]=(0,vp.useState)(null),[p,h]=(0,vp.useState)(null),[g,y]=(0,vp.useState)(null),[b,w]=(0,vp.useState)([]),[v,k]=(0,vp.useState)(()=>{const e=localStorage.getItem(wp);return e?parseInt(e,10):21}),N=Dt(()=>n?Ho.replaceable(_t,n).pipe(hn(e=>e??void 0)):void 0,[n]),j=Dt(()=>n&&"cashu"===s?Ho.model(x,n):void 0,[n,s]);(0,vp.useEffect)(()=>{if("cashu"===s&&j){const e=Object.entries(j).map(([e,t])=>({url:e,balance:t}));w(e);const t=Object.values(j).reduce((e,t)=>e+t,0);m(t)}},[j,s]);const S=(0,vp.useCallback)(async e=>{l(!0),y(null);try{if(!e.startsWith("nostr+walletconnect://"))throw new Error("Invalid NWC URI format");qr.pool=Ko,qr.subscriptionMethod=Xo,qr.publishMethod=Zo;const t=qr.fromConnectURI(e),n=await t.getInfo();h({type:"nwc",alias:n.alias,pubkey:n.pubkey,methods:n.methods});const s=await t.getBalance();m(s.balance),o(t),r("nwc"),localStorage.setItem(gp,e),localStorage.setItem(yp,"nwc")}catch(t){throw y(t instanceof Error?t.message:"Failed to connect wallet"),t}finally{l(!1)}},[]),C=(0,vp.useCallback)(async e=>{if(!t||!n)throw new Error("Not logged in");l(!0),y(null);try{await t.run(wr,{mints:e,relays:Vo}),r("cashu"),h({type:"cashu",mints:e}),localStorage.setItem(yp,"cashu"),e.length>0&&localStorage.setItem(bp,e[0])}catch(s){throw y(s instanceof Error?s.message:"Failed to create Cashu wallet"),s}finally{l(!1)}},[t,n]),E=(0,vp.useCallback)(async()=>{if(!t||!N)throw new Error("No wallet to unlock");d(!0),y(null);try{await t.run(Vn,{history:!0,tokens:!0});const e=nn(N);r("cashu"),h({type:"cashu",mints:e}),localStorage.setItem(yp,"cashu")}catch(e){throw y(e instanceof Error?e.message:"Failed to unlock wallet"),e}finally{d(!1)}},[t,N]),M=(0,vp.useCallback)(async e=>{if(!t||!N)throw new Error("No wallet available");y(null);try{const n=nn(N)||[];if(n.includes(e))throw new Error("Mint already added");await t.run(Or,[...n,e])}catch(n){throw y(n instanceof Error?n.message:"Failed to add mint"),n}},[t,N]),A=(0,vp.useCallback)(e=>{k(e),localStorage.setItem(wp,e.toString())},[]),P=(0,vp.useCallback)(()=>{o(null),m(null),h(null),r(null),y(null),w([]),localStorage.removeItem(gp),localStorage.removeItem(yp),localStorage.removeItem(bp)},[]),T=(0,vp.useCallback)(async()=>{if("nwc"===s&&a)try{const e=await a.getBalance();m(e.balance)}catch(e){}},[s,a]),R=(0,vp.useCallback)(async e=>{if("nwc"===s&&a){const t=await a.payInvoice(e);return T(),t}if("cashu"===s){if(!N||!Te(N))throw new Error("Cashu wallet not unlocked");const s=nn(N);if(!s||0===s.length)throw new Error("No mints configured");if(!n)throw new Error("Not logged in");const r=s[0],a=new i(r);await a.loadMint();const o=await a.createMeltQuoteBolt11(e),c=o.amount.add(o.fee_reserve).toNumber(),l=Ho.getByFilters([{kinds:[Ar],authors:[n]}]),{proofs:u}=Ce(l,c,r),d=await a.meltProofsBolt11(o,u);if(d.change&&d.change.length>0&&t){const e={mint:r,proofs:d.change};await t.run(Es,e)}return{preimage:"PAID"===d.quote?.state?"paid":""}}throw new Error("No wallet connected")},[s,a,N,n,t,T]);(0,vp.useEffect)(()=>{const e=localStorage.getItem(yp),t=localStorage.getItem(gp);"nwc"===e&&t&&S(t).catch(e=>{localStorage.removeItem(gp),localStorage.removeItem(yp)})},[S]),(0,vp.useEffect)(()=>{if("cashu"===localStorage.getItem("wallet-type")&&N&&n){r("cashu");const e=Te(N)?nn(N):[];h({type:"cashu",mints:e})}},[N,n]);const U="nwc"===s?null!==a:"cashu"===s,$=!!N&&Te(N);return(0,xp.jsx)(kp.Provider,{value:{walletType:s,isConnected:U,isConnecting:c,isUnlocking:u,error:g,walletInfo:p,balance:f,cashuMints:b,cashuWalletEvent:N,isCashuWalletUnlocked:$,defaultZapAmount:v,setDefaultZapAmount:A,connectNWC:S,createCashuWallet:C,unlockCashuWallet:E,addCashuMint:M,disconnect:P,refreshBalance:T,payInvoice:R},children:e})}function ox(){const e=(0,vp.useContext)(kp);if(!e)throw new Error("useWalletContext must be used within WalletProvider");return e}function ix(){return(ix=t(()=>{vp=Be(),ts(),un(),me(),Pa(),$r(),Wt(),y(),Se(),nu(),KN(),rx(),xp=Q(),kp=(0,vp.createContext)(null)}))()}function cx({eventId:e,authorPubkey:t}){const[n,s]=(0,Np.useState)(!1),[r,a]=(0,Np.useState)(!1),{user:o}=yu(),{isConnected:i,payInvoice:c,defaultZapAmount:l}=ox(),{config:u}=iu(),d=Cr(),f=Av(t),m=(0,Np.useMemo)(()=>{if(e)return d.getEvent(e)},[d,e]),p=(0,Np.useMemo)(()=>{const e=u.relays.filter(e=>e.tags.includes("write")).map(e=>e.url),t=m?Array.from(rr(m)||[]):[],n=f.data?.filter(e=>e.write||e.read).map(e=>e.url)||[];return Array.from(new Set([...t,...n,...e]))},[u.relays,m,f.data]);return{zap:(0,Np.useCallback)(async e=>{const{amount:n=l,comment:r,timestamp:u}=e||{};if(!o)return dr.error("Please log in to zap"),!1;if(!i)return a(!0),!1;const f=o.signer;if(!f)return dr.error("No signer available"),!1;s(!0);try{const e=d.getReplaceable(0,t);if(!e)return dr.error("Could not load author profile"),!1;const s=await Vu(e);if(!s)return dr.error("Author cannot receive zaps (no lightning address)"),!1;const a=qu({recipientPubkey:t,amount:n,comment:r,relays:p,event:m||void 0,timestamp:u}),o=await f.signEvent(a),i=await Ju(s,n,o);return await c(i),dr.success(`Zapped ${n} sats!`),!0}catch(h){return dr.error(h instanceof Error?h.message:"Zap failed"),!1}finally{s(!1)}},[o,i,d,t,p,m,c,l]),generateInvoice:(0,Np.useCallback)(async(e,n,s)=>{if(!o)return dr.error("Please log in to zap"),null;const r=o.signer;if(!r)return dr.error("No signer available"),null;try{const a=d.getReplaceable(0,t);if(!a)return dr.error("Could not load author profile"),null;const o=await Vu(a);if(!o)return dr.error("Author cannot receive zaps (no lightning address)"),null;const i=qu({recipientPubkey:t,amount:e,comment:n,relays:p,event:m||void 0,timestamp:s}),c=await r.signEvent(i);return await Ju(o,e,c)}catch(a){return dr.error(a instanceof Error?a.message:"Failed to generate invoice"),null}},[o,d,t,p,m]),isZapping:n,isConnected:i,needsWallet:r,setNeedsWallet:a}}function lx(){return(lx=t(()=>{Np=Be(),Wt(),xs(),KN(),ix(),Pv(),Gu(),Hr()}))()}function ux(e,t,n){Ep.set(e,{totalSats:t,zapCount:n,timestamp:Date.now()}),function(){try{const e={};Ep.forEach((t,n)=>{e[n]=t}),localStorage.setItem(Sp,JSON.stringify(e))}catch{}}()}function dx({eventId:e,authorPubkey:t,kind:n,identifier:s}){const r=Cr(),{pool:a}=iu(),o=34235===n||34236===n,i=(0,jp.useMemo)(()=>o&&s?`${n}:${t}:${s}`:null,[o,n,t,s]),c=(0,jp.useMemo)(()=>function(e){const t=Ep.get(e);return t&&Date.now()-t.timestamp{const t=[e];if(i)for(const e of Yu(i))t.includes(e)||t.push(e);return t},[e,i]);(0,jp.useEffect)(()=>{if(!e)return;const t=[{kinds:[9735],"#e":l}];i&&t.push({kinds:[9735],"#a":[i]});const n=a.subscription(zo,t).subscribe({next:e=>{"string"!=typeof e&&"kind"in e&&r.add(e)},error:e=>{}});return()=>n.unsubscribe()},[e,l,i,a,r]);const u=Dt(()=>r.timeline({kinds:[9735],"#e":l}),[r,l]),d=Dt(()=>i?r.timeline({kinds:[9735],"#a":[i]}):void 0,[r,i]),f=(0,jp.useMemo)(()=>{const e=u||[],t=d||[],n=new Set,s=[];for(const r of[...e,...t])n.has(r.id)||(n.add(r.id),s.push(r));return s},[u,d]),{totalSats:m,zapCount:p}=(0,jp.useMemo)(()=>{if(!f||0===f.length)return{totalSats:0,zapCount:0};let e=0;const t=new Set;for(const n of f){const s=n.tags.find(e=>"bolt11"===e[0])?.[1];if(s&&!t.has(s)){t.add(s);try{e+=Hu(s)}catch{}}}return{totalSats:e,zapCount:t.size}},[f]);(0,jp.useEffect)(()=>{e&&(m>0||p>0)&&ux(e,m,p)},[e,m,p]);const h=f.length>0;return{totalSats:h?m:c?.totalSats??0,zapCount:h?p:c?.zapCount??0,zaps:f,isLoading:!h&&!c}}function fx(){return(fx=t(()=>{jp=Be(),Wt(),Gu(),lu(),Zu(),Jl(),Sp="zap-totals-cache",Cp=36e5,Ep=new Map,function(){try{const e=localStorage.getItem(Sp);if(e){const t=JSON.parse(e),n=Date.now();for(const[e,s]of Object.entries(t))n-s.timestampe?.pubkey?{kinds:[9734],authors:[e.pubkey],limit:500}:null,[e?.pubkey]),{events:n,isLoading:s}=md(t),{zappedEventIds:r,zappedAddresses:a}=(0,Mp.useMemo)(()=>{if(!e||0===n.length)return{zappedEventIds:[],zappedAddresses:[]};const t=[...n].sort((e,t)=>t.created_at-e.created_at),s=[],r=[];for(const e of t){const t=e.tags.find(e=>"e"===e[0]);t?.[1]&&s.push(t[1]);const n=e.tags.find(e=>"a"===e[0]);n?.[1]&&r.push(n[1])}return{zappedEventIds:Array.from(new Set(s)),zappedAddresses:Array.from(new Set(r))}},[e,n]);return{data:r,zappedAddresses:a,isLoading:Boolean(e&&s),enabled:!!e}}function px(){return(px=t(()=>{bu(),Mp=Be(),pd()}))()}async function hx(e,t,n,s){const r=Math.floor(Date.now()/1e3);return e({kind:Ip,created_at:r,content:"upload"===t?"Upload Blob":"Delete Blob",tags:[["t",t],["expiration",String(r+Ap)],["x",n],...s?[["server",s]]:[]]})}function gx(){return(gx=t(()=>{Ip=24242,Ap=3600}))()}async function yx({mirrorServers:e,blob:t,signer:n,onServerStart:s,onServerSettle:r}){return(await Promise.allSettled(e.map(async(e,a)=>{s?.(e);try{if(await vx(e,t.sha256)){const n=wx(e,t.sha256,t.size,t.type||"application/octet-stream");return r?.({ok:!0,server:e,blob:n,alreadyExisted:!0}),n}const s=await hx(n,"upload",t.sha256,Cf(e)),a=await async function(e,t,n){const s=Mf(e),r=await fetch(`${s}/mirror`,{method:"PUT",headers:{"Content-Type":"application/json",Authorization:`Nostr ${n}`},body:JSON.stringify({url:t.url})});if(!r.ok)throw new Error(`Mirror request failed: ${r.status} ${r.statusText}`);return await r.json()}(e,t,Sf(s));return r?.({ok:!0,server:e,blob:a,alreadyExisted:!1}),a}catch(o){const t=o instanceof Error?o:new Error(String(o));throw r?.({ok:!1,server:e,error:t}),t}}))).filter(e=>"fulfilled"===e.status).map(e=>e.value)}function bx(e){if(e?.aborted)throw new DOMException("Aborted","AbortError")}function wx(e,t,n,s){return{sha256:t,size:n,type:s,url:`${Mf(e)}/${t}`,uploaded:Date.now()}}async function vx(e,t,n){const s=Mf(e);try{bx(n);return 200===(await fetch(`${s}/${t}`,{method:"HEAD",signal:n})).status}catch(r){if(r instanceof DOMException&&"AbortError"===r.name)throw r;return!1}}async function xx(e,t){Date.now();const n=await async function(e,t){const n=20971520;try{const s=await o();let r=0,a=0;for(;r{const l=g+c,d=l*u,h=await kx(i,t,0,m.length,f,e.type,e.size,d,p,o);n+=t.size,s=l+1;const y=(Date.now()-a)/1e3,b=n/1048576/y;return r.onProgress?.({uploadedBytes:n,totalBytes:e.size,percentage:Math.round(n/e.size*100),currentChunk:s,totalChunks:m.length,speedMBps:b}),r.onChunkComplete?.(l,m.length),h}),h=await Promise.all(l);t.push(...h)}if(l){bx(o);const c=m.length-1,d=c*u,h=await kx(i,l,0,m.length,f,e.type,e.size,d,p,o);n+=l.size,s=m.length;const g=(Date.now()-a)/1e3,y=n/1048576/g;r.onProgress?.({uploadedBytes:n,totalBytes:e.size,percentage:100,currentChunk:s,totalChunks:m.length,speedMBps:y}),r.onChunkComplete?.(c,m.length),t.push(h)}const h=t[t.length-1];if(200===h.status){return await h.json()}throw new Error("Chunked upload failed: No blob descriptor returned")}catch(h){if(h instanceof DOMException&&"AbortError"===h.name)throw h;throw Object.assign(new Error(`BUD-10 PATCH chunked upload failed for ${t}. Server must support PATCH /upload according to BUD-10 specification. Error: ${h instanceof Error?h.message:"Unknown error"}`),{cause:h})}}async function jx({file:e,servers:t,signer:n,options:s={},callbacks:r={},skipExistenceCheck:a=!1,signal:o}){const i=await xx(e,o);bx(o);const c=await Promise.allSettled(t.map(async t=>{if(!a&&await vx(t,i,o))return wx(t,i,e.size,e.type);if(e.size>104857600)try{return await Nx(e,t,n,s,r,i,o)}catch(c){}return await async function(e,t,n,s,r){const a=Mf(t);bx(r);const o=await hx(n,"upload",s,Cf(a)),i=Sf(o);bx(r);const c=await fetch(`${a}/upload`,{method:"PUT",headers:{"Content-Type":e.type,"X-SHA-256":s,Authorization:`Nostr ${i}`},body:e,signal:r});if(!c.ok)throw new Error(`Regular upload failed: ${c.status} ${c.statusText}`);return await c.json()}(e,t,n,i,o)})),l=c.filter(e=>"fulfilled"===e.status).map(e=>e.value);if(bx(o),0===l.length&&c.length>0){const e=c.find(e=>"rejected"===e.status)?.reason;throw e instanceof Error?e:new Error(null!=e?String(e):`Upload failed: all ${c.length} server(s) rejected`)}return l}async function Sx(e,t,n){const s=Mf(e);try{const e=Sf(await hx(n,"delete",t,Cf(s))),r=await fetch(`${s}/${t}`,{method:"DELETE",headers:{Authorization:`Nostr ${e}`}});return!!r.ok||404===r.status}catch(r){return!1}}function Cx(e){const t=new Map;for(const n of e)try{const e=new URL(n.url),s=`${e.protocol}//${e.host}`,r=`${n.sha256}:${s}`;t.set(r,{hash:n.sha256,server:s})}catch{}return Array.from(t.values())}function Ex(e){return Cx(e).length}async function Mx(e,t,n={}){if(0===e.length)return{totalSuccessful:0,totalFailed:0};const s=Cx(e);if(0===s.length)return{totalSuccessful:0,totalFailed:0};let r=0,a=0,o=0,i=0;const c=Math.max(1,n.concurrency??3),l=()=>{n.onProgress?.({completed:o,total:s.length,successful:r,failed:a})};return l(),await Promise.all(Array.from({length:Math.min(c,s.length)},()=>async function(){for(;i{gx(),rs(),If()}))()}function Ax(e){const[t,n]=(0,Pp.useState)(null),[s,r]=(0,Pp.useState)(!1),[a,o]=(0,Pp.useState)(null),i=(0,Pp.useRef)(e);return(0,Pp.useEffect)(()=>{i.current=e}),{upload:(0,Pp.useCallback)(async e=>{const{initialServers:t,mirrorServers:s=[],signer:a,chunkSize:c=Tp,maxConcurrentChunks:l=Rp}=i.current;r(!0),o(null),n(null);try{const o=await jx({file:e,servers:t,signer:a,options:{chunkSize:c,maxConcurrentChunks:l},callbacks:{onProgress:n}});let i=[];return s.length>0&&o.length>0&&(i=(await Promise.all(o.map(e=>yx({mirrorServers:s,blob:e,signer:a})))).flat()),r(!1),{uploadedBlobs:o,mirroredBlobs:i}}catch(u){const e=u instanceof Error?u.message:String(u);throw o(e),r(!1),u}},[]),deleteBlobs:(0,Pp.useCallback)(async e=>{0!==e.length&&await Mx(e,i.current.signer)},[]),progress:t,uploading:s,error:a,reset:(0,Pp.useCallback)(()=>{n(null),r(!1),o(null)},[])}}function Px(){return(Px=t(()=>{Pp=Be(),Ix(),Tp=10485760,Rp=2}))()}async function Tx(e,t,n){const s=new AbortController,r=setTimeout(()=>s.abort(),3e4),a=await fetch(e,{headers:{Range:`bytes=${t}-${n}`},signal:s.signal});if(clearTimeout(r),!a.ok)throw new Error("Fetch failed");let o;if(206===a.status)o=await a.arrayBuffer();else{if(200!==a.status||0!==t)throw new Error("Range request failed");{const e=a.body?.getReader();if(!e)throw new Error("No response body");const s=[];let r=0;const i=n-t+1;for(;r=i)break}o=c.buffer}}return new Promise(e=>{const n=xn();let s,r,a=!1;const i=setTimeout(()=>{a||(a=!0,e({}))},5e3);n.onError=t=>{a||(a=!0,clearTimeout(i),e({}))},n.onReady=t=>{if(!a){a=!0,clearTimeout(i);let n=0;for(const e of t.tracks)e.type&&"video"===e.type&&e.codec&&(s=e.codec),e.type&&"audio"===e.type&&e.codec&&(r=e.codec),!e.bitrate||"video"!==e.type&&"audio"!==e.type||(n+=e.bitrate);e({videoCodec:s,audioCodec:r,bitrate:n>0?Math.floor(n):void 0})}};try{const e=Object.assign(o,{fileStart:t});n.appendBuffer(e),n.flush()}catch(c){a||(a=!0,clearTimeout(i),e({}))}})}function Rx(){return(Rx=t(()=>{ln(),Up=e=>new Promise((t,n)=>{const s=xn();let r,a,o=!1;const i=setTimeout(()=>{o||(o=!0,n(new Error("Codec detection timeout")))},5e3);s.onError=e=>{o||(o=!0,clearTimeout(i),n(e))},s.onReady=e=>{if(!o){o=!0,clearTimeout(i);let n=0;for(const t of e.tracks)t.type&&"video"===t.type&&t.codec&&(r=t.codec),t.type&&"audio"===t.type&&t.codec&&(a=t.codec),!t.bitrate||"video"!==t.type&&"audio"!==t.type||(n+=t.bitrate);t({videoCodec:r,audioCodec:a,bitrate:n>0?Math.floor(n):void 0})}};const c=e.slice(0,2097152),l=new FileReader;l.onload=()=>{if(!o)try{const e=l.result,t=new Uint8Array(e);if(t.length>=8&&"ftyp"!==String.fromCharCode(t[4],t[5],t[6],t[7]))throw new Error("Not a valid MP4 file (missing ftyp box)");const n=Object.assign(e,{fileStart:0});s.appendBuffer(n),s.flush()}catch(e){o||(o=!0,clearTimeout(i),n(e))}},l.onerror=e=>{o||(o=!0,clearTimeout(i),n(e))},l.readAsArrayBuffer(c)}),$p=async e=>{const t=2097152;try{let s=0;try{const t=(await fetch(e,{method:"HEAD"})).headers.get("content-length");t&&(s=parseInt(t,10))}catch(n){}try{const n=await Tx(e,0,t);if(n.videoCodec||n.audioCodec)return n}catch(n){}if(s>t)try{const n=await Tx(e,Math.max(0,s-t),s-1);if(n.videoCodec||n.audioCodec)return n}catch(n){}return{}}catch(n){return{}}}}))()}function Ux(e){try{if(!e||!e.data)return null;const t=e.data;if(!t||t.length<8)return null;const n=new DataView(t.buffer||t),s=n.getUint32(0);n.getUint32(4);const r=t.slice(8);switch(s){case Dp.UTF8:return new TextDecoder("utf-8").decode(r);case Dp.UTF16:return new TextDecoder("utf-16").decode(r);case Dp.SJIS:try{return new TextDecoder("shift-jis").decode(r)}catch{return new TextDecoder("utf-8").decode(r)}default:return new TextDecoder("utf-8").decode(r)}}catch(t){return null}}function $x(e){return e.length>=3&&255===e[0]&&216===e[1]&&255===e[2]?{type:"jpeg",mimeType:"image/jpeg"}:e.length>=8&&137===e[0]&&80===e[1]&&78===e[2]&&71===e[3]&&13===e[4]&&10===e[5]&&26===e[6]&&10===e[7]?{type:"png",mimeType:"image/png"}:null}function Dx(e,t){return`data:${t};base64,${btoa(String.fromCharCode(...Array.from(e)))}`}function Lx(e){const t=Bx(e);if(t){const e=function(e){try{if(!e)return null;let t=null;if(e.list)for(const[i,c]of Object.entries(e.list)){const e=parseInt(i,10);if("covr"===String.fromCharCode(e>>24&255,e>>16&255,e>>8&255,255&e)){t=c;break}}if(!t&&e.boxes&&(t=e.boxes.find(e=>"covr"===e.type)),!t)return null;const n=t.data;if(!n||n.length<8)return null;const s=new DataView(n.buffer||n).getUint32(0),r=n.slice(8);let a,o;if(s===Dp.JPEG)a="jpeg",o="image/jpeg";else if(s===Dp.PNG)a="png",o="image/png";else{const e=$x(r);if(!e)return null;a=e.type,o=e.mimeType}return{type:a,data:r,dataUrl:Dx(new Uint8Array(r),o),source:"ilst"}}catch(t){return null}}(t);if(e)return e}return function(e){try{const t=e.boxes;if(!t||!Array.isArray(t))return null;const n=t.filter(e=>"free"===e.type||"skip"===e.type);for(const e of n){if(!e.data||e.data.length<100)continue;const t=new Uint8Array(e.data),n=$x(t);if(n){const s=Dx(t,n.mimeType);return{type:n.type,data:t,dataUrl:s,source:"free"===e.type?"free":"skip"}}}return null}catch(t){return null}}(e)}function Bx(e){try{const t=e.moov;if(!t)return null;const n=t.udta;if(!n)return null;const s=n.meta;if(!s)return null;const r=s.ilst;return r||null}catch(t){return null}}function zx(e){try{if(!e.data)return null;const t=e.data;if(t.length<2)return null;const n=t.slice(2);return new TextDecoder("utf-8").decode(n)}catch(t){return null}}function Fx(e){const t={};try{const n=e.moov;if(!n||!n.udta)return t;const s=n.udta;if(s.boxes)for(const e of s.boxes){const n=zx(e);n&&(t[e.type]=n)}for(const e of["titl","auth","dscp","cprt","yrrc","albm"])s[e]&&"string"==typeof s[e]&&(t[e]=s[e])}catch(n){}return t}function _x(e){const t=[e>>24&255,e>>16&255,e>>8&255,255&e];return String.fromCharCode(...t)}function Ox(e){try{if(e.value&&"string"==typeof e.value)return e.value;const t=Ux(e);if(t)return t;if(e.boxes){const t=e.boxes.find(e=>"data"===e.type);if(t)return Ux(t)}if(e.data&&e.data.length>0)try{return new TextDecoder("utf-8").decode(e.data)}catch{return null}return null}catch(t){return null}}function Wx(e){const t={};try{if(!e)return t;if(e.list)for(const[s,r]of Object.entries(e.list)){const e=_x(parseInt(s,10)),n=r?.value;n&&"string"==typeof n&&(t[e]=n)}if(e.boxes)for(const s of e.boxes){if(t[s.type])continue;const e=Ox(s);e&&(t[s.type]=e)}const n=function(e){const t={};try{if(!e||!e.boxes)return t;const n=e.boxes.filter(e=>"----"===e.type);for(const e of n){if(!e.boxes)continue;let n="",s="",r="";for(const t of e.boxes)if("mean"===t.type&&t.data){const e=t.data.slice(4);n=new TextDecoder("utf-8").decode(e)}else if("name"===t.type&&t.data){const e=t.data.slice(4);s=new TextDecoder("utf-8").decode(e)}else"data"===t.type&&(r=Ux(t)||"");s&&r&&(t[n?`${n}:${s}`:s]=r)}}catch(n){}return t}(e);Object.keys(n).length>0&&(t._custom=n)}catch(n){}return t}function Vx(){return(Vx=t(()=>{Dp={UTF8:1,UTF16:2,SJIS:3,HTML:6,XML:7,UUID:8,JPEG:13,PNG:14,SIGNED_INT:21,UNSIGNED_INT:22,FLOAT:23,DOUBLE:24}}))()}function qx(e){try{let t,n=1,s=1;if(8===e.length&&/^\d{8}$/.test(e))t=parseInt(e.substring(0,4),10),n=parseInt(e.substring(4,6),10),s=parseInt(e.substring(6,8),10);else if(e.includes("-")){const r=e.split("-");t=parseInt(r[0],10),r.length>1&&(n=parseInt(r[1],10)),r.length>2&&(s=parseInt(r[2],10))}else{if(4!==e.length||!/^\d{4}$/.test(e)){const t=Date.parse(e);return isNaN(t)?void 0:Math.floor(t/1e3)}t=parseInt(e,10)}const r=new Date(t,n-1,s,0,0,0,0);return Math.floor(r.getTime()/1e3)}catch(t){return}}function Jx(e){const t={};if(e["©nam"]&&(t.title=e["©nam"]),e["©ART"]&&(t.channel=e["©ART"]),e["©day"]){const n=qx(e["©day"]);n&&(t.publishAt=n)}return e["©alb"]&&(t.album=e["©alb"]),e["©gen"]&&(t.genre=e["©gen"]),e["©cmt"]&&(t.comment=e["©cmt"]),e.ldes?t.description=e.ldes:e.desc&&(t.description=e.desc),e.keyw&&(t.tags=e.keyw.split(/[,;]+/).map(e=>e.trim()).filter(e=>e.length>0)),e._custom&&e._custom,t}function Hx(){return(Hx=t(()=>{ln(),Vx(),Lp=e=>new Promise(t=>{const n=xn();let s=!1;const r=setTimeout(()=>{s||(s=!0,t({}))},5e3);n.onError=e=>{s||(s=!0,clearTimeout(r),t({}))},n.onReady=e=>{if(!s){s=!0,clearTimeout(r);try{let e={};const s=Bx(n);s&&(e=Jx(Wx(s)));const r=Lx(n);r&&(e.thumbnail=r);const a=Fx(n);if(Object.keys(a).length>0){if(!e.title&&a.titl&&(e.title=a.titl),!e.channel&&a.auth&&(e.channel=a.auth),!e.description&&a.dscp&&(e.description=a.dscp),!e.comment&&a.cprt&&(e.comment=a.cprt),!e.publishAt&&a.yrrc){const t=qx(a.yrrc);t&&(e.publishAt=t)}!e.album&&a.albm&&(e.album=a.albm)}t(e)}catch(a){t({})}}};const a=e.slice(0,5242880),o=new FileReader;o.onload=()=>{if(!s)try{const e=o.result,t=new Uint8Array(e);if(t.length>=8&&"ftyp"!==String.fromCharCode(t[4],t[5],t[6],t[7]))throw new Error("Not a valid MP4 file (missing ftyp box)");const s=Object.assign(e,{fileStart:0});n.appendBuffer(s),n.flush()}catch(e){s||(s=!0,clearTimeout(r),t({}))}},o.onerror=e=>{s||(s=!0,clearTimeout(r),t({}))},o.readAsArrayBuffer(a)}),Bp=async e=>{try{return await async function(e,t,n){const s=new AbortController,r=setTimeout(()=>s.abort(),3e4);try{const a=await fetch(e,{headers:{Range:`bytes=${t}-${n}`},signal:s.signal});if(clearTimeout(r),!a.ok)return{};let o;if(206===a.status)o=await a.arrayBuffer();else{if(200!==a.status||0!==t)return{};{const e=a.body?.getReader();if(!e)return{};const s=[];let r=0;const i=n-t+1;for(;r=i)break}o=c.buffer}}return new Promise(e=>{const n=xn();let s=!1;const r=setTimeout(()=>{s||(s=!0,e({}))},5e3);n.onError=t=>{s||(s=!0,clearTimeout(r),e({}))},n.onReady=t=>{if(!s){s=!0,clearTimeout(r);try{let t={};const s=Bx(n);s&&(t=Jx(Wx(s)));const r=Lx(n);r&&(t.thumbnail=r);const a=Fx(n);if(Object.keys(a).length>0){if(!t.title&&a.titl&&(t.title=a.titl),!t.channel&&a.auth&&(t.channel=a.auth),!t.description&&a.dscp&&(t.description=a.dscp),!t.comment&&a.cprt&&(t.comment=a.cprt),!t.publishAt&&a.yrrc){const e=qx(a.yrrc);e&&(t.publishAt=e)}!t.album&&a.albm&&(t.album=a.albm)}e(t)}catch(a){e({})}}};try{const e=Object.assign(o,{fileStart:t});n.appendBuffer(e),n.flush()}catch(a){s||(s=!0,clearTimeout(r),e({}))}})}catch(a){return{}}}(e,0,5242880)}catch(t){return{}}}}))()}function Kx({primaryBlob:e,candidateBlobs:t=[],directUrl:n}){const s=e??t[0],r=s?t.filter(e=>e.sha256===s.sha256&&e.url!==s.url):[];return{primaryBlob:s,fallbackBlobs:Array.from(new Map(r.map(e=>[e.url,e])).values()),...n&&n!==s?.url?{directUrl:n}:{}}}function Gx(e){if(e.placement)return e;const t=[...e.uploadedBlobs??[],...e.mirroredBlobs??[]],n=t.find(t=>t.url===e.url)??t[0];return{...e,placement:Kx({primaryBlob:n,candidateBlobs:t,directUrl:e.url})}}function Yx(e){const[t,n]=e.split("x").map(Number),s=Math.min(t,n),r=Math.max(t,n);return s>=2160||r>=3840?"4K":s>=1440||r>=2560?"2K":s>=1080?"1080p":s>=720?"720p":s>=480?"480p":s>=360?"360p":s>=240?"240p":`${s}p`}async function Xx(e){await new Promise((t,n)=>{e.onloadedmetadata=t,e.onerror=()=>n(new Error("Failed to load video metadata")),setTimeout(()=>n(new Error("Video loading timeout")),1e4)});const t=Math.round(e.duration);return{dimension:`${e.videoWidth}x${e.videoHeight}`,duration:t}}async function Zx(e,t){const n=document.createElement("video");n.src=URL.createObjectURL(e),n.muted=!0,n.playsInline=!0,n.preload="metadata";try{const{dimension:s,duration:r}=await Xx(n),a=e.size/1024/1024,o=Yx(s);let i;const[c,l]=await Promise.all([Up(e).catch(e=>({})),Lp(e).catch(e=>({}))]),u=c.videoCodec,d=c.audioCodec,f=c.bitrate;return Object.keys(l).length>0&&(i=l),{url:t[0]?.url,dimension:s,sizeMB:Number(a.toFixed(2)),duration:r,videoCodec:u,audioCodec:d,bitrate:f?Math.floor(f):void 0,uploadedBlobs:t,mirroredBlobs:[],placement:Kx({primaryBlob:t[0],candidateBlobs:t}),inputMethod:"file",file:e,qualityLabel:o,extractedMetadata:i}}finally{URL.revokeObjectURL(n.src)}}async function Qx(e){try{const t=(await fetch(e,{method:"HEAD"})).headers.get("Content-Length");if(t){const e=parseInt(t,10);if(!isNaN(e)&&e>0)return e}}catch(t){}}async function ek(e,t=[]){const n=document.createElement("video");n.src=e,n.crossOrigin="anonymous",n.muted=!0,n.playsInline=!0,n.preload="metadata";const[{dimension:s,duration:r},a]=await Promise.all([Xx(n),Qx(e)]),o=Yx(s),i=a?Number((a/1024/1024).toFixed(2)):void 0;let c;const[l,u]=await Promise.all([$p(e).catch(e=>({})),Bp(e).catch(e=>({}))]),d=l.videoCodec,f=l.audioCodec,m=l.bitrate;return Object.keys(u).length>0&&(c=u),{url:e,dimension:s,sizeMB:i,duration:r,videoCodec:d,audioCodec:f,bitrate:m?Math.floor(m):void 0,uploadedBlobs:[],mirroredBlobs:t,placement:Kx({candidateBlobs:t,directUrl:e}),inputMethod:"url",qualityLabel:o,extractedMetadata:c}}function tk(){return(tk=t(()=>{Rx(),Hx()}))()}function nk(e){const t=new Map;for(let g=1;gm.push(e)),t.get("mirror")?.forEach(e=>m.push(e));const p=[];let h;return t.get("image")?.forEach(e=>p.push(e)),r&&(h=Yx(r)),{raw:e,url:n,hash:l,size:o,duration:Number.isFinite(c)?c:void 0,dimensions:r,quality:h,mimeType:s,bitrate:f,fallbackUrls:m,thumbnailUrls:p,blurhash:u}}function sk(e){const{thumbnailUrls:t,blurhash:n}=e,s=Gx(e.variant),{placement:r}=s,a=["imeta",`dim ${s.dimension}`],o=r.primaryBlob?.url??r.directUrl;o&&a.push(`url ${o}`),r.primaryBlob&&a.push(`x ${r.primaryBlob.sha256}`);const i=s.mimeType||s.file?.type;if(a.push(`m ${il(i,s.videoCodec,s.audioCodec)}`),s.bitrate&&a.push(`bitrate ${s.bitrate}`),Number.isFinite(s.duration)&&a.push(`duration ${Math.floor(s.duration)}`),s.sizeMB){const e=Math.round(1024*s.sizeMB*1024);a.push(`size ${e}`)}t&&t.forEach(e=>a.push(`image ${e}`)),n&&a.push(`blurhash ${n}`);for(const c of r.fallbackBlobs)a.push(`fallback ${c.url}`);return r.directUrl&&a.push(`fallback ${r.directUrl}`),a}function rk(e){const{variant:t,originalImeta:n,thumbnailUrls:s,blurhash:r}=e;return sk({variant:t,thumbnailUrls:s??n?.thumbnailUrls??[],blurhash:r??n?.blurhash})}function ak(){return(ak=t(()=>{tk(),dl()}))()}function ok(e){const t=parseInt(e.qualityLabel,10);if(!Number.isNaN(t))return t;const[,n]=e.dimension.split("x").map(Number);return Number.isFinite(n)?n:0}function ik(e){return e.hlsVariants?[...e.hlsVariants].sort((e,t)=>ok(t)-ok(e))[0]:void 0}function ck(e){return e.map((e,t)=>function(e){return"application/vnd.apple.mpegurl"===e.mimeType&&(e.hlsVariants?.length??0)>0}(e)?{kind:"hls",master:e,streams:[...e.hlsVariants??[]].sort((e,t)=>ok(t)-ok(e)),originalIndex:t,highestStream:ik(e)}:{kind:"video",video:e,originalIndex:t})}function lk(){return(lk=t(()=>{}))()}async function uk(e,t,n,s,r,a){if(a?.aborted)throw new DOMException("Aborted","AbortError");const o=await jx({file:e,servers:t,signer:s,options:{chunkSize:zp,maxConcurrentChunks:2},callbacks:{onProgress:r},signal:a});if(a?.aborted)throw new DOMException("Aborted","AbortError");let i=[];return n.length>0&&o.length>0&&(i=(await Promise.all(o.map(e=>yx({mirrorServers:n,blob:e,signer:s})))).flat()),{...await Zx(e,o),mirroredBlobs:i}}function dk(){return(dk=t(()=>{Ix(),tk(),zp=10485760}))()}function fk(e){const t=localStorage.getItem(e);if(t)try{const e=JSON.parse(t);return e.items??e.drafts??[]}catch(n){}return[]}function mk(e,t){const n={version:"1",lastModified:Date.now(),items:t};localStorage.setItem(e,JSON.stringify(n))}function pk(e,t,n){const s=fk(e),r=function(e){const t=localStorage.getItem(e);if(t)try{return JSON.parse(t).lastModified||0}catch{return 0}return 0}(e),a=new Map;s.forEach(e=>a.set(e.id,e));const o=1e3*n>r;return t.forEach(e=>{const t=a.get(e.id);t?e.updatedAt>t.updatedAt&&a.set(e.id,e):o&&a.set(e.id,e)}),Array.from(a.values()).sort((e,t)=>t.updatedAt-e.updatedAt)}function hk(){return(hk=t(()=>{}))()}function gk(e,t,n,s,r,a){return Fp.run(e,t,n,s,r,a)}function yk(){return(yk=t(()=>{Fp=new class{worker=null;activeJobId=null;pendingJobs=new Map;queuedJobIds=[];run(e,t,n,s,r,a){const o=crypto.randomUUID();return new Promise((i,c)=>{const l={file:e,variants:t,sourceMeta:n,onProgress:s,onVariantError:r,resolve:i,reject:c,signal:a},u=()=>{this.cancel(o)};if(a.aborted)return void u();a.addEventListener("abort",u,{once:!0});this.pendingJobs.set(o,{...l,resolve:e=>{a.removeEventListener("abort",u),i(e)},reject:e=>{a.removeEventListener("abort",u),c(e)}}),this.queuedJobIds.push(o),this.startNext()})}cancel(e){const t=this.pendingJobs.get(e);if(this.activeJobId===e)return this.worker?.postMessage({type:"cancel",jobId:e}),this.worker?.terminate(),this.worker=null,t?.reject(new DOMException("Aborted","AbortError")),void this.finishJob(e);this.queuedJobIds=this.queuedJobIds.filter(t=>t!==e),this.pendingJobs.delete(e),t?.reject(new DOMException("Aborted","AbortError"))}getWorker(){return this.worker||(this.worker=new Worker(new URL("/assets/browserTranscode.worker-BTkjS3MB.js",""+import.meta.url),{type:"module"}),this.worker.onmessage=e=>{this.handleMessage(e.data)},this.worker.onerror=e=>{const t=this.activeJobId;t&&(this.pendingJobs.get(t)?.reject(new Error(e.message||"Browser transcode worker failed")),this.finishJob(t))}),this.worker}startNext(){if(this.activeJobId)return;const e=this.queuedJobIds.shift();if(!e)return;const t=this.pendingJobs.get(e);t?(this.activeJobId=e,this.getWorker().postMessage({type:"start",jobId:e,file:t.file,variants:t.variants,sourceMeta:t.sourceMeta})):this.startNext()}handleMessage(e){const t=this.pendingJobs.get(e.jobId);if(t)if("progress"!==e.type){if("complete"===e.type)return t.resolve(e.files),void this.finishJob(e.jobId);if("variant-error"!==e.type)return"cancelled"===e.type?(t.reject(new DOMException("Aborted","AbortError")),void this.finishJob(e.jobId)):void("error"===e.type&&(t.reject(new Error(e.message)),this.finishJob(e.jobId)));t.onVariantError(e.variantIndex,e.message)}else t.onProgress({variant:e.variant,variantIndex:e.variantIndex,progress:e.progress})}finishJob(e){this.pendingJobs.delete(e),this.activeJobId===e&&(this.activeJobId=null),this.startNext()}}}))()}async function bk(e){const{width:t,height:n,duration:s}=await async function(e){const t=URL.createObjectURL(e),n=document.createElement("video");n.muted=!0,n.preload="metadata",n.src=t;try{return await new Promise((e,t)=>{const s=window.setTimeout(()=>t(new Error("Video metadata timeout")),1e4);n.onloadedmetadata=()=>{window.clearTimeout(s),e()},n.onerror=()=>{window.clearTimeout(s),t(new Error("Failed to read video metadata"))}}),{width:n.videoWidth,height:n.videoHeight,duration:n.duration}}finally{URL.revokeObjectURL(t)}}(e);let r,a=s>0?8*e.size/(1e6*s):0;try{const t=await Up(e);r=t.videoCodec,t.bitrate&&t.bitrate>0&&(a=t.bitrate/1e6)}catch{}return{width:t,height:n,duration:s,sizeMB:e.size/1048576,bitrateMbps:a,videoCodec:r,mimeType:e.type}}function wk(e){if(!e)return!1;const t=e.toLowerCase();return t.startsWith("avc1")||t.startsWith("avc3")||t.startsWith("hvc1")||t.startsWith("hev1")}function vk(e){return"video/mp4"===e||"video/x-m4v"===e}function xk(e){return!!vk(e.mimeType)&&wk(e.videoCodec)}function kk(e){return vk(e.mimeType)&&wk(e.videoCodec)?Math.min(e.width,e.height)>1080?"full":e.bitrateMbps>8?"bitrate":"none":"full"}function Nk(e,t,n){const s=t>e,r=s?e:t,a=s?t:e,o=Math.min(n,r),i=o/r,c=Math.round(a*i),l=e=>e%2==0?e:e+1,u=l(o),d=l(c);return s?{width:u,height:d}:{width:d,height:u}}function jk(e,t,n="balanced",s){const r=Op[n]/(Vp*_p*30),a=Math.round(e*t*30*r);if(!s||s.bitrateMbps<=0||s.width<=0||s.height<=0)return a;const o=Math.max(0,1e6*s.bitrateMbps-qp),i=s.width*s.height,c=e*t,l=o*Math.min(1,c/i)*.65,u=Math.min(l,a*Jp[n]);return Math.round(Math.max(a,u))}function Sk(e,t){const n=t.includes("hevc"),s=Math.min(e.width,e.height);return Hp.filter(e=>e<=s).map(e=>({height:e,suggestedCodec:n?"hevc":"avc"}))}function Ck(e){return Ek([{height:480,suggestedCodec:e?"hevc":"avc"},{height:720,suggestedCodec:e?"hevc":"avc"}],e)}function Ek(e,t){if(!t||0===e.length)return e.map(e=>({...e,suggestedCodec:"avc"}));const n=Math.min(...e.map(e=>e.height));return e.map(e=>({...e,suggestedCodec:e.height===n?"avc":"hevc"}))}function Mk(e,t){const n=Sk(e,t);if(0===n.length)return[];const s=Math.min(e.width,e.height);if("none"===kk(e)){if(s<=480)return[];const e=n.find(e=>480===e.height);return e?[e]:[]}const r=Math.min(_p,s),a=n.find(e=>e.height===r)??n[n.length-1],o=[a];if(s>480){const e=n.find(e=>480===e.height);e&&e.height!==a.height&&o.push(e)}return o}function Ik(e,t,n,s="balanced"){return"hls"===t?e.map(e=>({codec:e.suggestedCodec,targetHeight:e.height,format:"hls",label:`${e.height}p`,qualityPreset:s})):e.map(e=>{const t=n??e.suggestedCodec;return{codec:t,targetHeight:e.height,format:"mp4",label:`${e.height}p ${"hevc"===t?"HEVC":"H.264"}`,qualityPreset:s}})}function Ak(e,t){if(0===t.length)return[];const n=t.map(e=>e.height);if(e.sizeMB>0&&e.sizeMB<50){const e=n[n.length-1];return void 0!==e?[e]:[]}const s=[720,480].filter(e=>n.includes(e));if(s.length>0)return s;const r=n[n.length-1];return void 0!==r?[r]:[]}function Pk(){return"undefined"!=typeof VideoEncoder&&"undefined"!=typeof VideoDecoder}async function Tk(e,t){const n=new Map;for(const[s,r]of e.entries())if(s.endsWith(".m3u8")){let e=await r.text();const a=s.replace(/\.m3u8$/,"/"),o=Array.from(t.keys()).sort((e,t)=>t.length-e.length);for(const n of o){const s=t.get(n).split("/").pop();if(e.includes(n))e=e.split(n).join(s);else if(a&&n.startsWith(a)){const t=n.slice(a.length);t&&e.includes(t)&&(e=e.split(t).join(s))}}n.set(s,new File([e],s,{type:r.type}))}else n.set(s,r);return n}function Rk(){return(Rk=t(()=>{Rx(),Wp=(Op={compact:45e5,balanced:675e4,"high-motion":9e6}).balanced,qp=96e3,Wp/((Vp=1920)*(_p=1080)*30),Jp={compact:1,balanced:1.35,"high-motion":1.5},Hp=[240,360,480,720,1080,1440,2160]}))()}function Uk(){return{version:Gp,jobs:[],lastUpdated:Date.now()}}function $k(){try{const e=localStorage.getItem(Kp);if(!e)return Uk();const t=JSON.parse(e);return t.version!==Gp?Uk():t}catch(e){return Uk()}}function Dk(e){try{e.lastUpdated=Date.now(),localStorage.setItem(Kp,JSON.stringify(e))}catch(t){}}function Lk(e){return $k().jobs.find(t=>t.draftId===e)}function Bk(e,t,n){const s=$k(),r=s.jobs.findIndex(t=>t.draftId===e),a=Date.now(),o={id:s.jobs[r]?.id??e,draftId:e,state:t,resultVideos:n,createdAt:s.jobs[r]?.createdAt??a,updatedAt:a};return-1===r?s.jobs.push(o):s.jobs[r]=o,Dk(s),function(e){Yp.forEach(t=>t(e))}(o),o}function zk(){return(zk=t(()=>{Kp="nostube_browser_transcode_jobs",Gp="1",Yp=new Set}))()}function Fk(e){return e.map(e=>({label:e.label,progress:0,status:"pending"}))}function _k(e,t){!function(e,t){const n=Lk(e);if(!n)return;const s=t(n);Bk(e,s.state,s.resultVideos)}(e,e=>({...e,state:t(e.state)}))}function Ok(e){const t=e?.split(",").map(e=>e.trim()).filter(Boolean)??[];return{videoCodec:t.find(e=>/^(avc1|avc3|hvc1|hev1)/i.test(e)),audioCodec:t.find(e=>/^(mp4a|ac-3|ec-3|opus)/i.test(e))}}function Wk(e){return e?`application/vnd.apple.mpegurl; codecs="${e}"`:"application/vnd.apple.mpegurl"}function Vk(e,t,n){const s=e.replace(/\.m3u8$/,"/"),r=t.split("\n").map(e=>e.trim()).filter(e=>e.length>0&&!e.startsWith("#")),a=new Set;for(const i of r)i.startsWith("http://")||i.startsWith("https://")||(i.includes("/")?a.add(i):a.add(`${s}${i}`));let o=0;return a.forEach(e=>{o+=n.get(e)?.size??0}),o}function qk(e,t){let n=0,s=null,r=null;return(...a)=>{const o=Date.now(),i=t-(o-n);i<=0?(s&&(clearTimeout(s),s=null),n=o,e(...a)):(r=a,s||(s=setTimeout(()=>{n=Date.now(),s=null,r&&(e(...r),r=null)},i)))}}async function Jk(e,t){const n=new Array(e.length);let s=0;return await Promise.all(Array.from({length:Math.min(t,e.length)},async function(){for(;st.endsWith(e))&&"video/mp4"!==e.type?new File([e],e.name,{type:"video/mp4",lastModified:e.lastModified}):e}(e),o=await jx({file:a,servers:t,signer:n,options:{chunkSize:zp,maxConcurrentChunks:2},callbacks:{onProgress:s},skipExistenceCheck:!0,signal:r});if(r?.aborted)throw new DOMException("Aborted","AbortError");if(0===o.length)throw new Error("No upload servers configured");return{url:o[0].url,blobs:o}}function Kk(e){return function(e){return Yp.add(e),()=>{Yp.delete(e)}}(e)}function Gk(e){return Lk(e)}function Yk(e){Zp.get(e)?.abort(),Zp.delete(e),function(e){const t=$k(),n=t.jobs.filter(t=>t.draftId!==e);n.length!==t.jobs.length&&(t.jobs=n,Dk(t))}(e)}async function Xk(e){const{draftId:t,file:n,variants:s,sourceMeta:r,mode:a,keepOriginal:o,initialServers:i,mirrorServers:c,signer:l}=e;if(Zp.has(t))throw new Error("A browser transcode job is already running for this draft.");const u=new AbortController;Zp.set(t,u),Bk(t,{status:"queued",mode:a,keepOriginal:o,sourceName:n.name,sourceSize:n.size,startedAt:Date.now(),updatedAt:Date.now(),variants:Fk(s),message:"Browser transcode queued."});try{_k(t,e=>({...e,status:"transcoding",updatedAt:Date.now(),message:"Transcoding video in background..."}));const e=s.some(e=>"hls"===e.format);let d=0;const f=qk(e=>{_k(t,t=>({...t,status:"transcoding",updatedAt:Date.now(),variants:t.variants.map(t=>({...t,progress:e,status:"active"}))}))},500),m=s.length>0?await gk(n,s,r,({progress:e})=>{const t=Date.now();(t-d>500||1===e)&&(d=t,f(e))},(e,n)=>{_k(t,t=>({...t,updatedAt:Date.now(),variants:t.variants.map((t,n)=>n===e?{...t,status:"error"}:t),message:n}))},u.signal):[];_k(t,e=>({...e,status:"uploading",updatedAt:Date.now(),variants:e.variants.map(e=>"active"===e.status||"pending"===e.status?{...e,progress:1,status:"done"}:e),message:"Uploading transcoded videos..."}));const p=[];if(e&&m instanceof Map){const e=new Map,n=[],s=Array.from(m.keys()),a=s.filter(e=>!e.endsWith(".m3u8")),o=s.filter(e=>e.endsWith(".m3u8")),d=a.length+o.length+1,f=s.reduce((e,t)=>e+(m.get(t)?.size??0),0);let h=0;const g=(e,n)=>{const s=f>0?Math.round(h/f*100):Math.round(e/d*100);_k(t,t=>({...t,updatedAt:Date.now(),message:n,uploadProgress:{uploadedBytes:h,totalBytes:f,percentage:s,currentChunk:e,totalChunks:d}}))};_k(t,e=>({...e,updatedAt:Date.now(),uploadProgress:{uploadedBytes:0,totalBytes:f,percentage:0,currentChunk:0,totalChunks:d}}));const y=[],b=new Map,w=new Map,v=i.map(e=>{try{return new URL(e).hostname}catch{return e}}),x=v.length>1,k=[],N=[],j=m.get("master.m3u8");if(j){const e=(await j.text()).split("\n").map(e=>e.trim());for(let t=0;te.trim())){if(!e||e.startsWith("#")){if(e.startsWith("#EXT-X-MAP:")){const t=e.match(/URI="([^"]+)"/);if(t){const e=t[1].includes("/")?t[1]:`${c}${t[1]}`;m.has(e)&&l.push(e)}}continue}if(e.startsWith("http://")||e.startsWith("https://"))continue;const t=e.includes("/")?e:`${c}${e}`;m.has(t)&&l.push(t)}N.push({label:a,segPaths:l})}for(const t of e){if(!t.startsWith("#EXT-X-MEDIA:")||!t.includes("TYPE=AUDIO"))continue;const e=t.match(/URI="([^"]+)"/);if(!e)continue;const n=e[1],s=t.match(/LANGUAGE="([^"]+)"/)?.[1],r=t.match(/NAME="([^"]+)"/)?.[1],a=r?`audio (${r})`:s?`audio (${s})`:"audio",o=m.get(n);if(!o)continue;const i=await o.text(),c=n.replace(/\.m3u8$/,"/"),l=[];for(const t of i.split("\n").map(e=>e.trim())){if(!t||t.startsWith("#")){if(t.startsWith("#EXT-X-MAP:")){const e=t.match(/URI="([^"]+)"/);if(e){const t=e[1].includes("/")?e[1]:`${c}${e[1]}`;m.has(t)&&l.push(t)}}continue}if(t.startsWith("http://")||t.startsWith("https://"))continue;const e=t.includes("/")?t:`${c}${t}`;m.has(e)&&l.push(e)}N.push({label:a,segPaths:l})}}for(const{label:t,segPaths:r}of N)for(const e of v){const n=k.length;k.push({streamLabel:t,serverLabel:x?e:void 0,statuses:r.map(()=>"pending")}),r.forEach((t,s)=>b.set(`${t}::${e}`,{stateIdx:n,segIdx:s}))}const S=k.map(e=>[...e.statuses]),C=qk(()=>{_k(t,e=>({...e,segmentStates:k.map((e,t)=>({streamLabel:e.streamLabel,serverLabel:e.serverLabel,statuses:[...S[t]]}))}))},150);k.length>0&&_k(t,e=>({...e,segmentStates:k}));let E=0;await Jk(a.map(t=>async()=>{if(u.signal.aborted)throw new DOMException("Aborted","AbortError");for(const e of v){const n=b.get(`${t}::${e}`);n&&(S[n.stateIdx][n.segIdx]="uploading")}C();const n=m.get(t),{url:s,blobs:r}=await Hk(n,i,l,void 0,u.signal);e.set(t,s),y.push(...r),h+=n.size,E++;const a=new Set(r.map(e=>{try{return new URL(e.url).hostname}catch{return""}}));for(const e of v){const n=b.get(`${t}::${e}`);n&&(S[n.stateIdx][n.segIdx]=a.has(e)?"done":"error")}for(const e of r)try{const n=new URL(e.url).hostname,s=b.get(`${t}::${n}`);s&&w.set(e.url,s)}catch{}C(),g(E,`Uploading HLS segments (${E}/${d})…`)}),2);const M=await Tk(m,e);if(u.signal.aborted)throw new DOMException("Aborted","AbortError");const I=M.get("master.m3u8"),A=I?await I.text():null,P=A?function(e){const t=e.split("\n").map(e=>e.trim()),n=new Map;for(let s=0;se.trim()),n=new Map;for(const s of t){if(!s.startsWith("#EXT-X-MEDIA:")||!s.includes("TYPE=AUDIO"))continue;const e=s.match(/URI="([^"]+)"/)?.[1];e&&n.set(e,{language:s.match(/LANGUAGE="([^"]+)"/)?.[1],name:s.match(/NAME="([^"]+)"/)?.[1]})}return n}(A):new Map,R=Array.from(M.keys()).filter(e=>e.endsWith(".m3u8")&&"master.m3u8"!==e);let U=0;if(await Jk(R.map(t=>async()=>{if(u.signal.aborted)throw new DOMException("Aborted","AbortError");const s=M.get(t),{url:r,blobs:a}=await Hk(s,i,l,void 0,u.signal);e.set(t,r),y.push(...a);const o=P.get(t);if(o){const e=m.get(t),a=Vk(t,e?await e.text():await s.text(),m)+s.size;n.push({url:r,dimension:`${o.width}x${o.height}`,qualityLabel:`${Math.min(o.width,o.height)}p`,sizeMB:a>0?a/1048576:void 0,mimeType:o.mimeType,videoCodec:o.videoCodec,audioCodec:o.audioCodec})}const c=T.get(t);if(c){const e=m.get(t),a=Vk(t,e?await e.text():await s.text(),m)+s.size,o=c.name??c.language??"audio";n.push({type:"audio",language:c.language,url:r,dimension:"-",qualityLabel:o,sizeMB:a>0?a/1048576:void 0})}h+=s.size,U++,g(E+U,`Uploading HLS playlists (${E+U}/${d})…`)}),2),u.signal.aborted)throw new DOMException("Aborted","AbortError");const $=M.get("master.m3u8"),D=(await Tk(new Map([["master.m3u8",$]]),e)).get("master.m3u8"),{url:L,blobs:B}=await Hk(D,i,l,void 0,u.signal);y.push(...B),h+=D.size,g(d,`Uploading master playlist (${d}/${d})…`);let z=[];if(c.length>0&&y.length>0){if(u.signal.aborted)throw new DOMException("Aborted","AbortError");let e=0;const n=y.length,s=k.map(e=>e.statuses.map(()=>"pending")),r=qk(()=>{_k(t,e=>({...e,mirrorSegmentStates:k.map((e,t)=>({streamLabel:e.streamLabel,statuses:[...s[t]]}))}))},150);k.length>0?_k(t,e=>({...e,mirrorProgress:{mirrored:0,total:n,percentage:0},mirrorSegmentStates:k.map(e=>({streamLabel:e.streamLabel,statuses:e.statuses.map(()=>"pending")}))})):_k(t,e=>({...e,mirrorProgress:{mirrored:0,total:n,percentage:0}})),z=(await Jk(y.map(a=>async()=>{if(u.signal.aborted)throw new DOMException("Aborted","AbortError");const o=w.get(a.url);o&&(s[o.stateIdx][o.segIdx]="mirroring",r());const i=await yx({mirrorServers:c,blob:a,signer:l});return e++,o&&(s[o.stateIdx][o.segIdx]="done",r()),_k(t,t=>({...t,mirrorProgress:{mirrored:e,total:n,percentage:Math.round(e/n*100)}})),i}),4)).flat(),_k(t,e=>({...e,mirrorProgress:{mirrored:n,total:n,percentage:100}}))}const F=n.sort((e,t)=>{const n=parseInt(e.qualityLabel,10)||0;return(parseInt(t.qualityLabel,10)||0)-n}),_=F[0],O=y.find(e=>e.url===L),W=O?z.filter(e=>e.sha256===O.sha256):[];p.push({url:L,mimeType:"application/vnd.apple.mpegurl",dimension:_?.dimension||`${r.width}x${r.height}`,qualityLabel:_?.qualityLabel,hlsVariants:F,duration:r.duration,uploadedBlobs:y,mirroredBlobs:z,placement:Kx({primaryBlob:O,candidateBlobs:[...y,...W],directUrl:L}),inputMethod:"url"})}else if(m instanceof Array){const e=o?[...m,n]:m;for(const n of e){const e=await uk(n,i,c,l,e=>{_k(t,t=>({...t,status:"uploading",updatedAt:Date.now(),uploadProgress:e}))},u.signal);p.push(e)}}const h=fk(Xp).find(e=>e.id===t)?.uploadInfo.videos??[],g="append"===a?[...h,...p]:p;Bk(t,{status:"complete",mode:a,keepOriginal:o,sourceName:n.name,sourceSize:n.size,startedAt:Lk(t)?.state.startedAt??Date.now(),updatedAt:Date.now(),completedAt:Date.now(),variants:Fk(s).map(e=>({...e,progress:1,status:"done"})),message:"Browser transcode and upload complete."},g)}catch(d){if(u.signal.aborted)return void _k(t,e=>({...e,status:"cancelled",updatedAt:Date.now(),message:"Browser transcode cancelled."}));_k(t,e=>({...e,status:"error",updatedAt:Date.now(),error:d instanceof Error?d.message:String(d)}))}finally{Zp.delete(t)}}function Zk(){return(Zk=t(()=>{dk(),Ix(),tk(),yk(),Rk(),zk(),Xp="nostube_upload_drafts",Zp=new Map}))()}function Qk(e){const t=e.replace(/\.(vtt|srt|ass|ssa|sub)$/i,"").toLowerCase(),n=t.match(/[_.-]([a-z]{2,3})(?:[_-][a-z]{2})?$/);if(n){const e=n[1],t=Qp.default.where("1",e)||Qp.default.where("2",e)||Qp.default.where("2T",e)||Qp.default.where("2B",e)||Qp.default.where("3",e);if(t)return t[1]||e}for(const[s,r]of Object.entries(eh))if(new RegExp(`[_.-]${s}$|^${s}[_.-]|^${s}$`).test(t))return r;return""}function eN(){return`sub_${Date.now()}_${Math.random().toString(36).slice(2,9)}`}function tN(){return(tN=t(()=>{Qp=e(ua(),1),eh={english:"en",german:"de",deutsch:"de",french:"fr",francais:"fr",spanish:"es",espanol:"es",italian:"it",italiano:"it",portuguese:"pt",portugues:"pt",russian:"ru",japanese:"ja",chinese:"zh",korean:"ko",dutch:"nl",polish:"pl",swedish:"sv",norwegian:"no",danish:"da",finnish:"fi",arabic:"ar",hebrew:"he",turkish:"tr",greek:"el",hindi:"hi",thai:"th",vietnamese:"vi",indonesian:"id",czech:"cs",hungarian:"hu",romanian:"ro",ukrainian:"uk"}}))()}async function nN(e){return new Promise(t=>{const n=new Image,s=URL.createObjectURL(e);n.onload=()=>{try{const e=32,r=32,a=document.createElement("canvas");a.width=e,a.height=r;const o=a.getContext("2d");if(!o)return URL.revokeObjectURL(s),void t(void 0);o.drawImage(n,0,0,e,r);const i=o.getImageData(0,0,e,r),c=Tr(i.data,e,r,4,3);URL.revokeObjectURL(s),t(c)}catch(e){URL.revokeObjectURL(s),t(void 0)}},n.onerror=()=>{URL.revokeObjectURL(s),t(void 0)},n.src=s})}function sN(){return(sN=t(()=>{js()}))()}async function rN(e,t,n){0!==e.length&&0!==n.length&&await Promise.allSettled(e.map(async e=>{if(0!==e.mirrorResults.length&&e.blob.hash)try{const s=function(e){const{blob:t,mirrorResults:n,videoEvent:s,relayHint:r}=e;if(0===n.length)throw new Error("No mirror results to announce");const a=n[0].url,o=n.slice(1).map(e=>e.url),i=[];i.push(["url",a]);for(const u of o)i.push(["fallback",u]);t.hash&&i.push(["x",t.hash]);const c=t.variant.mimeType||function(e){if(e.variant.mimeType)return e.variant.mimeType;const t=e.ext?.toLowerCase();switch(e.type){case"video":switch(t){case"mp4":default:return"video/mp4";case"webm":return"video/webm";case"mov":return"video/quicktime";case"avi":return"video/x-msvideo"}case"thumbnail":switch(t){case"jpg":case"jpeg":default:return"image/jpeg";case"png":return"image/png";case"webp":return"image/webp";case"gif":return"image/gif"}case"subtitle":switch(t){case"vtt":default:return"text/vtt";case"srt":return"text/srt"}default:return"application/octet-stream"}}(t);i.push(["m",c]);const l=n[0].size||t.variant.size;if(l&&i.push(["size",l.toString()]),t.variant.dimensions&&i.push(["dim",t.variant.dimensions]),i.push(["e",s.id,r]),(34235===s.kind||34236===s.kind)&&void 0!==s.dTag){const e=`${s.kind}:${s.pubkey}:${s.dTag}`;i.push(["a",e,r]),i.push(["k",s.kind.toString()])}return{kind:1063,content:"",created_at:ol(),tags:i}}(e),r=await t.signEvent(s);await Ko.publish(n,r)}catch(s){}}))}function aN(e,t){const n=new Set;for(const s of e)s&&n.add(s);for(const s of t)s&&n.add(s);return Array.from(n)}function oN(e){const{uploadedBlobs:t,variant:n,videoEvent:s,relayHint:r}=e;if(0===t.length)throw new Error("No uploaded blobs for contributed variant announcement");const a=t[0],o=il("video/mp4",n.videoCodec,n.audioCodec);return{blob:{type:"video",variant:{url:a.url,hash:a.sha256??void 0,size:n.sizeMB?Math.round(1024*n.sizeMB*1024):a.size,dimensions:n.dimension,mimeType:o,quality:n.qualityLabel,fallbackUrls:t.slice(1).map(e=>e.url)},label:`Variant ${n.qualityLabel??n.dimension}`,hash:a.sha256??"",ext:"mp4"},mirrorResults:t,videoEvent:s,relayHint:r}}function iN(){return(iN=t(()=>{nu(),dl()}))()}function cN(e){return e instanceof Error?e:new Error(String(e))}function lN(e){return Number.isNaN(e)?0:Math.max(0,Math.min(100,Math.round(e)))}async function uN({steps:e,onStateChange:t}){let n={phase:"validating",progress:0};const s=th.filter(t=>e[t]),r=s.length>0?100/s.length:100,a=e=>{n=function(e,t){switch(t.type){case"phase-start":return{phase:t.phase,progress:lN(t.progress)};case"phase-progress":return{...e,progress:lN(t.progress)};case"done":return{phase:"done",progress:100,result:t.result};case"failed":return{phase:"failed",progress:e.progress,error:t.error}}}(n,e),t?.(n)};try{let t;for(const[o,i]of s.entries()){const s=nh[i],c=o*r,l=(o+1)*r,u=e[i];a({type:"phase-start",phase:s,progress:c});const d={state:n,reportProgress:e=>{a({type:"phase-progress",progress:c+e/100*(l-c)})}};"publish"===i?t=await u(d):await u(d),a({type:"phase-progress",progress:l})}if(!t)throw new Error("Video publishing workflow completed without a publish result");return a({type:"done",result:t}),n}catch(o){return a({type:"failed",error:cN(o)}),n}}function dN(){return(dN=t(()=>{th=["validate","upload","transcode","mirror","publish"],nh={validate:"validating",upload:"uploading",transcode:"transcoding",mirror:"mirroring",publish:"publishing"}}))()}function fN(e){const{videos:t,title:n,description:s,tags:r,language:a,people:o,contentWarningEnabled:i,contentWarningReason:c,expiration:l,thumbnailUploadedBlobs:u,thumbnailMirroredBlobs:d,subtitles:f,draftId:m,thumbnailBlurhash:p,isPreview:h=!1,hasPendingThumbnail:g=!1,publishAt:y,origins:b=[]}=e,w=t[0],[v,x]=(k=w,ik(k)?.dimension||k.dimension).split("x").map(Number);var k;const N=x>v?34236:34235,{imetaTags:j,allFallbackUrls:S}=function(e){const{videos:t,thumbnailUploadedBlobs:n,thumbnailMirroredBlobs:s,thumbnailBlurhash:r,isPreview:a=!1,hasPendingThumbnail:o=!1}=e,i=[],c=[],l=[...n.map(e=>e.url),...s.map(e=>e.url)];a&&o&&0===n.length&&l.push("");for(const u of t){const e=sk({variant:u,thumbnailUrls:l,blurhash:r});i.push(e);const t=Gx(u).placement;c.push(...t.fallbackBlobs.map(e=>e.url),...t.directUrl?[t.directUrl]:[])}return{imetaTags:i,allFallbackUrls:c}}({videos:t,thumbnailUploadedBlobs:u,thumbnailMirroredBlobs:d,thumbnailBlurhash:p,isPreview:h,hasPendingThumbnail:g}),C=()=>"none"===l?null:(Math.floor(Date.now()/1e3)+{"1day":86400,"7days":604800,"1month":2592e3,"1year":31536e3}[l]).toString(),E=h?"":ol(),M=h?y?y.toString():"":(y??ol()).toString(),I=f.filter(e=>(e.uploadedBlobs?.length??0)>0&&e.lang).map(e=>["text-track",e.uploadedBlobs[0].url,e.lang]),A={kind:N,content:s,created_at:E,tags:[["d",m],["title",n],["alt",s],["published_at",M],["duration",w.duration.toString()],...j,...I,...i?[["content-warning",c.trim()?c:"NSFW"]]:[],...C()?[["expiration",C()]]:[],...r.map(e=>["t",e]),...o.map(e=>e.relays&&e.relays.length>0?["p",e.pubkey,e.relays[0]]:["p",e.pubkey]),...b.flat(),["L","ISO-639-1"],["l",a,"ISO-639-1"],["client","nostube"]]},P=Gx(w).placement;return{event:A,allFallbackUrls:S,primaryVideoUrl:P.primaryBlob?.url??P.directUrl}}function mN(e,t){const n=e,s={videos:(e?.uploadInfo?.videos??[]).map(Gx)},r=e?.uploadInfo?.videos.some(e=>!e.placement)??!1,a=(0,sh.useRef)(r),o=(0,sh.useRef)(r),i=(e?.id?Gk(e.id):void 0)?.state??n?.browserTranscodeState,[c,l]=(0,sh.useState)(e?.title||""),[u,d]=(0,sh.useState)(e?.description||""),[f,m]=(0,sh.useState)(()=>[...new Set(e?.tags||[])]),[p,h]=(0,sh.useState)(e?.language||"en"),[g,y]=(0,sh.useState)(e?.people||[]),[b,w]=(0,sh.useState)(e?.origins||[]),[v,x]=(0,sh.useState)(e?.inputMethod||"file"),[k,N]=(0,sh.useState)(e?.videoUrl||""),[j,S]=(0,sh.useState)(null),[C,E]=(0,sh.useState)(null),[M,I]=(0,sh.useState)(s),[A,P]=(0,sh.useState)(i&&["queued","transcoding","uploading"].includes(i.status)?"transcoding":s.videos.length>0?"finished":"initial"),[T,R]=(0,sh.useState)("replace"),[U,$]=(0,sh.useState)(i),[D,L]=(0,sh.useState)(e?.originalVideoInfo),[B,z]=(0,sh.useState)(null),[F,_]=(0,sh.useState)(void 0),[O,W]=(0,sh.useState)(e?.thumbnailSource||"generated"),[V,q]=(0,sh.useState)({uploadedBlobs:e?.thumbnailUploadInfo.uploadedBlobs||[],mirroredBlobs:e?.thumbnailUploadInfo.mirroredBlobs||[],uploading:!1}),[J,H]=(0,sh.useState)(e?.contentWarning.enabled||!1),[K,G]=(0,sh.useState)(e?.contentWarning.reason||""),[Y,X]=(0,sh.useState)(e?.expiration||"none"),[Z,Q]=(0,sh.useState)(e?.publishAt),[ee,te]=(0,sh.useState)(null),[ne,se]=(0,sh.useState)(null),[re,ae]=(0,sh.useState)({fallbackUrls:[]}),[oe,ie]=(0,sh.useState)(null),[ce,le]=(0,sh.useState)(e?.subtitles||[]),[ue,de]=(0,sh.useState)(!1),[fe]=(0,sh.useState)(()=>e?.id||crypto.randomUUID()),[me,pe]=(0,sh.useState)(null),[he,ge]=(0,sh.useState)(null),ye=(0,sh.useRef)(t);(0,sh.useEffect)(()=>{ye.current=t},[t]),(0,sh.useEffect)(()=>Kk(e=>{if(e.draftId!==fe)return;$(e.state);const t=e.state.status;"complete"===t?(e.resultVideos&&I({videos:e.resultVideos}),P("finished"),te(null)):"queued"===t||"transcoding"===t||"uploading"===t?P("transcoding"):"error"!==t&&"cancelled"!==t||("cancelled"===t&&($(void 0),Yk(fe)),P(M.videos.length>0?"finished":j?"transcoding":"initial"),te(null))}),[fe,j,M.videos.length]);const be=(0,sh.useRef)(!1),[we,ve]=(0,sh.useState)(!1);(0,sh.useEffect)(()=>{const e=M.videos[0],t=D?.extractedMetadata??e?.extractedMetadata;if(!t||be.current)return;const n=t;let s=!1;!c&&n.title&&(l(n.title),s=!0),!u&&n.description&&(d(n.description),s=!0),0===f.length&&n.tags&&n.tags.length>0&&(m(n.tags),s=!0),!Z&&n.publishAt&&(Q(n.publishAt),s=!0),s&&(be.current=!0,ve(!0))},[D,M.videos,c,u,f.length,Z]);const xe=(0,sh.useRef)(!1);(0,sh.useEffect)(()=>{if(xe.current||c||!D?.name)return;const e=D.name.replace(/\.[^/.]+$/,"").trim();e&&(xe.current=!0,l(e))},[D?.name,c]);const{user:ke}=yu(),{config:Ne}=iu(),{publish:je,isPending:Se}=ku(),Ce=Ne.blossomServers?.filter(e=>e.tags.includes("initial upload")),Ee=Ne.blossomServers?.filter(e=>e.tags.includes("mirror")),Me=ke?async e=>await ke.signer.signEvent(e):void 0,Ie=Ax({initialServers:Ce?.map(e=>e.url)||[],mirrorServers:Ee?.map(e=>e.url)||[],signer:Me||(async e=>e)});(0,sh.useEffect)(()=>{te(Ie.progress)},[Ie.progress]);const Ae=(0,sh.useCallback)(async e=>{if(!("generated"!==O||B||C||V.uploadedBlobs.length>0)){z(e);try{const t=new File([e],"thumbnail.webp",{type:e.type||"image/webp"}),n=await nN(t);_(n)}catch(t){}}},[C,B,O,V.uploadedBlobs.length]),Pe=e=>{e instanceof Error?"NotReadableError"===e.name||e.message.includes("NotReadableError")?alert(`Upload failed: File cannot be read by browser.\n\nThis usually happens with very large files (>2GB) or corrupted files.\n\nSolutions:\n- Try reducing file size\n- Use Chrome browser (better large file support)\n- Check if file is corrupted\n- Close other browser tabs to free memory\n\nError: ${e.message}`):e.message.includes("File too large for browser")?alert(`Upload failed: File too large for browser to process.\n\nTry:\n- Reducing file size\n- Using Chrome browser\n- Closing other browser tabs\n\nError: ${e.message}`):e.message.includes("does not support PATCH chunked uploads")?alert(`Upload failed: Server does not support BUD-10 PATCH chunked uploads.\n\n${e.message}\n\nTry using a different server that supports BUD-10 specification.`):e.message.includes("BUD-10 PATCH chunked upload failed")?alert(`Upload failed: BUD-10 PATCH upload failed.\n\n${e.message}\n\nThis server may not be BUD-10 compliant. Try a different server.`):e.message.includes("OPTIONS /upload failed")?alert(`Upload failed: Server capabilities negotiation failed.\n\n${e.message}\n\nThis server may not support BUD-10. Try a different server.`):alert(`Upload failed: ${e.message}`):alert("Upload failed due to an unknown error. Please try again.")},Te=async e=>{const t=await Ie.upload(e);return{...await Zx(e,t.uploadedBlobs),mirroredBlobs:t.mirroredBlobs}},Re=(0,sh.useMemo)(()=>{if(B)return URL.createObjectURL(B)},[B]);(0,sh.useEffect)(()=>()=>{Re&&URL.revokeObjectURL(Re)},[Re]);const Ue=(0,sh.useCallback)(async e=>{if(Ce&&0!==Ce.length&&ke){de(!0);for(const n of e){const e=eN(),s=Qk(n.name),r={id:e,filename:n.name,lang:s,uploadedBlobs:[],mirroredBlobs:[]};le(e=>[...e,r]);try{const t=await Ie.upload(n);le(n=>n.map(n=>n.id===e?{...n,uploadedBlobs:t.uploadedBlobs,mirroredBlobs:t.mirroredBlobs}:n))}catch(t){le(t=>t.filter(t=>t.id!==e))}}de(!1)}},[Ce,ke,Ie]),$e=(0,sh.useCallback)(async e=>{const t=ce.find(t=>t.id===e);if(!t||!ke)return void le(t=>t.filter(t=>t.id!==e));const n=[...t.uploadedBlobs,...t.mirroredBlobs];await Ie.deleteBlobs(n),le(t=>t.filter(t=>t.id!==e))},[ce,ke,Ie]),De=(0,sh.useCallback)((e,t)=>{le(n=>n.map(n=>n.id===e?{...n,lang:t}:n))},[]);(0,sh.useEffect)(()=>{a.current?a.current=!1:ye.current&&ye.current({title:c,description:u,tags:f,language:p,people:g,origins:b,inputMethod:v,videoUrl:k,contentWarning:{enabled:J,reason:K},expiration:Y,publishAt:Z,thumbnailSource:O,updatedAt:Date.now()})},[c,u,f,p,g,v,k,J,K,Y,Z,O,b]),(0,sh.useEffect)(()=>{o.current?o.current=!1:ye.current&&ye.current({uploadInfo:M,originalVideoInfo:D,thumbnailUploadInfo:{uploadedBlobs:V.uploadedBlobs,mirroredBlobs:V.mirroredBlobs},subtitles:ce,updatedAt:Date.now()})},[D,M,V,ce]);const Le=(0,sh.useMemo)(()=>{if(0===M.videos.length)return null;const e=V.uploadedBlobs,t=V.mirroredBlobs;return fN({videos:M.videos,title:c||"",description:u,tags:f,language:p,people:g,contentWarningEnabled:J,contentWarningReason:K,expiration:Y,thumbnailUploadedBlobs:e,thumbnailMirroredBlobs:t,subtitles:ce,draftId:fe,thumbnailBlurhash:F,isPreview:!0,hasPendingThumbnail:"generated"===O&&null!==B||"upload"===O&&null!==C&&0===(V.uploadedBlobs?.length??0),publishAt:Z,origins:b}).event},[M.videos,c,u,f,p,g,J,K,Y,O,C,V,B,F,ce,fe,Z,b]);return{title:c,setTitle:l,description:u,setDescription:d,tags:f,setTags:m,language:p,setLanguage:h,people:g,setPeople:y,origins:b,setOrigins:w,inputMethod:v,setInputMethod:x,videoUrl:k,setVideoUrl:N,file:j,thumbnail:C,setThumbnail:E,uploadInfo:M,originalVideoInfo:D,uploadState:A,thumbnailBlob:B,thumbnailSource:O,thumbnailUploadInfo:V,contentWarningEnabled:J,setContentWarningEnabled:H,contentWarningReason:K,setContentWarningReason:G,expiration:Y,setExpiration:X,publishAt:Z,setPublishAt:Q,uploadProgress:ee,workflowState:ne,browserTranscodeState:U,publishSummary:re,publishRelays:oe,setPublishRelays:ie,writeRelays:Ne.relays.filter(e=>e.tags.includes("write")).map(e=>e.url),blossomInitalUploadServers:Ce,blossomMirrorServers:Ee,isPublishing:Se||"validating"===ne?.phase||"uploading"===ne?.phase||"transcoding"===ne?.phase||"mirroring"===ne?.phase||"publishing"===ne?.phase,thumbnailUrl:Re,previewEvent:Le,videoToDelete:me,setVideoToDelete:pe,deletingIndex:he,subtitles:ce,subtitleUploading:ue,metadataDetected:we,handleUrlVideoProcessing:async e=>{if(e){I({videos:[]}),P("uploading");try{const n=Vl(e);let s=[];if(n.isBlossomUrl&&n.sha256&&ke&&Ee&&Ee.length>0)try{const t={url:e,sha256:n.sha256,size:0,type:"video/mp4",uploaded:Date.now()};s=await yx({mirrorServers:Ee.map(e=>e.url),blob:t,signer:async e=>await ke.signer.signEvent(e)})}catch(t){}const r=await ek(e,s);I({videos:[r]}),P("finished")}catch(t){P("initial"),I({videos:[]})}}},handleThumbnailDrop:async e=>{if(e[0]&&Ce&&ke){q({uploadedBlobs:[],mirroredBlobs:[],uploading:!0});try{const t=await Ie.upload(e[0]);q({uploadedBlobs:t.uploadedBlobs,mirroredBlobs:t.mirroredBlobs,uploading:!1}),E(e[0]);const n=await nN(e[0]);_(n)}catch{q({uploadedBlobs:[],mirroredBlobs:[],uploading:!1,error:"Failed to upload thumbnail."})}}},handleAutoThumbnailCapture:Ae,handleThumbnailSourceChange:e=>{W(e),"generated"===e&&E(null)},handleDeleteThumbnail:async()=>{if(!ke)return;const e=[...V.uploadedBlobs||[],...V.mirroredBlobs||[]];await Ie.deleteBlobs(e),E(null),z(null),q({uploadedBlobs:[],mirroredBlobs:[],uploading:!1}),_(void 0),W("upload")},onDrop:async e=>{if(!e[0]||!Ce||0===Ce.length||!ke)return;const t=e[0];Yk(fe),R("replace"),$(void 0),L(void 0),S(t),I({videos:[]}),te(null),P("transcoding");try{const e=await async function(e){const t=document.createElement("video");t.src=URL.createObjectURL(e),t.muted=!0,t.playsInline=!0,t.preload="metadata";try{const{dimension:n,duration:s}=await Xx(t),r=e.size/1024/1024,a=Yx(n),[o,i]=await Promise.all([Up(e).catch(e=>({})),Lp(e).catch(e=>({}))]);return{name:e.name,mimeType:e.type,size:e.size,sizeMB:Number(r.toFixed(2)),dimension:n,duration:s,videoCodec:o.videoCodec,audioCodec:o.audioCodec,bitrate:o.bitrate?Math.floor(o.bitrate):void 0,qualityLabel:a,extractedMetadata:Object.keys(i).length>0?i:void 0}}finally{URL.revokeObjectURL(t.src)}}(t);L(e),ye.current?.({originalVideoInfo:e,updatedAt:Date.now()})}catch(n){const e={name:t.name,mimeType:t.type,size:t.size,sizeMB:Number((t.size/1024/1024).toFixed(2)),dimension:"0x0",duration:0};L(e),ye.current?.({originalVideoInfo:e,updatedAt:Date.now()})}},handleBrowserTranscodeComplete:async e=>{P("uploading"),te(null);try{if(!(e instanceof Array))throw new Error("HLS upload is currently only supported in background mode.");const t=[];for(const n of e)t.push(await Te(n));I(e=>({videos:"append"===T?[...e.videos,...t]:t}))}catch(t){return P("append"===T?"finished":"initial"),"replace"===T&&I({videos:[]}),te(null),void Pe(t)}P("finished"),te(null)},handleBrowserTranscodeSkip:async()=>{if(j&&Ce&&0!==Ce.length&&ke){P("uploading"),te(null);try{const e=await Te(j);I(t=>({videos:"append"===T?[...t.videos,e]:[e]}))}catch(e){return P("append"===T?"finished":"initial"),"replace"===T&&I({videos:[]}),te(null),void Pe(e)}P("finished"),te(null)}else P("initial")},handleStartBrowserTranscodeUpload:async(e,t,n=!1)=>{j&&Ce&&0!==Ce.length&&ke&&Me?(P("transcoding"),te(null),Xk({draftId:fe,file:j,variants:e,sourceMeta:t,mode:T,keepOriginal:n,initialServers:Ce.map(e=>e.url),mirrorServers:Ee?.map(e=>e.url)||[],signer:Me})):P("initial")},handleCancelBrowserTranscodeUpload:()=>{!function(e){Zp.get(e)?.abort(),Zp.delete(e),_k(e,e=>({...e,status:"cancelled",updatedAt:Date.now(),message:"Browser transcode cancelled."}))}(fe),$(void 0),P(M.videos.length>0?"finished":j?"transcoding":"initial"),te(null)},handleReset:()=>{l(""),d(""),m([]),w([]),x("file"),N(""),S(null),E(null),I({videos:[]}),P("initial"),R("replace"),z(null),_(void 0),W("generated"),q({uploadedBlobs:[],mirroredBlobs:[],uploading:!1}),te(null)},handleSubmit:async e=>{e.preventDefault(),ae({fallbackUrls:[]});let t,n=[],s=[],r=[];const a=await uN({onStateChange:se,steps:{validate:()=>{if(!ke)throw new Error("User not logged in");if(0===M.videos.length)throw new Error("No video variants available")},upload:async({reportProgress:e})=>{if((V.uploadedBlobs?.length??0)>0)return n=V.uploadedBlobs,s=V.mirroredBlobs,void e(100);if("generated"===O&&B){const r=new File([B],"thumbnail.webp",{type:B.type||"image/webp",lastModified:Date.now()});try{const t=await Ie.upload(r);return n=t.uploadedBlobs,s=t.mirroredBlobs,void e(100)}catch(t){throw Object.assign(new Error("Failed to upload generated thumbnail"),{cause:t})}}throw new Error("No valid thumbnail available")},mirror:({reportProgress:e})=>{if(0===n.length)throw new Error("No valid thumbnail available");e(100)},publish:async()=>{const{event:e,allFallbackUrls:a,primaryVideoUrl:o}=fN({videos:M.videos,title:c,description:u,tags:f,language:p,people:g,contentWarningEnabled:J,contentWarningReason:K,expiration:Y,thumbnailUploadedBlobs:n,thumbnailMirroredBlobs:s,subtitles:ce,draftId:fe,thumbnailBlurhash:F,isPreview:!1,publishAt:Z,origins:b});r=a,t=o;const i=Ne.relays.filter(e=>e.tags.includes("write")).map(e=>e.url),l=await je({event:e,relays:oe??i});try{const e=[],t=i[0]||"";for(const n of M.videos){const s=Gx(n).placement;s.primaryBlob&&s.fallbackBlobs.length>0&&e.push({blob:{type:"video",variant:{url:s.primaryBlob.url,hash:s.primaryBlob.sha256,size:n.sizeMB?Math.round(1024*n.sizeMB*1024):void 0,dimensions:n.dimension,mimeType:n.file?.type,quality:n.qualityLabel,fallbackUrls:s.fallbackBlobs.map(e=>e.url)},label:`Video ${n.qualityLabel||n.dimension}`,hash:s.primaryBlob.sha256,ext:"mp4"},mirrorResults:s.fallbackBlobs,videoEvent:{id:l.id,kind:l.kind,pubkey:l.pubkey,dTag:fe},relayHint:t})}s.length>0&&n[0]?.sha256&&e.push({blob:{type:"thumbnail",variant:{url:n[0].url,hash:n[0].sha256,size:n[0].size,fallbackUrls:s.map(e=>e.url)},label:"Thumbnail",hash:n[0].sha256,ext:"webp"},mirrorResults:s,videoEvent:{id:l.id,kind:l.kind,pubkey:l.pubkey,dTag:fe},relayHint:t});for(const n of ce)n.mirroredBlobs.length>0&&n.uploadedBlobs[0]?.sha256&&e.push({blob:{type:"subtitle",variant:{url:n.uploadedBlobs[0].url,hash:n.uploadedBlobs[0].sha256,mimeType:"text/vtt",fallbackUrls:n.mirroredBlobs.map(e=>e.url)},label:`Subtitle (${n.lang})`,hash:n.uploadedBlobs[0].sha256,ext:"vtt"},mirrorResults:n.mirroredBlobs,videoEvent:{id:l.id,kind:l.kind,pubkey:l.pubkey,dTag:fe},relayHint:t});if(e.length>0&&ke){const t=aN(i,i);await rN(e,{signEvent:async e=>await ke.signer.signEvent(e)},t)}}catch(d){}return{id:l.id,kind:l.kind,pubkey:l.pubkey,identifier:fe}}}});if("done"===a.phase&&a.result)return ae({eventId:a.result.id,primaryUrl:t,fallbackUrls:r}),l(""),d(""),S(null),E(null),m([]),h("en"),a.result},handleAddVideo:async e=>{e&&e[0]&&Ce&&0!==Ce.length&&ke&&(Yk(fe),R("append"),S(e[0]),te(null),P("transcoding"))},handleRemoveVideo:e=>{const t=M.videos[e];t&&pe({index:e,video:t})},handleRemoveVideoFromFormOnly:()=>{if(null===me)return;const{index:e}=me;I(t=>({videos:t.videos.filter((t,n)=>n!==e)})),pe(null)},handleRemoveVideoWithBlobs:async()=>{if(null===me||!ke)return;const{video:e,index:t}=me;pe(null),ge(t);try{const n=[...e.uploadedBlobs,...e.mirroredBlobs],{totalSuccessful:s,totalFailed:r}=await Mx(n,async e=>await ke.signer.signEvent(e));return I(e=>({videos:e.videos.filter((e,n)=>n!==t)})),{successful:s,failed:r}}catch(n){}finally{ge(null)}},handleAddTranscodedVideo:e=>{I(t=>t.videos.some(t=>t.url===e.url)?t:{videos:[...t.videos,e]})},handleSubtitleDrop:Ue,handleRemoveSubtitle:$e,handleSubtitleLanguageChange:De}}function pN(){return(pN=t(()=>{sh=Be(),KN(),Ix(),Px(),dl(),tk(),ak(),Zk(),ql(),tN(),sN(),iN(),dN()}))()}function hN(e){const{initialUploadServers:t,mirrorServers:n,signer:s}=e,[r,a]=(0,rh.useState)("idle"),[o,i]=(0,rh.useState)(null),[c,l]=(0,rh.useState)(null),[u,d]=(0,rh.useState)(null),[f,m]=(0,rh.useState)(null),p=(0,rh.useCallback)(()=>{a("idle"),i(null),l(null),d(null),m(null)},[]);return{status:r,uploadProgress:o,mirrorProgress:c,result:u,error:f,uploadFile:(0,rh.useCallback)(async e=>{m(null),d(null),l(null);try{a("uploading"),i({uploadedBytes:0,totalBytes:e.size,percentage:0,currentChunk:0,totalChunks:1});const r=await jx({file:e,servers:t,signer:s,options:{chunkSize:10485760,maxConcurrentChunks:2},callbacks:{onProgress:e=>{i(e)}}});a("probing"),i(null);const o=await Zx(e,r);let c=[];n.length>0&&r[0]&&(a("mirroring"),l({completed:0,total:n.length}),c=await yx({mirrorServers:n,blob:r[0],signer:s}),l({completed:c.length,total:n.length}));const u={...o,mirroredBlobs:c};return d(u),a("done"),u}catch(r){const e=r instanceof Error?r.message:"Unknown upload error";throw m(e),a("error"),r}},[t,n,s]),processUrl:(0,rh.useCallback)(async e=>{m(null),d(null),i(null),l(null);try{a("probing");const r=Vl(e);let o=[];if(r.isBlossomUrl&&r.sha256&&n.length>0)try{a("mirroring"),l({completed:0,total:n.length});const t={url:e,sha256:r.sha256,size:0,type:"video/mp4",uploaded:Date.now()};o=await yx({mirrorServers:n,blob:t,signer:s}),l({completed:o.length,total:n.length})}catch(t){}a("probing");const i=await ek(e,o);return d(i),a("done"),i}catch(r){const e=r instanceof Error?r.message:"Unknown error processing URL";throw m(e),a("error"),r}},[n,s]),reset:p}}function gN(){return(gN=t(()=>{rh=Be(),Ix(),tk(),ql()}))()}function yN(e){const t=e.videoCodec?.toLowerCase()||"",[n,s]=e.dimension.split("x").map(Number),r=Math.max(n||0,s||0),a=Object.entries({hev1:"HEVC (hev1)",av01:"AV1",vp09:"VP9",vp9:"VP9"}).find(([e])=>t.startsWith(e));return a?{message:`Your video uses ${a[1]}, which isn't supported on all devices. Adding an H.264 version ensures everyone can watch it.`}:r>1080?{message:`Your video is ${r>=2160?"4K":"2K"} (${e.dimension}). Most viewers watch at 720p or lower — creating smaller versions saves bandwidth and loads faster.`}:{message:"Creating additional versions improves compatibility across devices and network conditions."}}function bN(e){try{return JSON.parse(e)}catch{return null}}function wN(){return(wN=t(()=>{ah={"1080p":"1920x1080","720p":"1280x720","480p":"854x480","360p":"640x360","240p":"426x240"},oh=["1080p","720p","480p","360p","240p"]}))()}function vN(e,t,n){const{videoCodec:s,audioCodec:r}=function(e){const t=e.match(/codecs="([^"]+)"/);if(!t)return{};const n=t[1].split(",").map(e=>e.trim()),s=["avc1","hvc1","hev1","av01","vp09","vp9","h264","hevc"],r=["mp4a","opus","flac","aac"];let a,o;for(const i of n){const e=i.toLowerCase();!a&&s.some(t=>e.startsWith(t))?a=i:!o&&r.some(t=>e.startsWith(t))&&(o=i)}return{videoCodec:a,audioCodec:o}}(e.mimetype||""),a=e.duration||t||0;let o=e.bitrate;!o&&e.size_bytes&&a>0&&(o=Math.round(8*e.size_bytes/a));const i=e.resolution||n||"720p",c=ah[i]||"1280x720";return{url:e.urls[0],dimension:c,sizeMB:e.size_bytes?e.size_bytes/1048576:void 0,duration:a,bitrate:o,videoCodec:s,audioCodec:r,uploadedBlobs:[],mirroredBlobs:[],placement:Kx({directUrl:e.urls[0]}),inputMethod:"url",qualityLabel:i}}function xN(){return(xN=t(()=>{dl(),wN(),tk(),ih=5207,ch=6207,lh=7e3,uh=86400,dh=class e{relays;user;pool;_subs=[];constructor(e,t,n){this.relays=e,this.user=t,this.pool=n}static hasEncryptedTag(e){return e.tags.some(e=>"encrypted"===e[0])}static detectPhaseFromMessage(e){if(!e)return"transcoding";const t=e.toLowerCase();return t.startsWith("uploading")?"uploading":(t.startsWith("transcoding")||t.startsWith("re-encoding"),"transcoding")}collectBids(e,t=5e3){return new Promise(n=>{const s=[],r=this.pool.subscription(this.relays,[{kinds:[lh],"#e":[e]}]).subscribe({next:e=>{if("string"==typeof e)return;const t=function(e){const t=e.tags.find(e=>"status"===e[0]);if("payment-required"!==t?.[1])return null;const n=e.tags.find(e=>"amount"===e[0])?.[1]||"0",s=t[2]||e.content||void 0,r=e.tags.find(e=>"cashu"===e[0]);return{pubkey:e.pubkey,amount:n,message:s,cashu:r?.[1],eventId:e.id}}(e);t&&s.push(t)}});this._subs.push(r),setTimeout(()=>{r.unsubscribe(),n(s)},t)})}async approveBid(e,t,n){const s={kind:lh,content:"",created_at:ol(),tags:[["e",e],["p",t],["status","approved"],["expiration",String(ol()+uh)]]},r=await this.user.signer.signEvent(s);return await this.pool.publish(n,r),r}subscribeToDvmResponses(t){const{requestEventId:n,dvmPubkey:s,originalDuration:r,requestedResolution:a,wasEncrypted:o=!1,onFeedback:i,onSilenceWarning:c}=t;return new Promise((t,l)=>{let u=null,d=!1;const f=this.user.signer,m=setTimeout(()=>{clearInterval(p),h.unsubscribe(),l(new Error("DVM job timed out after 10 minutes"))},6e5),p=setInterval(()=>{if(!u)return;const e=Date.now()-u;e>=18e4?(clearInterval(p),clearTimeout(m),h.unsubscribe(),l(new Error("DVM stopped responding. You can retry with a different service."))):e>=9e4&&!d&&(d=!0,c?.())},3e4),h=this.pool.subscription(this.relays,[{kinds:[lh,ch],authors:[s],"#e":[n]}]).subscribe({next:async n=>{if("string"==typeof n)return;const c=n;if(7e3===c.kind){u=Date.now();let t,n,r;if(e.hasEncryptedTag(c)&&o&&f.nip04)try{const e=function(e){try{return JSON.parse(e)}catch{return null}}(await f.nip04.decrypt(s,c.content));e&&(t=e.status,n=e.message||void 0,r=e.eta||void 0)}catch(d){const e=c.tags.find(e=>"status"===e[0]);if(e){const[,s,r]=e;t=s,n=r||"Processing..."}}else{const e=c.tags.find(e=>"status"===e[0]);if(e){const[,s,a]=e;t=s,n=c.tags.find(e=>"content"===e[0])?.[1]||a||("processing"===t?"Processing video...":"Processing...");const o=c.tags.find(e=>"eta"===e[0]);r=o?.[1]?parseInt(o[1],10):void 0}}if(t){const s=c.tags.find(e=>"progress"===e[0]);let a=s?.[1]?parseInt(s[1],10):void 0;if(void 0===a){const e=n?.match(/(\d+)%/);a=e?parseInt(e[1],10):void 0}const o=c.tags.find(e=>"phase"===e[0])?.[1]??e.detectPhaseFromMessage(n),u=c.tags.find(e=>"speed"===e[0]),d=u?.[1]?parseFloat(u[1]):void 0,f=c.tags.find(e=>"queue_position"===e[0]),g=f?.[1]?parseInt(f[1],10):void 0;"processing"===t||"partial"===t?i({status:t,message:n||"Processing...",percentage:a,phase:o,eta:r,speed:d,queuePosition:g}):"error"===t&&(clearTimeout(m),clearInterval(p),h.unsubscribe(),l(new Error(n||"DVM processing error")))}}else if(6207===c.kind){clearTimeout(m),clearInterval(p),h.unsubscribe();let n=c.content;if(e.hasEncryptedTag(c)&&o&&f.nip04)try{n=await f.nip04.decrypt(s,c.content)}catch{return void l(new Error("Failed to decrypt DVM result"))}const i=bN(n);if(!i||!i.urls||0===i.urls.length)return void l(new Error("Invalid DVM result: no URLs returned"));t(vN(i,r,a))}},error:e=>{clearTimeout(m),clearInterval(p),l(e)}});this._subs.push(h)})}queryForExistingResult(t,n,s,r){return new Promise(a=>{let o=!1;const i=setTimeout(()=>{o||(c.unsubscribe(),a(null))},5e3),c=this.pool.request(this.relays,[{kinds:[ch],authors:[n],"#e":[t],limit:1}]).subscribe({next:async t=>{if("string"==typeof t)return;o=!0,clearTimeout(i),c.unsubscribe();const l=t;let u=l.content;if(e.hasEncryptedTag(l)&&this.user.signer.nip04)try{u=await this.user.signer.nip04.decrypt(n,l.content)}catch{return void a(null)}const d=bN(u);a(d?.urls?.length?vN(d,s,r):null)},complete:()=>{o||(clearTimeout(i),a(null))}});this._subs.push(c)})}cancel(){this._subs.forEach(e=>e.unsubscribe()),this._subs.length=0}}}))()}function kN(){return(kN=t(()=>{Be(),bu(),lu(),nu(),dl(),xN(),ow(),Be()}))()}function NN(){const{user:e}=yu(),t=(0,fh.useRef)({time:0,serverCount:0,pubkey:""}),n=te(da,e?.pubkey?[e.pubkey]:null)??mh,s=(0,fh.useMemo)(()=>n.map(e=>e.toString()).filter(e=>!_l(e)),[n]),r=(0,fh.useMemo)(()=>({data:s,isLoading:e&&0===s.length,enabled:!!e?.pubkey}),[s,e]);return(0,fh.useEffect)(()=>{const n=Date.now();(n-t.current.time>1e4||t.current.serverCount!==s.length||t.current.pubkey!==e?.pubkey)&&(t.current={time:n,serverCount:s.length,pubkey:e?.pubkey||""})},[s,e?.pubkey,n,r]),r}function jN(){return(jN=t(()=>{fh=Be(),bu(),Wt(),xa(),Jl(),mh=[]}))()}function SN(e){for(const t of e){if(yh.has(t.id))continue;yh.add(t.id);const e=t.tags.filter(e=>"t"===e[0]&&e[1]).map(e=>e[1].toLowerCase().trim()).filter(e=>e.length>0);for(const t of e)gh.set(t,(gh.get(t)||0)+1)}}function CN(){const e=Cr(),[t,n]=(0,ph.useState)(bh),[s,r]=(0,ph.useState)(gh.size);return(0,ph.useEffect)(()=>{if(bh)return;const t=e.timeline({kinds:hh}),s=[],a=t.subscribe({next:e=>{e&&e.length>0&&s.push(...e)}});queueMicrotask(()=>{a.unsubscribe(),s.length>0&&SN(s),bh=!0,n(!0),r(gh.size)})},[e]),(0,ph.useEffect)(()=>{if(!t)return;const n=e.timeline({kinds:hh});let s=yh.size;const a=n.subscribe({next:e=>{if(e&&e.length>0){const t=e.filter(e=>!yh.has(e.id));t.length>0&&(SN(t),yh.size>s&&(s=yh.size,r(gh.size)))}}});return()=>a.unsubscribe()},[e,t]),{searchTags:(0,ph.useCallback)((e,t)=>function(e,t=8){if(!e)return[];const n=e.toLowerCase().trim().replace(/^#/,"");if(!n)return[];const s=[];for(const[r,a]of gh)r.startsWith(n)&&s.push({tag:r,count:a});return s.sort((e,t)=>t.count!==e.count?t.count-e.count:e.tag.localeCompare(t.tag)),s.slice(0,t)}(e,t),[]),getAllTags:(0,ph.useCallback)(()=>function(){const e=[];for(const[t,n]of gh)e.push({tag:t,count:n});return e.sort((e,t)=>t.count!==e.count?t.count-e.count:e.tag.localeCompare(t.tag)),e}(),[]),isReady:t,tagCount:s}}function EN(){return(EN=t(()=>{ph=Be(),Wt(),hh=[21,22,34235,34236],gh=new Map,yh=new Set,bh=!1}))()}function MN(e){const{neventRelays:t,videoEvent:n,playlistEvent:s,authorPubkey:r}=e,a=(0,wh.useMemo)(()=>t||[],[t]),o=(0,wh.useMemo)(()=>s?[s]:[],[s]),i=uu(),{data:c}=Av(r),l=(0,wh.useMemo)(()=>Do.map(e=>e.url),[]);return(0,wh.useMemo)(()=>{const e=[];if(a.length>0&&e.push(a),n){const t=rr(n);t&&e.push(Array.from(t))}for(const t of o){const n=rr(t);n&&e.push(Array.from(n))}if(c&&c.length>0){const t=c.filter(e=>e.write).map(e=>e.url);t.length>0&&e.push(t)}return e.push(i),e.push(l),al(e)},[a,n,o,c,i,l])}function IN(e){const{nprofileRelays:t,authorPubkey:n}=e,s=(0,wh.useMemo)(()=>t||[],[t]),r=uu(),{data:a}=Av(n),o=(0,wh.useMemo)(()=>Do.map(e=>e.url),[]);return(0,wh.useMemo)(()=>{const e=[];if(s.length>0&&e.push(s),a&&a.length>0){const t=a.filter(e=>e.write).map(e=>e.url);t.length>0&&e.push(t)}return e.push(r),e.push(o),e.push([Lo]),al(e)},[s,a,r,o])}function AN(){return(AN=t(()=>{wh=Be(),xs(),dl(),du(),Pv(),Jl()}))()}function PN(){return(PN=t(()=>{Be(),lu(),Uv()}))()}function TN(){return(TN=t(()=>{Be(),Wt(),be(),nu(),ow(),KN(),kd()}))()}function RN(){return(RN=t(()=>{Be()}))()}function UN(e=!1){const[t,n]=(0,vh.useState)(e),[s,r]=(0,vh.useState)(void 0),a=(0,vh.useCallback)(()=>{n(!0)},[]),o=(0,vh.useCallback)(()=>{n(!1),r(void 0)},[]),i=(0,vh.useCallback)(()=>{n(e=>!e)},[]),c=(0,vh.useCallback)(e=>{r(e),n(!0)},[]);return{open:t,setOpen:(0,vh.useCallback)(e=>{n(e),e||r(void 0)},[]),openDialog:a,closeDialog:o,toggle:i,openWith:c,data:s,clearData:()=>r(void 0)}}function $N(){return($N=t(()=>{vh=Be()}))()}function DN(){return(DN=t(()=>{Be(),Zd()}))()}function LN({onLoadMore:e,onPrefetch:t,loading:n,prefetching:s=!1,exhausted:r,subscriptionActive:a=!1,threshold:o=0,rootMargin:i="0px 0px 400px 0px",prefetchRootMargin:c="0px 0px 1000px 0px"}){const{ref:l,inView:u}=pn({threshold:o,rootMargin:i,triggerOnce:!1}),{ref:d,inView:f}=pn({threshold:o,rootMargin:c,triggerOnce:!1});return(0,xh.useEffect)(()=>{!u||r||n||a||e()},[u,r,n,a,e]),(0,xh.useEffect)(()=>{t&&(!f||r||n||s||a||t())},[f,r,n,s,a,t]),{loadMoreRef:l,prefetchRef:d,inView:u,prefetchInView:f}}function BN(){return(BN=t(()=>{xh=Be(),je()}))()}function zN(){return(zN=t(()=>{kh=Be()}))()}function FN(){const[e,t]=(0,Nh.useState)("undefined"!=typeof window?window.innerWidth:1200);return(0,Nh.useEffect)(()=>{let e;function n(){clearTimeout(e),e=setTimeout(()=>t(window.innerWidth),150)}return window.addEventListener("resize",n),()=>{clearTimeout(e),window.removeEventListener("resize",n)}},[]),e}function _N(){return(_N=t(()=>{Nh=Be()}))()}function ON(){if("undefined"==typeof window)return!1;const e=navigator.userAgent.toLowerCase(),t=["android","webos","iphone","ipad","ipod","blackberry","windows phone","opera mini","mobile"].some(t=>e.includes(t)),n=window.matchMedia("(pointer: coarse) and (hover: none)").matches,s=window.innerWidth{t(ON());const e=window.matchMedia("(max-width: 767px)"),n=()=>t(ON());let s;const r=()=>{clearTimeout(s),s=setTimeout(n,150)};return e.addEventListener("change",n),window.addEventListener("resize",r),()=>{clearTimeout(s),e.removeEventListener("change",n),window.removeEventListener("resize",r)}},[]),e}function VN(){return(VN=t(()=>{jh=e(Be(),1),Sh=768}))()}function qN(){const[e,t]=Ch.useState(()=>"undefined"==typeof window||window.innerHeight>window.innerWidth);return Ch.useEffect(()=>{const e=()=>{t(window.innerHeight>window.innerWidth)};return e(),window.addEventListener("resize",e),window.addEventListener("orientationchange",e),()=>{window.removeEventListener("resize",e),window.removeEventListener("orientationchange",e)}},[]),e}function JN(){return(JN=t(()=>{Ch=e(Be(),1)}))()}function HN(){return(HN=t(()=>{Be(),Zd()}))()}function KN(){return(KN=t(()=>{Al(),bu(),Bl(),wu(),gu(),xu(),Su(),Iu(),Fu(),Bu(),Ou(),mu(),rd(),cd(),ud(),Nd(),dd(),Jd(),lw(),bw(),vw(),kw(),Rw(),Bw(),Fw(),Ow(),Vw(),Jw(),pv(),ef(),gv(),nd(),_v(),Vv(),Kv(),sx(),lx(),fx(),px(),pN(),gN(),kN(),jN(),EN(),kd(),lu(),Nu(),AN(),du(),PN(),Pv(),od(),TN(),RN(),$N(),DN(),Kd(),Zd(),BN(),zN(),_N(),VN(),JN(),HN()}))()}function GN(){return(GN=t(()=>{Eh=e(Be(),1),ae(),Qn(),dl(),Mh=Q(),(Ih=Eh.forwardRef(({className:e,...t},n)=>(0,Mh.jsx)(zt,{ref:n,className:nl("peer h-4 w-4 shrink-0 rounded-sm border border-primary ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground",e),...t,children:(0,Mh.jsx)(en,{className:nl("flex items-center justify-center text-current"),children:(0,Mh.jsx)(na,{className:"h-4 w-4"})})}))).displayName=zt.displayName}))()}function YN(){return(YN=t(()=>{Ah=e(Be(),1),de(),S(),dl(),Ph=Q(),Th=kt("text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"),(Rh=Ah.forwardRef(({className:e,...t},n)=>(0,Ph.jsx)(Ht,{ref:n,className:nl(Th(),e),...t}))).displayName=Ht.displayName}))()}function XN({nsec:e,onConfirmed:t,onBack:n,keySecurity:s="secure"}){const{t:r}=ir(),[a,o]=(0,Uh.useState)(!1),[i,c]=(0,Uh.useState)(!1),[l,u]=(0,Uh.useState)(""),[d,f]=(0,Uh.useState)(""),[m,p]=(0,Uh.useState)(!1),[h,g]=(0,Uh.useState)(null),[y,b]=(0,Uh.useState)(!1),[w,x]=(0,Uh.useState)(""),[k,N]=(0,Uh.useState)(!1),j=l.length>=8&&l===d,S=w.trim()===Mo,C=(e,t)=>{const n=new Blob([e],{type:"text/plain"}),s=globalThis.URL.createObjectURL(n),r=document.createElement("a");r.href=s,r.download=t,document.body.appendChild(r),r.click(),globalThis.URL.revokeObjectURL(s),document.body.removeChild(r)},E=a&&i;return(0,$h.jsxs)("div",{className:"space-y-6",children:[(0,$h.jsxs)("div",{className:"space-y-2",children:[(0,$h.jsxs)("div",{className:"flex items-center gap-2 text-sm font-medium text-muted-foreground",children:[(0,$h.jsx)(Ss,{className:"h-4 w-4"}),(0,$h.jsx)("span",{children:r("onboarding.seedBackup.protectedTitle")})]}),(0,$h.jsx)("p",{className:"text-sm text-muted-foreground",children:r("onboarding.seedBackup.protectedDescription")})]}),(0,$h.jsxs)("div",{className:"flex items-start gap-3 p-3 rounded-lg bg-amber-50 dark:bg-amber-950 border border-amber-200 dark:border-amber-800",children:[(0,$h.jsx)(an,{className:"h-5 w-5 text-amber-600 dark:text-amber-400 shrink-0 mt-0.5"}),(0,$h.jsxs)("div",{className:"text-sm text-amber-800 dark:text-amber-200 space-y-1",children:[(0,$h.jsx)("p",{className:"font-medium",children:r("onboarding.seedBackup.important")}),(0,$h.jsxs)("ul",{className:"list-disc pl-4 space-y-0.5 text-amber-700 dark:text-amber-300",children:[(0,$h.jsx)("li",{children:r("onboarding.seedBackup.warning1")}),(0,$h.jsx)("li",{children:r("onboarding.seedBackup.warning2")}),(0,$h.jsx)("li",{children:r("onboarding.seedBackup.warning3")})]})]})]}),h&&(0,$h.jsx)("div",{className:"text-sm text-destructive border border-destructive/30 rounded-lg p-3",children:h}),(0,$h.jsxs)("div",{className:"space-y-3",children:[(0,$h.jsxs)("div",{className:"space-y-2",children:[(0,$h.jsx)(Rh,{htmlFor:"backup-password",children:r("onboarding.seedBackup.passwordLabel")}),(0,$h.jsx)(Ga,{id:"backup-password",type:"password",value:l,onChange:e=>u(e.target.value),placeholder:r("onboarding.seedBackup.passwordPlaceholder")})]}),(0,$h.jsxs)("div",{className:"space-y-2",children:[(0,$h.jsx)(Rh,{htmlFor:"backup-password-confirm",children:r("onboarding.seedBackup.confirmPasswordLabel")}),(0,$h.jsx)(Ga,{id:"backup-password-confirm",type:"password",value:d,onChange:e=>f(e.target.value),placeholder:r("onboarding.seedBackup.confirmPasswordPlaceholder")})]}),(0,$h.jsx)("p",{className:"text-xs text-muted-foreground",children:r("onboarding.seedBackup.passwordHint")})]}),(0,$h.jsxs)(Ja,{variant:a?"outline":"default",className:"w-full",onClick:async()=>{if(j){p(!0),g(null);try{const t=await $l(e,l,{keySecurity:s});C(t,"nostube-ncryptsec.txt"),o(!0)}catch(t){g(t instanceof Error?t.message:"Failed to create encrypted backup")}finally{p(!1)}}},disabled:!j||m,children:[(0,$h.jsx)(v,{className:"h-4 w-4 mr-2"}),r(m?"onboarding.seedBackup.encrypting":a?"onboarding.seedBackup.downloadAgain":"onboarding.seedBackup.downloadProtectedKey")]}),a&&(0,$h.jsxs)("div",{className:"flex items-center gap-2 text-sm text-green-600 dark:text-green-400",children:[(0,$h.jsx)(ut,{className:"h-4 w-4"}),(0,$h.jsx)("span",{children:r("onboarding.seedBackup.downloaded")})]}),(0,$h.jsxs)("div",{className:"flex items-start gap-3 p-3 rounded-lg border",children:[(0,$h.jsx)(Ih,{id:"backup-confirmed",checked:i,onCheckedChange:e=>c(!0===e),disabled:!a}),(0,$h.jsx)(Rh,{htmlFor:"backup-confirmed",className:"text-sm leading-relaxed cursor-pointer",children:r("onboarding.seedBackup.confirmBackup")})]}),(0,$h.jsxs)("div",{className:"space-y-2",children:[(0,$h.jsxs)("button",{type:"button",onClick:()=>b(!y),className:"flex items-center gap-2 text-sm text-muted-foreground hover:text-foreground transition-colors",children:[(0,$h.jsx)(Oe,{className:"h-4 w-4"}),(0,$h.jsx)("span",{children:r("onboarding.seedBackup.rawKeyAdvanced")})]}),y&&(0,$h.jsxs)("div",{className:"space-y-3 pl-6",children:[(0,$h.jsx)("div",{className:"rounded-lg border border-amber-200 dark:border-amber-800 bg-amber-50 dark:bg-amber-950 p-3 text-sm text-amber-800 dark:text-amber-200",children:r("onboarding.seedBackup.rawKeyWarning")}),(0,$h.jsx)(Ga,{value:w,onChange:e=>{x(e.target.value),N(!1)},placeholder:r("onboarding.seedBackup.rawKeyConfirmationPlaceholder",{phrase:"show my raw key"})}),S&&(0,$h.jsxs)("div",{className:"space-y-2",children:[k&&(0,$h.jsx)("div",{className:"p-4 rounded-lg border bg-muted/30 overflow-auto",children:(0,$h.jsx)("code",{className:"text-xs break-all select-all font-mono",children:e})}),(0,$h.jsxs)("div",{className:"flex gap-2",children:[(0,$h.jsx)(Ja,{type:"button",variant:"outline",onClick:()=>N(e=>!e),children:r(k?"onboarding.seedBackup.hideRawKey":"onboarding.seedBackup.showRawKey")}),(0,$h.jsxs)(Ja,{type:"button",variant:"secondary",onClick:()=>{S&&(C(e,"nostube-raw-nsec.txt"),o(!0))},children:[(0,$h.jsx)(v,{className:"h-4 w-4 mr-2"}),r("onboarding.seedBackup.downloadRawKey")]})]})]})]})]}),(0,$h.jsxs)("div",{className:"flex gap-2",children:[n&&(0,$h.jsx)(Ja,{variant:"outline",onClick:n,className:"flex-1",children:r("common.back")}),(0,$h.jsx)(Ja,{onClick:t,disabled:!E,className:"flex-1",children:r("onboarding.seedBackup.continue")})]})]})}function ZN(){return(ZN=t(()=>{Uh=Be(),Vr(),ml(),pl(),GN(),YN(),Jt(),He(),Tn(),bn(),a(),Dl(),$h=Q()}))()}function QN(){return null!==localStorage.getItem(Dh)}function ej(){localStorage.setItem(Dh,"imported")}function tj(){localStorage.setItem(Dh,"skipped")}function nj(){localStorage.setItem(Dh,"done")}function sj(){return"1"===localStorage.getItem(Lh)}function rj(){localStorage.setItem(Lh,"1")}function aj(){localStorage.removeItem(Lh)}function oj(){return(oj=t(()=>{Dh="nostube_onboarding_follow_import",Lh="nostube_onboarding_new_user"}))()}function ij(){return(ij=t(()=>{Bh=e(Be(),1),He(),ml(),hl(),KN(),os(),Vr(),ZN(),oj(),zh=Q(),Fh=({isOpen:e,onClose:t})=>{const{t:n}=ir(),[s,r]=(0,Bh.useState)("generate"),[a,o]=(0,Bh.useState)(!1),[i,c]=(0,Bh.useState)(""),l=Ll();return(0,zh.jsx)(Za,{open:e,onOpenChange:t,children:(0,zh.jsxs)(no,{className:"max-h-[90vh] overflow-y-auto sm:max-w-md p-0 rounded-2xl",children:[(0,zh.jsxs)(so,{className:"px-6 pt-6 pb-0 relative",children:[(0,zh.jsxs)(ao,{className:"text-xl font-semibold text-center",children:["generate"===s&&n("auth.signup.title"),"backup"===s&&n("auth.signup.downloadTitle"),"done"===s&&n("auth.signup.settingUpTitle")]}),(0,zh.jsxs)(oo,{className:"text-center text-muted-foreground mt-2",children:["generate"===s&&n("auth.signup.generateDescription"),"backup"===s&&n("auth.signup.keepSafeDescription"),"done"===s&&n("auth.signup.finalizingDescription")]})]}),(0,zh.jsxs)("div",{className:"px-6 py-8 space-y-6",children:["generate"===s&&(0,zh.jsxs)("div",{className:"text-center space-y-6",children:[(0,zh.jsx)("div",{className:"p-4 rounded-lg bg-gray-50 dark:bg-gray-800 flex items-center justify-center",children:(0,zh.jsx)(Oe,{className:"w-16 h-16 text-primary"})}),(0,zh.jsx)("p",{className:"text-sm text-gray-600 dark:text-gray-300",children:n("auth.signup.introText")}),(0,zh.jsx)(Ja,{className:"w-full rounded-full py-6",onClick:()=>{o(!0);try{const e=Hn();c(er.nsecEncode(e)),r("backup")}catch(e){Yd({title:n("auth.signup.errorTitle"),description:n("auth.signup.errorMessage"),variant:"destructive"})}finally{o(!1)}},disabled:a,children:n(a?"auth.signup.generating":"auth.signup.generateButton")})]}),"backup"===s&&(0,zh.jsx)(XN,{nsec:i,onConfirmed:async()=>{o(!0);try{await l.nsec(i),rj(),r("done"),t(),Yd({title:n("auth.signup.accountCreated"),description:n("auth.signup.accountCreatedMessage")})}catch(e){Yd({title:n("auth.signup.errorTitle"),description:e instanceof Error?e.message:n("auth.signup.errorMessage"),variant:"destructive"}),o(!1)}},onBack:()=>r("generate")}),"done"===s&&(0,zh.jsx)("div",{className:"flex justify-center items-center py-8",children:(0,zh.jsx)("div",{className:"animate-spin rounded-full h-12 w-12 border-b-2 border-primary"})})]})]})})}}))()}function cj(){return(cj=t(()=>{_h=e(Be(),1),Z(),Qn(),$n(),vn(),dl(),Oh=Q(),Wh=m,Vh=it,_h.forwardRef(({className:e,inset:t,children:n,...s},r)=>(0,Oh.jsxs)(Ke,{ref:r,className:nl("flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent data-[state=open]:bg-accent",t&&"pl-8",e),...s,children:[n,(0,Oh.jsx)(Ms,{className:"ml-auto h-4 w-4"})]})).displayName=Ke.displayName,_h.forwardRef(({className:e,...t},n)=>(0,Oh.jsx)(We,{ref:n,className:nl("z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-lg data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),...t})).displayName=We.displayName,(qh=_h.forwardRef(({className:e,sideOffset:t=4,...n},s)=>(0,Oh.jsx)(Qe,{children:(0,Oh.jsx)(ma,{ref:s,sideOffset:t,className:nl("z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),...n})}))).displayName=ma.displayName,(Jh=_h.forwardRef(({className:e,inset:t,...n},s)=>(0,Oh.jsx)(Rt,{ref:s,className:nl("relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t&&"pl-8",e),...n}))).displayName=Rt.displayName,(Hh=_h.forwardRef(({className:e,children:t,checked:n,...s},r)=>(0,Oh.jsxs)(M,{ref:r,className:nl("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",e),checked:n,...s,children:[(0,Oh.jsx)("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:(0,Oh.jsx)(V,{children:(0,Oh.jsx)(na,{className:"h-4 w-4"})})}),t]}))).displayName=M.displayName,_h.forwardRef(({className:e,children:t,...n},s)=>(0,Oh.jsxs)(_s,{ref:s,className:nl("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",e),...n,children:[(0,Oh.jsx)("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:(0,Oh.jsx)(V,{children:(0,Oh.jsx)(cn,{className:"h-2 w-2 fill-current"})})}),t]})).displayName=_s.displayName,(Kh=_h.forwardRef(({className:e,inset:t,...n},s)=>(0,Oh.jsx)(D,{ref:s,className:nl("px-2 py-1.5 text-sm font-semibold",t&&"pl-8",e),...n}))).displayName=D.displayName,(Gh=_h.forwardRef(({className:e,...t},n)=>(0,Oh.jsx)(Us,{ref:n,className:nl("-mx-1 my-1 h-px bg-muted",e),...t}))).displayName=Us.displayName,(({className:e,...t})=>(0,Oh.jsx)("span",{className:nl("ml-auto text-xs tracking-widest opacity-60",e),...t})).displayName="DropdownMenuShortcut"}))()}function lj(){return(lj=t(()=>{Yh=e(Be(),1),St(),dl(),Xh=Q(),(Zh=Yh.forwardRef(({className:e,...t},n)=>(0,Xh.jsx)(ka,{ref:n,className:nl("relative flex h-10 w-10 shrink-0 overflow-hidden rounded-full",e),...t}))).displayName=ka.displayName,(Qh=Yh.forwardRef(({className:e,...t},n)=>(0,Xh.jsx)(ya,{ref:n,className:nl("aspect-square h-full w-full",e),...t}))).displayName=ya.displayName,(eg=Yh.forwardRef(({className:e,...t},n)=>(0,Xh.jsx)(Bn,{ref:n,className:nl("flex h-full w-full items-center justify-center rounded-full bg-muted",e),...t}))).displayName=Bn.displayName}))()}function uj(e){return e?.trim().replace(/\/+$/,"")||"https://imgproxy.nostu.be"}function dj(){return(dj=t(()=>{0}))()}function fj(e,t,n,s={}){const{extension:r,serverHints:a,authorPubkey:o}=s,i=r?`${n}.${r}`:n,c=new URL(`${uj(e)}/v1/preset/${t}/${i}`),l=[...new Set((a??[]).filter(e=>Boolean(e)))].slice(0,tg);for(const u of l)c.searchParams.append("xs",u);return o&&c.searchParams.set("as",o),c.toString()}function mj(e,t,n){const{resize:s,width:r,height:a,quality:o}=ng[t],i=`f:webp/q:${o}/rs:${s}:${r}:${a}`;return`${uj(e)}/insecure/${i}/plain/${encodeURIComponent(n)}`}function pj(){return(pj=t(()=>{dj(),tg=4,ng={"feed-preview-v1":{resize:"fit",width:480,height:480,quality:82},"profile-avatar-v1":{resize:"fill",width:160,height:160,quality:85},"embed-card-v1":{resize:"fit",width:1200,height:630,quality:82}}}))()}function hj(e){const t=cu()?.config.imgproxyBaseUrl,n=e.variant??"preview",s=e.preset??("avatar"===n?"profile-avatar-v1":"feed-preview-v1"),r=e.src&&(hf(e.src)||e.src.startsWith("blob:")||e.src.startsWith("data:"))?e.src:null,a=e.videoUrl&&(hf(e.videoUrl)||e.videoUrl.startsWith("blob:")||e.videoUrl.startsWith("data:"))?e.videoUrl:null,o=(0,sg.useMemo)(()=>r?Vl(r):void 0,[r]),i=(0,sg.useMemo)(()=>a?Vl(a):void 0,[a]),c=e.authorPubkey??void 0,l=e.race??!0,u=e=>!e.startsWith("blob:")&&!e.startsWith("data:"),d=(0,sg.useMemo)(()=>r&&u(r)?o?.sha256?fj(t,s,o.sha256,{extension:o.ext,serverHints:[o.host],authorPubkey:c}):mj(t,s,r):r,[t,o,s,r,c]),f=(0,sg.useMemo)(()=>a&&u(a)?i?.sha256?fj(t,s,i.sha256,{extension:i.ext,serverHints:[i.host],authorPubkey:c}):mj(t,s,a):null,[t,s,i,a,c]),m=Boolean(f),p=(0,sg.useMemo)(()=>r?u(r)?"proxied":"raw":m?"video-frame":"exhausted",[r,m]),[h,g]=(0,sg.useState)(p),[y,b]=(0,sg.useState)(!1),[w,v]=(0,sg.useState)(null);(0,sg.useEffect)(()=>{g(p),b(!1),v(null)},[p,r,a]),(0,sg.useEffect)(()=>{if(!l||"proxied"!==h||!d||!r)return;if(w===d)return;const e=setTimeout(()=>b(!0),rg);return()=>clearTimeout(e)},[l,h,d,r,w]),(0,sg.useEffect)(()=>{if(!y||!d||w===r)return;let e=!1;const t=new Image;return t.onload=()=>{e||b(!1)},t.onerror=()=>{e||(b(!1),g("raw"))},t.src=d,()=>{e=!0,t.onload=null,t.onerror=null}},[y,d,r,w]);const x="video-frame"!==h||m?"proxied"===h&&y?"raw":h:"exhausted",k=(0,sg.useMemo)(()=>{switch(x){case"proxied":return d;case"raw":return r;case"video-frame":return f;case"exhausted":return null}},[x,d,f,r]),N=(0,sg.useCallback)(()=>{const e="video-frame"!==h||m?"proxied"===h&&y?"raw":h:"exhausted";b(!1),g("proxied"===e&&r?"raw":"proxied"!==e&&"raw"!==e||!m?"exhausted":"video-frame")},[h,y,r,m]),j=(0,sg.useCallback)(()=>v(k),[k]);return{src:k,loadedSrc:w,loaded:null!==k&&w===k,onError:N,onLoad:j,exhausted:"exhausted"===x,stage:x}}function gj(){return(gj=t(()=>{sg=Be(),lu(),ql(),pj(),rg=900}))()}function yj(){return(yj=t(()=>{ag=e(Be(),1),lj(),gj(),dl(),og=Q(),ig=ag.memo(function({picture:e,pubkey:t,name:n,className:s}){const r=hj({src:e,variant:"avatar",authorPubkey:t}),a=`https://api.dicebear.com/7.x/avataaars/svg?seed=${t||n||"default"}`,o=r.src??a,i=n?.charAt(0)||t?.charAt(0)||"?";return(0,og.jsxs)(Zh,{className:nl(s),children:[(0,og.jsx)(Qh,{src:o,alt:n||t?.slice(0,8)||"",referrerPolicy:"no-referrer",onError:r.onError,onLoad:r.onLoad}),(0,og.jsx)(eg,{children:i})]})})}))()}function bj(){return(bj=t(()=>{cg=e(Be(),1),dl(),lg=Q(),(ug=cg.forwardRef(({className:e,...t},n)=>(0,lg.jsx)("div",{ref:n,className:nl("rounded-lg border bg-card text-card-foreground shadow-sm",e),...t}))).displayName="Card",(dg=cg.forwardRef(({className:e,...t},n)=>(0,lg.jsx)("div",{ref:n,className:nl("flex flex-col space-y-1.5 p-6",e),...t}))).displayName="CardHeader",(fg=cg.forwardRef(({className:e,...t},n)=>(0,lg.jsx)("h3",{ref:n,className:nl("text-2xl font-semibold leading-none tracking-tight",e),...t}))).displayName="CardTitle",(mg=cg.forwardRef(({className:e,...t},n)=>(0,lg.jsx)("p",{ref:n,className:nl("text-sm text-muted-foreground",e),...t}))).displayName="CardDescription",(pg=cg.forwardRef(({className:e,...t},n)=>(0,lg.jsx)("div",{ref:n,className:nl("p-6 pt-0",e),...t}))).displayName="CardContent",cg.forwardRef(({className:e,...t},n)=>(0,lg.jsx)("div",{ref:n,className:nl("flex items-center p-6 pt-0",e),...t})).displayName="CardFooter"}))()}function wj(){return(wj=t(()=>{hg=e(Be(),1),aa(),dl(),gg=Q(),yg=ps,bg=Cn,(wg=hg.forwardRef(({className:e,align:t="center",sideOffset:n=4,...s},r)=>(0,gg.jsx)(vs,{children:(0,gg.jsx)(sr,{ref:r,align:t,sideOffset:n,className:nl("z-50 w-72 rounded-md border bg-popover p-4 text-popover-foreground shadow-md outline-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),...s})}))).displayName=sr.displayName}))()}function vj(){return(vj=t(()=>{vg=e(Be(),1),jr(),Hs(),dl(),hl(),xg=Q(),(kg=vg.forwardRef(({className:e,...t},n)=>(0,xg.jsx)(cs,{ref:n,className:nl("flex h-full w-full flex-col overflow-hidden rounded-md bg-popover text-popover-foreground",e),...t}))).displayName=cs.displayName,(Ng=vg.forwardRef(({className:e,...t},n)=>(0,xg.jsxs)("div",{className:"flex items-center border-b px-3","cmdk-input-wrapper":"",children:[(0,xg.jsx)(_n,{className:"mr-2 h-4 w-4 shrink-0 opacity-50"}),(0,xg.jsx)(cs.Input,{ref:n,className:nl("flex h-11 w-full rounded-md bg-transparent py-3 text-sm outline-none placeholder:text-muted-foreground disabled:cursor-not-allowed disabled:opacity-50",e),...t})]}))).displayName=cs.Input.displayName,(jg=vg.forwardRef(({className:e,...t},n)=>(0,xg.jsx)(cs.List,{ref:n,className:nl("max-h-[300px] overflow-y-auto overflow-x-hidden",e),...t}))).displayName=cs.List.displayName,(Sg=vg.forwardRef((e,t)=>(0,xg.jsx)(cs.Empty,{ref:t,className:"py-6 text-center text-sm",...e}))).displayName=cs.Empty.displayName,(Cg=vg.forwardRef(({className:e,...t},n)=>(0,xg.jsx)(cs.Group,{ref:n,className:nl("overflow-hidden p-1 text-foreground [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:text-xs [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",e),...t}))).displayName=cs.Group.displayName,(Eg=vg.forwardRef(({className:e,...t},n)=>(0,xg.jsx)(cs.Separator,{ref:n,className:nl("-mx-1 h-px bg-border",e),...t}))).displayName=cs.Separator.displayName,(Mg=vg.forwardRef(({className:e,...t},n)=>(0,xg.jsx)(cs.Item,{ref:n,className:nl("relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none data-[disabled=true]:pointer-events-none data-[selected='true']:bg-accent data-[selected=true]:text-accent-foreground data-[disabled=true]:opacity-50",e),...t}))).displayName=cs.Item.displayName,(({className:e,...t})=>(0,xg.jsx)("span",{className:nl("ml-auto text-xs tracking-widest text-muted-foreground",e),...t})).displayName="CommandShortcut"}))()}function xj(){return(xj=t(()=>{Ig=[21,100,500,1e3,5e3]}))()}function kj(){const{t:e}=ir(),t=yu(),[n,s]=(0,Ag.useState)(""),[r,a]=(0,Ag.useState)(""),[o,i]=(0,Ag.useState)([Tg[0]]),[c,l]=(0,Ag.useState)(!1),{walletType:u,isConnected:d,isConnecting:f,isUnlocking:m,balance:p,walletInfo:h,error:g,cashuMints:y,cashuWalletEvent:b,isCashuWalletUnlocked:w,defaultZapAmount:v,setDefaultZapAmount:x,connectNWC:k,createCashuWallet:N,unlockCashuWallet:j,addCashuMint:S,disconnect:C,refreshBalance:E}=ox(),M=(0,Ag.useCallback)(async()=>{try{await k(n.trim()),s("")}catch{}},[k,n]),I=(0,Ag.useCallback)(e=>{"Enter"===e.key&&n.trim()&&M()},[n,M]),A=(0,Ag.useCallback)(async()=>{if(0!==o.length)try{await N(o)}catch{}},[N,o]),P=(0,Ag.useCallback)(async e=>{const t=e||r.trim();if(t)try{await S(t),a(""),l(!1)}catch{}},[S,r]),T=(0,Ag.useCallback)(e=>{i(t=>t.includes(e)?t.filter(t=>t!==e):[...t,e])},[]);return d&&u?(0,Pg.jsx)("div",{className:"space-y-4",children:(0,Pg.jsxs)(ug,{children:[(0,Pg.jsx)(dg,{className:"pb-3",children:(0,Pg.jsxs)("div",{className:"flex items-center justify-between",children:[(0,Pg.jsxs)("div",{className:"flex items-center gap-2",children:[(0,Pg.jsx)("div",{className:"h-2 w-2 rounded-full bg-green-500"}),"nwc"===u?(0,Pg.jsx)(is,{className:"h-4 w-4 text-yellow-500"}):(0,Pg.jsx)(Qt,{className:"h-4 w-4 text-purple-500"}),(0,Pg.jsx)(fg,{className:"text-base",children:"nwc"===u?h?.alias||"Lightning Wallet (NWC)":"Cashu Wallet (NIP-60)"})]}),(0,Pg.jsx)(Ja,{variant:"outline",size:"sm",onClick:C,children:"Disconnect"})]})}),(0,Pg.jsxs)(pg,{className:"space-y-3",children:[null!==p&&(0,Pg.jsxs)("div",{className:"flex items-center gap-2 text-muted-foreground",children:[(0,Pg.jsx)(rt,{className:"h-4 w-4 text-yellow-500"}),(0,Pg.jsxs)("span",{children:["Balance: ",Ku(Math.floor("nwc"===u?p/1e3:p))," ","sats"]}),(0,Pg.jsx)(Ja,{variant:"ghost",size:"sm",className:"h-6 px-2",onClick:E,children:"Refresh"})]}),(0,Pg.jsxs)("div",{className:"space-y-2 pt-2 border-t",children:[(0,Pg.jsx)(Rh,{className:"text-sm",children:"Default Zap Amount"}),(0,Pg.jsx)("div",{className:"flex flex-wrap gap-2",children:Ig.map(e=>(0,Pg.jsxs)(Ja,{variant:v===e?"default":"outline",size:"sm",onClick:()=>x(e),className:"h-8",children:[e," sats"]},e))})]}),"cashu"===u&&y.length>0&&(0,Pg.jsxs)("div",{className:"space-y-2",children:[(0,Pg.jsx)(Rh,{className:"text-xs text-muted-foreground",children:"Mints"}),(0,Pg.jsx)("div",{className:"space-y-1",children:y.map(e=>(0,Pg.jsxs)("div",{className:"flex items-center justify-between rounded bg-muted/50 px-2 py-1 text-sm",children:[(0,Pg.jsx)("span",{className:"truncate font-mono text-xs",children:e.url}),(0,Pg.jsxs)("span",{className:"text-muted-foreground",children:[Ku(e.balance)," sats"]})]},e.url))})]}),"cashu"===u&&b&&!w&&(0,Pg.jsx)("div",{className:"flex items-center gap-2",children:(0,Pg.jsx)(Ja,{variant:"outline",size:"sm",onClick:j,disabled:m,children:m?(0,Pg.jsxs)(Pg.Fragment,{children:[(0,Pg.jsx)(Ze,{className:"mr-2 h-4 w-4 animate-spin"}),"Unlocking..."]}):(0,Pg.jsxs)(Pg.Fragment,{children:[(0,Pg.jsx)(W,{className:"mr-2 h-4 w-4"}),"Unlock Wallet"]})})}),"cashu"===u&&(0,Pg.jsxs)("div",{className:"space-y-2 pt-2 border-t",children:[(0,Pg.jsx)(Rh,{className:"text-xs",children:"Add Mint"}),(0,Pg.jsxs)(yg,{open:c,onOpenChange:l,children:[(0,Pg.jsx)(bg,{asChild:!0,children:(0,Pg.jsxs)(Ja,{variant:"outline",role:"combobox","aria-expanded":c,className:"w-full justify-between text-sm font-normal",children:[(0,Pg.jsx)("span",{className:"truncate text-muted-foreground",children:r||"Select or enter a mint URL..."}),(0,Pg.jsx)(mr,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),(0,Pg.jsx)(wg,{className:"w-[var(--radix-popover-trigger-width)] p-0",align:"start",children:(0,Pg.jsxs)(kg,{shouldFilter:!1,children:[(0,Pg.jsx)(Ng,{placeholder:"Enter mint URL...",value:r,onValueChange:a}),(0,Pg.jsxs)(jg,{children:[(0,Pg.jsx)(Sg,{children:r.trim()?(0,Pg.jsxs)(Ja,{variant:"ghost",className:"w-full justify-start",onClick:()=>P(),children:[(0,Pg.jsx)(ms,{className:"mr-2 h-4 w-4"}),'Add "',r,'"']}):"Enter a mint URL"}),(0,Pg.jsx)(Cg,{heading:"Popular Mints",children:Tg.filter(e=>!y.some(t=>t.url===e)).map(e=>(0,Pg.jsx)(Mg,{value:e,onSelect:()=>P(e),onMouseDown:t=>{t.preventDefault(),P(e)},className:"cursor-pointer",children:(0,Pg.jsx)("span",{className:"truncate font-mono text-xs",children:e})},e))})]})]})})]})]})]})]})}):(0,Pg.jsxs)("div",{className:"space-y-4",children:[(0,Pg.jsx)("p",{className:"text-sm text-muted-foreground",children:e("wallet.description")}),(0,Pg.jsxs)(lo,{defaultValue:"nwc",className:"w-full",children:[(0,Pg.jsxs)(uo,{className:"grid w-full grid-cols-2",children:[(0,Pg.jsxs)(fo,{value:"nwc",className:"flex items-center gap-2",children:[(0,Pg.jsx)(is,{className:"h-4 w-4"}),"Lightning (NWC)"]}),(0,Pg.jsxs)(fo,{value:"cashu",className:"flex items-center gap-2",disabled:!t,children:[(0,Pg.jsx)(Qt,{className:"h-4 w-4"}),"Cashu (NIP-60)"]})]}),(0,Pg.jsx)(mo,{value:"nwc",className:"space-y-4",children:(0,Pg.jsxs)(ug,{children:[(0,Pg.jsxs)(dg,{children:[(0,Pg.jsx)(fg,{className:"text-base",children:"Nostr Wallet Connect"}),(0,Pg.jsx)(mg,{children:"Connect to a Lightning wallet using NIP-47. Works with Alby, Mutiny, and other NWC-compatible wallets."})]}),(0,Pg.jsxs)(pg,{className:"space-y-4",children:[(0,Pg.jsxs)("div",{className:"space-y-2",children:[(0,Pg.jsx)(Rh,{htmlFor:"nwc-settings",children:"NWC Connection String"}),(0,Pg.jsx)(Ga,{id:"nwc-settings",placeholder:"nostr+walletconnect://...",value:n,onChange:e=>s(e.target.value),onKeyDown:I,disabled:f}),g&&(0,Pg.jsx)("p",{className:"text-sm text-destructive",children:g})]}),(0,Pg.jsxs)("div",{className:"flex items-center justify-between",children:[(0,Pg.jsxs)("a",{href:"https://nwc.getalby.com/",target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-1 text-sm text-primary hover:underline",children:["Get NWC from Alby",(0,Pg.jsx)(yt,{className:"h-3 w-3"})]}),(0,Pg.jsx)(Ja,{onClick:M,disabled:!n.trim()||f,children:f?(0,Pg.jsxs)(Pg.Fragment,{children:[(0,Pg.jsx)(Ze,{className:"mr-2 h-4 w-4 animate-spin"}),"Connecting..."]}):(0,Pg.jsxs)(Pg.Fragment,{children:[(0,Pg.jsx)(ht,{className:"mr-2 h-4 w-4"}),"Connect"]})})]})]})]})}),(0,Pg.jsx)(mo,{value:"cashu",className:"space-y-4",children:t?b?(0,Pg.jsxs)(ug,{children:[(0,Pg.jsxs)(dg,{children:[(0,Pg.jsx)(fg,{className:"text-base",children:"Existing Wallet Found"}),(0,Pg.jsx)(mg,{children:"You have a NIP-60 Cashu wallet. Unlock it to view your balance and make payments."})]}),(0,Pg.jsxs)(pg,{children:[(0,Pg.jsx)(Ja,{onClick:j,disabled:m,className:"w-full",children:m?(0,Pg.jsxs)(Pg.Fragment,{children:[(0,Pg.jsx)(Ze,{className:"mr-2 h-4 w-4 animate-spin"}),"Unlocking..."]}):(0,Pg.jsxs)(Pg.Fragment,{children:[(0,Pg.jsx)(W,{className:"mr-2 h-4 w-4"}),"Unlock Cashu Wallet"]})}),g&&(0,Pg.jsx)("p",{className:"mt-2 text-sm text-destructive",children:g})]})]}):(0,Pg.jsxs)(ug,{children:[(0,Pg.jsxs)(dg,{children:[(0,Pg.jsx)(fg,{className:"text-base",children:"Create Cashu Wallet"}),(0,Pg.jsx)(mg,{children:"Create a self-custodial e-cash wallet stored on Nostr relays (NIP-60). Select one or more mints to use."})]}),(0,Pg.jsxs)(pg,{className:"space-y-4",children:[(0,Pg.jsxs)("div",{className:"space-y-2",children:[(0,Pg.jsx)(Rh,{className:"text-sm",children:"Select Mints"}),(0,Pg.jsx)("div",{className:"space-y-2",children:Tg.map(e=>(0,Pg.jsxs)("label",{className:"flex items-center gap-2 rounded border p-2 cursor-pointer hover:bg-muted/50",children:[(0,Pg.jsx)("input",{type:"checkbox",checked:o.includes(e),onChange:()=>T(e),className:"h-4 w-4 rounded border-gray-300"}),(0,Pg.jsx)("span",{className:"truncate font-mono text-xs",children:e})]},e))})]}),(0,Pg.jsxs)("div",{className:"space-y-2",children:[(0,Pg.jsx)(Rh,{htmlFor:"custom-mint",className:"text-sm",children:"Or add a custom mint"}),(0,Pg.jsxs)("div",{className:"flex gap-2",children:[(0,Pg.jsx)(Ga,{id:"custom-mint",placeholder:"https://mint.example.com",value:r,onChange:e=>a(e.target.value),className:"flex-1 text-sm"}),(0,Pg.jsx)(Ja,{size:"sm",variant:"outline",onClick:()=>{r.trim()&&!o.includes(r.trim())&&(i(e=>[...e,r.trim()]),a(""))},disabled:!r.trim(),children:(0,Pg.jsx)(ms,{className:"h-4 w-4"})})]})]}),g&&(0,Pg.jsx)("p",{className:"text-sm text-destructive",children:g}),(0,Pg.jsx)(Ja,{onClick:A,disabled:0===o.length||f,className:"w-full",children:f?(0,Pg.jsxs)(Pg.Fragment,{children:[(0,Pg.jsx)(Ze,{className:"mr-2 h-4 w-4 animate-spin"}),"Creating Wallet..."]}):(0,Pg.jsxs)(Pg.Fragment,{children:[(0,Pg.jsx)(Qt,{className:"mr-2 h-4 w-4"}),"Create Cashu Wallet"]})}),(0,Pg.jsx)("p",{className:"text-xs text-muted-foreground",children:"Your wallet keys will be encrypted and stored on Nostr relays. Only you can access your funds."})]})]}):(0,Pg.jsx)(ug,{children:(0,Pg.jsx)(pg,{className:"py-6",children:(0,Pg.jsxs)("div",{className:"flex flex-col items-center gap-2 text-center",children:[(0,Pg.jsx)(fa,{className:"h-8 w-8 text-muted-foreground"}),(0,Pg.jsx)("p",{className:"text-sm text-muted-foreground",children:"Please log in to create or connect a Cashu wallet."})]})})})})]})]})}function Nj(){return(Nj=t(()=>{Ag=Be(),Vr(),ml(),pl(),YN(),ix(),Gu(),KN(),Fs(),G(),Ia(),Ea(),Sn(),Tt(),$(),re(),Nr(),Lr(),gl(),bj(),wj(),vj(),xj(),Pg=Q(),Tg=["https://mint.minibits.cash/Bitcoin","https://mint.coinos.io","https://mint.lnbits.com/cashu/api/v1/AptDNRABH9w6QrWcREZ9Pb"]}))()}function jj(){const{t:e}=ir(),[t,n]=(0,Rg.useState)(!1),{walletType:s,isConnected:r,balance:a}=ox();return(0,Ug.jsxs)(Ug.Fragment,{children:[(0,Ug.jsxs)(Jh,{onSelect:e=>{e.preventDefault(),n(!0)},className:"flex items-center gap-2 cursor-pointer p-2 rounded-md",children:[(0,Ug.jsx)(ht,{className:"w-4 h-4"}),(0,Ug.jsxs)("div",{className:"flex-1 flex items-center justify-between",children:[(0,Ug.jsx)("span",{children:e("wallet.title")}),r&&null!==a&&(0,Ug.jsxs)("div",{className:"flex items-center gap-1 text-xs text-muted-foreground",children:["nwc"===s?(0,Ug.jsx)(is,{className:"h-3 w-3 text-yellow-500"}):(0,Ug.jsx)(Qt,{className:"h-3 w-3 text-purple-500"}),(0,Ug.jsx)(rt,{className:"h-3 w-3 text-yellow-500"}),(0,Ug.jsx)("span",{children:Ku(Math.floor("nwc"===s?a/1e3:a))})]})]})]}),(0,Ug.jsx)(Za,{open:t,onOpenChange:n,children:(0,Ug.jsxs)(no,{className:"sm:max-w-md max-h-[90vh] overflow-y-auto",children:[(0,Ug.jsxs)(so,{children:[(0,Ug.jsx)(ao,{children:e("wallet.title")}),(0,Ug.jsx)(oo,{children:e("wallet.description")})]}),(0,Ug.jsx)(kj,{})]})})]})}function Sj(){return(Sj=t(()=>{Rg=Be(),Ea(),G(),Nr(),re(),cj(),ix(),Gu(),Vr(),hl(),Nj(),Ug=Q()}))()}function Cj(e){return`/p/${e}`}function Ej(e,t,n=[]){return Cj(function(e,t,n=[]){const s=t?rr(t):void 0,r=s?Array.from(s):n;return er.nprofileEncode({pubkey:e,relays:r.slice(0,5)})}(e,t,n))}function Mj(e,t=[]){return Cj(function(e,t=[]){return er.nprofileEncode({pubkey:e,relays:t.slice(0,5)})}(e,t))}function Ij(){return(Ij=t(()=>{os(),xs()}))()}function Aj(){return(Aj=t(()=>{$g=e(Be(),1),On(),dl(),fl(),Dg=Q(),Lg=Rn,Bg=Fr,zg=Cs,(Fg=$g.forwardRef(({className:e,...t},n)=>(0,Dg.jsx)(Ur,{className:nl("fixed inset-0 z-70 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",e),...t,ref:n}))).displayName=Ur.displayName,(_g=$g.forwardRef(({className:e,...t},n)=>(0,Dg.jsxs)(zg,{children:[(0,Dg.jsx)(Fg,{}),(0,Dg.jsx)(Jr,{ref:n,className:nl("fixed left-[50%] top-[50%] z-70 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",e),...t})]}))).displayName=Jr.displayName,(Og=({className:e,...t})=>(0,Dg.jsx)("div",{className:nl("flex flex-col space-y-2 text-center sm:text-left",e),...t})).displayName="AlertDialogHeader",(Wg=({className:e,...t})=>(0,Dg.jsx)("div",{className:nl("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",e),...t})).displayName="AlertDialogFooter",(Vg=$g.forwardRef(({className:e,...t},n)=>(0,Dg.jsx)(yr,{ref:n,className:nl("text-lg font-semibold",e),...t}))).displayName=yr.displayName,(qg=$g.forwardRef(({className:e,...t},n)=>(0,Dg.jsx)(ur,{ref:n,className:nl("text-sm text-muted-foreground",e),...t}))).displayName=ur.displayName,(Jg=$g.forwardRef(({className:e,...t},n)=>(0,Dg.jsx)(c,{ref:n,className:nl(Wa(),e),...t}))).displayName=c.displayName,(Hg=$g.forwardRef(({className:e,...t},n)=>(0,Dg.jsx)(ns,{ref:n,className:nl(Wa({variant:"outline"}),"mt-2 sm:mt-0",e),...t}))).displayName=ns.displayName}))()}function Pj({account:e,onClick:t}){const n=hu({pubkey:e.pubkey}),s=_r(n);return(0,Gg.jsxs)(Jh,{onClick:t,className:"flex items-center gap-2 cursor-pointer p-2 rounded-md",children:[(0,Gg.jsx)(ig,{picture:n?.picture,pubkey:e.pubkey,name:s||void 0,className:"w-8 h-8"}),(0,Gg.jsx)("div",{className:"flex-1 truncate",children:(0,Gg.jsx)("p",{className:"text-sm font-medium",children:s||e.pubkey.slice(0,8)})})]})}function Tj({onAddAccount:e}){const{t:t}=ir(),n=Ct(),s=Na(),r=hu(n?{pubkey:n?.pubkey}:void 0),a=h(),[o,i]=(0,Kg.useState)(!1),[c,l]=(0,Kg.useState)(null);if(!n||!s)return null;const u=(s.accounts||[]).filter(e=>e.pubkey!==n.pubkey),d=()=>{var e;Yn()?Qr("desktop_lock_account"):(e=n)&&s&&(s.removeAccount(e),jl(e.pubkey))};return(0,Gg.jsxs)(Gg.Fragment,{children:[(0,Gg.jsxs)(Wh,{children:[(0,Gg.jsx)(Vh,{asChild:!0,children:(0,Gg.jsxs)(Ja,{variant:"ghost",children:[(0,Gg.jsx)(ig,{picture:r?.picture,pubkey:n?.pubkey,name:_r(r)||void 0,className:"w-8 h-8"}),(0,Gg.jsx)("div",{className:"flex-1 text-left hidden md:block truncate",children:(0,Gg.jsx)("p",{className:"font-medium text-sm truncate",children:_r(r)})}),(0,Gg.jsx)(Jn,{className:"w-4 h-4 text-muted-foreground"})]})}),(0,Gg.jsxs)(qh,{className:"w-56 p-2 animate-scale-in",children:[(0,Gg.jsxs)(Jh,{onClick:()=>a(Mj(n.pubkey)),className:"flex items-center gap-2 cursor-pointer p-2 rounded-md",children:[(0,Gg.jsx)(Xt,{className:"w-4 h-4"}),(0,Gg.jsx)("span",{children:t("auth.account.profile")})]}),(0,Gg.jsx)(jj,{}),(0,Gg.jsx)(Gh,{}),(0,Gg.jsxs)(Jh,{onClick:()=>a("/playlists"),className:"flex items-center gap-2 cursor-pointer p-2 rounded-md",children:[(0,Gg.jsx)(f,{className:"w-4 h-4"}),(0,Gg.jsx)("span",{children:t("auth.account.playlists")})]}),(0,Gg.jsxs)(Jh,{onClick:()=>a("/upload"),className:"flex items-center gap-2 cursor-pointer p-2 rounded-md lg:hidden",children:[(0,Gg.jsx)(xe,{className:"w-4 h-4"}),(0,Gg.jsx)("span",{children:t("header.upload")})]}),(0,Gg.jsx)(Gh,{}),(0,Gg.jsxs)(Jh,{onClick:()=>a("/settings"),className:"flex items-center gap-2 cursor-pointer p-2 rounded-md",children:[(0,Gg.jsx)(gr,{className:"w-4 h-4"}),(0,Gg.jsx)("span",{children:t("settings.title")})]}),(0,Gg.jsx)(Gh,{}),u.length>0&&(0,Gg.jsxs)(Gg.Fragment,{children:[(0,Gg.jsx)("div",{className:"font-medium text-sm px-2 py-1.5",children:t("auth.account.switchAccount")}),u.map(e=>(0,Gg.jsx)(Pj,{account:e,onClick:()=>(e=>{e&&s&&(Yn()?Qr("desktop_unlock_account",{pubkey:e.pubkey}):(s.setActive(e),kl(e.pubkey)))})(e)},e.pubkey))]}),e&&(0,Gg.jsxs)(Jh,{onClick:e,className:"flex items-center gap-2 cursor-pointer p-2 rounded-md",children:[(0,Gg.jsx)(Ie,{className:"w-4 h-4"}),(0,Gg.jsx)("span",{children:"Add account"})]}),Yn()&&(0,Gg.jsxs)(Gg.Fragment,{children:[(0,Gg.jsx)(Jh,{onClick:()=>{Qr("desktop_export_credential",{pubkey:n.pubkey}).then(l)},children:"Recover credential"}),(0,Gg.jsx)(Jh,{onClick:()=>i(!0),className:"text-red-500 focus:text-red-500",children:"Remove from this device"})]}),(0,Gg.jsxs)(Jh,{onClick:()=>{d(),Yn()||(u.length>0&&s?(s.setActive(u[0]),kl(u[0].pubkey)):kl(null))},className:"flex items-center gap-2 cursor-pointer p-2 rounded-md text-red-500 focus:text-red-500",children:[(0,Gg.jsx)(jt,{className:"w-4 h-4"}),(0,Gg.jsx)("span",{children:t("auth.account.logout")})]})]})]}),(0,Gg.jsx)(Lg,{open:o,onOpenChange:i,children:(0,Gg.jsxs)(_g,{children:[(0,Gg.jsxs)(Og,{children:[(0,Gg.jsx)(Vg,{children:"Remove this account from this device?"}),(0,Gg.jsx)(qg,{children:"The Keychain credential and public desktop-account metadata will be deleted. Other accounts stay available."})]}),(0,Gg.jsxs)(Wg,{children:[(0,Gg.jsx)(Hg,{children:"Cancel"}),(0,Gg.jsx)(Jg,{onClick:()=>{Qr("desktop_remove_account",{pubkey:n.pubkey}).finally(()=>i(!1))},children:"Remove account"})]})]})}),(0,Gg.jsx)(Za,{open:null!==c,onOpenChange:e=>!e&&l(null),children:(0,Gg.jsxs)(no,{children:[(0,Gg.jsx)(so,{children:(0,Gg.jsx)(ao,{children:"Recovered credential"})}),(0,Gg.jsx)("p",{className:"break-all font-mono text-sm",children:c})]})})]})}function Rj(){return(Rj=t(()=>{Zs(),E(),dn(),Er(),zr(),ne(),Rs(),cj(),yj(),tt(),Wt(),KN(),br(),Sj(),ml(),Vr(),Ij(),Ks(),Kg=Be(),Aj(),hl(),Gg=Q()}))()}function Uj(){return(Uj=t(()=>{Yg=e=>({focusMain:async()=>{await e("open_desktop_window",{kind:"main"})},openAuth:async()=>{await e("open_desktop_window",{kind:"auth"})},openPlayer:async t=>{await e("open_desktop_window",{kind:"player",route:t})}})}))()}function $j(){return($j=t(()=>{Ks(),Xg=Be(),Uj(),Zg=()=>(0,Xg.useMemo)(()=>Yn()?Yg(Qr):void 0,[])}))()}function Dj({className:e}){const t=Ct(),[n,s]=(0,Qg.useState)(!1),[r,a]=(0,Qg.useState)(!1),o=Zg(),i=()=>{o?o.openAuth():s(!0)};return(0,ey.jsxs)("div",{className:nl("inline-flex items-center justify-center",e),children:[t?(0,ey.jsx)(Tj,{onAddAccount:i}):(0,ey.jsxs)(Ja,{onClick:i,children:[(0,ey.jsx)(Xt,{className:"w-4 h-4"}),(0,ey.jsx)("span",{className:"truncate",children:"Log in"})]}),(0,ey.jsx)(ai,{isOpen:n,onClose:()=>s(!1),onLogin:()=>{s(!1),a(!1)},onSignup:()=>a(!0)}),(0,ey.jsx)(Fh,{isOpen:r,onClose:()=>a(!1)})]})}function Lj(){return(Lj=t(()=>{Qg=Be(),ne(),ml(),au(),ij(),Rj(),dl(),Wt(),$j(),ey=Q()}))()}function Bj(e){const t=$u(e.kind),n=e.videoUrl&&hf(e.videoUrl)?e.videoUrl:null,s=e.thumbnail&&hf(e.thumbnail)?e.thumbnail:null,r=n?[{url:n,fallbackUrls:[]}]:[],a=s?[{url:s,fallbackUrls:[],mediaType:"image"}]:[];return{id:e.event_id,kind:e.kind,title:e.title,description:e.content_preview,images:s?[s]:[],pubkey:e.pubkey,created_at:e.created_at,published_at:e.published_at??void 0,duration:e.duration??0,tags:Array.isArray(e.tags)?e.tags:[],searchText:`${e.title} ${e.content_preview}`,urls:n?[n]:[],sourceUrls:e.videoUrl?[e.videoUrl]:[],mediaSourceStatus:n?"safe-declared-source":"unavailable",blockedEventMediaUrlCount:[e.videoUrl,e.thumbnail].filter(e=>Boolean(e)).filter(e=>!hf(e)).length,mimeType:e.mimeType??void 0,mediaType:e.mediaType??void 0,dimensions:e.dimensions??void 0,link:er.neventEncode({kind:e.kind,id:e.event_id,author:e.pubkey,relays:[]}),type:t,textTracks:(e.textTracks??[]).filter(e=>e.lang&&hf(e.url)).map(e=>({url:e.url,lang:e.lang})),contentWarning:e.contentWarning??void 0,origins:[],videoVariants:r,thumbnailVariants:a}}async function zj(e,t,n,s,r){try{const a=`${n}/api/search?q=${encodeURIComponent(e)}&limit=50&presetPubkey=${encodeURIComponent(s)}&nsfwFilter=${encodeURIComponent(r)}`,o=await fetch(a,{signal:t});return 503===o.status&&"preset_unavailable"===(await o.json().catch(()=>({})))?.code?{ok:!1,code:"preset_unavailable"}:o.ok?{ok:!0,data:((await o.json()).hits??[]).map(Bj)}:{ok:!1}}catch{return{ok:!1}}}async function Fj(e,t,n,s,r,a=100){try{const o=`${n}/api/tags?t=${encodeURIComponent(e.toLowerCase())}&limit=${a}&presetPubkey=${encodeURIComponent(s)}&nsfwFilter=${encodeURIComponent(r)}`,i=await fetch(o,{signal:t});return 503===i.status&&"preset_unavailable"===(await i.json().catch(()=>({})))?.code?{ok:!1,code:"preset_unavailable"}:i.ok?{ok:!0,data:((await i.json()).hits??[]).map(Bj)}:{ok:!1}}catch{return{ok:!1}}}async function _j(e,t,n,s,r,a=10){try{const o=`${n}/api/people?q=${encodeURIComponent(e)}&limit=${a}&presetPubkey=${encodeURIComponent(s)}&nsfwFilter=${encodeURIComponent(r)}`,i=await fetch(o,{signal:t});return 503===i.status&&"preset_unavailable"===(await i.json().catch(()=>({})))?.code?{ok:!1,code:"preset_unavailable"}:i.ok?{ok:!0,data:(await i.json()).hits??[]}:{ok:!1}}catch{return{ok:!1}}}function Oj(){return(Oj=t(()=>{os(),ty="https://nostube-search.apps2.slidestr.net"}))()}function Wj(e){return{pubkey:e.pubkey,profile:{name:e.name??void 0,display_name:e.display_name??void 0,username:e.username??void 0,about:e.about??void 0,picture:e.picture??void 0,nip05:e.nip05??void 0,lud16:e.lud16??void 0}}}function Vj({query:e,debounceMs:t=300,limit:n=10}){const s=Cr(),{config:r}=iu(),{presetContent:a,selectedPubkey:o}=vd(),i=sc(),c="hide"===(r.nsfwFilter??"hide"),l=(0,ny.useMemo)(()=>new kn,[]),[u,d]=(0,ny.useState)(!1),[f,m]=(0,ny.useState)([]),[p,h]=(0,ny.useState)([]),g=(0,ny.useRef)(null);(0,ny.useEffect)(()=>()=>l.close(),[l]);const[y,b]=(0,ny.useState)(e);return(0,ny.useEffect)(()=>{const n=setTimeout(()=>b(e),t);return()=>clearTimeout(n)},[e,t]),(0,ny.useEffect)(()=>{const e=y.trim();if(!e||e.length<2)return m([]),h([]),void d(!1);g.current?.abort();const t=new AbortController;g.current=t,d(!0);let a=0;const i=()=>{a++,2!==a||t.signal.aborted||d(!1)};return _j(e,t.signal,r.searchServiceUrl||"https://nostube-search.apps2.slidestr.net",o,r.nsfwFilter,n).then(e=>{t.signal.aborted||(e.ok?m((e.data??[]).map(Wj)):m([]))}).catch(()=>{t.signal.aborted||m([])}).finally(i),l.userSearch(e).then(e=>{if(t.signal.aborted)return;const r=[];for(const t of e.slice(0,2*n)){s.add(t);const e=Wn(t);e&&r.push({pubkey:t.pubkey,profile:e,event:t})}h(r)}).catch(()=>{t.signal.aborted||h([])}).finally(i),()=>t.abort()},[y,s,l,n,o,r.searchServiceUrl,r.nsfwFilter]),{profiles:(0,ny.useMemo)(()=>{const e=new Set,t=[];for(const n of f)e.has(n.pubkey)||(e.add(n.pubkey),t.push(n));for(const n of p)e.has(n.pubkey)||(e.add(n.pubkey),t.push(n));return function(e,t,n,s){return e.filter(e=>!(s?.[e.pubkey]||t&&Uf(e.pubkey,n)))}(t,c,a.nsfwPubkeys,i).slice(0,n)},[f,p,n,c,a.nsfwPubkeys,i]),loading:u}}function qj(){return(qj=t(()=>{ny=Be(),br(),En(),Wt(),Oj(),lu(),kd(),Nd()}))()}function Jj(){try{const e=localStorage.getItem(sy);if(!e)return[];const t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}function Hj(){return(Hj=t(()=>{sy="nostube:search-history",ry=20}))()}function Kj({className:e,clearButtonClassName:t,containerClassName:n,iconClassName:s,inputClassName:r,isMobileExpanded:a,onSearch:o,preserveSearchFilters:i=!1,syncWithSearchParam:c=!1}){const[l,u]=(0,ay.useState)(""),[d,f]=(0,ay.useState)(!1),[m,p]=(0,ay.useState)(-1),[g,y]=(0,ay.useState)(()=>Jj()),b=h(),w=Ws(),v=(0,ay.useRef)(null),x=(0,ay.useRef)(null),k=new URLSearchParams(w.search).get("q")??"";(0,ay.useEffect)(()=>{a&&v.current?.focus()},[a]),(0,ay.useEffect)(()=>{c&&"/search"===w.pathname&&u(k)},[w.pathname,k,c]);const{profiles:N,loading:j}=Vj({query:l,limit:10}),S=l.trim(),C=d&&S.length>=2,E=d&&0===S.length&&g.length>0;(0,ay.useEffect)(()=>{function e(e){x.current&&!x.current.contains(e.target)&&v.current&&!v.current.contains(e.target)&&f(!1)}const t=e=>{"/"!==e.key||"INPUT"===document.activeElement?.tagName||"TEXTAREA"===document.activeElement?.tagName||document.activeElement?.isContentEditable||(e.preventDefault(),v.current?.focus())};return document.addEventListener("mousedown",e),window.addEventListener("keydown",t),()=>{document.removeEventListener("mousedown",e),window.removeEventListener("keydown",t)}},[]);const M=e=>{if(!i||"/search"!==w.pathname)return void b(`/search?q=${encodeURIComponent(e)}`);const t=new URLSearchParams(w.search);t.set("q",e),b(`/search?${t.toString()}`)},I=()=>{f(!1),o?.()},A=e=>{I(),u(""),b(Mj(e))},P=e=>{I(),M(e)},T=(e,t)=>{e.stopPropagation();const n=function(e){const t=Jj().filter(t=>t!==e);return localStorage.setItem(sy,JSON.stringify(t)),t}(t);y(n),p(-1)};return(0,oy.jsx)("form",{onSubmit:e=>{e.preventDefault();const t=S;if(t){if(I(),(t.startsWith("npub1")||t.startsWith("nprofile1"))&&lf(t))return u(""),void b(Cj(t));if(t.startsWith("#")&&t.length>1){const e=t.slice(1).trim();if(e)return u(""),void b(`/tag/${encodeURIComponent(e)}`)}y(function(e){const t=e.trim();if(!t)return Jj();const n=[t,...Jj().filter(e=>e!==t)].slice(0,ry);return localStorage.setItem(sy,JSON.stringify(n)),n}(t)),M(t)}},className:nl("flex gap-2 items-center justify-center w-full",!a&&"hidden md:flex",e),children:(0,oy.jsxs)("div",{className:nl("relative w-full",!a&&"max-w-[20em] lg:max-w-[28em] lg:w-[28em]",n),children:[(0,oy.jsx)(Ga,{ref:v,value:l,onChange:e=>{u(e.target.value),p(-1),f(!0)},onFocus:()=>f(!0),onKeyDown:e=>{if(E){const t=g.length;switch(e.key){case"ArrowDown":e.preventDefault(),p(e=>(e+1)%t);break;case"ArrowUp":e.preventDefault(),p(e=>(e-1+t)%t);break;case"Enter":m>=0&&(e.preventDefault(),P(g[m]));break;case"Escape":f(!1)}return}if(!C||0===N.length)return;const t=N.length+1;switch(e.key){case"ArrowDown":e.preventDefault(),p(e=>(e+1)%t);break;case"ArrowUp":e.preventDefault(),p(e=>(e-1+t)%t);break;case"Enter":m>=0&&m{u(""),f(!1)},children:(0,oy.jsx)(ye,{className:"h-4 w-4"})}),E&&(0,oy.jsx)("div",{ref:x,className:"absolute top-full left-0 right-0 mt-1 bg-popover border rounded-md shadow-lg z-50 overflow-hidden",children:(0,oy.jsxs)("div",{className:"p-2",children:[(0,oy.jsxs)("div",{className:"flex items-center gap-2 px-2 py-1 text-xs font-medium text-muted-foreground",children:[(0,oy.jsx)(Ne,{className:"h-3 w-3"}),"Recent searches"]}),g.map((e,t)=>(0,oy.jsxs)("button",{type:"button",onClick:()=>P(e),className:nl("group w-full flex items-center gap-3 px-2 py-2 rounded-sm text-left hover:bg-accent transition-colors",m===t&&"bg-accent"),children:[(0,oy.jsx)(Ne,{className:"h-4 w-4 shrink-0 text-muted-foreground"}),(0,oy.jsx)("span",{className:"flex-1 min-w-0 truncate text-sm",children:e}),(0,oy.jsx)("span",{role:"button","aria-label":`Remove "${e}" from history`,onClick:t=>T(t,e),className:"opacity-0 group-hover:opacity-100 p-1 rounded hover:bg-background transition-opacity",children:(0,oy.jsx)(ye,{className:"h-3 w-3 text-muted-foreground"})})]},e))]})}),C&&(0,oy.jsxs)("div",{ref:x,className:"absolute top-full left-0 right-0 mt-1 bg-popover border rounded-md shadow-lg z-50 overflow-hidden",children:[(j||N.length>0)&&(0,oy.jsxs)("div",{className:"p-2",children:[(0,oy.jsxs)("div",{className:"flex items-center gap-2 px-2 py-1 text-xs font-medium text-muted-foreground",children:[(0,oy.jsx)(Xt,{className:"h-3 w-3"}),"Creators",j&&(0,oy.jsx)(Ze,{className:"h-3 w-3 animate-spin"})]}),N.map((e,t)=>(0,oy.jsxs)("button",{type:"button",onClick:()=>A(e.pubkey),className:nl("w-full flex items-center gap-3 px-2 py-2 rounded-sm text-left hover:bg-accent transition-colors",m===t&&"bg-accent"),children:[(0,oy.jsx)(ig,{picture:e.profile.picture,pubkey:e.pubkey,name:e.profile.name||e.profile.display_name,className:"h-8 w-8"}),(0,oy.jsxs)("div",{className:"flex-1 min-w-0",children:[(0,oy.jsx)("div",{className:"font-medium truncate",children:e.profile.display_name||e.profile.name||"Anonymous"}),e.profile.nip05&&(0,oy.jsx)("div",{className:"text-xs text-muted-foreground truncate",children:e.profile.nip05})]})]},e.pubkey)),!j&&0===N.length&&S.length>=2&&(0,oy.jsx)("div",{className:"px-2 py-2 text-sm text-muted-foreground",children:"No creators found"})]}),N.length>0&&(0,oy.jsx)("div",{className:"border-t"}),(0,oy.jsxs)("button",{type:"submit",className:nl("w-full flex items-center gap-3 px-4 py-3 text-left hover:bg-accent transition-colors",m===N.length&&"bg-accent"),children:[(0,oy.jsx)(_n,{className:"h-4 w-4 text-muted-foreground"}),(0,oy.jsxs)("span",{children:['Search videos for "',(0,oy.jsx)("span",{className:"font-medium",children:S}),'"']})]})]})]})})}function Gj(){return(Gj=t(()=>{ay=Be(),tt(),pl(),ml(),Hs(),$e(),ne(),Fs(),mn(),qj(),yj(),Ij(),df(),dl(),Hj(),oy=Q()}))()}function Yj(){try{const e=localStorage.getItem(iy);if(!e)return{lastLoginTime:0,notifications:[],lastFetchTime:0};const t=JSON.parse(e);return t.notifications=t.notifications.map(e=>({...e,notificationType:"video"})),t}catch(e){return{lastLoginTime:0,notifications:[],lastFetchTime:0}}}function Xj(e){try{localStorage.setItem(iy,JSON.stringify(e))}catch(t){}}function Zj(){const e=Yj();e.lastLoginTime=Math.floor(Date.now()/1e3),Xj(e)}function Qj(){try{const e=localStorage.getItem(cy);if(!e)return{notifications:[],lastFetchTime:0};const t=JSON.parse(e);return t.notifications=t.notifications.map(e=>({...e,notificationType:"zap"})),t}catch(e){return{notifications:[],lastFetchTime:0}}}function eS(e){try{localStorage.setItem(cy,JSON.stringify(e))}catch(t){}}function tS(){return(tS=t(()=>{iy="nostube_notifications",cy="nostube_zap_notifications",ly=604800}))()}function nS(e,t,n=[]){const s=34235===e.kind||34236===e.kind,r=n.flatMap(e=>sl(e));return s&&t?er.naddrEncode({kind:e.kind,pubkey:e.pubkey,identifier:t,relays:r}):er.neventEncode({kind:e.kind,id:e.id,author:e.pubkey,relays:r})}function sS(){return(sS=t(()=>{os(),dl()}))()}function rS(){const{user:e}=yu(),t=Cr(),n=uu(),[s,r]=(0,uy.useState)([]),[a,o]=(0,uy.useState)(!1),[i,c]=(0,uy.useState)(null),l=(0,uy.useRef)(!1),u=(0,uy.useRef)(null),d=(0,uy.useRef)([]);d.current=n,(0,uy.useEffect)(()=>{const e=Yj();r(e.notifications)},[]);const f=(0,uy.useMemo)(()=>s.filter(e=>!e.read).length,[s]),m=(0,uy.useCallback)(e=>{r(t=>{const n=t.map(t=>t.id===e?{...t,read:!0}:t),s=Yj();return s.notifications=n,Xj(s),n})},[]),p=(0,uy.useCallback)(()=>{r(e=>{const t=e.map(e=>({...e,read:!0})),n=Yj();return n.notifications=t,Xj(n),t})},[]),h=(0,uy.useRef)(null);h.current=e?.pubkey||null;const g=(0,uy.useRef)(t);g.current=t;const y=(0,uy.useCallback)(async()=>{const e=h.current;if(!e||l.current)return;const{lastLoginTime:t}=Yj();if(0!==t){l.current=!0,o(!0),c(null);try{const n=d.current;if(0===n.length)return;const s=[{kinds:[1111],"#P":[e],since:t,limit:100},{kinds:[1111],"#p":[e],since:t,limit:100}],a=[],o=new Set;await new Promise(e=>{let t;const r=Ko.subscription(n,s).subscribe({next:n=>{if("string"!=typeof n&&"kind"in n){if(o.has(n.id))return;o.add(n.id),a.push(n)}else"EOSE"===n&&(t||(t=setTimeout(()=>{r.unsubscribe(),e()},1e3)))},error:t=>{r.unsubscribe(),e()},complete:()=>{e()}}),i=setTimeout(()=>{r.unsubscribe(),e()},5e3);return()=>{clearTimeout(i),t&&clearTimeout(t)}});const i=[];for(const t of a){const n=t.tags.find(e=>"P"===e[0]),s=t.tags.find(e=>"p"===e[0])?.[1]===e&&n?.[1]!==e,r=t.tags.find(e=>"K"===e[0])?.[1];if(!r||!["21","22","34235","34236"].includes(r))continue;const a=t.tags.find(e=>"E"===e[0]);if(!a)continue;const o=a[1],c=g.current.getEvent(o),l=c?.tags.find(e=>"title"===e[0])?.[1]||"Unknown video",u=c?.tags.find(e=>"d"===e[0])?.[1],d={notificationType:"video",id:t.id,commentId:t.id,videoId:o,videoTitle:l,commenterPubkey:t.pubkey,commentContent:t.content.slice(0,100),timestamp:t.created_at,read:!1,videoEventId:c?nS({id:c.id,kind:c.kind,pubkey:c.pubkey},u,[]):nS({id:o,kind:34235,pubkey:e}),isReplyToComment:s};i.push(d)}r(e=>{const t=new Set(e.map(e=>e.id)),n=i.filter(e=>!t.has(e.id)),s=function(e){const t=Date.now()/1e3-ly;return e.filter(e=>e.timestamp>t).sort((e,t)=>t.timestamp-e.timestamp).slice(0,100)}([...e,...n]),r=Yj();return r.notifications=s,r.lastFetchTime=Math.floor(Date.now()/1e3),Xj(r),s})}catch(i){c("Failed to load notifications")}finally{o(!1),l.current=!1}}},[]);u.current=y,(0,uy.useEffect)(()=>{const e=e=>{if("nostube_notifications"===e.key&&e.newValue)try{const t=JSON.parse(e.newValue);r(t.notifications)}catch(i){}};return window.addEventListener("storage",e),()=>window.removeEventListener("storage",e)},[]);const b=e?.pubkey;return(0,uy.useEffect)(()=>{if(!b)return;u.current?.();const e=setInterval(()=>{u.current?.()},dy);return()=>{clearInterval(e)}},[b]),{notifications:s,unreadCount:f,isLoading:a,error:i,markAsRead:m,markAllAsRead:p,fetchNotifications:y}}function aS(){return(aS=t(()=>{uy=Be(),tS(),sS(),bu(),Wt(),nu(),du(),dy=15e4}))()}function oS(){return{notifications:[],lastUpdated:Date.now()}}function iS(e){try{e.lastUpdated=Date.now(),localStorage.setItem(my,JSON.stringify(e))}catch(t){}}function cS(e){const t=Date.now()/1e3-py,n=new Set;return e.filter(e=>!n.has(e.id)&&(n.add(e.id),!0)).filter(e=>e.timestamp>t).sort((e,t)=>t.timestamp-e.timestamp).slice(0,50)}function lS(){const[e,t]=(0,fy.useState)(()=>cS(function(){try{const e=localStorage.getItem(my);return e?JSON.parse(e):oS()}catch(e){return oS()}}().notifications));return(0,fy.useEffect)(()=>{const e=e=>{if(e.key===my&&e.newValue)try{const n=JSON.parse(e.newValue);t(cS(n.notifications))}catch(n){}};return window.addEventListener("storage",e),()=>window.removeEventListener("storage",e)},[]),{notifications:e,unreadCount:(0,fy.useMemo)(()=>e.filter(e=>!e.read).length,[e]),addNotification:(0,fy.useCallback)((e,n,s,r,a)=>{const o=Date.now(),i={id:`${e}-${n}-${o}`,type:e,draftId:n,videoTitle:s,timestamp:Math.floor(o/1e3),read:!1,resolution:r,errorMessage:a};let c=i;return t(t=>{const s=t.find(t=>t.type===e&&t.draftId===n&&Math.abs(t.timestamp-i.timestamp)<10);if(s)return c=s,t;const r=cS([i,...t]);return iS({notifications:r,lastUpdated:Date.now()}),r}),c},[]),markAsRead:(0,fy.useCallback)(e=>{t(t=>{const n=t.map(t=>t.id===e?{...t,read:!0}:t);return iS({notifications:n,lastUpdated:Date.now()}),n})},[]),markAllAsRead:(0,fy.useCallback)(()=>{t(e=>{const t=e.map(e=>({...e,read:!0}));return iS({notifications:t,lastUpdated:Date.now()}),t})},[]),removeNotification:(0,fy.useCallback)(e=>{t(t=>{const n=t.filter(t=>t.id!==e);return iS({notifications:n,lastUpdated:Date.now()}),n})},[]),removeByDraftId:(0,fy.useCallback)(e=>{t(t=>{const n=t.filter(t=>t.draftId!==e);return iS({notifications:n,lastUpdated:Date.now()}),n})},[]),clearAll:(0,fy.useCallback)(()=>{t([]),iS({notifications:[],lastUpdated:Date.now()})},[])}}function uS(){return(uS=t(()=>{fy=Be(),my="nostube_upload_notifications",py=604800}))()}function dS(e){try{const t=e.tags.find(e=>"description"===e[0]);if(!t?.[1])return null;const n=JSON.parse(t[1]);return{zapperPubkey:n.pubkey,comment:n.content||void 0}}catch{return null}}function fS(){const{user:e}=yu(),t=Cr(),n=uu(),[s,r]=(0,hy.useState)([]),[a,o]=(0,hy.useState)(!1),[i,c]=(0,hy.useState)(null),l=(0,hy.useRef)(!1),u=(0,hy.useRef)(null),d=(0,hy.useRef)([]);d.current=[...new Set([...n,...zo])],(0,hy.useEffect)(()=>{const e=Qj();r(e.notifications)},[]);const f=(0,hy.useMemo)(()=>s.filter(e=>!e.read).length,[s]),m=(0,hy.useCallback)(e=>{r(t=>{const n=t.map(t=>t.id===e?{...t,read:!0}:t),s=Qj();return s.notifications=n,eS(s),n})},[]),p=(0,hy.useCallback)(()=>{r(e=>{const t=e.map(e=>({...e,read:!0})),n=Qj();return n.notifications=t,eS(n),t})},[]),h=(0,hy.useRef)(null);h.current=e?.pubkey||null;const g=(0,hy.useRef)(t);g.current=t;const y=(0,hy.useCallback)(async()=>{const e=h.current;if(!e||l.current)return;const{lastLoginTime:t}=Yj();if(0!==t){l.current=!0,o(!0),c(null);try{const n=d.current;if(0===n.length)return;const s={kinds:[9735],"#p":[e],since:t,limit:100},a=[],o=new Set;await new Promise(e=>{let t;const r=Ko.subscription(n,[s]).subscribe({next:n=>{if("string"!=typeof n&&"kind"in n){if(o.has(n.id))return;o.add(n.id),a.push(n)}else"EOSE"===n&&(t||(t=setTimeout(()=>{r.unsubscribe(),e()},1e3)))},error:t=>{r.unsubscribe(),e()},complete:()=>{e()}}),i=setTimeout(()=>{r.unsubscribe(),e()},5e3);return()=>{clearTimeout(i),t&&clearTimeout(t)}});const i=[],c=new Set;for(const t of a){const n=t.tags.find(e=>"bolt11"===e[0])?.[1];if(!n||c.has(n))continue;c.add(n);const s=t.tags.find(e=>"e"===e[0]);if(!s?.[1])continue;const r=s[1],a=[21,22,34235,34236],o=t.tags.find(e=>"a"===e[0]),l=o?.[1]?parseInt(o[1].split(":")[0],10):null,u=g.current.getEvent(r);if(u){if(!a.includes(u.kind))continue}else{if(null===l)continue;if(!a.includes(l))continue}const d=dS(t);if(!d)continue;if(d.zapperPubkey===e)continue;let f;try{f=Hu(n)}catch{continue}const m=u?.tags.find(e=>"title"===e[0])?.[1],p=u?.tags.find(e=>"d"===e[0])?.[1],h={notificationType:"zap",id:t.id,zapperPubkey:d.zapperPubkey,amount:f,comment:d.comment,videoId:r,videoTitle:m,timestamp:t.created_at,read:!1,videoEventId:u?nS({id:u.id,kind:u.kind,pubkey:u.pubkey},p,[]):nS({id:r,kind:34235,pubkey:e})};i.push(h)}r(e=>{const t=new Set(e.map(e=>e.id)),n=i.filter(e=>!t.has(e.id)),s=function(e){const t=Date.now()/1e3-ly;return e.filter(e=>e.timestamp>t).sort((e,t)=>t.timestamp-e.timestamp).slice(0,100)}([...e,...n]),r=Qj();return r.notifications=s,r.lastFetchTime=Math.floor(Date.now()/1e3),eS(r),s})}catch(i){c("Failed to load zap notifications")}finally{o(!1),l.current=!1}}},[]);u.current=y,(0,hy.useEffect)(()=>{const e=e=>{if("nostube_zap_notifications"===e.key&&e.newValue)try{const t=JSON.parse(e.newValue);r(t.notifications)}catch(i){}};return window.addEventListener("storage",e),()=>window.removeEventListener("storage",e)},[]);const b=e?.pubkey;return(0,hy.useEffect)(()=>{if(!b)return;u.current?.();const e=setInterval(()=>{u.current?.()},gy);return()=>{clearInterval(e)}},[b]),{notifications:s,unreadCount:f,isLoading:a,error:i,markAsRead:m,markAllAsRead:p,fetchNotifications:y}}function mS(){return(mS=t(()=>{hy=Be(),tS(),sS(),Gu(),bu(),Wt(),nu(),du(),Jl(),gy=15e4}))()}function pS(){return(pS=t(()=>{yy=Be(),aS(),uS(),mS()}))()}function hS(e){return"notificationType"in e&&"video"===e.notificationType}function gS(e){return"type"in e&&["upload_complete","transcode_complete","upload_error","transcode_error"].includes(e.type)}function yS(e){return"notificationType"in e&&"zap"===e.notificationType}function bS(e){switch(e){case"de":return H;case"fr":return Is;case"es":return Ve;case"ru":return l;default:return ee}}function wS(){return(wS=t(()=>{Ee(),he(),ze(),nt(),Ds()}))()}function vS({notification:e,onClick:t}){const{t:n,i18n:s}=ir(),r=hu({pubkey:e.commenterPubkey}),a=r?.displayName||r?.name||e.commenterPubkey.slice(0,8),o=Re(new Date(1e3*e.timestamp),new Date,{addSuffix:!0,locale:bS(s.language)});return(0,by.jsx)("button",{onClick:()=>t(e),className:"w-full text-left px-4 py-3 hover:bg-muted/50 transition-colors "+(e.read?"opacity-60":""),children:(0,by.jsxs)("div",{className:"flex gap-3",children:[(0,by.jsx)(ig,{picture:r?.picture,pubkey:e.commenterPubkey,name:a,className:"h-8 w-8 shrink-0"}),(0,by.jsxs)("div",{className:"flex-1 min-w-0",children:[(0,by.jsxs)("p",{className:"text-sm",children:[(0,by.jsx)("span",{className:"font-medium",children:a})," ",e.isReplyToComment?n("notifications.repliedToYourComment"):n("notifications.commentedOnYourVideo")]}),e.videoTitle&&(0,by.jsx)("p",{className:"text-sm text-muted-foreground truncate mt-0.5",children:e.videoTitle}),(0,by.jsx)("p",{className:"text-xs text-muted-foreground mt-1",children:o})]})]})})}function xS(){return(xS=t(()=>{mt(),Vr(),yj(),wS(),gu(),by=Q()}))()}function kS({notification:e,onClick:t}){const{t:n,i18n:s}=ir(),r=Re(new Date(1e3*e.timestamp),new Date,{addSuffix:!0,locale:bS(s.language)}),{icon:a,bgColor:o,iconColor:i}=(()=>{switch(e.type){case"upload_complete":return{icon:(0,wy.jsx)(xe,{className:"h-4 w-4"}),bgColor:"bg-green-500/10",iconColor:"text-green-500"};case"transcode_complete":return{icon:(0,wy.jsx)(ut,{className:"h-4 w-4"}),bgColor:"bg-green-500/10",iconColor:"text-green-500"};case"upload_error":case"transcode_error":return{icon:(0,wy.jsx)(as,{className:"h-4 w-4"}),bgColor:"bg-red-500/10",iconColor:"text-red-500"};default:return{icon:(0,wy.jsx)(b,{className:"h-4 w-4"}),bgColor:"bg-muted",iconColor:"text-muted-foreground"}}})();return(0,wy.jsx)("button",{onClick:()=>t(e),className:"w-full text-left px-4 py-3 hover:bg-muted/50 transition-colors "+(e.read?"opacity-60":""),children:(0,wy.jsxs)("div",{className:"flex gap-3",children:[(0,wy.jsx)("div",{className:`h-8 w-8 shrink-0 rounded-full ${o} flex items-center justify-center ${i}`,children:a}),(0,wy.jsxs)("div",{className:"flex-1 min-w-0",children:[(0,wy.jsx)("p",{className:"text-sm font-medium",children:(()=>{switch(e.type){case"upload_complete":return n("notifications.uploadComplete","Upload complete");case"transcode_complete":return e.resolution?n("notifications.transcodeCompleteResolution",{defaultValue:"{{resolution}} transcode complete",resolution:e.resolution}):n("notifications.transcodeComplete","Transcode complete");case"upload_error":return n("notifications.uploadError","Upload failed");case"transcode_error":return n("notifications.transcodeError","Transcode failed");default:return""}})()}),e.videoTitle&&(0,wy.jsx)("p",{className:"text-sm text-muted-foreground truncate mt-0.5",children:e.videoTitle}),e.errorMessage&&(0,wy.jsx)("p",{className:"text-xs text-red-500 mt-0.5 line-clamp-2",children:e.errorMessage}),(0,wy.jsx)("p",{className:"text-xs text-muted-foreground mt-1",children:r})]})]})})}function NS(){return(NS=t(()=>{mt(),Vr(),a(),Kr(),dn(),Vt(),wS(),wy=Q()}))()}function jS({notification:e,onClick:t}){const{t:n,i18n:s}=ir(),r=hu({pubkey:e.zapperPubkey}),a=r?.displayName||r?.name||e.zapperPubkey.slice(0,8),o=Re(new Date(1e3*e.timestamp),new Date,{addSuffix:!0,locale:bS(s.language)});return(0,vy.jsx)("button",{onClick:()=>t(e),className:"w-full text-left px-4 py-3 hover:bg-muted/50 transition-colors "+(e.read?"opacity-60":""),children:(0,vy.jsxs)("div",{className:"flex gap-3",children:[(0,vy.jsx)(ig,{picture:r?.picture,pubkey:e.zapperPubkey,name:a,className:"h-8 w-8 shrink-0"}),(0,vy.jsxs)("div",{className:"flex-1 min-w-0",children:[(0,vy.jsxs)("p",{className:"text-sm",children:[(0,vy.jsx)("span",{className:"font-medium",children:a})," ",n("notifications.zappedYourVideo",{amount:Ku(e.amount)}),(0,vy.jsx)(rt,{className:"inline-block h-3.5 w-3.5 ml-1 text-yellow-500 fill-yellow-500"})]}),e.videoTitle&&(0,vy.jsx)("p",{className:"text-sm text-muted-foreground truncate mt-0.5",children:e.videoTitle}),e.comment&&(0,vy.jsxs)("p",{className:"text-sm text-muted-foreground truncate mt-0.5 italic",children:['"',e.comment,'"']}),(0,vy.jsx)("p",{className:"text-xs text-muted-foreground mt-1",children:o})]})]})})}function SS(){return(SS=t(()=>{mt(),G(),Vr(),yj(),wS(),gu(),Gu(),vy=Q()}))()}function CS(){return(CS=t(()=>{xy=e(Be(),1),z(),dl(),ky=Q(),(Ny=xy.forwardRef(({className:e,children:t,...n},s)=>(0,ky.jsxs)(vt,{ref:s,className:nl("relative overflow-hidden",e),...n,children:[(0,ky.jsx)(Mt,{className:"h-full w-full rounded-[inherit]",children:t}),(0,ky.jsx)(jy,{}),(0,ky.jsx)(ha,{})]}))).displayName=vt.displayName,(jy=xy.forwardRef(({className:e,orientation:t="vertical",...n},s)=>(0,ky.jsx)(N,{ref:s,orientation:t,className:nl("flex touch-none select-none transition-colors","vertical"===t&&"h-full w-2.5 border-l border-l-transparent p-[1px]","horizontal"===t&&"h-2.5 flex-col border-t border-t-transparent p-[1px]",e),...n,children:(0,ky.jsx)(ca,{className:"relative flex-1 rounded-full bg-border"})}))).displayName=N.displayName}))()}function ES({notifications:e,isLoading:t=!1,error:n=null,unreadCount:s=0,onNotificationClick:r,onMarkAllAsRead:a}){const{t:o}=ir();return n?(0,Sy.jsx)("div",{className:"px-4 py-8 text-center text-sm text-destructive",children:n}):t&&0===e.length?(0,Sy.jsx)("div",{className:"px-4 py-8 flex items-center justify-center",children:(0,Sy.jsx)(Ze,{className:"h-5 w-5 animate-spin"})}):0===e.length?(0,Sy.jsx)("div",{className:"px-4 py-8 text-center text-sm text-muted-foreground",children:o("notifications.noNotifications")}):(0,Sy.jsxs)("div",{className:"flex flex-col",children:[s>0&&a&&(0,Sy.jsx)("div",{className:"flex justify-end px-2 pt-2 pb-1 border-b",children:(0,Sy.jsxs)(Ja,{variant:"ghost",size:"sm",className:"h-7 text-xs text-muted-foreground hover:text-foreground",onClick:a,children:[(0,Sy.jsx)(ls,{className:"h-3.5 w-3.5 mr-1"}),o("notifications.markAllAsRead")]})}),(0,Sy.jsx)(Ny,{className:"h-[400px] max-h-[80dvh]",children:(0,Sy.jsx)("div",{className:"py-2",children:e.map(e=>hS(e)?(0,Sy.jsx)(vS,{notification:e,onClick:()=>r(e)},e.id):gS(e)?(0,Sy.jsx)(kS,{notification:e,onClick:()=>r(e)},e.id):yS(e)?(0,Sy.jsx)(jS,{notification:e,onClick:()=>r(e)},e.id):null)})})]})}function MS(){return(MS=t(()=>{Vr(),Fs(),Sr(),xS(),NS(),SS(),CS(),ml(),Sy=Q()}))()}function IS(){const{user:e}=yu(),t=h(),{notifications:n,unreadCount:s,isLoading:r,error:a,markVideoNotificationAsRead:o,markUploadNotificationAsRead:i,markZapNotificationAsRead:c,markAllAsRead:l}=function(){const{notifications:e,unreadCount:t,isLoading:n,error:s,markAsRead:r,markAllAsRead:a,fetchNotifications:o}=rS(),{notifications:i,unreadCount:c,addNotification:l,markAsRead:u,markAllAsRead:d}=lS(),{notifications:f,unreadCount:m,isLoading:p,error:h,markAsRead:g,markAllAsRead:y,fetchNotifications:b}=fS();return{notifications:(0,yy.useMemo)(()=>[...e,...i,...f].sort((e,t)=>t.timestamp-e.timestamp),[e,i,f]),unreadCount:t+c+m,isLoading:n||p,error:s||h,markVideoNotificationAsRead:r,markUploadNotificationAsRead:u,markZapNotificationAsRead:g,markAllAsRead:(0,yy.useCallback)(()=>{a(),d(),y()},[a,d,y]),addUploadNotification:l,refreshVideoNotifications:o,refreshZapNotifications:b,videoNotifications:e,uploadNotifications:i,zapNotifications:f}}();if(!e)return null;return 0===n.length?(0,Cy.jsx)(Ja,{variant:"ghost",size:"icon",className:"relative","aria-label":"Notifications",disabled:!0,children:(0,Cy.jsx)(hs,{className:"h-5 w-5"})}):(0,Cy.jsxs)(Wh,{children:[(0,Cy.jsx)(Vh,{asChild:!0,children:(0,Cy.jsxs)(Ja,{variant:"ghost",size:"icon",className:"relative","aria-label":"Notifications",children:[(0,Cy.jsx)(hs,{className:"h-5 w-5"}),s>0&&(0,Cy.jsx)("span",{className:"absolute top-1 right-1 h-2 w-2 rounded-full bg-red-500","aria-label":`${s} unread notification${1===s?"":"s"}`})]})}),(0,Cy.jsx)(qh,{align:"end",className:"w-80",children:(0,Cy.jsx)(ES,{notifications:n,isLoading:r,error:a,unreadCount:s,onNotificationClick:e=>{hS(e)?(o(e.id),t(Yv(e.videoEventId,"video",{comment:e.commentId}))):gS(e)?(i(e.id),t(`/upload?draft=${e.draftId}`)):yS(e)&&(c(e.id),t(Yv(e.videoEventId,"video")))},onMarkAllAsRead:l})})]})}function AS(){return(AS=t(()=>{Mn(),tt(),tx(),pS(),bu(),MS(),cj(),ml(),Cy=Q()}))()}function PS({transparent:e=!1}){const{t:t}=ir(),{toggleSidebar:n}=iu(),{scrollDirection:s,isAtTop:r}=function(){const[e,t]=(0,kh.useState)(null),[n,s]=(0,kh.useState)(!0);return(0,kh.useEffect)(()=>{let e=window.scrollY,n=!1;const r=()=>{const r=window.scrollY;s(r<10),Math.abs(r-e)<5||(t(r>e?"down":"up"),e=r>0?r:0),n=!1},a=()=>{n||(window.requestAnimationFrame(r),n=!0)};return window.addEventListener("scroll",a),()=>window.removeEventListener("scroll",a)},[]),{scrollDirection:e,isAtTop:n}}(),a=WN(),{colorTheme:o}=Fa(),i=Ra(o).appTitle||{text:"nostube",imageUrl:"/nostube.svg"},{user:c}=yu(),[l,u]=(0,Ey.useState)(!1),d=Ws(),f=d.pathname.startsWith("/short/")||"/shorts"===d.pathname,m=a&&"down"===s&&!r&&!l;return a&&l?(0,My.jsxs)("header",{className:"sticky top-0 z-50 bg-background flex items-center px-4 h-14 gap-2",style:{paddingTop:"env(safe-area-inset-top, 0)"},children:[(0,My.jsx)(Ja,{variant:"ghost",size:"icon",onClick:()=>u(!1),children:(0,My.jsx)(ia,{className:"h-5 w-5"})}),(0,My.jsx)("div",{className:"flex-1",children:!f&&(0,My.jsx)(Kj,{isMobileExpanded:!0,onSearch:()=>u(!1)})})]}):(0,My.jsx)("header",{className:`sticky top-0 z-50 transition-transform duration-300 ${e?"":"bg-background"} ${m?"-translate-y-full":"translate-y-0"}`,style:{paddingTop:"env(safe-area-inset-top, 0)"},children:(0,My.jsxs)("div",{className:"w-full px-4 py-2 flex items-center justify-between h-14",children:[(0,My.jsxs)("div",{className:"flex items-center gap-2",children:[(0,My.jsx)(Ja,{variant:"ghost",size:"icon",onClick:n,children:(0,My.jsx)(Ln,{})}),(0,My.jsxs)(P,{to:"/",className:"text-xl font-bold flex flex-row gap-2 items-center",children:[(0,My.jsx)("img",{className:"w-8",src:i.imageUrl,alt:"logo"}),!a&&(0,My.jsxs)("span",{className:"relative",children:[i.text,(0,My.jsx)("span",{className:"absolute -top-1 -right-6 text-[0.5rem] font-semibold text-muted-foreground",children:t("common.beta")})]})]})]}),(0,My.jsx)("div",{className:"flex-1 max-w-2xl mx-4 hidden lg:block",children:!f&&(0,My.jsx)(Kj,{})}),(0,My.jsxs)("div",{className:"flex items-center gap-1 lg:gap-2",children:[a&&(0,My.jsx)(Ja,{variant:"ghost",size:"icon",onClick:()=>u(!0),children:(0,My.jsx)(_n,{className:"h-5 w-5"})}),c&&(0,My.jsx)(P,{to:"/upload",className:"hidden lg:block",children:(0,My.jsxs)(Ja,{variant:"outline",children:[(0,My.jsx)(xe,{className:"h-4 w-4 mr-2"}),t("header.upload")]})}),(0,My.jsx)(IS,{}),(0,My.jsx)(Dj,{})]})]})})}function TS(){return(TS=t(()=>{Lj(),ml(),ga(),dn(),Hs(),ja(),tt(),lu(),zN(),VN(),tl(),Qc(),bu(),Gj(),AS(),Vr(),Ey=Be(),My=Q()}))()}function RS(){return(RS=t(()=>{Iy=e(Be(),1),Dn(),dl(),Ay=Q(),(Py=Iy.forwardRef(({className:e,orientation:t="horizontal",decorative:n=!0,...s},r)=>(0,Ay.jsx)(wa,{ref:r,decorative:n,orientation:t,className:nl("shrink-0 bg-border","horizontal"===t?"h-[1px] w-full":"h-full w-[1px]",e),...s}))).displayName=wa.displayName}))()}function US(e){return!!e&&Ty.includes(e)}function $S(){return($S=t(()=>{Ty=["b7c6f6915cfa9a62fff6a1f02604de88c23c6c6c6d1b8f62c7cc10749f307e81"]}))()}function DS(){return(DS=t(()=>{sn(),S(),$e(),Ry=e(Be(),1),dl(),Uy=Q(),$y=ve,Dy=Gt,(Ly=Ry.forwardRef(({className:e,...t},n)=>(0,Uy.jsx)(k,{className:nl("fixed inset-0 z-70 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",e),...t,ref:n}))).displayName=k.displayName,By=kt("fixed z-[70] gap-4 bg-background p-6 shadow-lg transition ease-in-out data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:duration-300 data-[state=open]:duration-500",{variants:{side:{top:"inset-x-0 top-0 border-b data-[state=closed]:slide-out-to-top data-[state=open]:slide-in-from-top",bottom:"inset-x-0 bottom-0 border-t data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom",left:"inset-y-0 left-0 h-full w-3/4 border-r data-[state=closed]:slide-out-to-left data-[state=open]:slide-in-from-left sm:max-w-sm",right:"inset-y-0 right-0 h-full w-3/4 border-l data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right sm:max-w-sm"}},defaultVariants:{side:"right"}}),(zy=Ry.forwardRef(({side:e="right",className:t,children:n,...s},r)=>(0,Uy.jsxs)(Dy,{children:[(0,Uy.jsx)(Ly,{}),(0,Uy.jsxs)(wt,{ref:r,className:nl(By({side:e}),t),...s,children:[n,(0,Uy.jsxs)(Le,{className:"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-secondary",children:[(0,Uy.jsx)(ye,{className:"h-4 w-4"}),(0,Uy.jsx)("span",{className:"sr-only",children:"Close"})]})]})]}))).displayName=wt.displayName,(Fy=({className:e,...t})=>(0,Uy.jsx)("div",{className:nl("flex flex-col space-y-2 text-center sm:text-left",e),...t})).displayName="SheetHeader",(({className:e,...t})=>(0,Uy.jsx)("div",{className:nl("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",e),...t})).displayName="SheetFooter",(_y=Ry.forwardRef(({className:e,...t},n)=>(0,Uy.jsx)(pe,{ref:n,className:nl("text-lg font-semibold text-foreground",e),...t}))).displayName=pe.displayName,Ry.forwardRef(({className:e,...t},n)=>(0,Uy.jsx)(Ta,{ref:n,className:nl("text-sm text-muted-foreground",e),...t})).displayName=Ta.displayName}))()}function LS({children:e,className:t}){return(0,Oy.jsx)("div",{"data-tauri-drag-region":!0,className:nl("cursor-default select-none",t),onMouseDown:e=>{0===e.button&&Yn()&&gs().startDragging()},children:e})}function BS(){return(BS=t(()=>{Ks(),us(),dl(),Oy=Q(),Wy="w-20",Vy="h-14",qy="h-12"}))()}function zS(e){const t=Math.floor(e/3600),n=Math.floor(e%3600/60),s=e%60;return t>0?`${t}:${n.toString().padStart(2,"0")}:${s.toString().padStart(2,"0")}`:`${n}:${s.toString().padStart(2,"0")}`}function FS(){return(FS=t(()=>{}))()}function _S({className:e,...t}){return(0,Jy.jsx)("div",{className:nl("animate-pulse rounded-md bg-muted",e),...t})}function OS(){return(OS=t(()=>{dl(),Jy=Q()}))()}function WS({videoId:e,duration:t}){const{user:n}=yu(),[s,r]=(0,Hy.useState)(null);(0,Hy.useEffect)(()=>{const t=n?.pubkey;if(!t||!e)return void r(null);const s=em,a=`${t}:${e}`;if(s.has(a))return void r(s.get(a)??null);let o=!1;return pw(t,e).then(e=>{o||r(e)}),()=>{o=!0}},[n?.pubkey,e]);const a=s?.duration||t,o=s?.time??0;return o<=0||a<=0||o>=a?null:(0,Ky.jsx)("div",{className:"absolute left-0 bottom-0 w-full h-1 bg-black/20 rounded-b-lg overflow-hidden",children:(0,Ky.jsx)("div",{className:"h-full bg-primary rounded-bl-lg transition-all duration-200",style:{width:`${Math.min(100,o/a*100)}%`,height:"4px"}})})}function VS(){return(VS=t(()=>{bu(),Hy=Be(),hw(),Ky=Q()}))()}function qS(){return(qS=t(()=>{Qs(),Gr(),Gy={videos:[],currentIndex:0,isLoading:!1},Yy=vr()(Vs((e,t)=>({...Gy,setVideos:(t,n=0)=>{e(e=>{e.videos=t,e.currentIndex=Math.max(0,Math.min(n,t.length-1)),e.isLoading=!1})},setCurrentIndex:t=>{e(e=>{const n=Math.max(0,e.videos.length-1);e.currentIndex=Math.max(0,Math.min(t,n))})},nextVideo:()=>{e(e=>{e.currentIndex{e(e=>{e.currentIndex>0&&(e.currentIndex-=1)})},appendVideos:t=>{e(e=>{const n=new Set(e.videos.map(e=>e.id)),s=t.filter(e=>!n.has(e.id));e.videos.push(...s)})},setLoading:t=>{e(e=>{e.isLoading=t})},clearFeed:()=>{e(e=>{e.videos=[],e.currentIndex=0,e.isLoading=!1})},getCurrentVideo:()=>{const e=t();return e.videos[e.currentIndex]||null}})))}))()}function JS(){return(JS=t(()=>{Xy="/assets/audio-fallback-BhmacZgr.webp"}))()}function HS({children:e,desktopCoordinator:t,desktopRoute:n,onClick:s,...r}){return(0,Zy.jsx)(P,{...r,onClick:async e=>{s?.(e),!e.defaultPrevented&&t&&n&&(e.preventDefault(),await t.openPlayer(n))},children:e})}function KS(){return(KS=t(()=>{tt(),Zy=Q()}))()}function GS(){return(GS=t(()=>{tt(),mt(),ow(),tx(),yj(),dl(),OS(),Qy=e(Be(),1),af(),VS(),gu(),Wt(),Ij(),KN(),gj(),qS(),X(),JS(),Vr(),wS(),g(),KS(),$j(),eb=Q(),tb=Qy.memo(function({video:e,hideAuthor:t,format:n="square",playlistParam:s,allVideos:r,videoIndex:a,tightGridGap:o,priority:i=!1}){const{t:c,i18n:l}=ir(),u=hu({pubkey:e.pubkey}),d=u?.display_name||u?.name||e?.pubkey.slice(0,8),f=Cr(),{config:m}=iu(),{setVideos:p}=Yy(),h=Zg(),g=bS(l.language),y=(0,Qy.useMemo)(()=>f.getEvent(e.id),[f,e.id]),b=(0,Qy.useMemo)(()=>Ej(e.pubkey,y),[e.pubkey,y]),w=m.nsfwFilter??"hide",v=e.contentWarning&&"warning"===w,x="vertical"==n?"aspect-[2/3]":"square"==n?"aspect-[1/1]":"aspect-video",k=hj({src:e.images?.[0],videoUrl:e.urls?.[0],variant:"preview",authorPubkey:e.pubkey,race:i}),N=k.loaded,j=k.loadedSrc,S=(0,Qy.useMemo)(()=>{const t=e.thumbnailVariants?.[0]?.blurhash;return rf(t)},[e.thumbnailVariants]),C="shorts"===e.type?"shorts":"video",E=(0,Qy.useMemo)(()=>s&&"video"===C?function(e,t="video",n){const s=Gv(e,t),r=new URLSearchParams;n?.playlist&&r.set("playlist",n.playlist),n?.timestamp&&n.timestamp>0&&r.set("t",String(Math.floor(n.timestamp))),n?.comment&&r.set("comment",n.comment),n?.autoplay&&r.set("autoplay","true");const a=r.toString();return{pathname:s,search:a?`?${a}`:""}}(e.link,"video",{playlist:s}):"shorts"===e.type&&r&&void 0!==a?{pathname:Gv(e.link,"shorts"),search:`?author=${e.pubkey}&video=${e.id}`}:Gv(e.link,C),[s,C,e.link,e.type,e.pubkey,e.id,r,a]),M="video"===C?`/desktop/player/${e.link}${s?`?playlist=${encodeURIComponent(s)}`:""}`:void 0,I=k.onLoad;return(0,eb.jsx)("div",{className:nl("hover:bg-accent transition-all duration-300 group hover:shadow-md hover:scale-[1.02]",o?"rounded-none sm:rounded-lg px-[0.5px] py-[0.5px] sm:px-2 sm:pt-2 sm:pb-4":"rounded-lg px-2 pt-2 pb-4"),style:{contain:"layout style paint"},children:(0,eb.jsxs)("div",{children:[(0,eb.jsx)(HS,{to:E,onClick:()=>{"shorts"===e.type&&r&&void 0!==a&&p(r,a)},desktopCoordinator:h,desktopRoute:M,children:(0,eb.jsxs)("div",{className:nl("w-full overflow-hidden rounded-none sm:rounded-lg relative bg-muted",x),children:[k.exhausted?"audio"===e.mediaType?(0,eb.jsx)("img",{src:Xy,alt:"","aria-hidden":"true",className:"absolute inset-0 w-full h-full object-cover"}):(0,eb.jsx)("div",{className:"absolute inset-0 bg-muted flex items-center justify-center",children:(0,eb.jsxs)("div",{className:"flex flex-col items-center gap-2 text-muted-foreground",children:[(0,eb.jsx)(ot,{className:"h-12 w-12"}),(0,eb.jsx)("span",{className:"text-sm",children:c("video.thumbnailUnavailable")})]})}):(0,eb.jsxs)(eb.Fragment,{children:[!N&&(j?(0,eb.jsx)("img",{src:j,alt:"","aria-hidden":"true",className:nl(v?"blur-lg":"","absolute inset-0 w-full h-full object-cover")}):S?(0,eb.jsx)("img",{src:S,alt:"","aria-hidden":"true",className:"absolute inset-0 w-full h-full object-cover"}):(0,eb.jsx)(_S,{className:"absolute inset-0 w-full h-full rounded-none sm:rounded-lg"})),(0,eb.jsx)("img",{src:k.src??"",loading:i?"eager":"lazy",fetchPriority:i?"high":"auto",decoding:"async",alt:e.title,referrerPolicy:"no-referrer",className:nl(v?"blur-lg":"","absolute inset-0 w-full h-full object-cover transition-opacity duration-300",!N&&"opacity-0"),onError:k.onError,onLoad:I})]}),v&&(0,eb.jsxs)("div",{className:"absolute top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2 text-center",children:[(0,eb.jsx)("div",{className:"text-2xl font-bold text-white drop-shadow-lg",children:"Content warning"}),(0,eb.jsx)("div",{className:"text-base font-semibold text-white drop-shadow-lg mt-4",children:e.contentWarning})]}),(0,eb.jsx)(WS,{videoId:e.id,duration:e.duration}),e.duration>0&&(0,eb.jsx)("div",{className:"absolute bottom-2 right-2 bg-black/50 text-white px-1 rounded text-sm",children:zS(e.duration)})]})}),(0,eb.jsx)("div",{className:nl("pt-3","vertical"===n&&"hidden sm:block"),children:(0,eb.jsxs)("div",{className:"flex gap-3",children:[!t&&"vertical"!==n&&(0,eb.jsx)(P,{to:b,className:"shrink-0",children:(0,eb.jsx)(ig,{picture:u?.picture,pubkey:e.pubkey,name:d,className:"h-10 w-10"})}),(0,eb.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,eb.jsx)(HS,{to:E,desktopCoordinator:h,desktopRoute:M,children:(0,eb.jsx)("h3",{className:"font-medium line-clamp-2 break-words",children:e.title})}),(0,eb.jsxs)("div",{className:"flex items-center text-xs",children:[!t&&(0,eb.jsx)(eb.Fragment,{children:(0,eb.jsx)(P,{to:b,className:"block text-muted-foreground hover:text-primary",children:d})}),d&&(0,eb.jsx)(eb.Fragment,{children:" • "}),(0,eb.jsx)("div",{className:"text-muted-foreground",title:Sa(new Date(1e3*Fb(e)),"PPpp",{locale:g}),children:Re(new Date(1e3*Fb(e)),new Date,{addSuffix:!0,locale:g})})]})]})]})})]})})}),nb=Qy.memo(function({format:e,tightGridGap:t}){const n="vertical"==e?"aspect-[2/3]":"square"==e?"aspect-[1/1]":"aspect-video";return(0,eb.jsxs)("div",{className:nl(t?"px-[0.5px] py-[0.5px] sm:px-2 sm:py-2":"px-2 py-2"),children:[(0,eb.jsx)(_S,{className:nl("w-full rounded-none sm:rounded-lg",n)}),(0,eb.jsx)("div",{className:nl("pt-3","vertical"===e&&"hidden sm:block"),children:(0,eb.jsxs)("div",{className:"flex gap-3",children:["vertical"!==e&&(0,eb.jsx)("div",{className:"shrink-0",children:(0,eb.jsx)(_S,{className:"h-10 w-10 rounded-full"})}),(0,eb.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,eb.jsx)(_S,{className:"h-5 w-full"}),(0,eb.jsx)(_S,{className:"h-4 w-2/3 mt-1"}),(0,eb.jsx)(_S,{className:"h-3 w-1/3 mt-1"})]})]})})]})})}))()}function YS(){return(0,sb.jsxs)("div",{className:"max-w-560 mx-auto",children:[(0,sb.jsx)("div",{className:"sm:px-2",children:(0,sb.jsx)("div",{className:"w-full overflow-x-auto scrollbar-hide sticky top-[env(safe-area-inset-top,0)] z-40 bg-background/80 backdrop-blur-md",children:(0,sb.jsx)("div",{className:"flex gap-2 p-2 min-w-max",children:Array.from({length:10}).map((e,t)=>(0,sb.jsx)(_S,{className:nl("h-8 rounded-full shrink-0",0===t?"w-12":"w-20")},t))})})}),(0,sb.jsx)("div",{className:"sm:px-2",children:(0,sb.jsx)("div",{className:nl("grid","grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 2xl:grid-cols-6"),children:Array.from({length:24}).map((e,t)=>(0,sb.jsx)(nb,{format:"horizontal"},t))})})]})}function XS(){return(XS=t(()=>{GS(),OS(),dl(),sb=Q()}))()}function ZS(){return(0,rb.jsx)("div",{className:"sm:px-2",children:(0,rb.jsx)("div",{className:"w-full overflow-x-auto scrollbar-hide sticky top-[env(safe-area-inset-top,0)] z-40 bg-background/80 backdrop-blur-md",children:(0,rb.jsx)("div",{className:"flex gap-2 p-2 min-w-max",children:Array.from({length:10}).map((e,t)=>(0,rb.jsx)(_S,{className:nl("h-8 rounded-full shrink-0",0===t?"w-12":"w-20")},t))})})})}function QS({count:e=24}){return(0,rb.jsx)("div",{className:ab,children:Array.from({length:e}).map((e,t)=>(0,rb.jsx)(nb,{format:"horizontal"},t))})}function eC(){return(0,rb.jsxs)("div",{className:"max-w-560 mx-auto",children:[(0,rb.jsx)(ZS,{}),(0,rb.jsx)("div",{className:"sm:p-2",children:(0,rb.jsx)("div",{className:ob,children:Array.from({length:24}).map((e,t)=>(0,rb.jsx)(nb,{format:"vertical",tightGridGap:!0},t))})})]})}function tC(){return(0,rb.jsx)("div",{className:"max-w-560 mx-auto sm:p-4",children:(0,rb.jsx)(QS,{})})}function nC(){return(0,rb.jsxs)("div",{className:"max-w-560 mx-auto sm:p-2",children:[(0,rb.jsx)("div",{className:"flex items-center gap-2 p-2",children:(0,rb.jsx)(_S,{className:"h-8 w-48"})}),(0,rb.jsx)(QS,{})]})}function sC(){return(0,rb.jsxs)("div",{className:"max-w-560 mx-auto sm:p-4",children:[(0,rb.jsxs)("div",{className:"flex flex-col gap-3 p-2 sm:flex-row sm:items-start sm:justify-between",children:[(0,rb.jsx)(_S,{className:"h-8 w-64"}),(0,rb.jsx)(_S,{className:"h-9 w-24"})]}),(0,rb.jsx)(QS,{})]})}function rC(){return(0,rb.jsxs)("div",{className:"max-w-560 mx-auto sm:p-4",children:[(0,rb.jsx)(_S,{className:"h-8 w-48 mb-4"}),(0,rb.jsx)(QS,{})]})}function aC(){return(0,rb.jsxs)("div",{className:"max-w-560 mx-auto sm:p-4",children:[(0,rb.jsxs)("div",{className:"p-2 flex justify-between items-center mb-4",children:[(0,rb.jsx)(_S,{className:"h-8 w-48"}),(0,rb.jsx)(_S,{className:"h-9 w-28"})]}),(0,rb.jsx)(QS,{})]})}function oC(){return(0,rb.jsxs)("div",{className:"container mx-auto py-6 max-w-4xl px-4",children:[(0,rb.jsxs)("div",{className:"mb-6 space-y-2",children:[(0,rb.jsx)(_S,{className:"h-9 w-64"}),(0,rb.jsx)(_S,{className:"h-4 w-96 max-w-full"})]}),(0,rb.jsx)("div",{className:"space-y-4",children:Array.from({length:4}).map((e,t)=>(0,rb.jsxs)("div",{className:"rounded-lg border p-4 flex gap-4",children:[(0,rb.jsx)(_S,{className:"w-40 h-24 rounded-md shrink-0"}),(0,rb.jsxs)("div",{className:"flex-1 space-y-2",children:[(0,rb.jsx)(_S,{className:"h-5 w-3/4"}),(0,rb.jsx)(_S,{className:"h-4 w-full"}),(0,rb.jsx)(_S,{className:"h-4 w-2/3"})]})]},t))})]})}function iC(){return(0,rb.jsxs)("div",{className:"max-w-3xl mx-auto p-4 space-y-6",children:[(0,rb.jsx)(_S,{className:"h-9 w-48"}),(0,rb.jsx)(_S,{className:"w-full h-48 rounded-lg"}),(0,rb.jsxs)("div",{className:"space-y-3",children:[(0,rb.jsx)(_S,{className:"h-10 w-full"}),(0,rb.jsx)(_S,{className:"h-32 w-full"}),(0,rb.jsx)(_S,{className:"h-10 w-full"})]}),(0,rb.jsxs)("div",{className:"flex justify-end gap-2",children:[(0,rb.jsx)(_S,{className:"h-10 w-24"}),(0,rb.jsx)(_S,{className:"h-10 w-32"})]})]})}function cC(){return(0,rb.jsxs)("div",{className:"max-w-560 mx-auto sm:p-4 p-2",children:[(0,rb.jsx)(_S,{className:"h-8 w-48 mb-4"}),(0,rb.jsx)("div",{className:"grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 gap-4",children:Array.from({length:8}).map((e,t)=>(0,rb.jsxs)("div",{className:"flex flex-col gap-2",children:[(0,rb.jsx)(_S,{className:"aspect-video rounded-lg"}),(0,rb.jsx)(_S,{className:"h-4 w-3/4"}),(0,rb.jsx)(_S,{className:"h-3 w-1/2"})]},t))})]})}function lC(){return(0,rb.jsxs)("div",{className:"max-w-560 mx-auto p-8 flex flex-col gap-8",children:[(0,rb.jsxs)("div",{className:"flex items-start gap-4",children:[(0,rb.jsxs)("div",{className:"flex-1 space-y-2",children:[(0,rb.jsx)(_S,{className:"h-8 w-64"}),(0,rb.jsx)(_S,{className:"h-4 w-96 max-w-full"})]}),(0,rb.jsx)(_S,{className:"h-9 w-[180px] shrink-0"})]}),(0,rb.jsx)("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:Array.from({length:6}).map((e,t)=>(0,rb.jsx)(_S,{className:"h-48 w-full"},t))})]})}function uC(){return(0,rb.jsxs)("div",{className:"max-w-560 mx-auto sm:p-4",children:[(0,rb.jsx)(_S,{className:"w-full h-32 sm:h-48 md:h-56 rounded-lg"}),(0,rb.jsxs)("div",{className:"flex items-start space-x-4 p-2 ml-6 -mt-16 sm:-mt-20 relative",children:[(0,rb.jsx)(_S,{className:"w-24 h-24 rounded-full ring-2 ring-background shrink-0"}),(0,rb.jsxs)("div",{className:"flex-1 min-w-0 space-y-2 mt-1",children:[(0,rb.jsx)(_S,{className:"h-7 w-48"}),(0,rb.jsx)(_S,{className:"h-4 w-full max-w-md"}),(0,rb.jsx)(_S,{className:"h-4 w-3/4 max-w-md"})]})]}),(0,rb.jsxs)("div",{className:"p-2",children:[(0,rb.jsx)("div",{className:"w-full overflow-x-auto scrollbar-hide -mx-2 px-2 py-2",children:(0,rb.jsx)("div",{className:"flex gap-2 min-w-max",children:Array.from({length:4}).map((e,t)=>(0,rb.jsx)(_S,{className:"h-9 w-24 rounded-full shrink-0"},t))})}),(0,rb.jsx)("div",{className:"mt-6 space-y-8",children:Array.from({length:2}).map((e,t)=>(0,rb.jsxs)("section",{className:"space-y-3",children:[(0,rb.jsx)(_S,{className:"h-5 w-40"}),(0,rb.jsx)("div",{className:"w-full overflow-x-auto scrollbar-hide",children:(0,rb.jsx)("div",{className:"flex gap-2 min-w-max",children:Array.from({length:4}).map((e,t)=>(0,rb.jsx)("div",{className:"w-80 shrink-0",children:(0,rb.jsx)(nb,{format:"horizontal"})},t))})})]},t))})]})]})}function dC(){return(0,rb.jsxs)("div",{className:"max-w-560 mx-auto p-4",children:[(0,rb.jsxs)("div",{className:"mb-6 space-y-2",children:[(0,rb.jsx)(_S,{className:"h-8 w-64"}),(0,rb.jsx)(_S,{className:"h-4 w-80 max-w-full"})]}),(0,rb.jsxs)("div",{className:"space-y-6",children:[Array.from({length:4}).map((e,t)=>(0,rb.jsxs)("div",{className:"rounded-lg border p-6 space-y-4",children:[(0,rb.jsx)(_S,{className:"h-6 w-48"}),(0,rb.jsx)(_S,{className:"h-4 w-64 max-w-full"}),(0,rb.jsx)(_S,{className:"h-10 w-full"})]},t)),(0,rb.jsx)("div",{className:"flex justify-end",children:(0,rb.jsx)(_S,{className:"h-10 w-32"})})]})]})}function fC(){return(0,rb.jsxs)("div",{className:"container mx-auto py-8 max-w-7xl px-4 space-y-6",children:[(0,rb.jsx)(_S,{className:"h-8 w-64"}),(0,rb.jsxs)("div",{className:"rounded-lg border p-6 space-y-4",children:[(0,rb.jsx)(_S,{className:"h-10 w-full"}),(0,rb.jsx)(_S,{className:"h-10 w-32"})]})]})}function mC(){return(0,rb.jsx)("div",{className:"fixed inset-0 bg-black flex items-center justify-center",children:(0,rb.jsx)(_S,{className:"w-full h-full max-w-md aspect-9/16"})})}function pC(){return(0,rb.jsx)("div",{className:"min-h-screen"})}function hC(){return(hC=t(()=>{GS(),OS(),dl(),rb=Q(),ab="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 2xl:grid-cols-6",ob="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 2xl:grid-cols-7"}))()}function gC(){return(gC=t(()=>{ib=e(Be(),1),In(),dl(),cb=Q(),lb=or,ub=Pr,db=Ns,(fb=ib.forwardRef(({className:e,sideOffset:t=4,...n},s)=>(0,cb.jsx)(Wr,{ref:s,sideOffset:t,className:nl("z-50 overflow-hidden rounded-md bg-popover/80 px-3 py-1.5 text-xs text-popover-foreground shadow-md animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),...n}))).displayName=Wr.displayName}))()}function yC(){return(yC=t(()=>{mb=e(Be(),1),dl(),pb=Q(),(hb=mb.forwardRef(({className:e,...t},n)=>(0,pb.jsx)("textarea",{className:nl("flex min-h-[80px] w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",e),ref:n,...t}))).displayName="Textarea"}))()}function bC(){return{version:yb,tasks:[],lastUpdated:Date.now()}}function wC(){try{const e=localStorage.getItem(gb);if(!e)return bC();const t=JSON.parse(e);return t.version!==yb?bC():t}catch(e){return bC()}}function vC(){return wC().tasks}function xC(e){const t=wC();t.tasks=e,function(e){try{e.lastUpdated=Date.now(),localStorage.setItem(gb,JSON.stringify(e))}catch(t){}}(t)}function kC(){return(kC=t(()=>{gb="nostube_upload_tasks",yb="1",bb=864e5}))()}function NC(e){return!!(e.uploadInfo?.videos||e.originalVideoInfo||e.thumbnailUploadInfo?.uploadedBlobs||e.thumbnailUploadInfo?.mirroredBlobs)}function jC(){return(jC=t(()=>{}))()}function SC(e){const{storageKey:t,nostrIdentifier:n,maxItems:s=50,isMilestone:r,debounceMs:a=5e3}=e,[o,i]=(0,wb.useState)(0),c=(0,wb.useMemo)(()=>fk(t),[t,o]),{user:l}=yu(),{pool:u}=iu(),{relays:d,publish:f}=Dv(),m=(0,wb.useRef)(null),p=(0,wb.useRef)(""),h=(0,wb.useCallback)(()=>i(e=>e+1),[]),g=(0,wb.useCallback)(async e=>{if(!l?.signer?.nip44)return;const t=JSON.stringify(e);if(t===p.current)return;const s=(async()=>{try{const s=JSON.stringify({version:"1",lastModified:Date.now(),drafts:e}),r={kind:30078,content:await l.signer.nip44.encrypt(l.pubkey,s),created_at:ol(),tags:[["d",n]]};await f(r),p.current=t}catch(s){}finally{m.current=null}})();return m.current=s,s},[l,d.length,f,t,n]),y=(0,wb.useRef)(g);(0,wb.useEffect)(()=>{y.current=g},[g]);const b=(0,wb.useMemo)(()=>function(e,t){let n=null,s=null;const r=(...r)=>{s=r,n&&clearTimeout(n),n=setTimeout(()=>{e(...r),s=null},t)};return r.flush=()=>{n&&(clearTimeout(n),n=null),s&&(e(...s),s=null)},r}(e=>{y.current(e)},a),[a]);(0,wb.useEffect)(()=>()=>{b.flush()},[b]);const w=(0,wb.useCallback)(e=>fk(t).find(t=>t.id===e),[t]),v=(0,wb.useCallback)(e=>{!function(e,t,n){const s=fk(e);if(s.length>=n)throw new Error(`Maximum ${n} items allowed`);mk(e,[...s,t])}(t,e,s),h()},[t,s,h]),x=(0,wb.useCallback)((e,n)=>{if(!function(e,t,n){const s=fk(e),r=s.findIndex(e=>e.id===t);if(-1===r)return;const a={...s[r],...n,updatedAt:Date.now()};return s[r]=a,mk(e,s),a}(t,e,n))return;h();const s=fk(t);r?.(n)?y.current(s):b(s)},[t,r,b,h]),k=(0,wb.useCallback)(e=>{!function(e,t){mk(e,fk(e).filter(e=>e.id!==t))}(t,e),h();const n=fk(t);y.current(n)},[t,h]),N=(0,wb.useCallback)(()=>{h()},[h]);return(0,wb.useEffect)(()=>{if(!l?.pubkey||!l.signer?.nip44||0===d.length)return;const e=ke(u)({kind:30078,pubkey:l.pubkey,identifier:n,relays:d}).subscribe(async e=>{if(e)try{let n=e.content;if(l.signer.nip44)try{n=await l.signer.nip44.decrypt(l.pubkey,e.content)}catch{}const s=JSON.parse(n),r=s.drafts||s.items||[],a=pk(t,r,e.created_at),o=fk(t);JSON.stringify(a)!==JSON.stringify(o)&&(mk(t,a),h())}catch(n){}});return()=>e.unsubscribe()},[l?.pubkey,l?.signer,u,d,t,n,h]),{items:c,getItem:w,createItem:v,updateItem:x,deleteItem:k,refreshItems:N,flushSync:(0,wb.useCallback)(async()=>{b.flush(),m.current&&await m.current},[b])}}function CC(){return(CC=t(()=>{wb=Be(),bu(),lu(),dl(),be(),Lv()}))()}function EC(){return{isDvmAvailable:jb.size>0,isLoading:Sb,dvmHandlers:jb}}function MC(){Pb=EC(),Ib.forEach(e=>e())}function IC(e){return Ib.add(e),()=>{Ib.delete(e)}}function AC(){return Pb}function PC(){const e=Math.floor(Date.now()/1e3)-xb;let t=!1;for(const[n,s]of jb)s.lastSeenAt{if("string"==typeof e)return void(Sb&&(Sb=!1,Mb&&(clearTimeout(Mb),Mb=null),MC()));const t=function(e){let t,n;try{const s=JSON.parse(e.content||"{}");t=s.name,n=s.about}catch{}const s=e.tags.find(e=>"name"===e[0]),r=e.tags.find(e=>"about"===e[0]);let a;s?.[1]&&(t=s[1]),r?.[1]&&(n=r[1]);const o={};let i,c,l,u;for(const d of e.tags){if("capability"===d[0]&&d[1]&&void 0!==d[2]){const e=d[1],t=d[2];if("hardware"===e)a=t;else if("max_concurrent"===e)i=parseInt(t,10);else if("queue_length"===e)c=parseInt(t,10);else if("codecs"===e)l=t.split(",").map(e=>e.trim());else if(e.startsWith("speed_")){const n=e.replace("speed_",""),s=parseFloat(t);isNaN(s)||(o[n]=s)}}"rate"===d[0]&&void 0!==d[1]&&(u=parseInt(d[1],10))}return{pubkey:e.pubkey,name:t,about:n,lastSeenAt:e.created_at,hardware:a,speeds:Object.keys(o).length>0?o:void 0,maxConcurrent:i,queueLength:c,codecs:l,rate:u}}(e),n=jb.get(t.pubkey);(!n||t.lastSeenAt>n.lastSeenAt)&&((jb=new Map(jb)).set(t.pubkey,t),MC())},error:e=>{Sb&&(Sb=!1,Mb&&(clearTimeout(Mb),Mb=null),MC())},complete:()=>{Sb&&(Sb=!1,Mb&&(clearTimeout(Mb),Mb=null),MC())}}),Mb=setTimeout(()=>{Sb&&(Sb=!1,MC()),Mb=null},Nb),Eb=setInterval(PC,kb)}function RC(){const{config:e,relayOverride:t}=iu(),n=(0,vb.useMemo)(()=>{const n=e.relays.filter(e=>e.tags.includes("read")).map(e=>e.url),s=e.relays.filter(e=>e.tags.includes("write")).map(e=>e.url),r=new Set([...n,...s,...Vo]);return t&&r.add(t),Array.from(r)},[e.relays,t]);return(0,vb.useEffect)(()=>{TC(n)},[n]),(0,vb.useSyncExternalStore)(IC,AC,AC)}function UC(){return(UC=t(()=>{vb=Be(),lu(),nu(),xb=1800,kb=6e4,Nb=5e3,jb=new Map,Sb=!0,Cb=null,Eb=null,Mb=null,Ib=new Set,Ab="",Pb=EC()}))()}function $C(){return($C=t(()=>{Tb=["pending","uploading","mirroring","transcoding"]}))()}function DC(e){return{...e,uploadInfo:{...e.uploadInfo,videos:e.uploadInfo.videos.map(Gx)}}}function LC({children:e}){const{user:t}=yu(),{config:n,relayOverride:s}=iu(),{addNotification:r}=lS(),a=(0,Rb.useMemo)(()=>{const e=n.relays.filter(e=>e.tags.includes("read")).map(e=>e.url),t=n.relays.filter(e=>e.tags.includes("write")).map(e=>e.url),r=new Set([...e,...t,...Vo]);return s&&r.add(s),Array.from(r)},[n.relays,s]),o=(0,Rb.useRef)(a);o.current=a;const[i,c]=(0,Rb.useState)(()=>{const e=vC();return new Map(e.map(e=>[e.id,e]))}),l=SC({storageKey:"nostube_upload_drafts",nostrIdentifier:"nostube-uploads",maxItems:10,isMilestone:NC}),u=(0,Rb.useMemo)(()=>l.items.map(DC),[l.items]),d=l.refreshItems,f=l.flushSync,[m,p]=(0,Rb.useState)(null),h=(0,Rb.useRef)(new Map),g=(0,Rb.useRef)(new Set),y=(0,Rb.useRef)(t),b=(0,Rb.useRef)(n),w=(0,Rb.useRef)(i);y.current=t,b.current=n,w.current=i,(0,Rb.useEffect)(()=>{!function(){const e=vC(),t=Date.now()-bb,n=e.filter(e=>!!["pending","uploading","mirroring","transcoding"].includes(e.status)||(e.completedAt||e.updatedAt)>t),s=e.length-n.length;s>0&&xC(n)}()},[]),(0,Rb.useEffect)(()=>{xC(Array.from(i.values()))},[i]),(0,Rb.useEffect)(()=>{const e=h.current;return()=>{e.forEach(e=>{e.session?.cancel(),e.abortController.abort()}),e.clear()}},[]);const v=(0,Rb.useCallback)(()=>{const e={id:crypto.randomUUID(),createdAt:Date.now(),updatedAt:Date.now(),title:"",description:"",tags:[],language:"en",people:[],contentWarning:{enabled:!1,reason:""},expiration:"none",inputMethod:"file",uploadInfo:{videos:[]},thumbnailUploadInfo:{uploadedBlobs:[],mirroredBlobs:[]},subtitles:[],thumbnailSource:"generated"};return l.createItem(e),e},[l]),x=(0,Rb.useCallback)((e,t)=>{const n=l.getItem(e),s=n&&DC(n),r=t.uploadInfo??s?.uploadInfo;l.updateItem(e,{...t,...r?{uploadInfo:{...r,videos:r.videos.map(Gx)}}:{}})},[l]),k=(0,Rb.useCallback)(e=>{l.deleteItem(e)},[l]),N=(0,Rb.useCallback)(e=>{const t=l.getItem(e);return t&&DC(t)},[l]),j=(0,Rb.useCallback)((e,t)=>{c(n=>{const s=n.get(e);if(!s)return n;const r=new Map(n);return r.set(e,{...s,...t,updatedAt:Date.now()}),r}),function(e,t){const n=vC(),s=n.findIndex(t=>t.id===e);if(-1===s)return;const r={...n[s],...t,updatedAt:Date.now()};n[s]=r,xC(n)}(e,t)},[]),S=(0,Rb.useCallback)((e,t)=>{const n=i.get(e);if(n)return n;const s={id:e,draftId:e,status:"pending",createdAt:Date.now(),updatedAt:Date.now(),videoTitle:t};return c(t=>new Map(t).set(e,s)),function(e){const t=vC().filter(t=>t.id!==e.id);t.push(e),xC(t)}(s),s},[i]),C=(0,Rb.useCallback)((e,t)=>{j(e,t)},[j]),E=(0,Rb.useCallback)(e=>{const t=i.get(e);j(e,{status:"complete",completedAt:Date.now()});const n=h.current.get(e);n&&(n.session?.cancel(),h.current.delete(e)),r("transcode_complete",e,t?.videoTitle)},[j,i,r]),M=(0,Rb.useCallback)((e,t,n=!0)=>{const s=i.get(e);j(e,{status:"error",error:{message:t,retryable:n}});const a=h.current.get(e);a&&(a.session?.cancel(),h.current.delete(e)),r("transcode_error",e,s?.videoTitle,void 0,t)},[j,i,r]),I=(0,Rb.useCallback)(e=>{j(e,{status:"cancelled"});const t=h.current.get(e);t&&(t.abortController.abort(),t.session?.cancel(),h.current.delete(e))},[j]),A=(0,Rb.useCallback)(e=>{c(t=>{const n=new Map(t);return n.delete(e),n}),function(e){xC(vC().filter(t=>t.id!==e))}(e);const t=h.current.get(e);t&&(t.session?.cancel(),h.current.delete(e))},[]),P=(0,Rb.useCallback)(async e=>{const t=y.current,n=b.current;if(!t)throw new Error("User not logged in");const s=n.blossomServers?.filter(e=>e.tags.includes("initial upload")).map(e=>e.url)||[],r=n.blossomServers?.filter(e=>e.tags.includes("mirror")).map(e=>e.url)||[];if(0===s.length&&0===r.length)return e;const{sha256:a}=Zb(e.url);let o,i=a;if(i)try{const t=(await fetch(e.url,{method:"HEAD"})).headers.get("content-length");o=t?parseInt(t,10):void 0}catch{o=e.sizeMB?Math.round(1024*e.sizeMB*1024):void 0}else try{const t=await fetch(e.url,{method:"HEAD"});i=t.headers.get("x-sha-256")||void 0;const n=t.headers.get("content-length");o=n?parseInt(n,10):void 0}catch{}if(!i)return e;const c={url:e.url,sha256:i,size:o||0,type:"video/mp4",uploaded:Date.now()},l={...e},u=e.placement.directUrl??e.url;if(s.length>0)try{const e=await yx({mirrorServers:s,blob:c,signer:async e=>await t.signer.signEvent(e)});l.uploadedBlobs=e,e.length>0&&(l.url=e[0].url)}catch(f){}if(r.length>0)try{l.mirroredBlobs=await yx({mirrorServers:r,blob:c,signer:async e=>await t.signer.signEvent(e)})}catch(f){}const d=[...l.uploadedBlobs,...l.mirroredBlobs];return l.placement=Kx({primaryBlob:l.uploadedBlobs[0]??l.mirroredBlobs[0],candidateBlobs:d,directUrl:u}),l.url=l.placement.primaryBlob?.url??u,l},[]),T=(0,Rb.useCallback)(async(e,t,n,s,r,a,o="h264",i)=>{const c=y.current,l=b.current;if(!c)throw new Error("User not logged in");const u=l.relays.filter(e=>e.tags.includes("write")&&e.url).map(e=>e.url);if(0===u.length)throw new Error("No write relays configured");const d=h.current.get(e);if(!d||!d.session)throw new Error("Job not found or session missing");const f=d.session,m=s?`Submitting ${n} transcode job...`:`Broadcasting ${n} transcode request...`;let p;if(j(e,{status:"transcoding",transcodeState:{status:s?"transcoding":"bidding",dvmPubkey:s?.pubkey,inputVideoUrl:t,originalDuration:r,startedAt:Date.now(),currentResolution:n,resolutionQueue:a?.resolutions||[n],completedResolutions:a?.completed||[],message:m,statusMessages:[{timestamp:Date.now(),message:m}]}}),s&&c.signer.nip04){const e=function(e,t,n,s="h264"){const r=[["param","mode",t],["param","codec",s]];return"mp4"===t&&r.push(["param","resolution",n]),{i:[e,"url"],params:r}}(t,"mp4",n,o),r=await c.signer.nip04.encrypt(s.pubkey,JSON.stringify(e));p={kind:ih,content:r,created_at:ol(),tags:[["p",s.pubkey],["relays",...u],["encrypted"],["expiration",String(ol()+uh)]]}}else p={kind:ih,content:"",created_at:ol(),tags:[["i",t,"url"],["param","mode","mp4"],["param","resolution",n],["param","codec",o],["relays",...u],["expiration",String(ol()+uh)]]},s&&p.tags.push(["p",s.pubkey]);const g=await c.signer.signEvent(p);await Ko.publish(u,g),j(e,{transcodeState:{...w.current.get(e)?.transcodeState,requestEventId:g.id}});let v=s?.pubkey;if(!v){const t="Waiting for DVM bids...",n=w.current.get(e);j(e,{transcodeState:{...n?.transcodeState,status:"bidding",message:t,statusMessages:[...n?.transcodeState?.statusMessages||[],{timestamp:Date.now(),message:t}]}});const s=await f.collectBids(g.id);if(0===s.length)throw new Error("No DVMs responded to the request");const r=s.find(e=>"0"===e.amount||0===parseInt(e.amount)),a=r?void 0:s[0];if(a){if(!i)throw new Error(`DVM requires payment of ${Math.ceil(parseInt(a.amount)/1e3)} sats but no payment handler is configured`);await i(a),v=a.pubkey}else v=r.pubkey;a||await f.approveBid(g.id,v,u);const o=`Selected DVM ${v.substring(0,8)}...`,c=w.current.get(e);j(e,{transcodeState:{...c?.transcodeState,status:"transcoding",dvmPubkey:v,message:o,statusMessages:[...c?.transcodeState?.statusMessages||[],{timestamp:Date.now(),message:o}]}})}if(d.abortController.signal.aborted)throw new Error("Cancelled");const x=await f.subscribeToDvmResponses({requestEventId:g.id,dvmPubkey:v,originalDuration:r,requestedResolution:n,wasEncrypted:p.tags.some(e=>"encrypted"===e[0]),onFeedback:t=>{const n=w.current.get(e),s=n?.transcodeState?.statusMessages||[],r=s[s.length-1]?.message===t.message?s:[...s,{timestamp:Date.now(),message:t.message,percentage:t.percentage}];j(e,{transcodeState:{...n?.transcodeState,status:"transcoding",phase:t.phase,message:t.message,percentage:t.percentage,eta:t.eta,speed:t.speed,queuePosition:t.queuePosition,lastFeedbackAt:Date.now(),statusMessages:r}})},onSilenceWarning:()=>{const t=w.current.get(e);j(e,{transcodeState:{...t?.transcodeState,message:"DVM seems unresponsive..."}})}});if(d.abortController.signal.aborted)throw new Error("Cancelled");const k=`Copying ${n} to your servers...`,N=w.current.get(e);return j(e,{status:"mirroring",transcodeState:{...N?.transcodeState,status:"mirroring",phase:"mirroring",message:k,percentage:void 0,eta:void 0,statusMessages:[...N?.transcodeState?.statusMessages||[],{timestamp:Date.now(),message:k}]}}),{...await P(x),dvmPubkey:v}},[j,P]),R=(0,Rb.useCallback)(async(e,t,n,s,r,a,i,c,u)=>{if(!y.current)return void M(e,"User not logged in");g.current.add(e);const d={session:new dh(o.current,y.current,Ko),abortController:new AbortController,onComplete:r,onAllComplete:a};h.current.set(e,d);const f=[];try{let r;const a=jb;if(c){const e=a.get(c);r={pubkey:c,name:e?.name,about:e?.about,createdAt:e?.lastSeenAt??0}}else if(a.size>0){let e;for(const t of a.values()){if(!e){e=t;continue}const n=e.queueLength??1/0,s=t.queueLength??1/0;(se.lastSeenAt)&&(e=t)}e&&(r={pubkey:e.pubkey,name:e.name,about:e.about,createdAt:e.lastSeenAt})}for(let o=0;oe.url===p.url)){const n=[...t,p];x(e,{uploadInfo:{videos:n}})}}d.onComplete?.(p)}E(e),d.onAllComplete?.()}catch(m){if(m instanceof Error&&"Cancelled"===m.message)return void j(e,{status:"cancelled"});const t=m instanceof Error?m.message:"Unknown error";M(e,t)}finally{g.current.delete(e)}},[j,T,E,M,l,x]),U=(0,Rb.useCallback)(async(e,t,n)=>{if(h.current.has(e))return;const s=w.current.get(e);if(!s||!s.transcodeState)return;const r=s.transcodeState;if(r.startedAt&&Date.now()-r.startedAt>432e5)return void M(e,"Transcode job expired (started over 12 hours ago)");if(!y.current)return void M(e,"User not logged in");const a=new dh(o.current,y.current,Ko),i={session:a,abortController:new AbortController,onComplete:t,onAllComplete:n};h.current.set(e,i);const c=r.resolutionQueue||["720p"],u=[...r.completedResolutions||[]],d=r.currentResolution||"720p",f=c.indexOf(d);try{const t=`Resuming ${d} transcode...`;if(j(e,{status:"transcoding",transcodeState:{...r,status:"transcoding",message:t,statusMessages:[...r.statusMessages||[],{timestamp:Date.now(),message:t}]}}),r.requestEventId&&r.dvmPubkey){const t=await a.queryForExistingResult(r.requestEventId,r.dvmPubkey,r.originalDuration,d);if(t){const n=`Copying ${d} to your servers...`,s=w.current.get(e);j(e,{status:"mirroring",transcodeState:{...s?.transcodeState,status:"mirroring",message:n,statusMessages:[...s?.transcodeState?.statusMessages||[],{timestamp:Date.now(),message:n}]}});const r=await P(t);u.push(d);const a=l.getItem(e);if(a){const t=a.uploadInfo?.videos||[];if(!t.some(e=>e.url===r.url)){const n=[...t,r];x(e,{uploadInfo:{videos:n}})}}i.onComplete?.(r)}else{const t=await a.subscribeToDvmResponses({requestEventId:r.requestEventId,dvmPubkey:r.dvmPubkey,originalDuration:r.originalDuration,requestedResolution:d,onFeedback:t=>{const n=w.current.get(e),s=n?.transcodeState?.statusMessages||[],r=s[s.length-1]?.message===t.message?s:[...s,{timestamp:Date.now(),message:t.message,percentage:t.percentage}];j(e,{transcodeState:{...n?.transcodeState,status:"transcoding",phase:t.phase,message:t.message,percentage:t.percentage,eta:t.eta,speed:t.speed,queuePosition:t.queuePosition,lastFeedbackAt:Date.now(),statusMessages:r}})},onSilenceWarning:()=>{const t=w.current.get(e);j(e,{transcodeState:{...t?.transcodeState,message:"DVM seems unresponsive..."}})}}),n=`Copying ${d} to your servers...`,s=w.current.get(e);j(e,{status:"mirroring",transcodeState:{...s?.transcodeState,status:"mirroring",message:n,resolutionQueue:s?.transcodeState?.resolutionQueue||c,completedResolutions:s?.transcodeState?.completedResolutions||u,statusMessages:[...s?.transcodeState?.statusMessages||[],{timestamp:Date.now(),message:n}]}});const o=await P(t);u.push(d);const f=l.getItem(e);if(f){const t=f.uploadInfo?.videos||[];if(!t.some(e=>e.url===o.url)){const n=[...t,o];x(e,{uploadInfo:{videos:n}})}}i.onComplete?.(o)}}const n=c.slice(f>=0?f+1:0);if(n.length>0){let t;for(let s=0;se.url===f.url)){const n=[...t,f];x(e,{uploadInfo:{videos:n}})}}i.onComplete?.(f)}}E(e),i.onAllComplete?.()}catch(m){if(m instanceof Error&&"Cancelled"===m.message)return void j(e,{status:"cancelled"});const t=m instanceof Error?m.message:"Unknown error";M(e,t)}},[j,T,P,E,M,l,x]),$=(0,Rb.useCallback)(e=>{const t=h.current.get(e);t&&(t.abortController.abort(),t.session?.cancel(),h.current.delete(e)),j(e,{status:"cancelled",transcodeState:void 0})},[j]);(0,Rb.useEffect)(()=>{if(!t)return;const e=vC().filter(e=>{if("transcoding"===e.status&&e.transcodeState){const t=e.transcodeState.startedAt||e.createdAt;return Date.now()-t<432e5}return!1});e.length;for(const t of e)if("transcoding"===t.status&&t.transcodeState){if(g.current.has(t.id))continue;if(h.current.has(t.id))continue;U(t.id)}},[t,U]);const D=(0,Rb.useCallback)(e=>i.get(e),[i]),L=(0,Rb.useCallback)(e=>{const t=i.get(e);return t?function(e){if("complete"===e.status)return{phase:"done",progress:100};if("error"===e.status||"cancelled"===e.status)return{phase:"failed",progress:e.transcodeState?.percentage??e.uploadProgress?.percentage??("cancelled"===e.status?0:100),error:new Error(e.error?.message??("cancelled"===e.status?"Upload cancelled":"Upload failed"))};if("uploading"===e.status)return{phase:"uploading",progress:lN(e.uploadProgress?.percentage??0)};if("mirroring"===e.status)return{phase:"mirroring",progress:lN(e.uploadProgress?.percentage??0)};if("transcoding"===e.status&&e.transcodeState){const t=e.transcodeState.phase;return{phase:"mirroring"===t?"mirroring":"uploading"===t?"uploading":"transcoding",progress:lN(e.transcodeState.percentage??0)}}return{phase:"validating",progress:0}}(t):void 0},[i]),B=(0,Rb.useCallback)(e=>{const t=i.get(e);return!!t&&Tb.includes(t.status)},[i]),z=(0,Rb.useCallback)(e=>Array.from(i.values()).filter(t=>t.draftId===e&&Tb.includes(t.status)),[i]),F=(0,Rb.useMemo)(()=>Array.from(i.values()).some(e=>Tb.includes(e.status)),[i]),_=(0,Rb.useMemo)(()=>Array.from(i.values()).filter(e=>Tb.includes(e.status)).length,[i]),O=(0,Rb.useMemo)(()=>({tasks:i,drafts:u,currentDraftId:m,createDraft:v,updateDraft:x,deleteDraft:k,getDraft:N,setCurrentDraftId:p,refreshDrafts:d,flushNostrSync:f,registerTask:S,updateTaskProgress:C,completeTask:E,failTask:M,cancelTask:I,removeTask:A,startTranscode:R,resumeTranscode:U,cancelTranscode:$,getTask:D,getWorkflowState:L,hasActiveTask:B,getActiveTasksForDraft:z,hasActiveUploads:F,activeTaskCount:_}),[i,u,m,v,x,k,N,d,f,S,C,E,M,I,A,R,U,$,D,L,B,z,F,_]);return(0,Ub.jsx)($b.Provider,{value:O,children:e})}function BC(){const e=(0,Rb.useContext)($b);if(!e)throw new Error("useUploadManager must be used within UploadManagerProvider");return e}function zC(){return(zC=t(()=>{Rb=Be(),kC(),jC(),CC(),bu(),lu(),nu(),dl(),wN(),xN(),ow(),UC(),Ix(),dN(),tk(),uS(),$C(),Ub=Q(),$b=(0,Rb.createContext)(void 0)}))()}function FC(){return(FC=t(()=>{zC()}))()}function _C(){return(_C=t(()=>{FC()}))()}function OC(e,t,n=Bb){return Promise.race([e,new Promise(e=>setTimeout(e,n,t))])}function WC(e){return new Promise(t=>{const n=window.indexedDB.deleteDatabase(e);let s=!1;const r=e=>{s||(s=!0,t())};n.onsuccess=()=>r(),n.onerror=()=>{r()},n.onblocked=()=>{r()}})}async function VC(){const e=await async function(){return"databases"in window.indexedDB?(await OC(window.indexedDB.databases(),[])).map(e=>e.name).filter(e=>"string"==typeof e&&e.length>0):Db}();await OC(Promise.all(e.map(WC)),[])}async function qC(){if(!("caches"in window))return;const e=await OC(window.caches.keys(),[]);await OC(Promise.all(e.map(e=>window.caches.delete(e))),[])}function JC(){sessionStorage.setItem(Lb,"true"),window.location.reload()}async function HC(){return"true"===sessionStorage.getItem(Lb)&&(sessionStorage.removeItem(Lb),async function(){try{return await Promise.all([VC(),qC()]),!0}catch(e){return!1}}())}function KC(){return(KC=t(()=>{Db=["nostr-events","nostr-idb","nostube-p2p-hls-blob-cache","nostube-play-positions"],Lb="clearCacheOnLoad",Bb=5e3}))()}export{Vy as $,hf as $a,Hw as $i,BN as $n,Wu as $o,Hx as $r,_l as $s,Nj as $t,mC as A,Hb as Aa,Qa as Ac,Wv as Ai,Vh as An,gd as Ao,Nk as Ar,iu as As,zj as At,GS as B,$f as Ba,ll as Bc,Pv as Bi,XN as Bn,ad as Bo,hk as Br,nu as Bs,Hg as Bt,nC as C,sw as Ca,gl as Cc,Gv as Ci,hj as Cn,sc as Co,qp as Cr,gu as Cs,nS as Ct,pC as D,ow as Da,ro as Dc,Kv as Di,Jh as Dn,vd as Do,Ik as Dr,du as Ds,Kj as Dt,fC as E,Fb as Ea,oo as Ec,Zv as Ei,qh as En,xd as Eo,Sk as Er,fu as Es,Zj as Et,hC as F,Wf as Fa,ml as Fc,Lv as Fi,sj as Fn,ud as Fo,Pk as Fr,ru as Fs,Lj as Ft,qS as G,qc as Ga,ol as Gc,mv as Gi,GN as Gn,Ri as Go,ck as Gr,Bo as Gs,Vg as Gt,KS as H,Ef as Ha,cl as Hc,gv as Hi,Rh as Hn,sd as Ho,dk as Hr,Ko as Hs,qg as Ht,YS as I,Of as Ia,Wa as Ic,Dv as Ii,nj as In,ld as Io,bk as Ir,Vo as Is,$j as It,VS as J,kf as Ja,Fa as Jc,rv as Ji,qN as Jn,Yu as Jo,nk as Jr,_o as Js,Cj as Jt,Yy as K,vf as Ka,el as Kc,cv as Ki,KN as Kn,ed as Ko,rk as Kr,Lo as Ks,Bg as Kt,XS as L,Bf as La,fl as Lc,Tv as Li,ej as Ln,cd as Lo,yk as Lr,Zl as Ls,Zg as Lt,tC as M,aw as Ma,Ga as Mc,zv as Mi,aj as Mn,qi as Mo,Mk as Mr,ii as Ms,Fj as Mt,iC as N,Qb as Na,pl as Nc,Fv as Ni,oj as Nn,Vi as No,Ak as Nr,ou as Ns,Oj as Nt,sC as O,nw as Oa,so as Oc,Hv as Oi,Kh as On,yd as Oo,xk as Or,uu as Os,Gj as Ot,oC as P,zb as Pa,Ja as Pc,$v as Pi,QN as Pn,fd as Po,Rk as Pr,su as Ps,Dj as Pt,FS as Q,bf as Qa,jm as Qi,FN as Qn,Hu as Qo,Bp as Qr,ql as Qs,kj as Qt,tb as R,zf as Ra,nl as Rc,Uv as Ri,tj as Rn,id as Ro,gk as Rr,Ho as Rs,Lg as Rt,cC as S,tw as Sa,fo as Sc,Qv as Si,gj as Sn,Nd as So,Zk as Sr,yu as Ss,lS as St,rC as T,ew as Ta,no as Tc,tx as Ti,Hh as Tn,wd as To,Ek as Tr,mu as Ts,tS as Tt,Xy as U,If as Ua,dl as Uc,hv as Ui,YN as Un,nd as Uo,uk as Ur,Ql as Us,Wg as Ut,HS as V,Uf as Va,Oa as Vc,Av as Vi,ZN as Vn,rd as Vo,mk as Vr,Zo as Vs,_g as Vt,JS as W,Mf as Wa,rl as Wc,pv as Wi,Ih as Wn,Ti as Wo,lk as Wr,Fo as Ws,Og as Wt,OS as X,jf as Xa,Ra as Xc,tv as Xi,WN as Xn,Xu as Xo,Yx as Xr,Do as Xs,Mj as Xt,_S as Y,xf as Ya,Da as Yc,sv as Yi,VN as Yn,Zu as Yo,Kx as Yr,Oo as Ys,Ej as Yt,zS as Z,Nf as Za,Qc as Zc,nv as Zi,_N as Zn,Ku as Zo,tk as Zr,Ol as Zs,Ij as Zt,lb as _,yw as _a,bo as _c,ox as _i,dg as _n,Wd as _o,oN as _r,Nu as _s,Ny as _t,FC as a,_w as aa,Bl as ac,Ex as ai,Ng as an,sf as ao,MN as ar,Bu as as,zy as at,dC as b,cw as ba,mo as bc,Xv as bi,ig as bn,jd as bo,rN as br,vu as bs,wS as bt,BC as c,Bw as ca,Ul as cc,yx as ci,Eg as cn,Qd as co,jN as cr,$u as cs,DS as ct,CC as d,Tw as da,Al as dc,fx as di,wg as dn,Xd as do,yN as dr,Ru as ds,Py as dt,Jw as ea,Ro as ec,Lx as ei,Ig as en,lf as eo,LN as er,Gu as es,qy as et,SC as f,kw as fa,Nl as fc,dx as fi,bg as fn,Kd as fo,wN as fr,Tu as fs,RS as ft,fb as g,bw as ga,wo as gc,ix as gi,mg as gn,Od as go,mN as gr,ju as gs,AS as gt,ub as h,ww as ha,yo as hc,ax as hi,pg as hn,qd as ho,pN as hr,Su as hs,IS as ht,_C as i,Ow as ia,Fl as ic,Ax as ii,Cg as in,af as io,IN as ir,zu as is,$y as it,lC as j,Kb as ja,hl as jc,_v as ji,cj as jn,Wi as jo,Ck as jr,cu as js,_j as jt,eC as k,Yb as ka,ao as kc,Vv as ki,Gh as kn,hd as ko,jk as kr,lu as ks,ty as kt,UC as l,Lw as la,Tl as lc,px as li,vj as ln,Zd as lo,NN as lr,Du as ls,$S as lt,yC as m,vw as ma,Il as mc,cx as mi,ug as mn,Jd as mo,hN as mr,Mu as ms,TS as mt,JC as n,Vw as na,Po as nc,Wx as ni,kg as nn,df as no,UN as nr,_u as ns,LS as nt,LC as o,Fw as oa,Ll as oc,Mx as oi,Mg as on,tf as oo,EN as or,Lu as os,Fy as ot,hb as p,xw as pa,Ml as pc,lx as pi,wj as pn,Hd as po,gN as pr,Iu as ps,PS as pt,WS as q,wf as qa,tl as qc,fv as qi,JN as qn,td as qo,ak as qr,Jl as qs,Aj as qt,KC as r,Ww as ra,zl as rc,Px as ri,Sg as rn,rf as ro,AN as rr,Fu as rs,BS as rt,zC as s,zw as sa,Dl as sc,Ix as si,jg as sn,ef as so,CN as sr,Uu as ss,_y as st,HC as t,qw as ta,To as tc,Vx as ti,xj as tn,cf as to,$N as tr,Ou as ts,Wy as tt,RC as u,Rw as ua,Pl as uc,mx as ui,yg as un,Yd as uo,oh as ur,Pu as us,US as ut,db as v,hw as va,yl as vc,sx as vi,fg as vn,_d as vo,aN as vr,ku as vs,CS as vt,aC as w,Zb as wa,Za as wc,Yv as wi,Wh as wn,kd as wo,kk as wr,hu as ws,sS as wt,uC as x,iw as xa,uo as xc,ex as xi,yj as xn,Md as xo,Gk as xr,bu as xs,uS as xt,gC as y,mw as ya,lo as yc,nx as yi,bj as yn,Vd as yo,iN as yr,xu as ys,bS as yt,nb as z,Lf as za,al as zc,Rv as zi,rj as zn,od as zo,fk as zr,tu as zs,Jg as zt};