| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354 |
- const __vite__fileDeps=["./chart-BIax9IsQ.js","./chart-CQQX2xOH.css","./mainTab-RurqNRXZ.js","./index-D_EGaVbS.js","./index-BQW3n_1i.css","./actions-BE1af_U3.js","./staticSwitch-C6FESQ3t.js","./staticSwitch-SO3mb_aI.css","./chatBackground-j-mSAtH4.js","./chatBackground-DT3l-EOo.css","./lottieAnimation-CTSJfq7Q.js","./lottieAnimation-Bh8Z3Bb3.css","./page-C6VUMrJP.js","./avatar-C4f7PAeP.js","./putPreloader-NOkcnuw_.js","./htmlToSpan-DhAls8qz.js","./textToSvgURL-Cnw_Q8Rw.js","./fastBlur-Co-79rP4.js","./countryInputField-yId9tpyt.js","./_commonjsHelpers-Cpj98o6Y.js","./codeInputField-4XE97kZh.js","./mainTab-B5uVZY8i.css","./enterPasswordTab-CiYs0tJz.js","./tab--r1i_QxL.js","./starsRangeInput-DUKz4CVH.js","./starsRangeInput-Cd-JjoxX.css","./tab-BgmK3oT5.css","./chargeForMessasgesSection-C_HrZ24y.js"],__vite__mapDeps=i=>i.map(i=>__vite__fileDeps[i]);
- var rL=Object.defineProperty;var oL=(a,e,t)=>e in a?rL(a,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):a[e]=t;var ro=(a,e,t)=>(oL(a,typeof e!="symbol"?e+"":e,t),t),Hw=(a,e,t)=>{if(!e.has(a))throw TypeError("Cannot "+t)};var ls=(a,e,t)=>(Hw(a,e,"read from private field"),t?t.call(a):e.get(a)),Ks=(a,e,t)=>{if(e.has(a))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(a):e.set(a,t)},ss=(a,e,t,s)=>(Hw(a,e,"write to private field"),s?s.call(a,t):e.set(a,t),t);import{g as ks,d as Be,a2 as Y,ac as le,ae as Vt,r as I,af as Mc,m as st,ag as ai,ah as lL,ai as Ae,I as Ne,aj as Yi,i as P,ak as Mo,al as Fy,am as Wt,an as cL,ao as DC,w as je,ap as Xd,aq as By,ar as jt,as as Bo,at as Lc,au as El,av as Qr,aw as Ec,a5 as V,J as Mt,ax as Ot,ay as pi,az as Ft,aA as Ho,W as ze,U as K,aB as Ht,aC as Dy,aD as Ya,aE as Gw,aF as ku,aG as mv,aH as Qt,aI as om,aJ as $y,aK as Ny,aL as Vs,aM as Xr,aN as Tu,aO as Gr,aP as Nt,c as St,aQ as Oy,f as Ns,aR as dL,k as Ei,aS as md,aT as Vn,aU as lm,H as wt,n as _e,e as J,aV as mr,M as $s,aW as Uy,aX as gv,aY as $C,aZ as ha,a_ as ii,a$ as hL,b0 as uL,b1 as Do,b2 as fs,b3 as as,b4 as pL,b5 as Ls,Y as k,Z as T,V as Me,b6 as Es,b7 as ne,$ as be,a1 as er,a0 as Js,X as Ue,b8 as so,R as ni,b9 as Vw,ba as zw,j as Vr,bb as Lo,bc as yi,bd as mL,be as en,bf as Ka,x as ue,bg as Go,t as os,bh as pn,bi as Hy,N as Mi,h as pt,bj as Eo,bk as wr,bl as Pt,bm as vn,u as ns,bn as Gi,bo as $o,bp as $t,B as ot,bq as NC,br as Qs,bs as zt,bt as Wl,E as hi,bu as hn,bv as tn,bw as _n,bx as cm,by as Ni,A as _o,y as Yt,z as yt,bz as OC,bA as Rh,bB as Kl,G as Bn,bC as Vo,bD as Rn,bE as vi,bF as dm,bG as ra,bH as UC,bI as It,p as Ki,s as jl,a as xu,bJ as ji,bK as kn,bL as No,bM as gL,bN as Xs,bO as Zd,bP as tr,L as hm,O as Di,bQ as Pn,bR as oa,_ as zo,bS as ug,bT as Fi,bU as ci,bV as yn,bW as HC,bX as GC,bY as dn,bZ as on,b_ as Ut,b$ as ua,c0 as fL,c1 as VC,c2 as Fh,c3 as Sn,c4 as Gy,c5 as gr,c6 as Au,c7 as zr,c8 as gs,c9 as vL,ca as Wo,cb as wi,cc as yL,cd as wa,ce as zC,a4 as Jt,cf as pg,cg as bL,ch as Vy,ci as pa,cj as zy,ck as Bh,a8 as fn,cl as wL,cm as WC,ab as fa,cn as mg,co as ql,cp as Ko,cq as Up,cr as Wy,cs as KC,ct as sr,cu as SL,cv as CL,cw as Ru,cx as _L,cy as IL,cz as jC,cA as Dh,a7 as gd,cB as Ii,cC as fv,cD as PL,P as gg,cE as ML,aa as ma,a3 as Fs,cF as Cs,a6 as Lr,cG as qC,cH as YC,cI as An,cJ as $h,cK as Or,cL as bl,cM as Pa,cN as Jd,cO as Nh,cP as LL,cQ as Zr,cR as vv,cS as Oh,cT as Fu,cU as fg,cV as Ky,cW as lh,cX as jy,cY as EL,cZ as yv,c_ as kL,c$ as Wr,d0 as TL,d1 as QC,d2 as XC,d3 as vg,d4 as qy,d5 as yg,d6 as xL,d7 as Yy,d8 as xn,d9 as bg,Q as Bu,da as Uh,db as AL,dc as Qy,dd as RL,de as wg,ad as zi,df as Ww,dg as js,dh as Xy,di as Kw,dj as fd,dk as us,dl as Qa,dm as ul,dn as Kc,dp as Hh,dq as bv,a9 as FL,dr as ZC,ds as JC,dt as e_,du as ch,dv as ka,dw as jc,dx as wv,dy as BL,dz as DL,dA as io,dB as $L,dC as jw,dD as NL,dE as um,dF as Hp,dG as Gh,dH as Mn,dI as Sv,dJ as qr,dK as OL,K as Al,dL as t_,dM as Zy,dN as UL,dO as s_,dP as i_,dQ as n_,b as Fa,dR as HL,dS as GL,dT as Cv,dU as _v,dV as fo,dW as VL,dX as Iv,dY as zL,dZ as WL,d_ as pp,d$ as KL,e0 as Pv,e1 as a_,e2 as jL,e3 as r_,e4 as qL,e5 as YL,e6 as QL,e7 as XL,e8 as ZL,e9 as JL,ea as Jy,eb as Mv,ec as mp,ed as eE,ee as tE,ef as sE,eg as iE,eh as nE,ei as qw,ej as eb,ek as Vh,el as Sg,em as o_,en as aE,eo as Yw,ep as rE,v as l_,eq as oE,er as Zi,es as On,et as lE,eu as cE,ev as dE,ew as hE,ex as c_,ey as Lv,ez as fc,eA as uE,eB as wl,eC as pE,eD as mE,eE as d_,eF as gE,eG as fE,eH as ea,o as Qw,eI as pm,eJ as mm,q as vc,eK as vE,eL as yE,eM as bE,eN as wE,eO as h_,eP as SE,eQ as Xw,eR as CE,eS as Zw,eT as gp,F as Jw,eU as _E,C as pf,eV as IE,eW as PE,eX as ME,eY as eS,eZ as Ev,e_ as LE,e$ as EE,f0 as kE,f1 as TE,f2 as xE,f3 as AE,f4 as tS,f5 as RE,f6 as FE,f7 as mf,f8 as BE,f9 as DE,fa as $E,fb as NE,fc as OE,fd as u_,fe as UE,ff as HE}from"./index-D_EGaVbS.js";import{T as Sr,h as vd}from"./page-C6VUMrJP.js";import{P as p_,r as GE}from"./avatar-C4f7PAeP.js";import{s as tb,p as Yn,P as VE}from"./putPreloader-NOkcnuw_.js";import{s as Ta,c as Ge,r as yd,a as sb,T as Du,C as zE,S as Kr,u as WE,b as kc,d as m_,e as kv,g as KE,h as g_,i as ib,f as f_,j as jE,k as qE}from"./chatBackground-j-mSAtH4.js";import{h as nb}from"./htmlToSpan-DhAls8qz.js";import{t as YE,b as QE}from"./textToSvgURL-Cnw_Q8Rw.js";import XE from"./fastBlur-Co-79rP4.js";import{C as ZE,f as bd,T as v_,a as JE}from"./countryInputField-yId9tpyt.js";import{g as ek}from"./_commonjsHelpers-Cpj98o6Y.js";import{C as tk,T as sk}from"./codeInputField-4XE97kZh.js";function y_(a){const e=document.createElement("span");return e.classList.add("badge-fake"),ks(e,a?"ScamMessage":"FakeMessage"),e}function ik(){return Be("star","premium-icon")}function nk(){const a=document.createElement("span");a.classList.add("verified-icon");const e=26,t=document.createElementNS("http://www.w3.org/2000/svg","svg");t.setAttributeNS(null,"viewBox",`0 0 ${e} ${e}`),t.setAttributeNS(null,"width",`${e}`),t.setAttributeNS(null,"height",`${e}`),t.classList.add("verified-icon-svg");const s=document.createElementNS("http://www.w3.org/2000/svg","use");s.setAttributeNS(null,"href","#verified-icon-background"),s.classList.add("verified-icon-background");const i=document.createElementNS("http://www.w3.org/2000/svg","use");return i.setAttributeNS(null,"href","#verified-icon-check"),i.classList.add("verified-icon-check"),t.append(i,s),a.append(t),a}const ak=[{x:20,y:0,scale:1,delay:500},{x:15,y:15,scale:.75,delay:3500},{x:10,y:35,scale:.75,delay:4500},{x:20,y:70,scale:1.25,delay:1500},{x:40,y:10,scale:1.25,delay:0},{x:45,y:60,scale:.75,delay:3e3},{x:60,y:-10,scale:1,delay:1e3},{x:55,y:40,scale:.75,delay:3e3},{x:70,y:65,scale:1,delay:4500},{x:80,y:10,scale:.75,delay:1500},{x:80,y:45,scale:1.25,delay:0}].map(a=>({...a,translateX:Math.cos(Math.atan2(-50+a.y,-50+a.x))*100,translateY:Math.sin(Math.atan2(-50+a.y,-50+a.x))*100}));function rk(){return{x:Math.random()*100,y:Math.random()*100,translateX:(Math.random()*5+15)*100,translateY:(Math.random()*10-5)*100,scale:Math.random()*.5+.5,delay:Math.random()*5e3}}const ok=Y('<svg viewBox="0 0 7 7" xmlns="http://www.w3.org/2000/svg" height="1em" width="1em"><use href="#star-sparkle"></use></svg>');function sS(a,e){let t;return e?(t=document.createElement("div"),t.textContent="✦"):t=ok(),t.classList.add("sparkles-sparkle"),t.style.setProperty("--sparkle-tx",a.translateX+"%"),t.style.setProperty("--sparkle-ty",a.translateY+"%"),t.style.setProperty("--sparkle-scale",a.scale*(Math.random()*.5+.25)+""),t.style.setProperty("--sparkle-rotate",(Math.random()*90-45)*4+"deg"),t.style.transform=`scale(${a.scale})`,t.style.top=a.y+"%",t.style.left=a.x+"%",t.style.animationDelay="-"+a.delay+"ms",t}function Rl(a){const e=document.createElement("div");return e.classList.add("sparkles-container"),a.mode==="button"?e.append(...ak.map(t=>sS(t,a.isDiv))):le(Vt(()=>a.count,(t,s=0)=>{const i=t-s;if(i>0)for(let n=0;n<i;n++)e.appendChild(sS(rk(),a.isDiv));else if(i<0)for(let n=0;n<-i;n++)e.lastChild.remove()})),e}async function b_({wrapOptions:a,emojiStatus:e,size:t=st.active.emojiStatus}){const{middleware:s,animationGroup:i,textColor:n}=a,r=document.createElement("span");r.classList.add("emoji-status");const o=await I.managers.acknowledged.appEmojiManager.getCustomEmojiDocument(e.document_id),l=async d=>{if(!s())return;const u=[],h=d.attributes.find(p=>p._==="documentAttributeCustomEmoji");h&&h.pFlags.text_color&&r.classList.add("emoji-status-text-color"),await ai({doc:d,div:r,width:t.width,height:t.height,loop:2,play:!0,group:i||"EMOJI-STATUS",loadPromises:u,middleware:s,static:d.mime_type==="video/webm"&&!lL,textColor:n||"primary-color"}),s()&&await Promise.all(u)};if(e._==="emojiStatusCollectible"&&(r.appendChild(Rl({mode:"button",isDiv:!0})),r.style.setProperty("--sparkles-color",Mc(e.center_color))),!s())return r;const c=o.result.then(l);return o.cached&&await c,r}async function Tv({peerId:a,noVerifiedIcon:e,noFakeIcon:t,noPremiumIcon:s,peer:i,wrapOptions:n}){i??(i=Ae.getPeer(a));const r=[];if(!i)return r;if((i.pFlags.fake||i.pFlags.scam)&&!t&&r.push(y_(i.pFlags.scam)),!s&&n?.middleware){const o=i.emoji_status,l=await Ae.isPremiumFeaturesHidden();if(o&&"document_id"in o&&!l){const{middleware:c}=n,d=await b_({emojiStatus:o,wrapOptions:n});if(!c())return r;r.push(d)}else i.pFlags.premium&&!l&&r.push(ik())}return i.pFlags.verified&&!e&&r.push(nk()),r}var Hn=(a=>(a[a.Seconds=0]="Seconds",a[a.Minutes=1]="Minutes",a[a.Hours=2]="Hours",a[a.Days=3]="Days",a[a.Weeks=4]="Weeks",a[a.Months=5]="Months",a[a.Years=6]="Years",a))(Hn||{});function Yl(a,e=2){a||(a=1);const t=[],s=[{m:1,t:0},{m:60,t:1},{m:60,t:2},{m:24,t:3},{m:7,t:4}];let n=1;s.forEach((o,l)=>{if(n=Math.round(n*o.m),a<n)return;let c=a/n;if(l!==s.length-1){const d=s[l===s.length-1?l:l+1].m;c%=d}t.push({duration:c|0,type:o.t})});const r=t.slice(-e).reverse();for(let o=r.length-1;o>=0;--o)r[o].duration===0&&r.splice(o,1);return r}function bn(a,e=!1){const t=parseInt(a+"",10);let s=Math.floor(t/3600),i=Math.floor((t-s*3600)/60),n=t-s*3600-i*60;return s&&s<10&&e&&(s="0"+s),i<10&&(s||e)&&(i="0"+i),n<10&&(n="0"+n),(s?s+":":"")+i+":"+n}const iS={[Hn.Seconds]:"Seconds",[Hn.Minutes]:"Minutes",[Hn.Hours]:"Hours",[Hn.Days]:"Days",[Hn.Weeks]:"Weeks",[Hn.Months]:"Months",[Hn.Years]:"Years"};function wd(a,e){if(e){const i=a.map(n=>Ne.format(iS[n.type],!0,[n.duration]));return Yi(i,!1,e)}const t=a.map(i=>P(iS[i.type],[i.duration])),s=document.createElement("span");return s.append(...Yi(t,!1)),s}function Gp(a,e){return wd(Yl(a,2),e)}function w_(a){const e=Yl(a,3);return e[0].type<=Hn.Hours?bn(a,!0):(e.splice(1,1/0),wd(e))}function S_(a){const e=Yl(a,3);return e[0].type===Hn.Seconds?wd(e):bn(a,!0)}const C_={AED:{code:"AED",title:"United Arab Emirates Dirham",symbol:"AED",native:"د.إ.",thousands_sep:",",decimal_sep:".",symbol_left:!0,space_between:!0,drop_zeros:!1,exp:2,min_amount:"367",max_amount:"3673020"},AFN:{code:"AFN",title:"Afghan Afghani",symbol:"AFN",native:"؋",thousands_sep:",",decimal_sep:".",symbol_left:!0,space_between:!1,drop_zeros:!1,exp:2,min_amount:"7092",max_amount:"70919694"},ALL:{code:"ALL",title:"Albanian Lek",symbol:"ALL",native:"Lek",thousands_sep:".",decimal_sep:",",symbol_left:!1,space_between:!1,drop_zeros:!1,exp:2,min_amount:"9249",max_amount:"92485282"},AMD:{code:"AMD",title:"Armenian Dram",symbol:"AMD",native:"դր.",thousands_sep:",",decimal_sep:".",symbol_left:!1,space_between:!0,drop_zeros:!1,exp:2,min_amount:"38785",max_amount:"387850064"},ARS:{code:"ARS",title:"Argentine Peso",symbol:"ARS",native:"$",thousands_sep:".",decimal_sep:",",symbol_left:!0,space_between:!0,drop_zeros:!1,exp:2,min_amount:"93178",max_amount:"931784401"},AUD:{code:"AUD",title:"Australian Dollar",symbol:"AU$",native:"$",thousands_sep:",",decimal_sep:".",symbol_left:!0,space_between:!1,drop_zeros:!1,exp:2,min_amount:"153",max_amount:"1534530"},AZN:{code:"AZN",title:"Azerbaijani Manat",symbol:"AZN",native:"ман.",thousands_sep:" ",decimal_sep:",",symbol_left:!1,space_between:!0,drop_zeros:!1,exp:2,min_amount:"170",max_amount:"1700517"},BAM:{code:"BAM",title:"Bosnia & Herzegovina Convertible Mark",symbol:"BAM",native:"KM",thousands_sep:".",decimal_sep:",",symbol_left:!1,space_between:!0,drop_zeros:!1,exp:2,min_amount:"181",max_amount:"1806101"},BDT:{code:"BDT",title:"Bangladeshi Taka",symbol:"BDT",native:"৳",thousands_sep:",",decimal_sep:".",symbol_left:!0,space_between:!0,drop_zeros:!1,exp:2,min_amount:"11744",max_amount:"117439546"},BGN:{code:"BGN",title:"Bulgarian Lev",symbol:"BGN",native:"лв.",thousands_sep:" ",decimal_sep:",",symbol_left:!1,space_between:!0,drop_zeros:!1,exp:2,min_amount:"181",max_amount:"1808709"},BND:{code:"BND",title:"Brunei Dollar",symbol:"BND",native:"$",thousands_sep:".",decimal_sep:",",symbol_left:!0,space_between:!1,drop_zeros:!1,exp:2,min_amount:"133",max_amount:"1330735"},BOB:{code:"BOB",title:"Bolivian Boliviano",symbol:"BOB",native:"Bs",thousands_sep:".",decimal_sep:",",symbol_left:!0,space_between:!0,drop_zeros:!1,exp:2,min_amount:"691",max_amount:"6906359"},BRL:{code:"BRL",title:"Brazilian Real",symbol:"R$",native:"R$",thousands_sep:".",decimal_sep:",",symbol_left:!0,space_between:!0,drop_zeros:!1,exp:2,min_amount:"577",max_amount:"5769050"},BYN:{code:"BYN",title:"Belarusian ruble",symbol:"BYN",native:"BYN",thousands_sep:" ",decimal_sep:",",symbol_left:!1,space_between:!0,drop_zeros:!1,exp:2,min_amount:"327",max_amount:"3270247"},CAD:{code:"CAD",title:"Canadian Dollar",symbol:"CA$",native:"$",thousands_sep:",",decimal_sep:".",symbol_left:!0,space_between:!1,drop_zeros:!1,exp:2,min_amount:"139",max_amount:"1387645"},CHF:{code:"CHF",title:"Swiss Franc",symbol:"CHF",native:"CHF",thousands_sep:"'",decimal_sep:".",symbol_left:!1,space_between:!0,drop_zeros:!1,exp:2,min_amount:"87",max_amount:"870429"},CLP:{code:"CLP",title:"Chilean Peso",symbol:"CLP",native:"$",thousands_sep:".",decimal_sep:",",symbol_left:!0,space_between:!0,drop_zeros:!1,exp:0,min_amount:"949",max_amount:"9486298"},CNY:{code:"CNY",title:"Chinese Renminbi Yuan",symbol:"CN¥",native:"CN¥",thousands_sep:",",decimal_sep:".",symbol_left:!0,space_between:!1,drop_zeros:!1,exp:2,min_amount:"721",max_amount:"7207705"},COP:{code:"COP",title:"Colombian Peso",symbol:"COP",native:"$",thousands_sep:".",decimal_sep:",",symbol_left:!0,space_between:!0,drop_zeros:!1,exp:2,min_amount:"408665",max_amount:"4086650000"},CRC:{code:"CRC",title:"Costa Rican Colón",symbol:"CRC",native:"₡",thousands_sep:".",decimal_sep:",",symbol_left:!0,space_between:!1,drop_zeros:!1,exp:2,min_amount:"52313",max_amount:"523125084"},CZK:{code:"CZK",title:"Czech Koruna",symbol:"CZK",native:"Kč",thousands_sep:" ",decimal_sep:",",symbol_left:!1,space_between:!0,drop_zeros:!1,exp:2,min_amount:"2332",max_amount:"23323050"},DKK:{code:"DKK",title:"Danish Krone",symbol:"DKK",native:"kr",thousands_sep:"",decimal_sep:",",symbol_left:!1,space_between:!0,drop_zeros:!1,exp:2,min_amount:"689",max_amount:"6887630"},DOP:{code:"DOP",title:"Dominican Peso",symbol:"DOP",native:"$",thousands_sep:",",decimal_sep:".",symbol_left:!0,space_between:!1,drop_zeros:!1,exp:2,min_amount:"5945",max_amount:"59453394"},DZD:{code:"DZD",title:"Algerian Dinar",symbol:"DZD",native:"د.ج.",thousands_sep:",",decimal_sep:".",symbol_left:!0,space_between:!0,drop_zeros:!1,exp:2,min_amount:"13449",max_amount:"134492834"},EGP:{code:"EGP",title:"Egyptian Pound",symbol:"EGP",native:"ج.م.",thousands_sep:",",decimal_sep:".",symbol_left:!0,space_between:!0,drop_zeros:!1,exp:2,min_amount:"4869",max_amount:"48686201"},ETB:{code:"ETB",title:"Ethiopian Birr",symbol:"ETB",native:"ብር",thousands_sep:",",decimal_sep:".",symbol_left:!0,space_between:!1,drop_zeros:!1,exp:2,min_amount:"8093",max_amount:"80931744"},EUR:{code:"EUR",title:"Euro",symbol:"€",native:"€",thousands_sep:" ",decimal_sep:",",symbol_left:!1,space_between:!0,drop_zeros:!1,exp:2,min_amount:"92",max_amount:"923025"},GBP:{code:"GBP",title:"British Pound",symbol:"£",native:"£",thousands_sep:",",decimal_sep:".",symbol_left:!0,space_between:!1,drop_zeros:!1,exp:2,min_amount:"78",max_amount:"784671"},GEL:{code:"GEL",title:"Georgian Lari",symbol:"GEL",native:"GEL",thousands_sep:" ",decimal_sep:",",symbol_left:!1,space_between:!0,drop_zeros:!1,exp:2,min_amount:"271",max_amount:"2709634"},GTQ:{code:"GTQ",title:"Guatemalan Quetzal",symbol:"GTQ",native:"Q",thousands_sep:",",decimal_sep:".",symbol_left:!0,space_between:!1,drop_zeros:!1,exp:2,min_amount:"775",max_amount:"7745760"},HKD:{code:"HKD",title:"Hong Kong Dollar",symbol:"HK$",native:"$",thousands_sep:",",decimal_sep:".",symbol_left:!0,space_between:!1,drop_zeros:!1,exp:2,min_amount:"781",max_amount:"7810275"},HNL:{code:"HNL",title:"Honduran Lempira",symbol:"HNL",native:"L",thousands_sep:",",decimal_sep:".",symbol_left:!0,space_between:!0,drop_zeros:!1,exp:2,min_amount:"2474",max_amount:"24741783"},HRK:{code:"HRK",title:"Croatian Kuna",symbol:"HRK",native:"kn",thousands_sep:".",decimal_sep:",",symbol_left:!1,space_between:!0,drop_zeros:!1,exp:2,min_amount:"691",max_amount:"6907950"},HUF:{code:"HUF",title:"Hungarian Forint",symbol:"HUF",native:"Ft",thousands_sep:" ",decimal_sep:",",symbol_left:!1,space_between:!0,drop_zeros:!1,exp:2,min_amount:"36623",max_amount:"366225500"},IDR:{code:"IDR",title:"Indonesian Rupiah",symbol:"IDR",native:"Rp",thousands_sep:".",decimal_sep:",",symbol_left:!0,space_between:!1,drop_zeros:!1,exp:2,min_amount:"1620255",max_amount:"16202550000"},ILS:{code:"ILS",title:"Israeli New Sheqel",symbol:"₪",native:"₪",thousands_sep:",",decimal_sep:".",symbol_left:!0,space_between:!0,drop_zeros:!1,exp:2,min_amount:"380",max_amount:"3801205"},INR:{code:"INR",title:"Indian Rupee",symbol:"₹",native:"₹",thousands_sep:",",decimal_sep:".",symbol_left:!0,space_between:!1,drop_zeros:!1,exp:2,min_amount:"8374",max_amount:"83744750"},ISK:{code:"ISK",title:"Icelandic Króna",symbol:"ISK",native:"kr",thousands_sep:".",decimal_sep:",",symbol_left:!1,space_between:!0,drop_zeros:!1,exp:0,min_amount:"139",max_amount:"1389014"},JMD:{code:"JMD",title:"Jamaican Dollar",symbol:"JMD",native:"$",thousands_sep:",",decimal_sep:".",symbol_left:!0,space_between:!1,drop_zeros:!1,exp:2,min_amount:"15637",max_amount:"156368606"},JPY:{code:"JPY",title:"Japanese Yen",symbol:"¥",native:"¥",thousands_sep:",",decimal_sep:".",symbol_left:!0,space_between:!1,drop_zeros:!1,exp:0,min_amount:"149",max_amount:"1490865"},KES:{code:"KES",title:"Kenyan Shilling",symbol:"KES",native:"Ksh",thousands_sep:",",decimal_sep:".",symbol_left:!0,space_between:!1,drop_zeros:!1,exp:2,min_amount:"12996",max_amount:"129960065"},KGS:{code:"KGS",title:"Kyrgyzstani Som",symbol:"KGS",native:"KGS",thousands_sep:" ",decimal_sep:"-",symbol_left:!1,space_between:!0,drop_zeros:!1,exp:2,min_amount:"8403",max_amount:"84030175"},KRW:{code:"KRW",title:"South Korean Won",symbol:"₩",native:"₩",thousands_sep:",",decimal_sep:".",symbol_left:!0,space_between:!1,drop_zeros:!1,exp:0,min_amount:"1367",max_amount:"13667698"},KZT:{code:"KZT",title:"Kazakhstani Tenge",symbol:"KZT",native:"₸",thousands_sep:" ",decimal_sep:"-",symbol_left:!0,space_between:!1,drop_zeros:!1,exp:2,min_amount:"47435",max_amount:"474353706"},LBP:{code:"LBP",title:"Lebanese Pound",symbol:"LBP",native:"ل.ل.",thousands_sep:",",decimal_sep:".",symbol_left:!0,space_between:!0,drop_zeros:!1,exp:2,min_amount:"8950019",max_amount:"89500191612"},LKR:{code:"LKR",title:"Sri Lankan Rupee",symbol:"LKR",native:"රු.",thousands_sep:",",decimal_sep:".",symbol_left:!0,space_between:!0,drop_zeros:!1,exp:2,min_amount:"30176",max_amount:"301757853"},MAD:{code:"MAD",title:"Moroccan Dirham",symbol:"MAD",native:"د.م.",thousands_sep:",",decimal_sep:".",symbol_left:!0,space_between:!0,drop_zeros:!1,exp:2,min_amount:"987",max_amount:"9874277"},MDL:{code:"MDL",title:"Moldovan Leu",symbol:"MDL",native:"MDL",thousands_sep:",",decimal_sep:".",symbol_left:!1,space_between:!0,drop_zeros:!1,exp:2,min_amount:"1777",max_amount:"17770719"},MMK:{code:"MMK",title:"Myanmar kyat",symbol:"MMK",native:"MMK",thousands_sep:",",decimal_sep:".",symbol_left:!0,space_between:!1,drop_zeros:!1,exp:2,min_amount:"324796",max_amount:"3247960992"},MNT:{code:"MNT",title:"Mongolian Tögrög",symbol:"MNT",native:"MNT",thousands_sep:" ",decimal_sep:",",symbol_left:!0,space_between:!1,drop_zeros:!1,exp:2,min_amount:"345000",max_amount:"3450000346"},MOP:{code:"MOP",title:"Macanese pataca",symbol:"MOP",native:"MOP",thousands_sep:",",decimal_sep:".",symbol_left:!0,space_between:!1,drop_zeros:!1,exp:2,min_amount:"804",max_amount:"8040613"},MUR:{code:"MUR",title:"Mauritian Rupee",symbol:"MUR",native:"MUR",thousands_sep:",",decimal_sep:".",symbol_left:!0,space_between:!1,drop_zeros:!1,exp:2,min_amount:"4675",max_amount:"46749662"},MVR:{code:"MVR",title:"Maldivian Rufiyaa",symbol:"MVR",native:"MVR",thousands_sep:",",decimal_sep:".",symbol_left:!1,space_between:!0,drop_zeros:!1,exp:2,min_amount:"1535",max_amount:"15350296"},MXN:{code:"MXN",title:"Mexican Peso",symbol:"MX$",native:"$",thousands_sep:",",decimal_sep:".",symbol_left:!0,space_between:!1,drop_zeros:!1,exp:2,min_amount:"1898",max_amount:"18980550"},MYR:{code:"MYR",title:"Malaysian Ringgit",symbol:"MYR",native:"RM",thousands_sep:",",decimal_sep:".",symbol_left:!0,space_between:!1,drop_zeros:!1,exp:2,min_amount:"450",max_amount:"4497502"},MZN:{code:"MZN",title:"Mozambican Metical",symbol:"MZN",native:"MTn",thousands_sep:",",decimal_sep:".",symbol_left:!0,space_between:!1,drop_zeros:!1,exp:2,min_amount:"6390",max_amount:"63899991"},NGN:{code:"NGN",title:"Nigerian Naira",symbol:"NGN",native:"₦",thousands_sep:",",decimal_sep:".",symbol_left:!0,space_between:!1,drop_zeros:!1,exp:2,min_amount:"163953",max_amount:"1639530235"},NIO:{code:"NIO",title:"Nicaraguan Córdoba",symbol:"NIO",native:"C$",thousands_sep:",",decimal_sep:".",symbol_left:!0,space_between:!0,drop_zeros:!1,exp:2,min_amount:"3679",max_amount:"36791630"},NOK:{code:"NOK",title:"Norwegian Krone",symbol:"NOK",native:"kr",thousands_sep:" ",decimal_sep:",",symbol_left:!0,space_between:!0,drop_zeros:!1,exp:2,min_amount:"1100",max_amount:"10996470"},NPR:{code:"NPR",title:"Nepalese Rupee",symbol:"NPR",native:"नेरू",thousands_sep:",",decimal_sep:".",symbol_left:!0,space_between:!1,drop_zeros:!1,exp:2,min_amount:"13390",max_amount:"133897859"},NZD:{code:"NZD",title:"New Zealand Dollar",symbol:"NZ$",native:"$",thousands_sep:",",decimal_sep:".",symbol_left:!0,space_between:!1,drop_zeros:!1,exp:2,min_amount:"168",max_amount:"1679219"},PAB:{code:"PAB",title:"Panamanian Balboa",symbol:"PAB",native:"B/.",thousands_sep:",",decimal_sep:".",symbol_left:!0,space_between:!0,drop_zeros:!1,exp:2,min_amount:"100",max_amount:"999469"},PEN:{code:"PEN",title:"Peruvian Nuevo Sol",symbol:"PEN",native:"S/.",thousands_sep:",",decimal_sep:".",symbol_left:!0,space_between:!0,drop_zeros:!1,exp:2,min_amount:"374",max_amount:"3740759"},PHP:{code:"PHP",title:"Philippine Peso",symbol:"PHP",native:"₱",thousands_sep:",",decimal_sep:".",symbol_left:!0,space_between:!1,drop_zeros:!1,exp:2,min_amount:"5806",max_amount:"58056502"},PKR:{code:"PKR",title:"Pakistani Rupee",symbol:"PKR",native:"₨",thousands_sep:",",decimal_sep:".",symbol_left:!0,space_between:!1,drop_zeros:!1,exp:2,min_amount:"27836",max_amount:"278360445"},PLN:{code:"PLN",title:"Polish Złoty",symbol:"PLN",native:"zł",thousands_sep:" ",decimal_sep:",",symbol_left:!1,space_between:!0,drop_zeros:!1,exp:2,min_amount:"396",max_amount:"3957640"},PYG:{code:"PYG",title:"Paraguayan Guaraní",symbol:"PYG",native:"₲",thousands_sep:".",decimal_sep:",",symbol_left:!0,space_between:!0,drop_zeros:!1,exp:0,min_amount:"7569",max_amount:"75694544"},QAR:{code:"QAR",title:"Qatari Riyal",symbol:"QAR",native:"ر.ق.",thousands_sep:",",decimal_sep:".",symbol_left:!0,space_between:!0,drop_zeros:!1,exp:2,min_amount:"364",max_amount:"3644355"},RON:{code:"RON",title:"Romanian Leu",symbol:"RON",native:"RON",thousands_sep:".",decimal_sep:",",symbol_left:!1,space_between:!0,drop_zeros:!1,exp:2,min_amount:"459",max_amount:"4592300"},RSD:{code:"RSD",title:"Serbian Dinar",symbol:"RSD",native:"дин.",thousands_sep:".",decimal_sep:",",symbol_left:!1,space_between:!0,drop_zeros:!1,exp:2,min_amount:"10802",max_amount:"108020115"},RUB:{code:"RUB",title:"Russian Ruble",symbol:"RUB",native:"₽",thousands_sep:" ",decimal_sep:",",symbol_left:!1,space_between:!0,drop_zeros:!1,exp:2,min_amount:"8990",max_amount:"89898410"},SAR:{code:"SAR",title:"Saudi Riyal",symbol:"SAR",native:"ر.س.",thousands_sep:",",decimal_sep:".",symbol_left:!0,space_between:!0,drop_zeros:!1,exp:2,min_amount:"375",max_amount:"3754022"},SEK:{code:"SEK",title:"Swedish Krona",symbol:"SEK",native:"kr",thousands_sep:".",decimal_sep:",",symbol_left:!1,space_between:!0,drop_zeros:!1,exp:2,min_amount:"1069",max_amount:"10689290"},SGD:{code:"SGD",title:"Singapore Dollar",symbol:"SGD",native:"$",thousands_sep:",",decimal_sep:".",symbol_left:!0,space_between:!1,drop_zeros:!1,exp:2,min_amount:"133",max_amount:"1331235"},THB:{code:"THB",title:"Thai Baht",symbol:"฿",native:"฿",thousands_sep:",",decimal_sep:".",symbol_left:!0,space_between:!1,drop_zeros:!1,exp:2,min_amount:"3535",max_amount:"35351502"},TJS:{code:"TJS",title:"Tajikistani Somoni",symbol:"TJS",native:"TJS",thousands_sep:" ",decimal_sep:";",symbol_left:!1,space_between:!0,drop_zeros:!1,exp:2,min_amount:"1057",max_amount:"10569158"},TRY:{code:"TRY",title:"Turkish Lira",symbol:"TRY",native:"TL",thousands_sep:".",decimal_sep:",",symbol_left:!1,space_between:!0,drop_zeros:!1,exp:2,min_amount:"3317",max_amount:"33166840"},TTD:{code:"TTD",title:"Trinidad and Tobago Dollar",symbol:"TTD",native:"$",thousands_sep:",",decimal_sep:".",symbol_left:!0,space_between:!1,drop_zeros:!1,exp:2,min_amount:"677",max_amount:"6768188"},TWD:{code:"TWD",title:"New Taiwan Dollar",symbol:"NT$",native:"NT$",thousands_sep:",",decimal_sep:".",symbol_left:!0,space_between:!1,drop_zeros:!1,exp:2,min_amount:"3281",max_amount:"32805499"},TZS:{code:"TZS",title:"Tanzanian Shilling",symbol:"TZS",native:"TSh",thousands_sep:",",decimal_sep:".",symbol_left:!0,space_between:!1,drop_zeros:!1,exp:2,min_amount:"270000",max_amount:"2700000297"},UAH:{code:"UAH",title:"Ukrainian Hryvnia",symbol:"UAH",native:"₴",thousands_sep:" ",decimal_sep:",",symbol_left:!1,space_between:!1,drop_zeros:!1,exp:2,min_amount:"4124",max_amount:"41236639"},UGX:{code:"UGX",title:"Ugandan Shilling",symbol:"UGX",native:"USh",thousands_sep:",",decimal_sep:".",symbol_left:!0,space_between:!1,drop_zeros:!1,exp:0,min_amount:"3723",max_amount:"37234902"},USD:{code:"USD",title:"United States Dollar",symbol:"$",native:"$",thousands_sep:",",decimal_sep:".",symbol_left:!0,space_between:!1,drop_zeros:!1,exp:2,min_amount:"100",max_amount:1e6},UYU:{code:"UYU",title:"Uruguayan Peso",symbol:"UYU",native:"$",thousands_sep:".",decimal_sep:",",symbol_left:!0,space_between:!0,drop_zeros:!1,exp:2,min_amount:"4027",max_amount:"40269076"},UZS:{code:"UZS",title:"Uzbekistani Som",symbol:"UZS",native:"UZS",thousands_sep:" ",decimal_sep:",",symbol_left:!1,space_between:!0,drop_zeros:!1,exp:2,min_amount:"1256851",max_amount:"12568510387"},VND:{code:"VND",title:"Vietnamese Đồng",symbol:"₫",native:"₫",thousands_sep:".",decimal_sep:",",symbol_left:!1,space_between:!0,drop_zeros:!1,exp:0,min_amount:"25218",max_amount:"252175000"},YER:{code:"YER",title:"Yemeni Rial",symbol:"YER",native:"ر.ي.",thousands_sep:",",decimal_sep:".",symbol_left:!0,space_between:!0,drop_zeros:!1,exp:2,min_amount:"25035",max_amount:"250350255"},ZAR:{code:"ZAR",title:"South African Rand",symbol:"ZAR",native:"R",thousands_sep:",",decimal_sep:".",symbol_left:!0,space_between:!0,drop_zeros:!1,exp:2,min_amount:"1819",max_amount:"18193780"}};function lk(a,e,t,s){a=(a+"").replace(/[^0-9+\-Ee.]/g,"");var i=isFinite(+a)?+a:0,n=isFinite(+e)?Math.abs(e):0,r=typeof s>"u"?",":s,o=typeof t>"u"?".":t,l="",c=function(d,u){var h=Math.pow(10,u);return""+Math.round(d*h)/h};return l=(n?c(i,n):""+Math.round(i)).split("."),l[0].length>3&&(l[0]=l[0].replace(/\B(?=(?:\d{3})+(?!\d))/g,r)),(l[1]||"").length<n&&(l[1]=l[1]||"",l[1]+=new Array(n-l[1].length+1).join("0")),l.join(o)}function qi(a,e,t,s,i){if(a=+a,e===Mo){if(i)return Ne.format("StarsCount",!0,[a]);const p=document.createElement("span");return p.classList.add("xtr"),p.append(Be("star","xtr-icon")," ",""+a),p}const n=a<0,r=C_[e];if(!r)throw new Error("CURRENCY_WRAP_INVALID");const o=a/Math.pow(10,r.exp);let l=r.exp;e=="IRR"&&Math.floor(o)==o&&(l=0);let c=lk(o,l,r.decimal_sep,r.thousands_sep);if(t)return c;let d=s&&r.native||r.symbol;n&&!r.space_between&&r.symbol_left&&(d="-"+d,c=c.replace("-",""));let u;const h=r.space_between?" ":"";return r.symbol_left?u=d+h+c:u=c+h+d,u}window.p=qi;function it(a){if(a!==void 0&&(a.isPeerId&&a.isPeerId()))return a;if(Fy(a)){const s=a.user_id;if(s!==void 0)return s.toPeerId(!1);const i=a.channel_id||a.chat_id;return i!==void 0?i.toPeerId(!0):Wt}else if(!a)return Wt;const e=a.charAt(0)==="u",t=a.substr(1).split("_");return e?t[0].toPeerId():(t[0]||"").toPeerId(!0)}function Oo(a,e=[]){return e.forEach(t=>{t._==="messageEntitySpoiler"&&(a=cL(a,t).text)}),a}function Cg(a,e){const{text:t,entities:s}=DC(a,e);return je(t,void 0,s)}let oo,fp,nS;const aS=new Map;function ck(a,e){if(!oo){nS=document.getElementById("svg-defs");const r="http://www.w3.org/2000/svg";oo=document.createElementNS(r,"svg"),oo.setAttributeNS(null,"width","26"),oo.setAttributeNS(null,"height","26"),oo.setAttributeNS(null,"viewBox","0 0 26 26"),oo.classList.add("topic-icon-svg");const o=document.createElementNS(r,"use");o.setAttributeNS(null,"href","#topic-icon"),oo.append(o),fp=document.createElement("span"),fp.classList.add("topic-icon","avatar-like");const l=document.createElement("span");l.classList.add("topic-icon-content"),fp.append(oo,l)}a||(console.error("NO TOPIC ICON COLOR!"),a=Xd[0]),e||(console.error("NO TOPIC NAME!"),e="");const t=a.toString(16),s=`topic-icon-gradient-${a}`;let i=aS.get(a);if(!i){const{h:r,s:o,l,a:c}=By("#"+t);nS.insertAdjacentHTML("beforeend",`
- <linearGradient id="${s}" x1="0" x2="0" y1="0" y2="1">
- <stop style="stop-color: #${t};" offset="0%" />
- <stop style="stop-color: hsla(${r}, ${o}%, ${Math.max(0,l-30)}%, ${c});" offset="100%" />
- </linearGradient>
- `),aS.set(a,i=`hsla(${r}, ${o}%, ${Math.max(0,l-40)}%, ${c})`)}const n=fp.cloneNode(!0);return n.firstElementChild.style.fill=`url(#${s})`,n.firstElementChild.style.stroke=i,n.lastElementChild.append(Cg(e,!0)),n}function ab({docIds:a,loadPromises:e,middleware:t,lazyLoadQueue:s,customEmojiSize:i,animationGroup:n}){const r=" ".repeat(a.length),o=[];return a.forEach((c,d)=>{o.push({_:"messageEntityCustomEmoji",offset:d,length:1,document_id:c})}),jt(r,{entities:o,loadPromises:e,animationGroup:n,customEmojiSize:i,middleware:t,lazyLoadQueue:s})}function dk(a){const e=a.loadPromises??(a.loadPromises=[]),t=ab(a);return Promise.all(e).then(()=>t)}function rS(a){const e=a.action,{onclick:t,url:s}=Bo(`tg://voicechat?chat_id=${a.peerId.toChatId()}&id=${e.call.id}&access_hash=${e.call.access_hash}`);if(!t)return document.createElement("span");const i=document.createElement("a");return i.href=s,i.setAttribute("onclick",t+"(this)"),i}function qc(a,e){const t=[],s=[];for(let i=0,n=a.length;i<n;++i){const r=a[i];(e(r,i,a)?t:s).push(r)}return[t,s]}function $u(a){if(a instanceof DocumentFragment)return a;const e=document.createElement("template");return a=a.trim(),e.innerHTML=a,e.content}const hk=new Set(["all","web","webk"]),uk=new Set;function __(a){return a.find(e=>hk.has(e.platform)&&!uk.has(e.reason))}function I_(a){return!!__(a)}function pk(a){return a.replace(/[|\\{}()[\]^$+*?.]/g,"\\$&").replace(/-/g,"\\x2d")}function P_(a){return!!(a.restriction_reason&&I_(a.restriction_reason))}function rb(a,e){return a=a.replace(/[\u2640\u2642\u2764](?!\ufe0f)/g,(t,s,i)=>{if(e){const n=t.length;s+=n,e.forEach(r=>{const o=r.offset+r.length;o===s?r.length+=n:o>s&&(r.offset+=n)})}return t+"️"}),a}function xv(a,e=[]){a=rb(a,e);const t=Lc(a),s=El(e,t);return{message:a,entities:e,myEntities:t,totalEntities:s}}function Yc(a){const{message:e,entities:t,myEntities:s}=xv(a.text,a.entities),i=El(t,s.filter(n=>n._==="messageEntityCustomEmoji"||n._==="messageEntityEmoji"));return{_:"textWithEntities",text:e,entities:i}}async function mk(a){return{cached:a.cached,result:a.cached?await a.result:a.result}}function Fl(a){return a.then(mk)}const[gk,fk]=Qr({}),M_=a=>{I.managers.appProfileManager.getProfileByPeerId(a).then(e=>{fk(a,Ec(e))})};I.addEventListener("peer_full_update",M_);function L_(a){return V(()=>{if(!a())return;const e=gk[a()];return e||M_(a()),e})}let vp,gf;function E_(a){vp||(vp=new Worker(new URL(""+new URL("tinyld.worker-sOiVgKBT.js",import.meta.url).href,import.meta.url),{type:"module"}),vp.addEventListener("message",t=>{const{lang:s}=t.data;gf.shift().resolve(s)}),gf=[]);const e=Mt();return gf.push(e),vp.postMessage({text:a}),e}const vk=8,yk=.65;let ko,cr,Av,_g=()=>{_g=void 0,[ko,cr]=Qr({}),Ft(()=>{const[a]=Ho();Av=V(()=>new Set(a.translations.doNotTranslate.concat(navigator.language.split("-")[0],Ne.langCodeNormalized()))),le(Vt(Av,e=>pi(()=>{for(const t in ko){const s=ko[t];if(!s)continue;let i=0;for(const n in s.languages)e.has(n)||(i+=s.languages[n]);cr(t.toPeerId(),"totalForeign",i)}}),{defer:!0}))})};function k_(){return{messages:{},languages:{},language:void 0,total:0,totalForeign:0}}function bk(a){_g?.(),Ot(()=>ko[a])||cr(a,k_()),cr(a,"isFull",!0)}async function wk(a,e){if(_g?.(),ko[a]&&ko[a].messages[e])return;const s=Ae.getMessageByPeer(a,e).message;if(!s)return;const i=await E_(s),n=!Av().has(i);pi(()=>{let r=Ot(()=>ko[a]);if(!r)cr(a,r=k_());else if(r.messages[e])return;const o=(r.languages[i]??0)+1,l=r.total+1,c=r.totalForeign+(n?1:0);cr(a,"messages",e,i),cr(a,"languages",i,o),cr(a,"total",l),n&&cr(a,"totalForeign",c);const d=r.language;(r.languages[d]||0)<o&&cr(a,"language",i)})}function Sk(a,e){return V(()=>{const t=a();if(!t)return;_g?.();const s=ko[t];if(!(s&&s.total<vk&&!s.isFull)&&!(s&&s.totalForeign/s.total<yk))return s?.language})}const ff=new Map;function T_(a,e){return V(()=>{const t=a();let s=ff.get(t);return s||(s={count:0,factory:e},s.value=Ft(i=>(s.dispose=i,e())),ff.set(t,s)),++s.count,ze(()=>{--s.count||(s.dispose(),ff.delete(t))}),s.value})}const[Ck,x_]=Ft(()=>K(I.premium)),oS=()=>{I.managers.rootScope.getPremium().then(x_)};I.addEventListener("premium_toggle",x_);I.myId?oS():I.addEventListener("user_auth",oS);function Ig(){return Ck}function _k(a){const[e,t]=Ho(),s=L_(()=>a),i=Sk(()=>a),n=Ig(),r=V(()=>{if(!(!n()||!s()||!i()||!e.translations.enabled))return!(s().pFlags.translations_disabled||e.translations.doNotTranslate.includes(i()))}),o={peerLanguage:i,language:()=>e.translations.peers[a]||Ne.langCodeNormalized(),setLanguage:l=>t("translations","peers",a,l),enabled:V(()=>!!(n()&&e.translations.enabled&&e.translations.enabledPeers[a])&&r()),toggle:l=>t("translations","enabledPeers",a,l?!0:void 0),shouldShow:r};return le(()=>{o.shouldShow()===!1&&o.enabled()&&o.toggle(!1)}),o}function Qc(a){return T_(()=>Qc.name+"-"+a,()=>_k(a))()}function ui(){const a=Ht();return ze(()=>a.destroy()),a}const Ik=!1;function A_(a){const e=Ik,[t,s]=K(!e),i=V(f=>f||t()),[n,r]=K(),o=Qc(a.peerId),l=Mt();let c=a.textWithEntities,d=!0,u=!1;const h=a.enabled,p=a.container??document.createElement("span");p.classList.add("translatable-message"),a.message&&(wk(a.peerId,a.message.mid),c={_:"textWithEntities",text:a.message.message,entities:a.message.totalEntities}),a.richTextOptions?.loadPromises&&a.richTextOptions.loadPromises.push(l);const m=(f,v)=>Fl(I.managers.acknowledged.appTranslationsManager.translateText({...a.message?{peerId:a.message.peerId,mid:a.message.mid}:{text:a.textWithEntities},lang:f,onlyCache:v})),g=f=>{r(c),p.classList.toggle("text-loading",!!f)};if(a.observer&&a.observeElement&&e){const f=v=>{s(v.isIntersecting)};a.observer.observe(a.observeElement,f),ze(()=>{a.observer.unobserve(a.observeElement,f)})}return le(async()=>{const f=ui().get(),v=d;if(d=!1,!o.enabled()&&!a.enabled||!i()&&!v){g();return}const y=await m(o.language(),v&&e);if(!f())return;if(!y.cached)h?p.classList.add("text-loading"):g(!0);else if(!y.result){g();return}const w=await y.result;if(f()){if(!w){g();return}r(w)}}),le(()=>{let f=n();if(!f)return;a.onTextWithEntities&&(f=a.onTextWithEntities(f)),(c!==f||!a.message)&&(f=Yc(f));const v=ui().get(),y=[],w=jt(f.text,{...a.richTextOptions||{},loadPromises:y,entities:f.entities});Promise.all(y).then(()=>{if(!v())return;const b=()=>{v()&&(l.resolve(),p.replaceChildren(w),(u||h)&&p.classList.remove("text-loading"),u=!0)};if(u&&a.onTranslation){a.onTranslation(b);return}b()})}),p}function Nu(a){return Ft(e=>(a.middleware.onDestroy(e),A_(a)))}async function gm(a){try{return await Pk(a)}catch(e){return console.error("wrapMessageActionTextNewUnsafe error:",e),a.plain?"":document.createElement("span")}}async function To(a){a.text??(a.text=a.message.message),!a.plain&&a.highlightWord&&(a.highlightWord=a.highlightWord.trim());const{message:e,usingMids:t,plain:s,highlightWord:i,withoutMediaType:n}=a,r=[];let o=!1;const l=(g,f,v)=>{if(g){if(f===void 0&&o)return;f=s?Ne.format(g,!0,v):P(g,v)}if(s)r.push(f);else{const y=document.createElement("span");typeof f=="string"?y.innerHTML=f:y.append(f),r.push(y)}},d=(a.managers||I.managers).appMessagesManager,u=()=>a.managers?a.managers.rootScope.getMyId():I.myId,h=P_(e),p={...a,noLinebreaks:!0,noLinks:!0,noTextFormat:!0};let m=e.totalEntities??e.entities;if(e.media&&!h){let g=!0;if(e.grouped_id){if(t){const y=await d.getMidsByMessage(e);if(t.length===y.length){for(const w of y)if(!t.includes(w)){g=!1;break}}else g=!1}if(g){const y=await d.getGroupedText(e.grouped_id);a.text=y?.message||"",m=y?.totalEntities||[],n||(l("AttachAlbum"),o=!0)}}else g=!1;let f=1;if(!g&&!n||!a.text){const y=e.media;switch(y?._){case"messageMediaPhoto":l("AttachPhoto");break;case"messageMediaDice":l(void 0,s?y.emoticon:je(y.emoticon));break;case"messageMediaVenue":{a.text=y.title,l("AttachLocation");break}case"messageMediaGeo":l("AttachLocation");break;case"messageMediaGeoLive":l("AttachLiveLocation");break;case"messageMediaPoll":const w="📊 ";if(s){const b=w+y.poll.question.text;l(void 0,b)}else{const b=Yc(y.poll.question),S=jt(b.text,{...p,entities:b.entities});S.prepend(je(w)),l(void 0,S)}break;case"messageMediaContact":l("AttachContact");break;case"messageMediaGame":{const b="🎮 "+y.game.title;l(void 0,s?b:je(b));break}case"messageMediaDocument":{const b=y.document;if(b.type==="video")l("AttachVideo");else if(b.type==="voice")l("AttachAudio");else if(b.type==="gif")l("AttachGif");else if(b.type==="round")l("AttachRound");else if(b.type==="sticker"){const S=r.length;if(b.stickerEmojiRaw){const M=b.stickerEmojiRaw+" ";l(void 0,s?M:je(M))}l("AttachSticker");const _=r.splice(S,2);if(s)r.push(_[0]+(_[1]?_[1]:""));else{const M=window.document.createElement("span");M.append(..._),r.push(M)}a.text=""}else if(b.type==="audio"){const S=b.attributes.find(M=>M._==="documentAttributeAudio"&&(M.title||M.performer)),_="🎵 "+(S?[S.title,S.performer].filter(Boolean).join(" - "):b.file_name);l(void 0,s?_:je(_))}else l(void 0,s?b.file_name:je(b.file_name));break}case"messageMediaInvoice":{y.extended_media?._==="messageExtendedMediaPreview"?l(void 0,s?y.description:je(y.description)):l(void 0,s?y.title:je(y.title));break}case"messageMediaUnsupported":{l(mv);break}case"messageMediaStory":{if(y.pFlags.via_mention){const b=it(y.peer),S=b===await u();l(S?"StoryMentionYou":"StoryMention",void 0,[await qe({peerId:S?e.peerId:b,plainText:s})])}else l("Story");break}case"inputMediaWebPage":case"messageMediaPhotoExternal":case"messageMediaDocumentExternal":case"messageMediaWebPage":break;case"messageMediaGiveaway":{const b=Dy(new Date(y.until_date*1e3));l("Giveaway.ToBeSelectedFull",void 0,[P("Giveaway.ToBeSelected",[y.quantity,s?b.textContent:b])]);break}case"messageMediaGiveawayResults":{const{langPackKey:b,args:S}=F_(y,s);l(b,void 0,S);break}case"messageMediaPaidMedia":{const b=y.extended_media,[S,_]=qc(b,C=>C._==="messageExtendedMediaPreview"?C.video_duration===void 0:C.media._==="messageMediaPhoto");s||(f+=2,l(void 0,Be("star","xtr-icon")),l(void 0," "));const M=S.length+_.length;if(M<2){l(S.length?"AttachPhoto":"AttachVideo");break}l(S.length&&_.length?"Media":S.length?"Photos":"Videos",void 0,[M]);break}default:l(mv),a.text="";break}}const v=r.length;for(;f<v;f+=2)r.splice(f,0,", ");a.text&&v&&r.push(", ")}if(e.action){const g=await gm({...a,noLinks:!0,noTextFormat:!0});g&&l(void 0,g)}if(h&&(a.text=__(e.restriction_reason).text,m=[]),a.text)if(a.text=Ya(a.text,100),m??(m=Lc(a.text)),s)r.push(Oo(a.text,m));else{if(i){let f=!1,v;const y=new RegExp(pk(i),"gi");for(m=m.slice();(v=y.exec(a.text))!==null;)m.push({_:"messageEntityHighlight",length:i.length,offset:v.index}),f=!0;f&&Gw(m)}if(e.peerId===ku&&e.fromId===e.peerId){const f=a.text.match(/[\d\-]{5,7}/);f&&(m=m.slice(),m.push({_:"messageEntitySpoiler",offset:f.index,length:f[0].length}),Gw(m))}let g;a.canTranslate?g=Nu({peerId:e.peerId,message:e,richTextOptions:p,middleware:a.middleware,onTextWithEntities:f=>({...f,text:Ya(f.text,100)})}):(g=jt(a.text,{...p,entities:m}),g=$u(g)),r.push(g)}if(s)return r.join("");{const g=document.createDocumentFragment();return g.append(...r),g}}function fm(a){return a._==="payments.checkedGiftCode"?!a.from_id:(a.amount||a.crypto_amount)!==void 0}async function lS(a){const e=await To(a);if(a.plain)return e;const t=document.createElement("i");return t.dataset.savedFrom=a.message.peerId+"_"+a.message.mid,t.append(e),Xr(t),t}function eh(a,e){return e?a:nb(je(a))}async function Pg(a){const e=a.topic;let t=e?.icon_emoji_id;return e?.id===Tu&&(t="5390854796011906616"),t?a.plain?I.managers.appEmojiManager.getCustomEmojiDocument(t).then(s=>s.stickerEmojiRaw):dk({...a,docIds:[t]}).then(s=>(s.lastElementChild.classList.add("topic-icon"),s)):a.plain?"":ck(e?.icon_color,e?.title)}function R_(a){const e=a.message.action;return Pg({...a,topic:e})}async function cS(a){const e=a.message.action,t=document.createElement("span");return t.classList.add("topic-name"),t.append(await R_(a),eh(e.title,a.plain)),t}function F_(a,e){let t="Giveaway.Results",s=[a.winners_count];const i=(n,r)=>{s=[e?Ne.format(t,!0,s):P(t,s)],t="Giveaway.Results.Combined",s.push(e?Ne.format(n,!0,r):P(n,r))};return a.winners_count?a.unclaimed_count&&i("Giveaway.Results.Unclaimed",[a.unclaimed_count]):(t=a.pFlags.stars?"Giveaway.Results.NoWinners.Stars":"Giveaway.Results.NoWinners",s=[a.unclaimed_count]),{langPackKey:t,args:s}}async function Pk(a){const{plain:e,message:t,noLinks:s}=a,i=e?void 0:document.createElement("span"),n="action"in t&&t.action;if(n._==="messageActionCustomAction"&&n.message){const r=n.message;return e?Oo(r):(Qt(i,jt(r,{noLinebreaks:!0})),i)}else{let r=n._,o,l;const c=I.managers,d=(p,m)=>m?Gr({peerId:p,plainText:m}):qe({peerId:p}),u=async(p,m)=>{if(p.length===1)return d(p[0],m);const g=Yi(await Promise.all(p.map(f=>d(f,m))),!1,m);if(m)return Array.isArray(g)?g.join(""):g;{const f=document.createElement("span");return f.append(...g),l.push(f),f}};switch(n._){case"messageActionPhoneCall":{r+="."+n.type,l=[Gp(n.duration,e)];break}case"messageActionGroupCall":{r+="."+n.type,l=[],!r.endsWith("You")&&!t.pFlags.post&&l.push(d(t.fromId,e)),n.duration!==void 0?l.push(Gp(n.duration,e)):s?l.push(""):l.push(rS(t));break}case"messageActionInviteToGroupCall":{const p=[t.fromId,n.users[0].toPeerId()];let m="Chat.Service.VoiceChatInvitation";const g=I.myId;p[0]===g?m+="ByYou":p[1]===g&&(m+="ForYou"),Vs(p,g),o=m,l=p.map(f=>d(f,e)),l.push(s?"":rS(t));break}case"messageActionGroupCallScheduled":{const p=new Date,m=new Date(n.schedule_date*1e3),g=(m.getTime()-p.getTime())/864e5,f=new Date(p);f.setDate(f.getDate()+1);const v=await c.appPeersManager.isBroadcast(t.peerId);o=v?"ChatList.Service.VoiceChatScheduled.Channel":"ChatList.Service.VoiceChatScheduled",l=[];const y=I.myId;t.fromId===y?o+="You":v||l.push(d(t.fromId,e));let w;const b=[];g<1&&m.getDate()===p.getDate()?w="TodayAtFormattedWithToday":g<2&&m.getDate()===f.getDate()?w="Time.TomorrowAt":(w="formatDateAtTime",b.push(new Ne.IntlDateElement({date:m,options:{day:"2-digit",month:"2-digit",year:"2-digit"}}).element)),b.push(Ny(m));const S=P(w,b);l.push(S);break}case"messageActionChatCreate":{const p=I.myId;t.fromId===p?r+="You":l=[d(t.fromId,e)];break}case"messageActionPinMessage":{const p=t.peerId,m=await c.appMessagesManager.getMessageByPeer(p,t.reply_to_mid);l=[d(t.fromId,e)],m?l.push(lS({...a,message:m})):(o="ActionPinnedNoText",t.reply_to_mid&&c.appMessagesManager.fetchMessageReplyTo(t));break}case"messageActionChatJoinedByRequest":{const p=await c.appPeersManager.isBroadcast(t.peerId);t.pFlags.out?o=p?"RequestToJoinChannelApproved":"RequestToJoinGroupApproved":(o=p?"ChatService.UserJoinedChannelByRequest":"ChatService.UserJoinedGroupByRequest",l=[d(t.fromId,e)]);break}case"messageActionGiveawayLaunch":{o=n.stars?"BoostingStarsGiveawayJustStarted":"BoostingGiveawayJustStarted",l=[d(t.fromId,e)],n.stars&&l.unshift(+n.stars);break}case"messageActionContactSignUp":case"messageActionChatReturn":case"messageActionChatLeave":case"messageActionChatJoined":case"messageActionChatEditPhoto":case"messageActionChatDeletePhoto":case"messageActionChatEditVideo":case"messageActionChatJoinedByLink":case"messageActionChannelEditVideo":case"messageActionChannelDeletePhoto":{l=[d(t.fromId,e)];break}case"messageActionChannelEditTitle":case"messageActionChatEditTitle":{l=[],n._==="messageActionChatEditTitle"&&l.push(d(t.fromId,e)),l.push(eh(n.title,e));break}case"messageActionChatDeleteUser":case"messageActionChatAddUsers":case"messageActionChatAddUser":{const p=n.users||[n.user_id];l=[d(t.fromId,e)];const m=p.map(g=>g.toPeerId(!1));l.push(u(m,e));break}case"messageActionBotAllowed":{if(n.pFlags?.attach_menu){o="ActionAttachMenuBotAllowed";break}else if(n.pFlags?.from_request){o="ActionBotAllowedRequest";break}else if(!n.domain)break;const p=jt(n.domain,{entities:[{_:"messageEntityUrl",length:n.domain.length,offset:0}],noLinks:s});l=[nb(p)];break}case"messageActionPaymentSent":{const p=n.pFlags.recurring_init,m=n.pFlags.recurring_used;if(o=m?"Chat.Service.PaymentSentRecurringUsedNoTitle":p?"Chat.Service.PaymentSentRecurringInitNoTitle":"Chat.Service.PaymentSent1NoTitle",l=[qi(n.total_amount,n.currency,void 0,void 0,e),d(t.peerId,e)],t.reply_to_mid){const f=t.reply_to,v=await c.appMessagesManager.getMessageByPeer(f?.reply_to_peer_id?it(f.reply_to_peer_id):t.peerId,t.reply_to_mid);v?(o=m?"Chat.Service.PaymentSentRecurringUsed":p?"Chat.Service.PaymentSentRecurringInit":"Chat.Service.PaymentSent1",l.push(lS({...a,message:v}).then(y=>(y instanceof HTMLElement&&y.classList.add("is-receipt-link"),y)))):c.appMessagesManager.fetchMessageReplyTo(t)}break}case"messageActionPaymentRefunded":{const p=qi(n.total_amount,n.currency,void 0,void 0,e);l=[d(t.fromId,e),p],o="Chat.Service.Refund";break}case"messageActionSetMessagesTTL":{l=[];const p=await c.appPeersManager.isBroadcast(t.peerId);if(n.period){p?o="ActionTTLChannelChanged":t.fromId===I.myId?o="ActionTTLYouChanged":(o="ActionTTLChanged",l.push(d(t.fromId,e)));let m;if(n.period>1814400){let g;const f=[];n.period>=31536e3?(g="Years",f.push(n.period/31536e3|0)):(g="Months",f.push(n.period/($y*30)|0)),m=e?Ne.format(g,!0,f):P(g,f)}else m=Gp(n.period,e);l.push(m)}else p?o="ActionTTLChannelDisabled":t.fromId===I.myId?o="ActionTTLYouDisabled":(o="ActionTTLDisabled",l.push(d(t.fromId,e)));break}case"messageActionTopicEdit":{let p,m,g;const f=!!t.pFlags.out,v=n.icon_emoji_id!==void 0,y=v&&!+n.icon_emoji_id,w=n.title!==void 0,b=n.hidden!==void 0;f||(g=d(t.fromId,e)),w&&(m=eh(n.title,e)),v&&!y&&(p=R_(a)),l=g?[g]:[],n.closed?o=f?"Chat.Service.Group.TopicEdited.You.Paused":"Chat.Service.Group.TopicEdited.Paused":n.closed===!1?o=f?"Chat.Service.Group.TopicEdited.You.Resumed":"Chat.Service.Group.TopicEdited.Resumed":y&&w?(o=f?"Chat.Service.TopicEdited.You.Mixed.IconRemoved":"Chat.Service.TopicEdited.Mixed.IconRemoved",l.push(m)):v&&w?(o=f?"Chat.Service.TopicEdited.You.Mixed":"Chat.Service.TopicEdited.Mixed",l.push(cS(a))):y?o=f?"Chat.Service.Group.TopicEdited.You.Icon.Removed":"Chat.Service.Group.TopicEdited.Icon.Removed":w?(o=f?"Chat.Service.Group.TopicEdited.You.Title":"Chat.Service.Group.TopicEdited.Title",l.push(m)):v?(o=f?"Chat.Service.Group.TopicEdited.You.Icon":"Chat.Service.Group.TopicEdited.Icon",l.push(p)):b&&(o=f?n.hidden?"Chat.Service.Group.TopicEdited.You.Hided":"Chat.Service.Group.TopicEdited.You.Unhided":n.hidden?"Chat.Service.Group.TopicEdited.Hided":"Chat.Service.Group.TopicEdited.Unhided");break}case"messageActionTopicCreate":{l=[cS(a)],o="TopicWasCreatedAction";break}case"messageActionSetChatTheme":{const p=!!t.pFlags.out;let m;p||(m=d(t.fromId,e)),l=m?[m]:[],n.emoticon?(l.push(eh(n.emoticon,e)),o=p?"ChatThemeChangedYou":"ChatThemeChangedTo"):o=p?"ChatThemeDisabledYou":"ChatThemeDisabled";break}case"messageActionPrizeStars":{o="BoostingReceivedGiftNoName";break}case"messageActionGiftStars":case"messageActionGiftCode":case"messageActionGiftPremium":{const p=n._==="messageActionGiftCode";if(p&&!fm(n)){o="BoostingReceivedGiftNoName",n.boost_peer&&(o="BoostingReceivedGiftFrom",l=[d(it(n.boost_peer),e)]);break}const m=!!t.pFlags.out&&!p;let g;m||(g=d(t.fromId,e)),l=g?[g]:[],l.push(qi(n.amount,n.currency,!1,!0,e)),o=m?"ActionGiftOutbound":"ActionGiftInbound";break}case"messageActionWebViewDataSent":{o="ActionBotWebViewData",l=[eh(n.text,e)];break}case"messageActionRequestedPeer":{o="Chat.Service.PeerRequested",l=[u(n.peers.map(p=>it(p)),e),d(t.peerId,e)];break}case"messageActionGiveawayResults":{const p=F_(n,e);o=p.langPackKey,l=p.args;break}case"messageActionSetChatWallPaper":{const p=t.peerId.isUser();if(l=[d(p?t.peerId:t.fromId,e)],p){t.pFlags.out?o=n.pFlags.for_both?"ActionSetWallpaperForThisChatSelfBoth":n.pFlags.same?"ActionSetSameWallpaperForThisChatSelf":"ActionSetWallpaperForThisChatSelf":o=n.pFlags.for_both?"ActionSetWallpaperForThisChatBoth":n.pFlags.same?"ActionSetSameWallpaperForThisChat":"ActionSetWallpaperForThisChat";break}if(await c.appPeersManager.isBroadcast(t.peerId)){o="ActionSetWallpaperForThisChannel";break}o=t.fromId===t.peerId?"ActionSetWallpaperForThisGroup":"ActionSetWallpaperForThisGroupByUser";break}case"messageActionPaidMessagesPrice":{o=!+n.stars?"PaidMessages.GroupPriceChangedFree":"PaidMessages.GroupPriceChanged",l=[+n.stars];break}case"messageActionPaidMessagesRefunded":{o="PaidMessages.StarsRefundedShort",l=[+n.stars];break}case"messageActionStarGift":t.pFlags.out?(o="StarGiftSentMessageOutgoing",l=[n.gift.stars]):(o="StarGiftSentMessageIncoming",l=[d(t.fromId,e),n.gift.stars]);break;case"messageActionStarGiftUnique":n.pFlags.upgrade?o=t.pFlags.out?"ActionGiftUpgradedOutbound":"ActionGiftUpgradedInbound":o=t.pFlags.out?"ActionGiftTransferredOutbound":"ActionGiftTransferredInbound",l=[d(t.peerId,e)];break;default:o=om[r]||`[${n._}]`;break}o||(o=om[r],o===void 0&&(o="["+r+"]"));const h=l&&await Promise.all(l);return e?Ne.format(o,!0,h):ks(i,o,h)}}const B_=new WeakMap;I.addEventListener("peer_title_edit",({peerId:a,threadId:e})=>{let t=`.peer-title[data-peer-id="${a}"]`;e&&(t+=`[data-thread-id="${e}"]`),Array.from(document.querySelectorAll(t)).forEach(i=>{B_.get(i)?.update()})});class Xt{constructor(e){this.element=document.createElement("span"),this.element.classList.add("peer-title"),Xr(this.element),this.options={},e&&this.update(e),B_.set(this.element,this)}setOptions(e){if(e){Nt(this.options,e);for(const t in e){const s=e[t];typeof s!="object"&&typeof s!="function"&&(this.element.dataset[t]=s?""+(typeof s=="boolean"?+s:s):"0")}}}setHasInner(e){this.hasInner!==e&&(this.hasInner=e,this.element.classList.toggle("with-icons",e))}async update(e){var r;this.setOptions(e);let t=this.options.fromName;if(t!==void 0){this.options.limitSymbols!==void 0&&(t=Ya(t,this.options.limitSymbols,this.options.limitSymbols)),Qt(this.element,je(t));return}(r=this.options).peerId??(r.peerId=Wt);let s;const{peerId:i,threadId:n}=this.options;if(i===I.myId&&this.options.dialog){let o;this.options.meAsNotes?o=P(this.options.onlyFirstName?"MyNotesShort":"MyNotes"):o=P(this.options.onlyFirstName?"Saved":"SavedMessages"),St(this.element,o)}else if(i===Oy)St(this.element,P(this.options.onlyFirstName?"AuthorHiddenShort":"AuthorHidden"));else{if(n){const[u,h]=await Promise.all([I.managers.dialogsStorage.getForumTopic(i,n),I.managers.appPeersManager.isForum(i)]);if(!u&&h){I.managers.dialogsStorage.getForumTopicById(i,n).then(p=>{if(!p&&this.options.threadId===n){this.options.threadId=void 0,this.update({threadId:void 0});return}this.update()},()=>{this.options.threadId===n&&(this.options.threadId=void 0,this.update({threadId:void 0}))}),Qt(this.element,P("Loading")),this.setHasInner(!1);return}}const o=n&&this.options.withIcons?I.managers.dialogsStorage.getForumTopic(i,n).then(u=>Pg({...this.options.wrapOptions??{},topic:u})):void 0,[l,c,d]=await Promise.all([Gr(this.options),this.options.withIcons&&Tv({peerId:i,wrapOptions:this.options.wrapOptions})||this.options.withPremiumIcon&&Tv({peerId:i,wrapOptions:this.options.wrapOptions,noVerifiedIcon:!0,noFakeIcon:!0}),o]);if(c?.length||d){const u=document.createElement("span");u.classList.add("peer-title-inner"),s=!0,Qt(u,l);const h=document.createDocumentFragment();h.append(...[d,u,...c??[]].filter(Boolean)),Qt(this.element,h)}else Qt(this.element,l)}this.setHasInner(s)}}function D_(a,e){const t=a.querySelector(".emoji-status-text-color"),s=t&&Ns.getAnimation(t);s&&s.setColor(e,!0)}async function qe(a){const e=new Xt;return await e.update(a),e.element}function Rv(a){const e=new Xt;return le(()=>e.update(a)),e.element}function $_(a,e){const t=Array.isArray(e)?e:dL(e);let s=a;for(const i of t)if(s=s?.[i],!s)break;return s}class _t{constructor(e={}){const t=this.label=document.createElement("label");t.classList.add("checkbox-field"),e.restriction&&!e.toggle&&t.classList.add("checkbox-field-restriction"),e.round&&t.classList.add("checkbox-field-round"),e.disabled&&this.toggleDisability(!0),this.listenerSetter=e.listenerSetter;const s=this.input=document.createElement("input");if(s.classList.add("checkbox-field-input"),s.type=e.asRadio?"radio":"checkbox",e.name&&(s[e.asRadio?"name":"id"]="input-"+e.name),e.checked&&(s.checked=!0),e.stateKey){let n=e.checked!==void 0;const r=()=>{if(!n)return;let o;e.stateValues?o=e.stateValues[s.checked?1:0]:(o=s.checked,e.stateValueReverse&&(o=!o)),I.managers.appStateManager.setByKey(e.stateKey,o)};!n&&Ae.getState().then(o=>{n=!0;const l=$_(o,e.stateKey);let c;e.stateValues?c=e.stateValues.indexOf(l)===1:(c=l,e.stateValueReverse&&(c=!c)),this.setValueSilently(c)}),e.listenerSetter?e.listenerSetter.add(s)("change",r):s.addEventListener("change",r)}let i;if(e.text?(i=this.span=document.createElement("span"),i.classList.add("checkbox-caption"),ks(i,e.text,e.textArgs)):t.classList.add("checkbox-without-caption"),t.append(s),e.toggle){t.classList.add("checkbox-field-toggle"),e.restriction&&t.classList.add("checkbox-field-toggle-restriction");const n=document.createElement("div");n.classList.add("checkbox-toggle");const r=document.createElement("div");r.classList.add("checkbox-toggle-circle"),n.append(r),t.append(n)}else{const n=document.createElement("div");n.classList.add("checkbox-box");const r=document.createElementNS("http://www.w3.org/2000/svg","svg");r.classList.add("checkbox-box-check"),r.setAttributeNS(null,"viewBox","0 0 24 24");const o=document.createElementNS("http://www.w3.org/2000/svg","use");o.setAttributeNS(null,"href","#check"),o.setAttributeNS(null,"x","-1"),r.append(o);const l=document.createElement("div");l.classList.add("checkbox-box-background");const c=document.createElement("div");c.classList.add("checkbox-box-border"),n.append(c,l,r),t.append(n)}i&&t.append(i),e.withRipple?(t.classList.add("checkbox-ripple","hover-effect"),Ei(t,void 0,void 0,!0)):e.withHover&&t.classList.add("hover-effect")}get checked(){return this.input.checked}set checked(e){this.setValueSilently(e),md(this.input,"change")}setValueSilently(e){this.input.checked=e}isDisabled(){return this.label.classList.contains("checkbox-disabled")}toggleDisability(e){return this.label.classList.toggle("checkbox-disabled",e),this.input.disabled=e,()=>this.toggleDisability(!e)}}function Mk(a){const e=a?.restriction_reason;return!!(e&&a.pFlags.restricted&&I_(e))}function Lk(a){if(!(!a||Mk(a)))return a?.photo}function Ek(a){let e="";return a&&(e=a.title??[a.first_name,a.last_name].filter(Boolean).join(" ")),Cg(e)}function kl(a){const e=new Array(a.childNodes.length);let t=a.firstChild,s=0;for(;t;)e[s++]=t.nodeType===t.TEXT_NODE?t.nodeValue:t,t=t.nextSibling;return e}class kk{constructor(){this.canvas=document.createElement("canvas"),this.context=this.canvas.getContext("2d"),this.dpr=window.devicePixelRatio}prepare(e){this.canvas.width=this.width=e.width*this.dpr,this.canvas.height=this.height=e.height*this.dpr,this.centerX=this.width/2,this.centerY=this.height/2,this.radius=e.radius*this.dpr,this.gapLength=e.gap*this.dpr,this.totalLength=Math.PI*this.radius*2,this.startAngle=-1.5}render(e){this.context.clearRect(0,0,this.width,this.height);const t=e.reduce((n,r)=>n+r.length,0),s=e.length;this.context.lineCap="round",e.length===1&&e[0].length===1?this.context.setLineDash([]):this.context.setLineDash([this.totalLength/t-this.gapLength,this.gapLength]);let i=0;for(let n=0;n<s;++n){const r=e[n],o=r.length/t,l=this.startAngle+i*2*Math.PI,c=l+o*2*Math.PI;this.context.beginPath(),this.context.arc(this.centerX,this.centerY,this.radius,l,c,!1),this.context.strokeStyle=r.color,this.context.lineWidth=r.lineWidth*this.dpr,this.context.stroke(),i+=o}}}function N_({container:a,media:e,url:t,needFadeIn:s,aspecter:i=a,thumbImage:n,fadeInElement:r=e,onRender:o,onRenderFinish:l,useRenderCache:c}){return s&&r.classList.add("fade-in"),Vn(e,t,c).then(()=>lm.mutateElement(a,()=>{i?.append(e),s?(o?.(),r.addEventListener("animationend",()=>{lm.mutate(()=>{r.classList.remove("fade-in"),n?.remove(),a.classList.add("no-background"),l?.()})},{once:!0})):(n?.remove(),a.classList.add("no-background"),o?.(),l?.())}))}const yp=Symbol("RAF"),vf=Symbol("TIMEOUT"),Dt=a=>{const{element:e,className:t,forwards:s,duration:i,onTransitionEnd:n,onTransitionStart:r,useRafs:o}=a,l=t&&t.split(" "),c=e[vf],d=e[yp];if(c!==void 0&&clearTimeout(+c),d!==void 0&&(window.cancelAnimationFrame(+d),o||delete e[yp]),o&&wt.isAvailable("animations")&&i){e[yp]=""+window.requestAnimationFrame(()=>{delete e[yp],Dt({...a,useRafs:o-1})});return}s&&t&&e.classList.add(...l);const u=()=>{delete e[vf],!s&&t&&e.classList.remove("backwards",...l),e.classList.remove("animating"),n?.()};if(r?.(),!wt.isAvailable("animations")||!i){e.classList.remove("animating","backwards"),u();return}e.classList.add("animating"),e.classList.toggle("backwards",!s),e[vf]=""+setTimeout(u,i)},yf=200;class Kn{constructor(e){this.tempId=0,this.detached=!0,this.promise=null,this.isUpload=!1,this.cancelable=!0,this.streamable=!1,this.rtmp=!1,this.tryAgainOnFail=!0,this.attachMethod="append",this.onClick=t=>{t&&_e(t),this.preloader.classList.contains("manual")?this.loadFunc?.(t):this.promise?.cancel?.()},e&&Nt(this,e),this.isUpload&&(this.tryAgainOnFail=!1)}constructContainer(e={}){this.preloader||(this.preloader=document.createElement("div"),this.rtmp?this.preloader.classList.add("preloader-container-rtmp"):this.preloader.classList.add("preloader-container"),e.color&&this.preloader.classList.add("preloader-"+e.color),e.bold&&this.preloader.classList.add("preloader-bold"),this.streamable&&this.preloader.classList.add("preloader-streamable"))}constructDownloadIcon(){this.constructContainer()}construct(){this.construct=null,this.constructContainer(),this.rtmp?this.preloader.innerHTML=`
- <div class="loading-wrap is-loading">
- <div class="loading"></div>
- <div class="loading_bezel-wrap">
- <div class="loading"></div>
- </div>
- </div>`:this.preloader.innerHTML=`
- <div class="you-spin-me-round">
- <svg xmlns="http://www.w3.org/2000/svg" class="preloader-circular" viewBox="${this.streamable?"25 25 50 50":"27 27 54 54"}">
- <circle class="preloader-path-new" cx="${this.streamable?"50":"54"}" cy="${this.streamable?"50":"54"}" r="${this.streamable?19:24}" fill="none" stroke-miterlimit="10"/>
- </svg>
- </div>`,this.streamable?this.totalLength=118.61124420166016:this.totalLength=149.82473754882812,this.cancelable?(this.preloader.innerHTML+=`
- <svg xmlns="http://www.w3.org/2000/svg" class="preloader-close" viewBox="0 0 24 24">
- <g fill="none" fill-rule="evenodd">
- <polygon points="0 0 24 0 24 24 0 24"/>
- <path fill="#000" fill-rule="nonzero" d="M5.20970461,5.38710056 L5.29289322,5.29289322 C5.65337718,4.93240926 6.22060824,4.90467972 6.61289944,5.20970461 L6.70710678,5.29289322 L12,10.585 L17.2928932,5.29289322 C17.6834175,4.90236893 18.3165825,4.90236893 18.7071068,5.29289322 C19.0976311,5.68341751 19.0976311,6.31658249 18.7071068,6.70710678 L13.415,12 L18.7071068,17.2928932 C19.0675907,17.6533772 19.0953203,18.2206082 18.7902954,18.6128994 L18.7071068,18.7071068 C18.3466228,19.0675907 17.7793918,19.0953203 17.3871006,18.7902954 L17.2928932,18.7071068 L12,13.415 L6.70710678,18.7071068 C6.31658249,19.0976311 5.68341751,19.0976311 5.29289322,18.7071068 C4.90236893,18.3165825 4.90236893,17.6834175 5.29289322,17.2928932 L10.585,12 L5.29289322,6.70710678 C4.93240926,6.34662282 4.90467972,5.77939176 5.20970461,5.38710056 L5.29289322,5.29289322 L5.20970461,5.38710056 Z"/>
- </g>
- </svg>
- <svg xmlns="http://www.w3.org/2000/svg" class="preloader-download" viewBox="0 0 24 24">
- <g fill="none" fill-rule="evenodd">
- <polygon points="0 0 24 0 24 24 0 24"/>
- <path fill="#000" fill-rule="nonzero" d="M5,19 L19,19 C19.5522847,19 20,19.4477153 20,20 C20,20.5128358 19.6139598,20.9355072 19.1166211,20.9932723 L19,21 L5,21 C4.44771525,21 4,20.5522847 4,20 C4,19.4871642 4.38604019,19.0644928 4.88337887,19.0067277 L5,19 L19,19 L5,19 Z M11.8833789,3.00672773 L12,3 C12.5128358,3 12.9355072,3.38604019 12.9932723,3.88337887 L13,4 L13,13.585 L16.2928932,10.2928932 C16.6533772,9.93240926 17.2206082,9.90467972 17.6128994,10.2097046 L17.7071068,10.2928932 C18.0675907,10.6533772 18.0953203,11.2206082 17.7902954,11.6128994 L17.7071068,11.7071068 L12.7071068,16.7071068 C12.3466228,17.0675907 11.7793918,17.0953203 11.3871006,16.7902954 L11.2928932,16.7071068 L6.29289322,11.7071068 C5.90236893,11.3165825 5.90236893,10.6834175 6.29289322,10.2928932 C6.65337718,9.93240926 7.22060824,9.90467972 7.61289944,10.2097046 L7.70710678,10.2928932 L11,13.585 L11,4 C11,3.48716416 11.3860402,3.06449284 11.8833789,3.00672773 L12,3 L11.8833789,3.00672773 Z"/>
- </g>
- </svg>`,this.downloadSvg=this.preloader.lastElementChild,this.cancelSvg=this.downloadSvg.previousElementSibling):this.preloader.classList.add("preloader-swing"),this.circle=this.preloader.firstElementChild.firstElementChild.firstElementChild,this.cancelable&&J(this.preloader,this.onClick)}setDownloadFunction(e){this.loadFunc=e}setManual(){this.preloader.classList.add("manual"),this.setProgress(0)}attachPromise(e){if(this.isUpload&&this.promise)return;this.promise=e;const t=--this.tempId,s=Date.now(),i=n=>{if(e.notify=e.notifyAll=null,t!==this.tempId)return;const r=Date.now()-s;if(!n&&this.cancelable){this.setProgress(100);const o=yf*.75;r<o?this.detach():setTimeout(()=>{t===this.tempId&&this.detach()},o)}else this.tryAgainOnFail?(this.attach(this.preloader.parentElement),$s(()=>{this.setManual()})):this.detach();this.promise=e=null};e.then(()=>i(null)).catch(n=>i(n)),e.addNotifyListener?.(n=>{if(t!==this.tempId)return;const r=n.done/n.total*100;this.setProgress(r)})}attach(e,t=!1,s){if(!this.detached&&(!this.preloader||!this.preloader.classList.contains("manual")))return;this.construct?.(),this.preloader.parentElement&&this.preloader.classList.remove("manual"),this.detached=!1,s&&this.attachPromise(s);let i=0;(this.detached||this.preloader.parentElement!==e)&&(i=mr(this.preloader)?1:2,this.preloader.parentElement!==e&&e[this.attachMethod](this.preloader)),Dt({element:this.preloader,className:"is-visible",forwards:!0,duration:yf,useRafs:i}),this.cancelable&&t&&this.setProgress(0)}detach(){this.detached||(this.detached=!0,this.preloader?.parentElement&&Dt({element:this.preloader,className:"is-visible",forwards:!1,duration:yf,onTransitionEnd:()=>{this.preloader.remove()},useRafs:1}))}setProgress(e){if(!(!this.totalLength&&!mr(this.circle))){if(e===0){this.circle.style.strokeDasharray="";return}try{this.totalLength||(this.totalLength=this.circle.getTotalLength()),this.circle.style.strokeDasharray=""+Math.max(5,e/100*this.totalLength)+", "+this.totalLength}catch{}}}}function zh({photo:a,cacheContext:e,useBlur:t,ignoreCache:s,onlyStripped:i}){const n=["video","gif"].includes(a.type);if(!e.downloaded||n||s){if(a._==="document"&&e.downloaded&&!s&&(!n||e.type!==Uy))return null;const r=a.sizes||a.thumbs,o=r?.length;if(!o)return null;let l=-1;if(!i)for(let d=o-1;d>=0;--d){const u=r[d];if(u.type===e.type)l=d;else if(l){const h=Ae.getCacheContext(a,u.type);if(h.downloaded)return gv(a,u,!1,h.url)}}const c=r.find(d=>d._==="photoStrippedSize");if(c&&"bytes"in c)return gv(a,c,t)}return null}const Fv=320,Tk=120,xk=200,Ak=368;function Tc({photo:a,element:e,boxWidth:t,boxHeight:s,noZoom:i=!0,message:n,pushDocumentSize:r,photoSize:o,size:l,canHaveVideoPlayer:c}){const d=$C(a);!o&&!l&&(o=ha(a,t,s,void 0,r));const u=a?._==="document";l||(u||d?l=ii(a.w||o.w||512,a.h||o.h||512):l=ii(o.w||100,o.h||100));let h=ii(t,s);h=l=l.aspect(h,i);let p=!0;if(!u||["video","gif"].includes(a.type)||d){const m=xk;h.width<m&&h.height<m&&(h=l=l.aspectCovered(ii(m,m))),n&&(n.message||n.factcheck||n.reply_to_mid||n.media.webpage||n.replies&&n.replies.pFlags.comments&&n.replies.channel_id.toChatId()!==hL)&&h.width<Fv&&(h=ii(Fv,h.height),p=!1);const g=a?.type==="video"&&c?Ak:Tk;h.width<g&&n&&(h=ii(g,h.height),p=!1)}return e.style.width=h.width+"px",e.style.height=h.height+"px",{photoSize:o,size:l,isFit:p}}async function Bi({photo:a,message:e,container:t,boxWidth:s,boxHeight:i,withTail:n,isOut:r,lazyLoadQueue:o,middleware:l,size:c,withoutPreloader:d,loadPromises:u,autoDownloadSize:h,noBlur:p,noThumb:m,noFadeIn:g,blurAfter:f,managers:v=I.managers,processUrl:y,fadeInElement:w,onRender:b,onRenderFinish:S,useBlur:_,useRenderCache:M,canHaveVideoPlayer:C,uploadingFileName:L}){const E={loadPromises:{thumb:Promise.resolve(),full:Promise.resolve()},images:{thumb:null,full:null},preloader:null,aspecter:null};t||(d=!0,o=void 0);const x=uL(a),R=a._==="document",B=R&&a.mime_type.startsWith("image/")&&!c,N=$C(a);if(!(a.sizes||a.thumbs)&&!N&&!B&&!x)return s&&i&&!c&&R&&Tc({photo:a,element:t,boxWidth:s,boxHeight:i,message:e,canHaveVideoPlayer:C}),E;let G=h===0;c||(s===void 0&&(s=st.active.regular.width),i===void 0&&(i=st.active.regular.height)),t&&t.classList.add("media-container");let O=t,$=!0,H=Promise.resolve(),D,U;if(s&&i&&!c&&!x&&t){const ae=Tc({photo:a,element:t,boxWidth:s,boxHeight:i,message:e,photoSize:B?{_:"photoSize",w:a.w,h:a.h,size:a.size,type:Uy}:void 0,canHaveVideoPlayer:C});if(c=ae.photoSize,$=ae.isFit,U=Ae.getCacheContext(a,c.type),!$&&!N){O=document.createElement("div"),O.classList.add("media-container-aspecter"),O.style.width=ae.size.width+"px",O.style.height=ae.size.height+"px";const ke=zh({photo:a,cacheContext:U,useBlur:_!==void 0?_:!p,ignoreCache:!0,onlyStripped:!0});if(ke){H=ke.loadPromise;const re=ke.image;re.classList.add("media-photo"),t.append(re)}else(await Bi({container:t,message:e,photo:a,boxWidth:0,boxHeight:0,size:c,lazyLoadQueue:o,isOut:r,loadPromises:u,middleware:l,withoutPreloader:!0,withTail:n,autoDownloadSize:h,noBlur:p,noThumb:!0,blurAfter:!0,managers:v})).images.full.classList.add("media-photo","thumbnail");t.classList.add("media-container-fitted"),t.append(O)}}else!c&&!x&&(c=ha(a,s,i,!0)),U=Ae.getCacheContext(a,c?.type);if(!m&&!N&&!x&&O){const ae=zh({photo:a,cacheContext:U,useBlur:_!==void 0?_:!p});ae&&(H=Promise.all([H,ae.loadPromise]),E.loadPromises.thumb=E.loadPromises.full=H,D=E.images.thumb=ae.image,D.classList.add("media-photo"),O.append(D))}if(E.aspecter=O,c?._==="photoSizeEmpty"&&R||c?.bytes)return E;let j;c?._==="videoSize"?(j=E.images.full=Do({middleware:l}),j.autoplay=!0,j.loop=!0,j.muted=!0,j.classList.add("media-photo")):(j=E.images.full=new Image,j.classList.add("media-photo"));const q=(D||!U.downloaded)&&wt.isAvailable("animations")&&!g;let W;L??(L=e?.uploadingFileName?.[0]),d||((!U.downloaded||L)&&(W=new Kn({attachMethod:"prepend",isUpload:!!L})),L&&(W.attachPromise(fs.getUpload(L)),W.attach(t),G=void 0));const ee=()=>{const ae=B&&!c;return fs.downloadMediaURL({media:a,thumb:c,queueId:o&&o.queueId,onlyCache:ae?void 0:G})},z=ae=>N_({container:t,media:j,url:ae,needFadeIn:q,aspecter:O,thumbImage:D,fadeInElement:w,onRender:b,onRenderFinish:S,useRenderCache:M}),Z=async ae=>{if(!(l&&!l())){if(y&&(ae=await y(ae)),f){const ke=pL(ae,12);return ke.promise.then(()=>z(ke.canvas.toDataURL()))}return z(ae)}};let de;const ie=!x&&c.w>=150&&c.h>=150||G,oe=async()=>{G&&!d&&W&&(W.construct(),W.setManual());const ae=ee(),ke=Ae.getCacheContext(a,c?.type);W&&!ke.downloaded&&!d&&ie&&W.attach(t,!1,ae),G=void 0;const re=ae.then(Z);return re.catch(as),{download:ae,render:re}};return W&&W.setDownloadFunction(oe),U.downloaded?H=de=(await oe()).render:o?o.push({div:t,load:()=>oe().then(({download:ae})=>ae)}):de=(await oe()).render,u&&H&&u.push(H),E.loadPromises.thumb=H,E.loadPromises.full=de||Promise.resolve(),E.preloader=W,E}function Mg(){const[a,e]=K(Ls.isNight());return Ta(I)("theme_changed",()=>{e(Ls.isNight())}),a}const Rk=Y('<svg><path d="M8.7221 7.50194L11.1473 2.67049C11.4277 2.11345 12.106 1.88988 12.6593 2.17029C12.8753 2.28018 13.0496 2.45828 13.1595 2.67807L15.452 7.339C15.6377 7.72173 16.0053 7.97941 16.4259 8.02867L21.2195 8.60465C21.8712 8.68423 22.3373 9.27916 22.2615 9.93473C22.2274 10.2038 22.1062 10.4539 21.9129 10.6433L18.1198 14.3835C17.9644 14.535 17.8924 14.7472 17.9189 14.9632L18.5517 20.0107C18.6427 20.7345 18.1311 21.3938 17.4111 21.4848C17.1383 21.5189 16.8655 21.4696 16.623 21.337L12.6176 19.1467C12.3258 18.9876 11.9772 18.9838 11.6854 19.1353L7.53223 21.265C6.94867 21.5643 6.23627 21.3294 5.93691 20.742C5.82322 20.5222 5.78533 20.2759 5.81944 20.0334L6.14911 17.7143C6.31205 16.5813 7.01309 15.5961 8.02864 15.0769L12.6365 12.7237C12.7578 12.6631 12.807 12.5115 12.7464 12.3865C12.6972 12.2917 12.5948 12.2349 12.4887 12.25L6.85015 13.061C5.98996 13.1822 5.1184 12.9397 4.4401 12.3865L2.56436 10.8555C2.03006 10.4198 1.9429 9.624 2.37868 9.08591C2.58331 8.83581 2.87509 8.67286 3.1934 8.63118L8.00591 8.01351C8.31285 7.97183 8.58189 7.78236 8.7221 7.50194Z"fill=url(#paint0_linear_6651_5783)></svg>',!1,!0),Fk=Y('<svg width=24 height=24 viewBox="0 0 24 24"fill=none xmlns=http://www.w3.org/2000/svg><path d="M12.989 3.53063C12.5001 3.42074 11.981 3.65568 11.746 4.12557L9.31704 8.95703C9.17684 9.23744 8.91158 9.42691 8.60085 9.46859L3.78834 10.09C3.47761 10.1317 3.19341 10.2833 2.99257 10.522L4.77358 11.9772C5.33441 12.4357 6.06197 12.6365 6.77816 12.5342L12.413 11.7271C12.7464 11.6816 13.0723 11.8483 13.2201 12.1477C13.4134 12.5304 13.2618 13.0003 12.8791 13.1973L11.4088 13.9476L13.0837 13.7051C13.1898 13.69 13.2959 13.7468 13.3414 13.8415C13.4058 13.9666 13.3527 14.1182 13.2315 14.1788L8.62359 16.532C7.60803 17.0511 6.907 18.0364 6.74405 19.1694L6.52806 20.6738C6.72511 20.8708 7.03584 20.9239 7.29351 20.7913L11.4391 18.6616C11.89 18.4305 12.4243 18.4381 12.8677 18.6806L16.8731 20.8708C17.0171 20.9504 17.1838 20.9807 17.3467 20.9618C17.7711 20.9087 18.0781 20.5146 18.025 20.0789L17.396 15.0276C17.3505 14.6487 17.4794 14.2735 17.7484 14.0083L21.5416 10.2682C21.606 10.2037 21.6553 10.1279 21.6894 10.0446L17.0208 9.48375C16.6002 9.43449 16.2364 9.17302 16.047 8.79408L15.8651 8.41893C15.4824 8.2522 15.1678 7.95663 14.9784 7.5739L12.989 3.53063Z"fill=url(#paint1_linear_6651_5783)></path><path d="M12.898 1.69684C12.0795 1.2838 11.0867 1.61348 10.6774 2.43198L8.24845 7.26723C8.18782 7.38849 8.07035 7.47186 7.93772 7.48701L3.12521 8.10847C2.67048 8.16531 2.25365 8.40025 1.96566 8.75646C1.34799 9.52191 1.46546 10.6436 2.22713 11.265L4.10666 12.7997C4.89864 13.4439 5.91798 13.7281 6.92596 13.5841L10.9086 13.0119L7.78615 14.6073C6.61523 15.206 5.81188 16.3352 5.6262 17.6388L5.29273 19.9579C5.24347 20.3103 5.30031 20.6665 5.46326 20.9848C5.89146 21.8298 6.92975 22.1671 7.77478 21.7351L11.9241 19.6054C12.0606 19.5335 12.2235 19.5372 12.3599 19.613L16.3653 21.7995C16.7026 21.9852 17.0929 22.061 17.4756 22.0117C18.4874 21.8829 19.1998 20.9545 19.0747 19.9465L18.4457 14.8953C18.4381 14.846 18.457 14.7929 18.4911 14.7588L22.2843 11.0187C22.5609 10.7421 22.739 10.3821 22.7845 9.99558C22.8944 9.05203 22.2275 8.19563 21.2839 8.08195L16.4866 7.50596C16.2478 7.47944 16.0356 7.32786 15.9257 7.10808L13.6369 2.44335C13.4778 2.12125 13.2163 1.85979 12.898 1.69684ZM11.621 2.90565C11.7688 2.61008 12.1288 2.49261 12.4206 2.6404C12.5342 2.69724 12.629 2.79576 12.6858 2.91323L14.9784 7.5739C15.2436 8.11578 15.7628 8.48362 16.3615 8.55562L21.1589 9.1316C21.5189 9.17329 21.7765 9.50296 21.7348 9.87053C21.7159 10.0221 21.6477 10.1621 21.5416 10.2682L17.7484 14.0083C17.4794 14.2735 17.3505 14.6487 17.396 15.0276L18.025 20.0789C18.0781 20.5146 17.7711 20.9087 17.3467 20.9618C17.1838 20.9807 17.0171 20.9504 16.8731 20.8708L12.8677 18.6806C12.4243 18.4381 11.89 18.4345 11.4391 18.6657L7.28974 20.7953C6.96764 20.9583 6.57354 20.8294 6.40681 20.5035C6.34618 20.3823 6.32345 20.2421 6.34239 20.1056L6.67207 17.7903C6.80849 16.8278 7.40721 15.9904 8.2674 15.5508L12.8753 13.1976C13.2618 13.0006 13.4134 12.5304 13.2201 12.1477C13.0685 11.8483 12.7464 11.6817 12.413 11.7271L6.77438 12.5345C6.05819 12.6368 5.33441 12.4357 4.77358 11.9772L2.89785 10.4427C2.58712 10.1888 2.53786 9.73033 2.79174 9.4196C2.90921 9.2756 3.07595 9.18087 3.25784 9.15813L8.07035 8.53667C8.55539 8.47604 8.97601 8.17668 9.19579 7.7409L11.621 2.90565Z"fill=url(#paint2_linear_6651_5783)>');function dS(a){return(()=>{const e=Rk();return Me(()=>Es(e,"class",a.stroke&&"currency-star-icon-stroke")),e})()}function ob(a={}){return(()=>{const e=Fk(),t=e.firstChild;return k(e,(()=>{const s=V(()=>!!a.stroke);return()=>s()&&T(dS,{stroke:!0})})(),t),k(e,T(dS,{}),t),Me(()=>Es(e,"class",Ge("currency-star-icon",a.class))),e})()}const Bk=Y("<div class=avatar-stories-simple>"),Dk=Y("<div><div>"),$k=Y("<div class=avatar-background>"),Nk=Y("<div>"),Ok=200,yc=new Map,ic=new Map,bf=new Set;function lb(a,e){return a+(e?"_"+e:"")}const O_=({peerId:a,threadId:e})=>{const t=lb(a,e),s=yc.get(t);if(s?.size)for(const i of s)i.render()},Lg=({peerId:a})=>{const e=lb(a),t=yc.get(e);if(t?.size)for(const s of t)s.updateStoriesSegments()};I.addEventListener("avatar_update",O_);I.addEventListener("peer_title_edit",async a=>{await I.managers.appAvatarsManager.isAvatarCached(a.peerId)||O_(a)});I.addEventListener("peer_stories",({peerId:a})=>{Lg({peerId:a})});I.addEventListener("stories_read",Lg);I.addEventListener("story_deleted",Lg);I.addEventListener("story_new",Lg);const hS=async(a,e)=>{if(e){const s=[{length:1,type:await I.managers.appStoriesManager.getUnreadType(a,e)}];return{cached:!0,result:Promise.resolve(s)}}return I.managers.acknowledged.appStoriesManager.getPeerStoriesSegments(a)},Uk=(a,e,t)=>{const s=a.createLinearGradient(e*.9156*t,e*-.05695821429*t,e*.1342364286*t,e*1.02370714286*t);return s.addColorStop(0,yi.getProperty("avatar-color-story-unread-from")),s.addColorStop(1,yi.getProperty("avatar-color-story-unread-to")),s},Hk=(a,e,t)=>{const s=a.createLinearGradient(e*.5*t,e*0*t,e*.5*t,e*1*t);return s.addColorStop(0,yi.getProperty("avatar-color-story-close-from")),s.addColorStop(1,yi.getProperty("avatar-color-story-close-to")),s};function Wh(a){let e=ne(a,"avatar");return e&&(e=ne(e,"has-stories")||e),e}const Gk=a=>{const e=Math.round(a*.8888888888888888),t=a*(1+2/54),s=a/54,i=2*s;return{size:a,willBeSize:e,totalSvgSize:t,multiplier:s,strokeWidth:i}};function U_(a,e,t=100,s){return Bi({container:a.node,message:null,photo:e,boxHeight:t,boxWidth:t,withoutPreloader:!0,size:s}).then(i=>(a.node.classList.replace("media-container","avatar-relative"),a.node.style.width=a.node.style.height="",[i.images.thumb,i.images.full].forEach(n=>{n&&n.classList.replace("media-photo","avatar-photo")}),i.images.thumb&&i.images.thumb.classList.add("avatar-photo-thumbnail"),i.loadPromises.thumb))}function Vk(a){const[e,t]=K(),s=V(n=>{if(e()!==void 0)return n?.size===a.size?n:Gk(a.size)}),i=V(()=>{const n=s();if(!n)return;let r;if(a.isStoryFolded!==void 0){const f=V(()=>{const v=e();return(v.find(b=>b.type==="close")||v.find(b=>b.type==="unread")||v[0]).type});r=(()=>{const v=Bk();return Me(y=>er(v,{["is-"+f()]:!0},y)),v})()}const o=(f,v)=>f.type==="read"?{color:a.colors?.read||yi.getProperty("avatar-color-story-read"),length:f.length,lineWidth:n.strokeWidth/2}:f.type==="close"||v?{color:p??(p=Hk(d,c.width,u)),length:f.length,lineWidth:n.strokeWidth}:{color:h??(h=Uk(d,c.width,u)),length:f.length,lineWidth:n.strokeWidth},l=new kk,{canvas:c,context:d,dpr:u}=l;l.prepare({radius:n.size/2,gap:4*n.multiplier,width:n.totalSvgSize,height:n.totalSvgSize});let h,p;c.style.setProperty("--offset",`${(n.totalSvgSize-n.size)/-2}px`),c.classList.add("avatar-stories-svg");const m=()=>{const f=e(),v=f.find(b=>b.type==="close");let y=f.map(b=>o(b,!!v));const w=y.reduce((b,S)=>b+S.length,0);w>30&&(y=y.map(b=>({...b,length:Math.floor(b.length/w*30)})).filter(b=>b.length>0)),l.render(y)},g=Mg();return le(Vt([g,e],()=>{h=p=void 0,m()})),r?[c,r]:c});return{setStoriesSegments:t,storyDimensions:s,storiesCircle:i}}const jn=a=>{const[e,t]=K(!1),[s,i]=K(),[n,r]=K(),[o,l]=K(),[c,d]=K(),[u,h]=K(),[p,m]=K(!1),[g,f]=K(!1),[v,y]=K(!1),{setStoriesSegments:w,storyDimensions:b,storiesCircle:S}=Vk({size:a.size,colors:a.storyColors,isStoryFolded:a.isStoryFolded}),_=Mt(),M=Mt(),C=I.myId,L=I.managers,E=a.wrapOptions?.middleware?a.wrapOptions.middleware.create():Ht();let x=!1,R;ze(()=>{R=void 0,E.destroy(),_.resolve(),O(),a.lazyLoadQueue?.delete({div:oe})});const B=re=>{r(re),t(!0),_.resolve(),M.resolve()},N=re=>{l(re),t(!0),M.resolve()},G=()=>lb(a.peerId,a.threadId),O=()=>{if(!q)return;const re=ic.get(q);re&&(re.delete(void 0),re.size||ic.delete(q));const ce=yc.get(q);ce?.delete(ke)&&(ce.size||yc.delete(q))},$=async re=>{const ce=E.get(),{peerId:Ie,useCache:Ve}=a,{photo:fe,size:Xe}=re,Ye=Ae.loadAvatar(Ie,fe,Xe,a.accountNumber),Ze=Ye,Je=!(Ye instanceof Promise),tt=!Je&&wt.isAvailable("animations");let ht;const Ee=ht=document.createElement("img");Ee.className=Ge("avatar-photo",tt&&"fade-in");let ve,Qe,A,F;if(Je)Qe=()=>{ce()&&B(Ee)};else{if(Xe==="photo_big"){const X=await $({photo:fe,size:"photo_small"});if(!ce())return;ve=X.loadThumbPromise||X.loadPromise,A=X.thumbImage}else if(fe.stripped_thumb){F=A=document.createElement("img"),A.className="avatar-photo avatar-photo-thumbnail";const X=mL(fe.stripped_thumb);ve=Vn(A,X,a.useCache,a.processImageOnLoad).then(()=>{n()||!ce()||N(F)})}Qe=()=>{ce()&&(B(Ee),tt?setTimeout(()=>{ht.classList.remove("fade-in"),l()},tt?Ok:0):l())}}const Q=en(Ze,X=>{const ge=Ka(ht,X,void 0,Ve,a.processImageOnLoad);return en(ge,Qe),ge instanceof Promise?ge:Promise.resolve(ge)});return{cached:Je,loadPromise:Q,loadThumbPromise:Je?Q:ve||Promise.resolve(),thumbImage:A,thumbElement:F,image:ht,element:Ee}},H=({abbreviature:re,icon:ce,color:Ie,isForum:Ve,isTopic:fe,isSubscribed:Xe,storiesSegments:Ye})=>{l(),r(),i(ce),d(re),h(Ie),m(Ve),f(fe),y(Xe),w(Ye)},D=async()=>{if(!a.withStories||a.peerId===I.myId&&a.isDialog)return;const re=await(await hS(a.peerId,a.storyId)).result;R&&await(await R)?.loadThumbPromise,w(re)},U=async re=>{const ce=E.get(),{isDialog:Ie,withStories:Ve,storyId:fe,isBig:Xe,peerTitle:Ye,threadId:Ze,wrapOptions:Je}=a;let{peerId:tt}=a;if(Ye!==void 0&&(tt=Wt),tt===C&&Ie){H({icon:a.meAsNotes?"mynotes":"saved",isForum:!a.meAsNotes&&Vw.savedAsForum}),!a.meAsNotes&&Ft(Se=>{le(Vt(()=>Vw.savedAsForum,m,{defer:!0})),ce.onDestroy(Se)});return}const ht=a.peer??Ae.getPeer(tt);if(Ye){const Se=zw(ht),xe=Cg(Ye);H({abbreviature:kl(xe),color:Se});return}if(Ze){const Se=await L.dialogsStorage.getForumTopic(tt,Ze);return H({isTopic:!0}),Pg({...Je,middleware:ce,topic:Se,lazyLoadQueue:!1}).then(xe=>{B(xe)})}if(!ce())return;if(tt!==Wt&&tt.isUser()&&ht?.pFlags?.deleted){H({color:"archive",icon:"deletedaccount"});return}const Ee=!!ht?.pFlags?.forum,ve=a.isSubscribed??!!ht?.subscription_until_date,Qe=Ve&&(ht?.stories_max_id||fe)&&await hS(tt,fe),A=Qe?.cached?await Qe.result:void 0;if(!ce())return;const F=Xe?"photo_big":"photo_small",Q=Lk(ht),X=!!Q,ge=X&&!!n(),he=a.accountNumber===Vr()&&X&&Ae.isAvatarCached(tt,F);if(!ce())return;let Le=!1;if(!ge&&!he){let Se;if(tt&&(tt!==C||!Ie)&&(Se=zw(ht)),tt===Lo){H({color:Se,icon:"reply_filled"});return}if(tt===Oy){H({color:"violet",icon:"author_hidden"});return}const xe=Ek(ht);H({abbreviature:kl(xe),color:Se,isForum:Ee,isSubscribed:ve,storiesSegments:A}),Le=!0}if(Qe&&!Qe.cached&&D(),X){const Se=$({photo:Q,size:F,onlyThumb:re});if(Le)return Se;const xe=!!A,lt=Ee!==p(),mt=ve!==v();return Se.then(({loadThumbPromise:at})=>at).then(()=>{ce()&&(xe&&w(A),lt&&m(Ee),mt&&y(ve))}),Se}},j=re=>(!re&&!g()&&B(),R=void 0,re);let q;const W=async re=>{const ce=G();if(ce!==q){O(),q=ce;let Ye=yc.get(ce);Ye||yc.set(ce,Ye=new Set),Ye.add(ke)}re?.peerId!==void 0&&a.peerId!==re.peerId&&(oe.dataset.peerId=""+re.peerId),re&&Object.assign(a,re),E.clean();const Ie=E.get();if(a.lazyLoadQueue)if(bf.has(a.peerId))x&&a.lazyLoadQueue.delete({div:oe});else{if(x)return;x=!0;const Ye=G();let Ze=ic.get(Ye);Ze||ic.set(Ye,Ze=new Set),Ze.add(ke),a.lazyLoadQueue.push({div:oe,load:()=>(bf.add(a.peerId),W())});const tt=await(R=U(!0));return Ie()?j(tt):void 0}bf.add(a.peerId);const Ve=R=U(),fe=ic.get(ce);if(fe){fe.delete(ke);const Ye=Array.from(fe);ic.delete(ce);for(let Ze=0,Je=Ye.length;Ze<Je;++Ze)Ye[Ze].render()}const Xe=await Ve;if(Ie())return x&&(x=!1),j(Xe)};a.onStoriesStatus&&le(()=>{a.onStoriesStatus(!!b())});const ee=()=>({"is-forum":p(),"is-topic":g(),"avatar-relative":!!o()||v()}),z=()=>({...!S()&&ee(),"has-stories":!!b()}),Z=()=>{const re=b();return{padding:re?(re.size-re.willBeSize)/2+"px":void 0,"--size":g()&&a.wrapOptions.customEmojiSize.width?a.wrapOptions.customEmojiSize.width+"px":void 0}},de=[V((()=>{const re=V(()=>!!s());return()=>re()&&Be(s(),"avatar-icon","avatar-icon-"+s())})()),V(o),V(()=>[n(),c()].find(Boolean)),V((()=>{const re=V(()=>!!v());return()=>re()&&ob({class:"avatar-star",stroke:!0})})())],ie=T(Js,{get when(){return b()},fallback:de,get children(){const re=Dk(),ce=re.firstChild;return k(re,S,ce),k(re,(()=>{const Ie=V(()=>a.isStoryFolded!==void 0);return()=>Ie()&&$k()})(),ce),k(ce,de),Me(Ie=>{const Ve=`avatar avatar-like avatar-${b().willBeSize} avatar-gradient`,fe=ee(),Xe=u();return Ve!==Ie._v$&&be(ce,Ie._v$=Ve),Ie._v$2=er(ce,fe,Ie._v$2),Xe!==Ie._v$3&&Es(ce,"data-color",Ie._v$3=Xe),Ie},{_v$:void 0,_v$2:void 0,_v$3:void 0}),re}});let oe;const ke={element:(()=>{const re=Nk(),ce=oe;return typeof ce=="function"?Ue(ce,re):oe=re,so(re,ni({get class(){return`avatar avatar-like avatar-${a.size} avatar-gradient`},get classList(){return z()},get"data-color"(){return u()},get"data-peer-id"(){return a.peerId},get"data-story-id"(){return a.storyId},get style(){return Z()}},()=>a.props||{}),!1,!0),k(re,ie),re})(),ready:e,readyPromise:_,readyThumbPromise:M,node:oe,render:W,setIcon:i,setStoriesSegments:w,setIsSubscribed:y,updateStoriesSegments:D,set:H,color:u};return(a.peerId!==void 0||a.peerTitle!==void 0||a.peer!==void 0)&&W(),ke};function Eg(a){return jn(a).element}function vs(a){return Ft(e=>(a.middleware.onDestroy(e),(a.wrapOptions??(a.wrapOptions={})).middleware=a.middleware,jn(a)))}class mi extends ue{constructor(e,t={}){if(super("popup-peer"+(e?" "+e:""),{overlayClosable:!0,...t,title:!0,buttons:t.buttons&&Go(t.buttons)}),this.className=e,t.peerId){const i=!!(t.peerId===I.myId&&t.threadId),{node:n}=vs({middleware:this.middlewareHelper.get(),size:32,isDialog:!0,peerId:i?t.threadId:t.peerId,threadId:i?void 0:t.threadId,meAsNotes:i});this.header.prepend(n)}t.noTitle||(t.titleLangKey||!t.title?this.title.append(P(t.titleLangKey||"AppName",t.titleLangArgs)):t.title instanceof HTMLElement||t.title instanceof DocumentFragment?this.title.append(t.title):this.title.innerText=t.title||"");const s=document.createDocumentFragment();if(t.descriptionLangKey||t.description||t.descriptionRaw){const i=this.description=document.createElement("p");i.classList.add("popup-description"),t.descriptionLangKey?i.append(P(t.descriptionLangKey,t.descriptionLangArgs)):t.description&&t.description!==!0?Qt(i,t.description):t.descriptionRaw&&i.append(je(t.descriptionRaw)),s.append(i)}if(t.inputField&&s.append(t.inputField.container),t.checkboxes&&(this.container.classList.add("have-checkbox"),t.checkboxes.forEach(i=>{i.withRipple=!0;const n=new _t(i);i.checkboxField=n,s.append(n.label)}),t.buttons.forEach(i=>{if(i.callback){const r=i.callback;i.callback=o=>{const l=new Set;t.checkboxes.forEach(c=>{c.checkboxField.checked&&l.add(c.text)}),r(o,l)}}const n=i.onlyWithCheckbox;if(n){const r=()=>{os([i.element],!n.checkboxField.checked)};this.listenerSetter.add(n.checkboxField.input)("change",r),r()}})),t.inputField){const i=t.buttons.find(n=>!n.isCancel);this.listenerSetter.add(t.inputField.input)("input",()=>{os([i.element],!t.inputField.isValid())})}this.header.after(s)}}class kg{constructor(e,t,s,i){this.peerId=e,this.peerType=t,this.onSelect=s,this.threadId=i,this.construct()}async construct(){let{peerId:e,peerType:t,onSelect:s,threadId:i}=this;const n=await I.managers.appPeersManager.isSavedDialog(e,i),r=await qe({peerId:n?i:e,threadId:n?void 0:i,meAsNotes:n}),o=ue.MANAGERS;t===void 0&&(t=await o.appPeersManager.getDialogType(e,i));const l=(f,v,y=g&&!!v.size)=>{let w=o.appChatsManager.leave(e.toChatId());y&&(w=w.then(()=>o.appMessagesManager.flushHistory(e))),s?.(w)},c=(f,v)=>{let y;if(n)y=o.appMessagesManager.flushHistory(e,!1,!0,i);else if(i)y=o.appMessagesManager.flushHistory(e,!1,!0,i);else if(e.isUser())y=o.appMessagesManager.flushHistory(e,!1,g?!!v.size:void 0);else if(v.size)y=o.appChatsManager.delete(e.toChatId());else return l(f,v);s?.(y)};let d,u,h,p,m,g;switch(t){case"channel":{await o.appChatsManager.hasRights(e.toChatId(),"delete_chat")?(d="ChannelDeleteMenu",h="AreYouSureDeleteAndExitChannel",m=[{langKey:"ChannelDeleteMenu",isDanger:!0,callback:c}],g=[{text:"DeleteChannelForAll"}]):(d="LeaveChannelMenu",h="ChannelLeaveAlertWithName",p=[r],m=[{langKey:"LeaveChannel",isDanger:!0,callback:l}]);break}case"chat":{d="DeleteChatUser",h="AreYouSureDeleteThisChatWithUser",p=[r],m=[{langKey:"DeleteChatUser",isDanger:!0,callback:c}],g=[{text:"DeleteMessagesOptionAlso",textArgs:[await qe({peerId:e})]}];break}case"saved":{d="DeleteChatUser",h="AreYouSureDeleteThisChatSavedMessages",m=[{langKey:"DeleteChatUser",isDanger:!0,callback:c}];break}case"savedDialog":{d="DeleteChatUser",h="DeleteSavedDialogDescription",p=[r],m=[{langKey:"DeleteChatUser",isDanger:!0,callback:c}];break}case"megagroup":case"group":{i?(d="DeleteTopics",u=[1],h="DeleteSelectedTopic",p=[r],m=[{langKey:"Delete",isDanger:!0,callback:c}]):await o.appChatsManager.hasRights(e.toChatId(),"delete_chat")?(d="DeleteMegaMenu",h="AreYouSureDeleteAndExit",m=[{langKey:"DeleteMegaMenu",isDanger:!0,callback:c}],g=[{text:"DeleteChat.DeleteGroupForAll"}]):(d="LeaveMegaMenu",h="AreYouSureDeleteAndExitName",p=[r],m=[{langKey:"DeleteChatUser",isDanger:!0,callback:(f,v)=>l(f,v,!0)}]);break}}ue.createPopup(mi,"popup-delete-chat",{peerId:e,threadId:i,titleLangKey:d,titleLangArgs:u,descriptionLangKey:h,descriptionLangArgs:p,buttons:m,checkboxes:g}).show()}}class Tg extends pn{constructor(e,t){super(!1),this.navigationType=e,this.withOverlay=t,this.onClick=s=>{Hy(s)||this.element&&!(this.element===document.body)&&Mi(s.target,this.element)||(this.listenerOptions?.capture&&_e(s),this.close())},this.listenerOptions=t?{}:{capture:!0}}close(){this.element&&(this.overlay?.remove(),this.element=void 0,this.dispatchEvent("toggle",!1)),pt||window.removeEventListener("contextmenu",this.onClick,this.listenerOptions),document.removeEventListener(Eo,this.onClick,this.listenerOptions),!wr&&this.navigationType&&Pt.removeByType(this.navigationType)}open(e=document.body){this.close(),!wr&&this.navigationType&&Pt.pushItem({type:this.navigationType,onPop:s=>{this.close()}}),this.element=e,!this.overlay&&this.withOverlay&&(this.overlay=document.createElement("div"),this.overlay.classList.add("btn-menu-overlay"),this.overlay.addEventListener(Eo,s=>{_e(s),this.onClick(s)}));const t=this.element===document.body;this.overlay&&(t?this.element.append(this.overlay):this.element.parentElement.insertBefore(this.overlay,this.element)),pt||window.addEventListener("contextmenu",this.onClick,{...this.listenerOptions,once:!0}),document.addEventListener(Eo,this.onClick,this.listenerOptions),this.dispatchEvent("toggle",!0)}}const Vp=document.createElement("div");Vp.classList.add("toasts-container");const Nr=document.createElement("div");Nr.classList.add("toast");let Sl;const dh=new Tg("toast");dh.addEventListener("toggle",a=>{a||no()});function no(){dh.close(),Nr.classList.remove("is-visible"),Sl&&clearTimeout(+Sl),Sl=window.setTimeout(()=>{Nr.remove(),Sl=void 0},200)}function Wi(a,e){dh.close(),St(Nr,a),Nr.parentElement||(Vp.parentNode||document.body.append(Vp),Vp.append(Nr),Nr.offsetLeft),Nr.classList.add("is-visible"),Sl&&clearTimeout(+Sl),dh.open(Nr),Sl=window.setTimeout(no,3e3),e&&dh.addEventListener("toggle",e,{once:!0})}function $e(a){Wi(P(a.langPackKey,a.langPackArguments),a.onClose)}class rn{constructor(e){const t=this.label=document.createElement("label");t.classList.add("radio-field"),e.alignRight&&t.classList.add("radio-field-right");const s=this.input=document.createElement("input");if(s.type="radio",s.name="input-radio-"+e.name,e.value){s.value=e.value;const n=()=>"valueForState"in e?e.valueForState:e.value;e.stateKey&&(Ae.getState().then(r=>{s.checked=$_(r,e.stateKey)===n()}),s.addEventListener("change",()=>{I.managers.appStateManager.setByKey(e.stateKey,n())}))}const i=this.main=document.createElement("div");i.classList.add("radio-field-main"),e.textElement?i.append(e.textElement):e.text?i.textContent=e.text:e.langKey&&ks(i,e.langKey),t.append(s,i)}get checked(){return this.input.checked}set checked(e){this.setValueSilently(e),md(this.input,"change")}get locked(){return!!this.lockIcon}set locked(e){if(!e){this.lockIcon?.remove(),this.lockIcon=void 0,this.main.classList.remove("is-locked");return}this.lockIcon||(this.main.prepend(this.lockIcon=Be("premium_lock","radio-field-lock")),this.main.classList.add("is-locked"))}setValueSilently(e){this.input.checked=e}}function H_(a,e){const t=document.createElement("form");return a.forEach(s=>{const{container:i,input:n}=s;t.append(i),n.addEventListener("change",r=>{n.checked&&e(n.value,r)})}),t}function va(a){return a.reduce((e,t)=>(e.push(...t),e),[])}class zk extends Tg{constructor(){super("menu",!0),this.additionalMenus=[],this.onMouseMove=e=>{const t=[...[...this.additionalMenus].reverse(),{triggerElement:void 0,level:0,element:this.element,close:()=>this.close()}];function s(i,n){const{clientX:r,clientY:o}=e,l=i.getBoundingClientRect(),c=r>=l.right?r-l.right:l.left-r,d=o>=l.bottom?o-l.bottom:l.top-o;return c>=n||d>=n}for(const i of t){if(i.triggerElement&&!s(i.triggerElement,40))break;if(s(i.element,i.level===0?100:40))this.closeAndRemoveMenu(i);else break}},st.addEventListener("resize",()=>{this.element&&this.close()})}isOpened(){return!!this.element}closeAndRemoveMenu(e){e.close();const t=this.additionalMenus.indexOf(e);t>-1&&this.additionalMenus.splice(t,1)}closeMenusByLevel(e){this.additionalMenus.filter(t=>t.level===e).forEach(t=>{t.close();const s=this.additionalMenus.indexOf(t);s>-1&&this.additionalMenus.splice(s,1)})}close(){if(this.element){const{parentElement:e}=this.element;if(this.element.classList.remove("active"),e&&e.classList.remove("menu-open"),this.element.classList.contains("night")){const t=this.element;setTimeout(()=>{t.classList.contains("active")||t.classList.remove("night")},400)}}this.additionalMenus.forEach(e=>{e.close()}),this.additionalMenus=[],super.close(),pt||window.removeEventListener("mousemove",this.onMouseMove)}openBtnMenu(e,t){vn.isDarkOverlayActive&&e.classList.add("night"),super.open(e);const{parentElement:s}=this.element;this.element.classList.add("active","was-open"),s.classList.add("menu-open"),t&&this.addEventListener("toggle",t,{once:!0}),pt||window.addEventListener("mousemove",this.onMouseMove)}addAdditionalMenu(e,t,s,i){this.closeMenusByLevel(s),this.additionalMenus.push({element:e,triggerElement:t,level:s,close:()=>{e.classList.remove("active"),ns(400).then(()=>e.remove()),i()}}),e.classList.add("active","was-open"),i&&this.addEventListener("toggle",i,{once:!0})}}const Li=new zk;let uS=!1;function G_({doc:a,element:e,size:t,textColor:s,strokeWidth:i}){e.classList.add("is-external"),uS||(uS=!0,I.addEventListener("theme_changed",()=>{document.querySelectorAll(".is-external").forEach(l=>{const c=l.set;c?.(!0)})}));const n=async o=>{const l=e.svg,c=yi.getProperty(s());l.querySelectorAll("path").forEach(u=>{u.setAttributeNS(null,"fill",c),u.style.stroke=c,u.style.strokeWidth=i()+"px"});const d=await YE(l.outerHTML);if(!o)return d;e.image.src=d},r=Bi({container:e,photo:a,boxWidth:t,boxHeight:t,withoutPreloader:!0,noFadeIn:!0,noBlur:!0,processUrl:async o=>{const l=await(await fetch(o)).text(),d=new DOMParser().parseFromString(l,"image/svg+xml").firstElementChild;return e.svg=d,e.set=n,n()}});return r.then(async o=>(e.style.width=e.style.height="",e.image=o.images.full,await o.loadPromises.thumb,r))}function Wk(a){if(a.element)return[a.separator,a.element].filter(Boolean);const{icon:e,iconDoc:t,avatarInfo:s,className:i,text:n,onClick:r,checkboxField:o,noCheckboxClickListener:l,emptyIcon:c}=a,d=document.createElement("div"),u=e?.split(" ");if(d.className="btn-menu-item rp-overflow"+(u?.length>1?" "+u.slice(1).join(" "):"")+(i?" "+i:"")+(a.danger?" danger":""),Gi&&Ei(d),u)d.append(Be(u[0],"btn-menu-item-icon"));else if(c){const g=document.createElement("span");g.classList.add("btn-menu-item-icon"),d.append(g)}let h=a.textElement;if(h||(h=a.textElement=n?P(n,a.textArgs):document.createElement("span"),a.regularText&&(Qt(h,a.regularText),h.dir="")),t){const g=document.createElement("span");g.classList.add("btn-menu-item-icon"),d.append(g);const f=()=>document.documentElement.classList.contains("is-mobile");a.loadPromise=G_({doc:t,element:g,size:24,textColor:()=>f()?"secondary-text-color":"primary-text-color",strokeWidth:()=>f()?.625:.375})}if(s){const g=Ft(f=>(a.dispose=f,jn({size:24,...s})));g.node.classList.add("btn-menu-item-icon","is-external","btn-menu-item-avatar"),s.active&&g.node.classList.add("active"),d.append(g.node)}if(h.classList.add("btn-menu-item-text"),d.append(h),a.new){const g=document.createElement("span");g.classList.add("btn-menu-item-badge"),ks(g,"New"),d.append(g)}const p=!!o||!!a.keepOpen;r&&J(d,g=>{_e(g);const f=ne(g.target,"btn-menu");f&&!f.classList.contains("active")||(r(g),a.checkForClose?.()!==!1&&(p||Li.close(),o&&!l&&(o.checked=o.input.type==="radio"?!0:!o.checked)))},a.options),o&&d.append(o.label),(a.separator===!0||a.separatorDown)&&(a.separator=document.createElement("hr")),a.secondary&&(d.classList.add("is-secondary"),a.multiline=!0),a.multiline&&d.classList.add("is-multiline"),a.inner&&(d.append(Be("next","btn-menu-item-icon","btn-menu-item-icon-right")),d.classList.add("has-inner"),d.inner=a.inner);const m=[a.element=d];return a.separator&&m[a.separatorDown?"push":"unshift"](a.separator),m.filter(Boolean)}function xa({listenerSetter:a,buttons:e,radioGroups:t}){const s=document.createElement("div");s.classList.add("btn-menu"),t&&e.forEach(n=>{n.radioGroup&&(n.checkboxField??(n.checkboxField=new _t))}),a&&e.forEach(n=>{(n.options??(n.options={})).listenerSetter=a});const i=e.map(Wk);return s.append(...va(i)),t&&t.forEach(n=>{const r=e.filter(c=>c.radioGroup===n.name),o=document.createElement("hr");r[0].element.replaceWith(o);const l=H_(r.map((c,d)=>{const u=c.checkboxField.input;return u.type="radio",u.name=n.name,u.value=""+ +(d===n.checked),u.checked=d===n.checked,{container:c.element,input:c.checkboxField.input}}),n.onChange);o.before(l),l.append(o)}),s}async function Kh(a){const e=xa(a);return await Promise.all(a.buttons.map(({loadPromise:t})=>t)),e}async function zn(a,e){const t=a.map(async(s,i,n)=>{if(await e(s,i,n))return s});return(await Promise.all(t)).filter(Boolean)}const V_=8,Kk=V_,z_=8,jk=z_;function Ql(a,e,t,s){a.touches&&(a=a.touches[0]);const{pageX:i,pageY:n}=a,r=Array.from(e.children).find(M=>M.classList.contains("btn-menu-items")||M.classList.contains("btn-menu-item")&&!M.classList.contains("hide"))||e;let{scrollWidth:o}=r;const{scrollHeight:l}=e,c=document.body.getBoundingClientRect(),d=c.width,u=c.height;o+=r.offsetLeft*2;let h=V_,p=jk,m=Kk,g=z_;s&&(s.top&&(h+=s.top),s.right&&(p+=s.right),s.bottom&&(m+=s.bottom),s.left&&(g+=s.left)),Ne.isRTL?t=st.isMobile?"left":"right":t=st.isMobile?"right":"left";let f="top";const v=u-l-m,y=d-o-p,w=g,S={x:{left:i,right:Math.min(y,i-o)},intermediateX:t==="right"?w:y,y:{top:n,bottom:n-l},intermediateY:v},_={x:{left:S.x.left+o+p<=d,right:S.x.right>=g},y:{top:S.y.top+l+m<=u,bottom:S.y.bottom-m>=m}};{const M=_.x[t]?S.x[t]:(t="center",S.intermediateX);e.style.left=M+"px"}{const M=_.y[f]?S.y[f]:(f="center",S.intermediateY);e.style.top=M+"px"}return e.className=e.className.replace(/(top|center|bottom)-(left|center|right)/g,""),e.classList.add((f==="center"?f:"bottom")+"-"+(t==="center"?t:(Ne.isRTL?t==="right":t==="left")?"right":"left")),{width:o,height:l}}let Bv=!1,bp=0;function W_(){bp&&clearTimeout(bp),bp=window.setTimeout(()=>{bp=0,Bv=!1},400),Bv=!0}function Er({element:a,callback:e,listenerSetter:t,listenerOptions:s}){const i=t?t.add(a):a.addEventListener.bind(a),n=t?t.removeManual.bind(t,a):a.removeEventListener.bind(a);if($o&&pt||s){let r;const o={...s||{},capture:!0},l=()=>{clearTimeout(r),n("touchmove",l,o),n("touchend",l,o),n("touchcancel",l,o)};i("touchstart",c=>{if(c.touches.length>1){l();return}i("touchmove",l,o),i("touchend",l,o),i("touchcancel",l,o),r=window.setTimeout(()=>{if(Bv){l();return}e(c),l(),Li.isOpened()&&i("touchend",_e,{once:!0})},400)},s)}else i("contextmenu",pt?r=>{e(r),Li.isOpened()&&i("touchend",_e,{once:!0})}:e,s)}function Dn({buttons:a,findElement:e,listenTo:t,appendTo:s,filterButtons:i,onOpen:n,onClose:r,onCloseAfter:o,onElementReady:l,onOpenBefore:c,listenerSetter:d,middleware:u,listenForClick:h}){s??(s=document.body),d??(d=new $t);const p=new $t,m=u?u.create():Ht();let g;const f=b=>{const S=e?e(b):t;if(!S)return;let _=g;if((b instanceof MouseEvent||b.hasOwnProperty("preventDefault"))&&b.preventDefault(),_&&_.classList.contains("active"))return!1;(b instanceof MouseEvent||b.hasOwnProperty("cancelBubble"))&&(b.cancelBubble=!0),(async()=>{await n?.(b,S);const C=await w();if(!C){r?.();return}S.classList.add("menu-open"),_=C.element;const{cleanup:L,destroy:E}=C;Ql(b,_),Li.openBtnMenu(_,()=>{S.classList.remove("menu-open"),r?.(),L(),setTimeout(()=>{o?.(),E()},300)})})()};Er({element:t,callback:f,listenerSetter:d});const v=()=>{p.removeAll(),m.clean()},y=()=>{v(),d.removeAll()},w=async()=>{v(),a.forEach(M=>M.element=void 0);const S=await(i||(M=>zn(M,C=>C?.verify?en(C.verify(),L=>L??!1):!0)))(a);if(!S.length)return;const _=g=await Kh({buttons:S,listenerSetter:p});return _.classList.add("contextmenu"),await c?.(),l?.(_),s.append(_),{element:_,cleanup:v,destroy:()=>{_.remove()}}};return u&&u.onDestroy(()=>{y()}),h&&J(t,f,{listenerSetter:d}),{element:g,destroy:y,open:f}}const wp=(a,e)=>{e===!0||(typeof e=="string"?Qt(a,e):a.append(e))};class Fe{constructor(e={}){this.freezed=!1,e.checkboxFieldOptions&&(e.checkboxField=new _t({listenerSetter:e.listenerSetter,...e.checkboxFieldOptions}));const t=e.asLink?"a":e.radioField||e.checkboxField||e.asLabel?"label":"div";if(this.container=document.createElement(t),this.container.classList.add("row","no-subtitle"),e.noWrap&&this.container.classList.add("no-wrap"),e.subtitle||e.subtitleLangKey){const i=this.subtitle;if(e.subtitleLangKey?i.append(P(e.subtitleLangKey,e.subtitleLangArgs)):wp(i,e.subtitle),e.noWrap&&i.classList.add("no-wrap"),e.subtitleRight){this.container.append(this.subtitleRow=this.createRow()),this.subtitleRow.classList.add("row-subtitle-row");const n=this.subtitleRight=document.createElement("div");n.classList.add("row-subtitle","row-subtitle-right"),wp(n,e.subtitleRight),this.subtitleRow.append(i,n)}}let s=!!e.havePadding;if(e.radioField||e.checkboxField){if(e.radioField&&(this.radioField=e.radioField,this.container.append(this.radioField.label),s=!0),e.checkboxField){this.checkboxField=e.checkboxField;const n=e.checkboxField.label.classList.contains("checkbox-field-toggle");if(n?(this.container.classList.add("row-with-toggle"),e.titleRight=this.checkboxField.label):(s=!0,this.checkboxField.span||this.checkboxField.label.classList.add("checkbox-field-absolute"),this.container.append(this.checkboxField.label)),e.withCheckboxSubtitle&&!n){e.checkboxKeys??(e.checkboxKeys=["Checkbox.Enabled","Checkbox.Disabled"]);const[r,o]=e.checkboxKeys,l=()=>{St(this.subtitle,P(this.checkboxField.checked?r:o))};e.listenerSetter?e.listenerSetter.add(this.checkboxField.input)("change",l):this.checkboxField.input.addEventListener("change",l)}}(e.radioField||e.checkboxField).label.classList.add("disable-hover")}if(e.title||e.titleLangKey||e.titleRight||e.titleRightSecondary){let i;const n=e.titleRight||e.titleRightSecondary;if(n?(this.container.append(i=this.titleRow=this.createRow()),this.titleRow.classList.add("row-title-row")):i=this.container,this._title=this.createTitle(),e.noWrap&&this.title.classList.add("no-wrap"),e.title?wp(this.title,e.title):e.titleLangKey&&this.title.append(P(e.titleLangKey,e.titleLangArgs)),i.append(this.title),n){const r=this.titleRight=document.createElement("div");r.classList.add("row-title","row-title-right"),e.titleRightSecondary&&r.classList.add("row-title-right-secondary"),wp(r,n),i.append(r)}}if(e.icon&&(s=!0,e.iconClasses?.length?this.container.append(Be(e.icon,"row-icon",...e.iconClasses)):this.container.append(Be(e.icon,"row-icon")),this.container.classList.add("row-with-icon")),s&&this.container.classList.add("row-with-padding"),e.navigationTab){let i=e.navigationTab.getInitArgs;if(!i){const r=e.navigationTab.constructor.getInitArgs;r&&(i=()=>r())}let n=e.navigationTab.args??i?.();e.clickable=async()=>{n instanceof Promise&&(n=await n);const r=e.navigationTab.slider.createTab(e.navigationTab.constructor);r.open(n);const o=r.eventListener;o&&i&&o.addEventListener("destroyAfter",l=>{n=l.then(()=>i())})}}if((e.clickable||e.radioField||e.checkboxField)&&(typeof e.clickable=="function"&&J(this.container,i=>{this.freezed||e.clickable(i)},{listenerSetter:e.listenerSetter}),this.container.classList.add("row-clickable","hover-effect"),e.noRipple||Ei(this.container,void 0,void 0,!0)),(e.buttonRight||e.buttonRightLangKey)&&(e.rightContent=this.buttonRight=e.buttonRight instanceof HTMLElement?e.buttonRight:ot("btn-primary btn-color-primary btn-control-small",{text:e.buttonRightLangKey})),e.rightTextContent&&(e.rightContent=document.createElement("span"),e.rightContent.classList.add("row-title-right-secondary"),e.rightContent.textContent=e.rightTextContent),e.rightContent&&(e.rightContent.classList.add("row-right"),this.container.classList.add("row-grid"),this.container.append(e.rightContent)),e.contextMenu){const{open:i}=Dn({...e.contextMenu,listenTo:this.container,listenerSetter:e.listenerSetter});this.openContextMenu=i}}get title(){return this._title}get subtitle(){return this._subtitle??(this._subtitle=this.createSubtitle())}get midtitle(){return this._midtitle??(this._midtitle=this.createMidtitle())}createRow(){const e=document.createElement("div");return e.classList.add("row-row"),e}createTitle(){const e=document.createElement("div");return e.classList.add("row-title"),Xr(e),e}createSubtitle(){const e=document.createElement("div");return e.classList.add("row-subtitle"),Xr(e),this.title?this.title.after(e):this.container.prepend(e),this.container.classList.remove("no-subtitle"),e}createMidtitle(){const e=document.createElement("div");return e.classList.add("row-midtitle"),this.subtitle.parentElement.insertBefore(e,this.subtitle),e}createMedia(e){const t=document.createElement("div");return this.applyMediaElement(t,e)}applyMediaElement(e,t){return this.container.classList.add("row-with-padding"),this.media=e,e.classList.add("row-media"),t&&e.classList.add("row-media-"+t),this.container.append(e),e}isDisabled(){return this.container.classList.contains("is-disabled")}toggleDisability(e=!this.container.classList.contains("is-disabled")){return this.container.classList.toggle("is-disabled",e),()=>this.toggleDisability(!e)}disableWithPromise(e){const t=this.toggleDisability(!0);e.finally(()=>{t()})}makeSortable(){const e=Be("menu","row-sortable-icon");this.container.classList.add("row-sortable"),this.container.append(e)}toggleSorting(e){this.container.classList.toggle("cant-sort",!e)}}const qk=a=>new Fe(a).container,jr=a=>new Fe({checkboxField:a,listenerSetter:a.listenerSetter}),Sd=(a,e)=>H_(a.map(t=>({container:t.container,input:t.radioField.input})),e),vm=(a,e,t)=>{const s="name-"+(Math.random()*8388607|0);let i;const n=a.map(({langPackKey:o,value:l,checked:c,textElement:d})=>{const u=new Fe({radioField:new rn({textElement:d,langKey:o,name:s,value:""+l})});return c&&(i=u.radioField),u}),r=Sd(n,e);return i&&(t?i.checked=!0:i.setValueSilently(!0)),r},$d=3600,Yk=[{value:$d,langPackKey:"ChatList.Mute.1Hour"},{value:$d*4,langPackKey:"ChatList.Mute.4Hours"},{value:$d*8,langPackKey:"ChatList.Mute.8Hours"},{value:$d*24,langPackKey:"ChatList.Mute.1Day"},{value:$d*24*3,langPackKey:"ChatList.Mute.3Days"},{value:-1,langPackKey:"ChatList.Mute.Forever",checked:!0}];class K_ extends mi{constructor(e,t){super("popup-mute",{peerId:e,titleLangKey:"Notifications",buttons:[{langKey:"ChatList.Context.Mute",callback:()=>{this.managers.appMessagesManager.mutePeer({peerId:e,muteUntil:s===-1?NC:Qs(!0)+s,threadId:t})}}],body:!0});let s;const i=vm(Yk,n=>{s=+n},!0);this.body.append(i),this.show()}}function j_(a,e,t,s){return a>=s?e+t:q_(a/s,t)+e}function q_(a,e){return-e/2*(Math.cos(Math.PI*a)-1)}function Dv(a,e,t,s){const i=d=>{t({x:d.pageX,y:d.pageY,event:d})},n=d=>{document.removeEventListener("mousemove",i),a.addEventListener("mousedown",r,{once:!0}),s?.({x:d.pageX,y:d.pageY,event:d})},r=d=>{if(d.button!==0){a.addEventListener("mousedown",r,{once:!0});return}e({x:d.pageX,y:d.pageY,event:d}),i(d),document.addEventListener("mousemove",i),document.addEventListener("mouseup",n,{once:!0})};a.addEventListener("mousedown",r,{once:!0});const o=d=>{d.preventDefault(),t({x:d.touches[0].clientX,y:d.touches[0].clientY,isTouch:!0,event:d})},l=d=>{document.removeEventListener("touchmove",o),a.addEventListener("touchstart",c,{passive:!1,once:!0});const u=d.touches[0]||d.changedTouches[0];s?.({x:u.clientX,y:u.clientY,isTouch:!0,event:d})},c=d=>{e({x:d.touches[0].clientX,y:d.touches[0].clientY,isTouch:!0,event:d}),o(d),document.addEventListener("touchmove",o,{passive:!1}),document.addEventListener("touchend",l,{passive:!1,once:!0})};return a.addEventListener("touchstart",c,{passive:!1,once:!0}),()=>{a.removeEventListener("mousedown",r),document.removeEventListener("mousemove",i),document.removeEventListener("mouseup",n),a.removeEventListener("touchstart",c),document.removeEventListener("touchmove",o),document.removeEventListener("touchend",l)}}class Xl{constructor(e,t=0){this.mousedown=!1,this.events={},this.withTransition=!1,this.useTransform=!1,this.useProperty=!1,this.vertical=!1,this.offsetAxisValue=0,this.onMouseMove=r=>{this.scrub(r)},this.onMouseDown=r=>{this.rect=this.container.getBoundingClientRect(),this.mousedown=!0,this.scrub(r),this.container.classList.add("is-focused"),this.events?.onMouseDown&&this.events.onMouseDown(r)},this.onMouseUp=r=>{this.mousedown=!1,this.container.classList.remove("is-focused"),this.events?.onMouseUp&&this.events.onMouseUp(r)},this.onInput=()=>{const r=+this.seek.value;this.setFilled(r),this.events?.onScrub&&this.events.onScrub(r)},Nt(this,e),this.container=document.createElement("div"),this.container.classList.add("progress-line"),this.useTransform?this.container.classList.add("use-transform"):this.withTransition&&this.container.classList.add("with-transition"),this.filled=document.createElement("div"),this.filled.classList.add("progress-line__filled");const s=this.seek=document.createElement("input");s.classList.add("progress-line__seek"),s.type="range",s.step=""+this.step,this.setMinMax(this.min,this.max),s.value=""+t,t&&this.setProgress(t);const i=""+this.step,n=i.indexOf(".");this.decimals=n===-1?0:i.length-n-1,this.container.append(this.filled,s)}setMinMax(e,t){this.min=e??this.min??(this.min=0),this.max=t??this.max??(this.max=0),this.seek.min=""+e,this.seek.max=""+t}get value(){return+this.seek.value}setHandlers(e){this.events=e}setListeners(){this.seek.addEventListener("input",this.onInput),this._removeListeners=Dv(this.container,this.onMouseDown,this.onMouseMove,this.onMouseUp)}setProgress(e){this.seek.value=""+e,this.setFilled(+this.seek.value)}addProgress(e){this.seek.value=""+(+this.seek.value+e),this.setFilled(+this.seek.value)}setFilled(e){let t=(e-this.min)/(this.max-this.min);t=zt(t,0,1),this.useTransform?this.filled.style.transform=`scaleX(${t})`:this.useProperty?this.container.style.setProperty("--progress",""+t):this.filled.style.width=t*100+"%"}scrub(e,t){let s=this.vertical?this.rect.height:this.rect.width;this.offsetAxisValue&&(s-=this.offsetAxisValue);let i=zt(this.vertical?-(e.y-this.rect.bottom):e.x-this.rect.left-this.offsetAxisValue/2,0,s);!this.vertical&&Ne.isRTL&&(i=s-i);let n=this.min+i/s*(this.max-this.min);return n-this.min<(this.max-this.min)/2&&(n-=this.step/10),n=+n.toFixed(this.decimals),n=zt(n,this.min,this.max),t&&(n=t(n)),this.setProgress(n),this.events?.onScrub&&this.events.onScrub(n),n}removeListeners(){this._removeListeners&&(this._removeListeners(),this._removeListeners=null),this.seek.removeEventListener("input",this.onInput),this.events={}}}class xg{constructor(e){this.setHintActive=()=>{this.hint.classList.add("active")};let t,s;if(e.hint){t=document.createElement("div"),t.classList.add("limit-line-container"),s=this.hint=document.createElement("div"),s.classList.add("limit-line-hint","is-locked");const n=Be(e.hint.icon,"limit-line-hint-icon");s.append(n),e.hint.content&&s.append(e.hint.content),this.hintNoStartEnd=e.hint.noStartEnd,t.append(s)}const i=e.slider?this.constructSlider(e):this.constructLine(e,t);this.container=t||i,t&&i&&t.append(i)}constructLine(e,t){const s=this.line=document.createElement("div");s.classList.add("limit-line"),t||s.classList.add("is-alone");const i=this.left=document.createElement("div");i.classList.add("limit-line-part","limit-line-empty");const n=this.right=document.createElement("div");return n.classList.add("limit-line-part","limit-line-filled"),e.progress&&(n.classList.add("limit-line-absolute"),e.progress!==!0&&this.setProgressElements(e.progress)),e.limitPremium!==void 0&&(e.limitFree===void 0?ks(i,"LimitFree"):i.append(P("LimitFree"),""+e.limitFree),e.color!==void 0&&n.style.setProperty("--limit-background",e.color),s.append(n),n.append(P("LimitPremium"),""+e.limitPremium)),s.append(i,n),s}constructSlider(e){const t=new Xl({step:1e-4,min:0,max:1,useProperty:!0,offsetAxisValue:30},e.sliderValue??0);return t.setListeners(),t.setHandlers({onScrub:e.slider}),t.container.classList.add("limit-line-slider"),this.line=t.container}setProgressElements(e){this.left.replaceChildren(e.from1,e.to1),this.right.replaceChildren(e.from2,e.to2)}setProgress(e,t,s){const i=this.lastProgress;this.hint&&(this.hint.classList.remove("is-locked"),t&&this.hint.replaceChildren(this.hint.firstElementChild,t));const n=r=>{this.container.style.setProperty("--limit-progress",r*100+"%"),this.hint&&(this.hintNoStartEnd?this.hint.style.setProperty("--limit-progress",zt(r,.1,1-.1)*100+"%"):(this.hint.classList.toggle("is-start",r<=.1),this.hint.classList.toggle("is-end",r>=1-.1)))};if(i!==void 0&&wt.isAvailable("animations")){const o=Date.now(),l=e-this.lastProgress;Wl(()=>{const c=(Date.now()-o)/200,d=i+q_(l*c,1);return n(d),c<1},this.container)}else n(e);s&&this.setProgressElements(s),this.lastProgress=e}_setHintActive(){wt.isAvailable("animations")?hi().then(this.setHintActive):this.setHintActive()}}function ur(a,e="auto"){if(a===0)return P("FileSize.B",[0]);const t=e==="auto",s=1024,i=Math.floor(Math.log(a)/Math.log(s)),n=e==="auto"?Math.max(0,i-1):e,r=Math.max(0,n),o=["FileSize.B","FileSize.KB","FileSize.MB","FileSize.GB"],l=(a/Math.pow(s,i)).toFixed(r);return P(o[i],[t?l:parseFloat(l)])}const pS=["#ef6922","#e95a2c","#e74e33","#e3433c","#db374b","#cb3e6d","#bc4395","#ab4ac4","#9b4fed","#8958ff","#676bff","#5b79ff","#4492ff","#429bd5","#41a6a5","#3eb26d","#3dbd4a"],Qk={feature:"stories",icon:"stories",titleLangKey:"Premium.Boarding.Stories.Title",subtitleLangKey:"Premium.Boarding.Stories.Info",type:"upgraded-stories",content:[{titleLangKey:"PremiumStoriesPriority",subtitleLangKey:"PremiumStoriesPriorityDescription",iconColor:"#0079FE",icon:"multistories"},{titleLangKey:"PremiumStoriesStealth",subtitleLangKey:"PremiumStoriesStealthDescription",iconColor:"#7889FE",icon:"eyecross_outline"},{titleLangKey:"PremiumStoriesViews",subtitleLangKey:"PremiumStoriesViewsDescription",iconColor:"#A45FE6",icon:"eye"},{titleLangKey:"PremiumStoriesExpiration",subtitleLangKey:"PremiumStoriesExpirationDescription",iconColor:"#C355AE",icon:"timer"},{titleLangKey:"PremiumStoriesSaveToGallery",subtitleLangKey:"PremiumStoriesSaveToGalleryDescription",iconColor:"#E85D43",icon:"arrowcircle"},{titleLangKey:"PremiumStoriesCaption",subtitleLangKey:"PremiumStoriesCaptionDescription",iconColor:"#F1822A",icon:"list"},{titleLangKey:"PremiumStoriesFormatting",subtitleLangKey:"PremiumStoriesFormattingDescription",iconColor:"#E6AC19",icon:"limit_link"}]},Jo=a=>e=>e.apiManager.getLimit(a,!0).then(t=>[t]),Xk={feature:"double_limits",icon:"premium_limits",titleLangKey:"Premium.Boarding.Double.Title",subtitleLangKey:"Premium.Boarding.Double.Info",headerLangKey:"Premium.Boarding.Double.Title",_subtitleLangArgs:a=>Promise.all(["channels","folders","pin","links"].map(e=>a.apiManager.getLimit(e,!0))),type:"limits",content:[{titleLangKey:"GroupsAndChannelsLimitTitle",subtitleLangKey:"GroupsAndChannelsLimitSubtitle",_subtitleLangArgs:Jo("channels"),limitType:"channels",backgroundColor:"#5B9FFF"},{titleLangKey:"PinChatsLimitTitle",subtitleLangKey:"PinChatsLimitSubtitle",_subtitleLangArgs:Jo("pin"),limitType:"pin",backgroundColor:"#7889FE"},{titleLangKey:"PublicLinksLimitTitle",subtitleLangKey:"PublicLinksLimitSubtitle",_subtitleLangArgs:Jo("links"),limitType:"links",backgroundColor:"#9376FF"},{titleLangKey:"SavedGifsLimitTitle",subtitleLangKey:"SavedGifsLimitSubtitle",_subtitleLangArgs:Jo("gifs"),limitType:"gifs",backgroundColor:"#AB63F2"},{titleLangKey:"FavoriteStickersLimitTitle",subtitleLangKey:"FavoriteStickersLimitSubtitle",_subtitleLangArgs:Jo("favedStickers"),limitType:"favedStickers",backgroundColor:"#C456AE"},{titleLangKey:"BioLimitTitle",subtitleLangKey:"BioLimitSubtitle",limitType:"bio",backgroundColor:"#CE569A"},{titleLangKey:"CaptionsLimitTitle",subtitleLangKey:"CaptionsLimitSubtitle",limitType:"caption",backgroundColor:"#DA5786"},{titleLangKey:"FoldersLimitTitle",subtitleLangKey:"FoldersLimitSubtitle",_subtitleLangArgs:Jo("folders"),limitType:"folders",backgroundColor:"#DB496F"},{titleLangKey:"ChatPerFolderLimitTitle",subtitleLangKey:"ChatPerFolderLimitSubtitle",_subtitleLangArgs:Jo("folderPeers"),limitType:"folderPeers",backgroundColor:"#E85D43"},{titleLangKey:"ConnectedAccountsLimitTitle",subtitleLangKey:"ConnectedAccountsLimitSubtitle",subtitleLangArgs:[4],free:3,premium:4,backgroundColor:"#F1822A"}]},mS=a=>ur(a*1.024*512*1024,0),gS={stories:Qk,double_limits:Xk,voice_to_text:{feature:"voice_to_text",icon:"premium_transcription",titleLangKey:"Premium.Boarding.Voice.Title",subtitleLangKey:"Premium.Boarding.Voice.Info",videoPosition:"top"},faster_download:{feature:"faster_download",icon:"premium_speed",titleLangKey:"Premium.Boarding.Download.Title",subtitleLangKey:"Premium.Boarding.Download.Info",videoPosition:"top"},translations:{feature:"translations",icon:"premium_translate",titleLangKey:"Premium.Boarding.Translate.Title",subtitleLangKey:"Premium.Boarding.Translate.Info",videoPosition:"top"},animated_emoji:{feature:"animated_emoji",icon:"premium_emoji",titleLangKey:"Premium.Boarding.Emoji.Title",subtitleLangKey:"Premium.Boarding.Emoji.Info"},more_upload:{feature:"more_upload",icon:"premium_filesize",titleLangKey:"Premium.Boarding.FileSize.Title",_titleLangArgs:a=>a.apiManager.getLimit("uploadFileParts",!0).then(e=>[mS(e)]),subtitleLangKey:"Premium.Boarding.FileSize.Info",_subtitleLangArgs:a=>Promise.all([!1,!0].map(async e=>{const t=await a.apiManager.getLimit("uploadFileParts",e);return mS(t)}))},emoji_status:{feature:"emoji_status",icon:"premium_status",titleLangKey:"Premium.Boarding.Status.Title",subtitleLangKey:"Premium.Boarding.Status.Info",videoPosition:"top"},peer_colors:{feature:"peer_colors",icon:"premium_colors",titleLangKey:"Premium.Promo.Colors.Title",subtitleLangKey:"Premium.Promo.Colors.Subtitle",videoPosition:"top"},wallpapers:{feature:"wallpapers",icon:"premium_wallpaper",titleLangKey:"Premium.Promo.Wallpaper.Title",subtitleLangKey:"Premium.Promo.Wallpaper.Subtitle",videoPosition:"top",new:!0},profile_badge:{feature:"profile_badge",icon:"star",titleLangKey:"Premium.Boarding.Badge.Title",subtitleLangKey:"Premium.Boarding.Badge.Info",videoPosition:"top"},advanced_chat_management:{feature:"advanced_chat_management",icon:"premium_management",titleLangKey:"Premium.Boarding.Chats.Title",subtitleLangKey:"Premium.Boarding.Chats.Info",videoPosition:"top"},no_ads:{feature:"no_ads",icon:"premium_noads",titleLangKey:"Premium.Boarding.NoAds.Title",subtitleLangKey:"Premium.Boarding.NoAds.Info"},infinite_reactions:{feature:"infinite_reactions",icon:"premium_reactions",titleLangKey:"Premium.Boarding.ReactionsNew.Title",subtitleLangKey:"Premium.Boarding.ReactionsNew.Info",videoPosition:"top"},animated_userpics:{feature:"animated_userpics",icon:"premium_avatars",titleLangKey:"Premium.Boarding.Avatar.Title",subtitleLangKey:"Premium.Boarding.Avatar.Info",videoPosition:"top"},premium_stickers:{feature:"premium_stickers",icon:"premium_stickers",titleLangKey:"Premium.Boarding.Stickers.Title",subtitleLangKey:"Premium.Boarding.Stickers.Info",type:"premium-stickers"},last_seen:{feature:"last_seen",icon:"premium_lastseen",titleLangKey:"PremiumPreviewLastSeen",subtitleLangKey:"PremiumPreviewLastSeenDescription",new:!0},message_privacy:{feature:"message_privacy",icon:"premium_privacy",titleLangKey:"PremiumPreviewMessagePrivacy",subtitleLangKey:"PremiumPreviewMessagePrivacyDescription",new:!0},saved_tags:{feature:"saved_tags",icon:"premium_tags",titleLangKey:"PremiumPreviewTags",subtitleLangKey:"PremiumPreviewTagsDescription2"}};function Y_(a){hn(a.messages,(e,t,s)=>{e.action.photo||(s.splice(t,1),a.count!==void 0&&--a.count)})}class Ag{constructor(e){this.previous=[],this.next=[],this.reverse=!1,this.loadCount=50,this.loadWhenLeft=20,this.loadedAllUp=!1,this.loadedAllDown=!1,Nt(this,e)}setTargets(e,t,s){this.previous=e,this.next=t,this.reverse=s}get index(){return this.count!==void 0?this.previous.length:-1}reset(e=!1){this.current=void 0,this.previous=[],this.next=[],this.setLoaded(!0,e),this.setLoaded(!1,e)}go(e,t=!0){let s,i;if(e>0){if(s=this.next.splice(0,e),i=s.pop(),!i)return;this.current!==void 0&&s.unshift(this.current),this.previous.push(...s)}else{if(s=this.previous.splice(Math.max(0,this.previous.length+e),-e),i=s.shift(),!i)return;this.current!==void 0&&s.push(this.current),this.next.unshift(...s)}return this.next.length<this.loadWhenLeft&&this.load(!this.reverse),this.previous.length<this.loadWhenLeft&&this.load(this.reverse),this.current=i,t&&this.onJump?.(i,e>0),this.current}unsetCurrent(e){e?this.previous.push(this.current):this.next.unshift(this.current),this.current=void 0}goUnsafe(e,t){const s=e>0?Math.max(0,e-this.next.length):Math.min(0,e+this.previous.length),i=this.go(e,s?!1:t);return{item:s?void 0:i,leftLength:s}}setLoaded(e,t){return(e?this.loadedAllDown:this.loadedAllUp)!==t?(e?this.loadedAllDown=t:this.loadedAllUp=t,t||(e?this.loadPromiseDown=null:this.loadPromiseUp=null),!0):!1}load(e){if(e?this.loadedAllDown:this.loadedAllUp)return Promise.resolve();let t=e?this.loadPromiseDown:this.loadPromiseUp;if(t)return t;let s;return e?s=this.reverse?this.previous[0]:this.next[this.next.length-1]:s=this.reverse?this.next[this.next.length-1]:this.previous[0],s??(s=this.current),t=this.loadMore(s,e,this.loadCount).then(async i=>{if((e?this.loadPromiseDown:this.loadPromiseUp)!==t)return;i.items.length<this.loadCount&&this.setLoaded(e,!0),this.count===void 0&&(this.count=i.count||i.items.length);const n=[];(e&&!this.reverse?i.items.forEach.bind(i.items):hn.bind(null,i.items))(l=>{const c=this.processItem?this.processItem(l):l;c&&n.push(c)});const o=(await Promise.all(n)).filter(Boolean);(e?this.loadPromiseDown:this.loadPromiseUp)===t&&(e?this.reverse?this.previous.unshift(...o):this.next.push(...o):this.reverse?this.next.push(...o):this.previous.unshift(...o),this.onLoadedMore?.())},()=>{}).then(()=>{e?this.loadPromiseDown=null:this.loadPromiseUp=null}),e?this.loadPromiseDown=t:this.loadPromiseUp=t,t}}class Rg extends Ag{constructor(e={}){super({...e,loadMore:async(t,s,i)=>{const n=s?0:i;let r=t?.mid??this.searchContext.maxId;s||(r=await this.managers.appMessagesIdsManager.incrementMessageId(r,1));const o=this.searchContext.peerId||t?.peerId;return this.managers.appMessagesManager.getHistory({...this.searchContext,peerId:o,offsetId:r,offsetPeerId:o?void 0:t?.peerId,limit:n?0:i,backLimit:n}).then(l=>(this.searchContext.inputFilter._==="inputMessagesFilterChatPhotos"&&Y_(l),l.nextRate&&(this.searchContext.nextRate=l.nextRate),l.messages||(l.messages=l.history.map(c=>Ae.getMessageByPeer(o,c))),{count:l.count,items:l.messages}))},processItem:async t=>{if((await this.filterMids([t.mid])).length)return e.processItem(t)}}),this.onHistoryDelete=({peerId:t,msgs:s})=>{const i=r=>r.peerId===t&&s.has(r.mid),n=(r,o,l)=>{i(r)&&l.splice(o,1)};hn(this.previous,n),hn(this.next,n),this.current&&i(this.current)&&(this.current=void 0,this.onEmptied&&this.onEmptied())},this.onHistoryMultiappend=async t=>{const{searchContext:s}=this;if(s.folderId!==void 0||!this.loadedAllUp||this.loadPromiseUp||t.peerId!==s.peerId)return;const i=await this.filterMids([t.mid]);if(this.searchContext!==s)return;const n=(await Promise.all(i.map(o=>this.processItem(o)))).filter(Boolean);this.searchContext!==s||!n.length||this.previous.concat(this.next,this.current?[this.current]:[]).some(o=>o?.mid===t.mid)||(this.current?this.next.push(...n):this.previous.push(...n))},this.onMessageSent=({message:t})=>{this.onHistoryMultiappend(t)},this.managers??(this.managers=I.managers),I.addEventListener("history_delete",this.onHistoryDelete),I.addEventListener("history_multiappend",this.onHistoryMultiappend),I.addEventListener("message_sent",this.onMessageSent),e.isInner||(this.otherSideLoader=new Rg({...e,isInner:!0}))}async filterMids(e){const t=`${this.searchContext.peerId}_${this.searchContext.isScheduled?"scheduled":"history"}`;return await this.managers.appMessagesManager.filterMessagesByInputFilterFromStorage(this.searchContext.inputFilter._,e,t,e.length)}setSearchContext(e){this.searchContext=e,this.searchContext.folderId!==void 0&&(this.loadedAllUp=!0,this.searchContext.nextRate===void 0&&(this.loadedAllDown=!0)),this.searchContext.inputFilter._==="inputMessagesFilterChatPhotos"&&(this.loadedAllUp=!0),this.searchContext.useSearch===!1&&(this.loadedAllDown=this.loadedAllUp=!0),this.otherSideLoader&&this.otherSideLoader.setSearchContext(e)}reset(){super.reset(),this.searchContext=void 0,this.otherSideLoader&&this.otherSideLoader.reset()}getPrevious(e){let t=this.previous;return this.otherSideLoader&&e&&(t=t.concat(this.otherSideLoader.previous)),t}getNext(e){let t=this.next;return this.otherSideLoader&&e&&(t=t.concat(this.otherSideLoader.next)),t}getCurrent(){return this.current||this.otherSideLoader?.current}goToOtherEnd(e){return e>0?this.go(-this.previous.length):this.go(this.next.length)}goRound(e,t){let s;if(this.otherSideLoader?.current){if(s=this.otherSideLoader.goUnsafe(e,t),s.item)return s.item;if(e=s.leftLength,!(e>0?this.otherSideLoader.next:this.otherSideLoader.previous).length){if(!(e>0?this.otherSideLoader.loadedAllUp:this.otherSideLoader.loadedAllDown))return;if(e>0&&(this.otherSideLoader.searchContext.maxId===1||this.otherSideLoader.loadedAllDown)||e<0&&(this.otherSideLoader.searchContext.maxId===0||this.otherSideLoader.loadedAllUp))return this.otherSideLoader.goToOtherEnd(e);this.otherSideLoader.unsetCurrent(e>0)}}if(s=this.goUnsafe(e,t),!s.item){if(this.loadedAllUp&&this.loadedAllDown)return this.goToOtherEnd(e);this.otherSideLoader&&(e=s.leftLength,s=this.otherSideLoader.goUnsafe(e,t),s.item&&this.unsetCurrent(e>0))}return s?.item}setLoaded(e,t){const s=super.setLoaded(e,t);if(s&&this.otherSideLoader&&t&&this.searchContext?.useSearch!==!1){const i=this.loadedAllUp;this.otherSideLoader.setSearchContext({...this.searchContext,maxId:i?1:0}),this.otherSideLoader.reverse=this.reverse,this.otherSideLoader.setLoaded(i,!0),this.otherSideLoader.load(!i)}return s}cleanup(){this.reset(),I.removeEventListener("history_delete",this.onHistoryDelete),I.removeEventListener("history_multiappend",this.onHistoryMultiappend),I.removeEventListener("message_sent",this.onMessageSent),this.onEmptied=void 0,this.otherSideLoader&&(this.otherSideLoader.cleanup(),this.otherSideLoader=void 0)}}class aa{constructor(e,t,s=!0,i,n=!0,r=!0,o,l){this.name=e,this.type=t,this.clearable=s,this.autonomous=r,this.onFound=o,this.noIcons=l,this.list=nt.createChatList(),this.container=document.createElement("div"),i&&(this.container.className=i),e&&(this.nameEl=document.createElement("div"),this.nameEl.classList.add("search-group__name"),typeof e=="string"&&this.nameEl.append(P(e)),this.container.append(this.nameEl)),this.container.classList.add("search-group","search-group-"+t),this.container.append(this.list),this.container.style.display="none",n&&nt.setListClickListener({list:this.list,onFound:o,withContext:void 0,autonomous:r})}clear(){this.container.style.display="none",this.clearable&&Array.from(this.list.children).forEach(e=>{const t=e.dialogElement;t?t?.remove():e.remove()})}setActive(){this.container.style.display=""}toggle(){this.list.childElementCount?this.setActive():this.clear()}}class Zk{constructor(e,t,s,i,n,r,o){this.container=e,this.searchInput=t,this.searchGroups=s,this.onSearch=n,this.noIcons=r,this.fromSavedDialog=o,this.minMsgId=0,this.loadedCount=-1,this.foundCount=-1,this.searchPromise=null,this.searchTimeout=0,this.query="",this.listsContainer=null,this.threadId=0,this.middlewareHelper=i.create(),this.scrollable=new tn(this.container),this.listsContainer=this.scrollable.container;for(const l in this.searchGroups)this.listsContainer.append(this.searchGroups[l].container);this.searchGroups.messages&&this.scrollable.setVirtualContainer(this.searchGroups.messages.list),this.searchInput.onChange=l=>{this.query=l,this.reset(!1),this.searchMore()},this.scrollable.onScrolledBottom=()=>{this.query.trim()&&(this.searchTimeout||(this.searchTimeout=window.setTimeout(()=>{this.searchMore(),this.searchTimeout=0},0)))}}reset(e=!0){e&&(this.searchInput.value="",this.query="",this.peerId=void 0,this.threadId=0),this.middlewareHelper.clean(),this.minMsgId=0,this.loadedCount=-1,this.foundCount=-1;for(const t in this.searchGroups)this.searchGroups[t].clear();this.searchPromise=null}beginSearch(e,t=0,s=""){this.peerId=e,this.threadId=t,this.query!==s&&(this.searchInput.inputField.value=s),this.searchInput.input.focus()}searchMore(){if(this.searchPromise)return this.searchPromise;const e=this.query;if(!e.trim()){this.onSearch?.(0);return}if(this.foundCount!==-1&&this.loadedCount>=this.foundCount)return Promise.resolve();const t=this.minMsgId||0,s=this.middlewareHelper.get();return this.searchPromise=I.managers.appMessagesManager.getHistory({peerId:this.peerId,query:e,inputFilter:{_:"inputMessagesFilterEmpty"},offsetId:t,limit:20,threadId:this.threadId}).then(i=>{if(!s()||(this.searchPromise=null,this.searchInput.value!==e))return;let{count:n,messages:r,history:o}=i;r||(r=i.messages=o.map(c=>Ae.getMessageByPeer(this.peerId,c))),r.length&&r[0].mid===this.minMsgId&&r.shift();const l=this.searchGroups.messages;r.forEach(c=>{try{const d=this.peerId?c.fromId:c.peerId;nt.addDialogAndSetLastMessage({peerId:this.fromSavedDialog?I.myId:d,container:this.scrollable,avatarSize:"bigger",meAsSaved:!1,message:c,query:e,noIcons:this.noIcons,wrapOptions:{middleware:s},threadId:this.fromSavedDialog?c.saved_peer_id?it(c.saved_peer_id):I.myId:void 0})}catch(d){console.error("[appSearch] render search result",d)}}),l.toggle(),this.minMsgId=r.length&&r[r.length-1].mid,this.loadedCount===-1&&(this.loadedCount=0),this.loadedCount+=r.length,this.foundCount===-1&&(this.foundCount=n,l.nameEl&&St(l.nameEl,P(n?"Chat.Search.MessagesFound":"Chat.Search.NoMessagesFound",[n])),this.onSearch?.(this.foundCount))}).catch(i=>{s()&&(console.error("search error",i),this.searchPromise=null)})}}var $v=(a=>(a[a.Connected=0]="Connected",a[a.Connecting=1]="Connecting",a[a.Closed=2]="Closed",a[a.TimedOut=3]="TimedOut",a))($v||{});const fl=class fl{constructor(){this.hadConnect=!1,this.connecting=!1,this.timedOut=!1,this.updating=!1,this.setConnectionStatus=e=>{Promise.all([I.managers.apiManager.getBaseDcId(),I.managers.rootScope.getConnectionStatus()]).then(([t,s])=>{t||(t=_o.baseDcId),this.setFirstConnectionTimeout&&(clearTimeout(this.setFirstConnectionTimeout),this.setFirstConnectionTimeout=0);const i=s["NET-"+t],n=i&&(e??i.status)===$v.Connected;this.connecting&&n&&this.managers.apiUpdatesManager.forceGetDifference(),n&&!this.hadConnect&&(this.hadConnect=!0),this.timedOut=i&&(e??i.status)===$v.TimedOut,this.connecting=!n,this.retryAt=i&&i.retryAt,_n&&this.log("connecting",this.connecting),this.setState()})},this.wrapSetStatusText=(...e)=>()=>this.inputSearch.setPlaceholder(...e),this.setState=()=>{if(cm.deactivatedReason)return;let e;if(this.connecting)if(this.timedOut)e=this.wrapSetStatusText("Updating");else if(this.hadConnect)if(this.retryAt!==void 0){const t=document.createElement("span"),s=this.retryAt,i=()=>{const r=Date.now();t.innerText=""+Math.max(0,Math.round((s-r)/1e3)),r>s&&clearInterval(n)},n=setInterval(i,1e3);i(),e=this.wrapSetStatusText("ConnectionStatus.ReconnectInPlain",[t])}else e=this.wrapSetStatusText("ConnectionStatus.Reconnecting");else e=this.wrapSetStatusText("ConnectionStatus.Waiting");else this.updating?e=this.wrapSetStatusText("Updating"):e=this.wrapSetStatusText("Search");_n&&this.log("setState",this.connecting||this.updating),this.rAF&&window.cancelAnimationFrame(this.rAF),this.rAF=window.requestAnimationFrame(()=>{this.rAF=0,this.setStateTimeout&&clearTimeout(this.setStateTimeout);const t=this.inputSearch.isLoading(),s=()=>{e();const i=this.connecting||this.updating;this.inputSearch.toggleLoading(i),this.setStateTimeout=0,_n&&this.log("setState: isShown:",i)};t?s():this.setStateTimeout=window.setTimeout(s,fl.CHANGE_STATE_DELAY)})}}construct(e,t,s){this.managers=e,this.inputSearch=s,this.log=Ni("CS",void 0,void 0),this.inputSearch.setPlaceholder("Search"),I.addEventListener("connection_status_change",i=>{this.setConnectionStatus()}),I.addEventListener("state_synchronizing",()=>{this.updating=!0,_n&&this.log("updating",this.updating),this.setState()}),I.addEventListener("state_synchronized",()=>{_n&&this.log("state_synchronized"),this.updating=!1,_n&&this.log("updating",this.updating),this.setState()}),this.setFirstConnectionTimeout=window.setTimeout(this.setConnectionStatus,fl.INITIAL_DELAY)}getA(e,t){const s=document.createElement("a");return s.classList.add("force-reconnect"),s.append(P(e)),J(s,i=>{_e(i),t()}),s}};fl.CHANGE_STATE_DELAY=400,fl.INITIAL_DELAY=2e3,fl.ANIMATION_DURATION=250;let jh=fl;class jo{constructor(e={}){this.prevValue="",this.timeout=0,this.setArrowBack=n=>{this.arrowBack!==n&&(this.arrowBack=n,this.container.classList.toggle("with-arrow-back",n),n&&!this.backBtn&&(this.backBtn=this.createButtonIcon("arrow_prev","input-search-icon","input-search-back"),this.container.append(this.backBtn),J(this.backBtn,this.onBack,{listenerSetter:this.listenerSetter,cancelMouseDown:!0})),this.searchIcon.classList.toggle("hide",n),this.backBtn&&this.backBtn.classList.toggle("hide",!n),this.clearBtn.classList.toggle("always-visible",!n&&!!this.alwaysShowClear))},this.setPlaceholder=(n,r)=>{if(this.currentLangPackKey===n)return;this.currentLangPackKey=n;const o=this.currentPlaceholder;o&&Dt({element:o,className:"is-hiding",forwards:!0,duration:jh.ANIMATION_DURATION,onTransitionEnd:()=>{o.remove()}}),this.currentPlaceholder=P(n,r),this.currentPlaceholder.classList.add("input-search-placeholder","will-animate"),this.container.append(this.currentPlaceholder)},this.onInput=()=>{if(!this.onChange)return;const{value:n,prevValue:r}=this;if(n!==r){if(this.prevValue=n,this.verifyDebounce?.(n,r)===!1){this.clearTimeout(!1),this.onChange(n);return}this.clearTimeout(!0),this.timeout=window.setTimeout(()=>{this.onDebounce?.(!1),this.onChange(n)},this.debounceTime)}},this.onClearClick=n=>{const r=this.inputField.isEmpty();this.value="",this.onChange?.(""),this.onClear?.(n,r)},this.clearTimeout=n=>{clearTimeout(this.timeout),this.onDebounce?.(n)},this.inputField=new Yt({plainText:!0,withBorder:!e.noBorder}),this.listenerSetter=new $t,this.container=this.inputField.container,this.container.classList.remove("input-field"),this.container.classList.add("input-search"),e.oldStyle&&this.container.classList.add("old-style"),this.onChange=e.onChange,this.onClear=e.onClear,this.onDebounce=e.onDebounce,this.onBack=e.onBack,this.debounceTime=e.debounceTime??300,this.verifyDebounce=e.verifyDebounce,this.alwaysShowClear=e.alwaysShowClear;const t=this.input=this.inputField.input;t.classList.add("input-search-input"),e.noFocusEffect||t.classList.add("with-focus-effect");const s=this.searchIcon=this.createIcon("search","input-search-icon"),i=this.clearBtn=this.createButtonIcon("close","input-search-clear");this.listenerSetter.add(t)("input",this.onInput),J(i,this.onClearClick,{listenerSetter:this.listenerSetter,cancelMouseDown:!0}),e.placeholder&&(t.placeholder=" ",this.setPlaceholder(e.placeholder)),e.onFocusChange&&(this.listenerSetter.add(t)("focusin",()=>{e.onFocusChange?.(!0)}),this.listenerSetter.add(t)("focusout",()=>{e.onFocusChange?.(!1)})),this.container.append(s,i),this.setArrowBack(e.arrowBack)}createButtonIcon(e,...t){return t??(t=[]),t.push("input-search-part","input-search-button"),yt(e+" "+t.join(" "),{noRipple:!0})}createIcon(e,...t){return Be(e,"input-search-part",...t)}isLoading(){return this.container.classList.contains("is-connecting")}toggleLoading(e){const t=this.arrowBack?this.clearBtn:this.searchIcon;this.statusPreloader||(this.statusPreloader=new Kn({cancelable:!1}),this.statusPreloader.constructContainer({color:"transparent",bold:!0}),this.statusPreloader.construct?.(),this.statusPreloader.preloader.classList.add("is-visible","will-animate"),t.classList.add("will-animate")),e&&!this.statusPreloader.preloader.parentElement&&this.container.append(this.statusPreloader.preloader),this.statusPreloader.preloader.classList.toggle("is-hiding",!e),t.classList.toggle("is-hiding",e||t===this.clearBtn&&this.inputField.isEmpty()),Dt({element:this.container,className:"is-connecting",forwards:e,duration:jh.ANIMATION_DURATION,onTransitionEnd:e?void 0:()=>{this.statusPreloader.preloader.remove()}})}get value(){return this.inputField.value}set value(e){this.prevValue=e,this.clearTimeout(!1),this.inputField.value=e}remove(){this.clearTimeout(!1),this.verifyDebounce=void 0,this.listenerSetter.removeAll()}}class Zt{constructor(e,t){this._constructor(e,t)}_constructor(e,t=!0){this.slider=e,this.middlewareHelper=e?e.getMiddleware().create():Ht(),this.destroyable=t,this.container=document.createElement("div"),this.container.classList.add("tabs-tab","sidebar-slider-item"),this.header=document.createElement("div"),this.header.classList.add("sidebar-header"),this.closeBtn=yt("left sidebar-close-button",{noRipple:!0}),this.title=document.createElement("div"),this.title.classList.add("sidebar-header__title"),this.header.append(this.closeBtn,this.title),this.content=document.createElement("div"),this.content.classList.add("sidebar-content"),this.scrollable=new tn(this.content,void 0,void 0,!0),this.scrollable.attachBorderListeners(this.container),this.container.append(this.header,this.content),this.slider?.addTab(this),this.listenerSetter=new $t}close(){return this.slider.closeTab(this)}async open(...e){if(this.init)try{const t=this.init(...e);this.init=null,t instanceof Promise&&await t}catch(t){console.error("open tab error",t)}this.slider.selectTab(this)}init(...e){}onOpen(){}onOpenAfterTimeout(){}onClose(){}onCloseAfterTimeout(){this.destroyable&&(this.slider?.deleteTab(this),this.container.remove(),this.scrollable.destroy(),this.listenerSetter?.removeAll(),this.middlewareHelper?.destroy())}setTitle(e){this.title.replaceChildren(P(e))}}class Bs extends Zt{constructor(e){super(e),this.eventListener=new pn}onClose(){this.eventListener.dispatchEvent("close")}onCloseAfterTimeout(){const e=this.eventListener.dispatchResultableEvent("destroy");return this.eventListener.dispatchEvent("destroyAfter",Promise.all(e).then(as,as)),this.eventListener.cleanup(),super.onCloseAfterTimeout()}}const wf=250;class cb{constructor(e){this.historyTabIds=[],this.canHideFirst=!1,this.onCloseBtnClick=()=>{Pt.findItemByType(this.navigationType)?(Pt.back(this.navigationType),this.onTabsCountChange?.()):this.historyTabIds.length&&this.closeTab(this.historyTabIds[this.historyTabIds.length-1])},this.closeTab=(t,s,i)=>{if(t!==void 0&&this.historyTabIds[this.historyTabIds.length-1]!==t)return this.removeTabFromHistory(t),!1;const n=this.historyTabIds.pop();this.onCloseTab(n,s,i);const r=this.historyTabIds[this.historyTabIds.length-1];return this._selectTab(r!==void 0?r instanceof Zt?r.container:r:this.canHideFirst?-1:0,s),!0},Nt(this,e),this.tabs??(this.tabs=new Map),this.tabsContainer=this.sidebarEl.querySelector(".sidebar-slider"),this._selectTab=Sr({content:this.tabsContainer,type:"navigation",transitionTime:wf}),this.canHideFirst||this._selectTab(0),this.middlewareHelper=Ht()}getMiddleware(){return this.middlewareHelper.get()}pushNavigationItem(e){const t={type:this.navigationType,onPop:s=>{if(e.isConfirmationNeededOnClose){const i=e.isConfirmationNeededOnClose();if(i)return Promise.resolve(i).then(()=>{Pt.removeItem(t),this.onTabsCountChange?.(),this.closeTab(void 0,void 0,!0)},()=>{}),!1}return this.closeTab(void 0,s,!0),this.onTabsCountChange?.(),!0}};Pt.pushItem(t),this.onTabsCountChange?.()}async selectTab(e){if(this.historyTabIds[this.historyTabIds.length-1]===e)return!1;const t=e instanceof Zt?e:this.tabs.get(e);return this.onOpenTab&&await this.onOpenTab(),t&&(t.onOpen?.(),t.onOpenAfterTimeout&&setTimeout(()=>{t.onOpenAfterTimeout()},wf)),this.pushNavigationItem(t),this.historyTabIds.push(e),this._selectTab(e instanceof Zt?e.container:e),!0}removeTabFromHistory(e){Vs(this.historyTabIds,e),this.onCloseTab(e,void 0)}closeAllTabs(){const e=this.hasTabsInNavigation();for(let t=this.historyTabIds.length-1;t>=0;--t){const s=this.historyTabIds[t];(s instanceof Zt?s:this.tabs.get(s)).close()}return e}sliceTabsUntilTab(e,t){for(let s=this.historyTabIds.length-1;s>=0;--s){const i=this.historyTabIds[s];if(i!==t){if(i instanceof e)break;this.removeTabFromHistory(i)}}}getTab(e){return this.historyTabIds.find(t=>t instanceof e)}getHistory(){return this.historyTabIds}isTabExists(e){return!!this.getTab(e)}onCloseTab(e,t,s){s||(Pt.removeByType(this.navigationType,!0),this.onTabsCountChange?.());const i=e instanceof Zt?e:this.tabs.get(e);if(i){try{i.onClose?.()}catch{console.error("tab onClose error",i)}i.onCloseAfterTimeout&&setTimeout(()=>{i.onCloseAfterTimeout()},wf+30)}}addTab(e){e.container.parentElement||(this.tabsContainer.append(e.container),e.closeBtn&&e.closeBtn.addEventListener("click",this.onCloseBtnClick))}deleteTab(e){this.tabs.delete(e)}createTab(e,t=!0,s){const i=new e(s?void 0:this,t);return i.managers=this.managers,i}hasTabsInNavigation(){return!!Pt.findItemByType(this.navigationType)}}class db{constructor(e,t){this.container=document.createElement("div"),this.container.classList.add("avatar-edit"),this.canvas=document.createElement("canvas"),this.canvas.classList.add("avatar-edit-canvas"),this.icon=Be("cameraadd","avatar-edit-icon"),this.container.append(this.canvas,this.icon),J(this.container,()=>{ue.createPopup(p_,t).open(this.canvas,e)})}clear(){this.canvas.getContext("2d").clearRect(0,0,this.canvas.width,this.canvas.height)}}const Cn=(a={})=>{const e=ot("btn-circle btn-corner z-depth-1"+(a.className?" "+a.className:""),a);return e.tabIndex=-1,e};function ln(a,e=" "){if(a===void 0)return"";const t=a.toString().split(".");return t[0]=t[0].replace(/\B(?=(\d{3})+(?!\d))/g,e),t.join(".")}function hb(a){return a===void 0?"":ln(a,",")}function Jr(a){return a===void 0?"":ln(a,",")}function qo(a){if(!a)return document.createElement("span");let e,t;switch(a.id){case Lo.toUserId():e="Peer.RepliesNotifications";break;case ku.toUserId():e="Peer.ServiceNotifications";break;default:{if(a.pFlags.bot){if(a.bot_active_users===void 0){e="Bot";break}e="BotUsers",t=[ln(a.bot_active_users)];break}if(a.pFlags.support){e="SupportStatus";break}switch(a.status?._){case"userStatusRecently":{e="Lately";break}case"userStatusLastWeek":{e="WithinAWeek";break}case"userStatusLastMonth":{e="WithinAMonth";break}case"userStatusOffline":{const s=a.status.was_online,i=new Date,r=(i.getTime()/1e3|0)-s;if(r<60)e="Peer.Status.justNow";else if(r<3600)e="Peer.Status.minAgo",t=[r/60|0];else if(r<86400&&i.getDate()===new Date(s*1e3).getDate())e="LastSeen.HoursAgo",t=[r/3600|0];else{e="Peer.Status.LastSeenAt";const{dateEl:o,timeEl:l}=OC(s);t=[o,l]}break}case"userStatusOnline":{e="Online";break}default:{e="ALongTimeAgo";break}}break}}return P(e,t)}const Fg=()=>{const a=document.createElement("div");return a.classList.add("gradient-delimiter"),a},Nd="sidebar-left-section";class Oe{constructor(e={}){const t=this.container=document.createElement("div");t.classList.add(Nd+"-container");const s=this.innerContainer=document.createElement("div");if(s.classList.add(Nd),e.noShadow&&s.classList.add("no-shadow"),e.fakeGradientDelimiter)s.append(Fg()),s.classList.add("with-fake-delimiter");else if(e.noDelimiter)s.classList.add("no-delimiter");else{const r=document.createElement("hr");s.append(r)}const i=this.content=this.generateContentElement();if(e.name){const r=this.title=document.createElement("div");r.classList.add("sidebar-left-h2",Nd+"-name"),typeof e.name=="string"?Rh({element:r,key:e.name,args:e.nameArgs}):r.append(e.name),i.append(r)}t.append(s);const n=e.caption??e.captionOld;if(n){const r=this.caption=this.generateContentElement();r.classList.add(Nd+"-caption"),e.captionOld||t.append(r),n!==!0&&Rh({element:r,key:n,args:e.captionArgs})}}generateContentElement(){const e=document.createElement("div");return e.classList.add(Nd+"-content"),this.innerContainer.append(e),e}}const Xc=(a,e,t)=>{const s=new Oe({name:e,caption:t});return a.append(s.container),s.content};class Q_ extends Zt{constructor(){super(...arguments),this.uploadAvatar=null,this.isGeoChat=!1}init({peerIds:e,isGeoChat:t=!1,onCreate:s,openAfter:i=!0,title:n,asChannel:r=!1}){this.isGeoChat=t,this.peerIds=e,this.container.classList.add("new-group-container"),this.setTitle("NewGroup"),this.avatarEdit=new db(g=>{this.uploadAvatar=g});const o=new Oe({}),l=document.createElement("div");l.classList.add("input-wrapper"),this.groupNameInputField=new Yt({label:"CreateGroup.NameHolder",maxLength:128}),this.groupLocationInputField=new Yt({label:"ChatLocation",name:"location",canBeEdited:!1}),l.append(this.groupNameInputField.container,this.groupLocationInputField.container),this.listenerSetter.add(this.groupNameInputField.input)("input",()=>{let f=!!this.groupNameInputField.value.length&&!this.groupNameInputField.input.classList.contains("error");this.isGeoChat&&(f=f&&!!this.userLocationCoords&&!!this.userLocationAddress),this.nextBtn.classList.toggle("is-visible",!!f)}),this.nextBtn=Cn({icon:"arrow_next"}),J(this.nextBtn,()=>{const g=this.groupNameInputField.value,f=this.peerIds.map(y=>y.toUserId());let v;if(this.isGeoChat){if(!this.userLocationAddress||!this.userLocationCoords)return;v=this.managers.appChatsManager.createChannel({title:g,about:"",geo_point:{_:"inputGeoPoint",...this.userLocationCoords},address:this.userLocationAddress,megagroup:!0}).then(y=>(this.uploadAvatar&&this.uploadAvatar().then(w=>{this.managers.appChatsManager.editPhoto(y,w)}),this.peerIds.length&&this.managers.appChatsManager.inviteToChannel(y,this.peerIds),y))}else this.nextBtn.disabled=!0,r?(v=this.managers.appChatsManager.createChannel({megagroup:!0,title:g,about:""}),e.length&&(v=v.then(y=>this.managers.appChatsManager.inviteToChannel(y,f).then(()=>y)))):v=this.managers.appChatsManager.createChat(g,f),v=v.then(y=>(this.uploadAvatar&&this.uploadAvatar().then(w=>{this.managers.appChatsManager.editPhoto(y,w)}),y));v&&v.then(y=>{s?.(y),this.close(),i&&Ce.setInnerPeer({peerId:y.toPeerId(!0)})})},{listenerSetter:this.listenerSetter});const c=new Oe({name:"Members",nameArgs:[this.peerIds.length]});this.peerIds.length||c.container.classList.add("hide");const d=this.list=nt.createChatList({new:!0});c.content.append(d),o.content.append(this.avatarEdit.container,l),this.content.append(this.nextBtn),this.scrollable.append(o.container,c.container),t?(this.setTitle("NearbyCreateGroup"),this.groupLocationInputField.container.classList.remove("hide"),this.groupLocationInputField.setValueSilently(Ne.format("Loading",!0)),this.startLocating()):this.groupLocationInputField.container.classList.add("hide");const u=Promise.all(this.peerIds.map(g=>this.managers.appUsersManager.getUser(g.toUserId()))),h=this.managers.appUsersManager.getSelf(),p=u.then(g=>g.map(f=>{const{dom:v}=nt.addDialogNew({peerId:f.id.toPeerId(!1),container:this.list,rippleEnabled:!1,avatarSize:"abitbigger",wrapOptions:{middleware:this.middlewareHelper.get()}});v.lastMessageSpan.append(qo(f))}));let m;return n?this.groupNameInputField.setDraftValue(n):m=this.peerIds.length>0&&this.peerIds.length<5?Promise.all([u,h]).then(([g,f])=>{const v=g.map(w=>[w.first_name,w.last_name].filter(Boolean).join(" "));v.unshift(f.first_name);const y=Kl(v,w=>w?", ":" & ").join("");this.groupNameInputField.setDraftValue(y)}):Promise.resolve(),Promise.all([p,m])}onCloseAfterTimeout(){this.avatarEdit.clear(),this.uploadAvatar=null,this.groupNameInputField.value="",this.groupLocationInputField.container.classList.add("hide"),this.nextBtn.disabled=!1}startLocating(){navigator.geolocation.getCurrentPosition(e=>{this.userLocationCoords={lat:e.coords.latitude,long:e.coords.longitude};let t="https://nominatim.openstreetmap.org/reverse";t+="?lat="+e.coords.latitude,t+="&lon="+e.coords.longitude,t+="&format=json",t+="&addressdetails=1",t+="&accept-language=en",fetch(t).then(s=>s.json()).then(s=>{this.userLocationAddress=s.display_name,this.groupLocationInputField.setValueSilently(s.display_name)})},e=>{e instanceof GeolocationPositionError?this.groupLocationInputField.setValueSilently("Location permission denied. Please retry later."):this.groupLocationInputField.setValueSilently("An error has occurred. Please retry later.")})}}function di(a,e,t,s){return s===void 0&&(s=a.parentElement===e?Bn(a):-1),s===t?!1:(s!==-1&&s<t&&(t+=1),t?e.childElementCount>t?e.insertBefore(a,e.children[t]):e.append(a):e.prepend(a),!0)}function Tl(a,e,t,s,i){if(!t)t=o=>o;else if(typeof t!="function"){const o=t;t=l=>l[o]}i||(i=(o,l)=>o-l);const n=t(e);if(s??(s=a.indexOf(e)),s!==-1){const o=a[s-1],l=a[s+1];if((!o||i(t(o),n)>=0)&&(!l||i(t(l),n)<=0))return s;a.splice(s,1)}const r=a.length;if(!r||i(n,t(a[r-1]))<=0)return a.push(e)-1;if(i(n,t(a[0]))>=0)return a.unshift(e),0;for(let o=0;o<r;o++)if(i(n,t(a[o]))>0)return a.splice(o,0,e),o;return console.error("wtf",a,e),a.indexOf(e)}const Jk=Vo("MIDDLEWARE");function Bl(a,e=Jk){return t=>{if(!(t instanceof Promise)){if(t instanceof Error)throw t;return t}return t.then(s=>{if(!a())throw e;return s})}}let eT=0;class X_{constructor(e){Nt(this,e),this.queue=[],this.middlewareHelper??(this.middlewareHelper=Ht());const t="BATCH-PROCESSOR-"+ ++eT,s=Rn.Log|Rn.Warn|Rn.Error;this.log?this.log=this.log.bindPrefix(t,s):this.log=Ni(t,s)}get queuePromise(){return this.promise}clear(){this.log("clear"),this.queue.length=0,this.promise=void 0,this.middlewareHelper.clean()}addToQueue(e){return this.queue.push(e),this.setQueue()}setQueue(){if(!this.queue.length)return Promise.resolve();if(this.promise)return this.promise;const e=this.middlewareHelper.get(),t=this.log.bindPrefix("queue"),s=Bl(e,this.possibleError),i=async()=>{t("start",this.queue.length);const r=this.queue.splice(0,this.queue.length),o=performance.now(),l=r.map(d=>(d instanceof Promise&&d.then(u=>{t("render item time",performance.now()-o,u)}),d)),c=await s(Promise.all(l));if(await s(this.process(c,s,t)),t("queue rendered"),this.queue.length)return t("have new items to render"),i();t("end")};t("setting pause");const n=this.promise=s(ns(0)).then(()=>i().catch(r=>{throw r!==this.possibleError&&t.error("process queue error",r),r}),r=>{throw t("pause has been cleared"),r}).finally(()=>{this.promise===n&&(this.promise=void 0)});return n}}class Bg{constructor(e){this.updateElementWith=t=>t(),this.updateListWith=t=>t(!0),Nt(this,e),this.elements=new Map,this.sorted=[],this.middlewareHelper=e.middleware?.create()||Ht(),this.batchProcessor=new X_({log:this.log,process:async(t,s,i)=>{const r=t.map(o=>this.update(o.id,o));await s(Promise.all(r))}})}clear(){this.batchProcessor.clear(),this.middlewareHelper.clean(),this.elements.clear(),this.sorted.length=0}_updateList(){this.elements.forEach(e=>{this.update(e.id)}),this.onSort&&this.sorted.forEach((e,t)=>{this.onSort(e,t)})}updateList(e){const t=this.middlewareHelper.get();this.updateListWith(s=>{if(!t()||s!==void 0&&!s){e?.(!1);return}this._updateList(),e?.(!0)})}has(e){return this.elements.has(e)}get(e){return this.elements.get(e)}getAll(){return this.elements}async add(e){if(this.get(e))return;const s={id:e,index:0};this.elements.set(e,s);let i=this.onElementCreate(s);if(i instanceof Promise){let n=!1;i=Promise.race([i.then(r=>(n=!0,r)),ns(1e3).then(()=>{if(!n)return console.error("loadPromises are still pending?",s),s})])}return this.batchProcessor.addToQueue(i)}delete(e,t){const s=this.elements.get(e);if(!s)return!1;this.elements.delete(e);const i=this.sorted.indexOf(s);if(i!==-1&&this.sorted.splice(i,1),this.onDelete)if(t)this.onDelete(s);else{const n=this.middlewareHelper.get();this.updateElementWith(()=>{n()&&this.onDelete(s)})}return!0}async update(e,t=this.get(e)){if(!t||(t.index=await this.getIndex(t),this.get(e)!==t))return;this.onUpdate?.(t);const s=Tl(this.sorted,t,"index");this.onSort(t,s)}}function Z_(a){return a.participants_count||a.participants?.participants?.length||1}function fS(a,e){let t;e?t=Z_(e):t=a.participants_count||a.participants?.participants.length;const s=a.pFlags.broadcast;return t=t||1,P(s?"Peer.Status.Subscribers":"Peer.Status.Member",[ln(t)])}function ja(a,e=I.managers,t,s,i){if(t??(t=Ae.getChat(a)),t._==="chatForbidden")return P("YouWereKicked");if(s)return fS(t,void 0);const n=i||e.appProfileManager.getCachedFullChat(a);return en(n,r=>fS(t,r))}function ub(a){return a.rank||(a._==="channelParticipantAdmin"||a._==="chatParticipantAdmin"?2:a._==="chatParticipantCreator"||a._==="channelParticipantCreator"?1:void 0)}function J_(a){return typeof a=="object"&&(a=ub(a)),typeof a=="number"?P(a?a===1?"Chat.OwnerBadge":"ChatAdmin":"Chat.ChannelBadge"):je(a)}const og=class og extends Bg{constructor(e){super({getIndex:e.getIndex||(s=>s.id.isAnyChat()?0:this.managers.appUsersManager.getUserStatusForSort(s.id)),onDelete:s=>{s.dialogElement.remove(),this.onListLengthChange?.()},onUpdate:e.onUpdate||(async s=>{if(s.id.isAnyChat()){const i=await ja(s.id.toChatId(),this.managers);St(s.dom.lastMessageSpan,i)}else{const i=qo(await this.managers.appUsersManager.getUser(s.id));St(s.dom.lastMessageSpan,i)}}),onSort:(s,i)=>{const n=s.dom.listEl.parentElement!==this.list;di(s.dom.listEl,this.list,i),n&&this.onListLengthChange&&this.onListLengthChange()},onElementCreate:s=>{const i=nt.addDialogNew({peerId:s.id,container:!1,avatarSize:this.avatarSize,autonomous:this.autonomous,meAsSaved:!1,rippleEnabled:this.rippleEnabled,wrapOptions:{lazyLoadQueue:this.lazyLoadQueue,middleware:this.middlewareHelper.get()},withStories:!0}),n=this.ranks.get(s.id);return n&&i.titleRight.replaceChildren(J_(n)),s.dom=i.dom,s.dialogElement=i,s},updateElementWith:$s,updateListWith:async s=>{if(!Array.from(this.elements.values()).some(i=>i.id.isUser())||!mr(this.list)||(await vi(),!mr(this.list)))return s(!1);s(!0)},middleware:e.middleware}),this.ranks=new Map,this.avatarSize="abitbigger",this.rippleEnabled=!0,this.autonomous=!0,Nt(this,e),this.list=nt.createChatList(this.createChatListOptions);const t=()=>{window.setTimeout(()=>{this.updateList(s=>{s&&t()})},og.SORT_INTERVAL)};t()}};og.SORT_INTERVAL=3e4;let qh=og;class Ou{constructor(e){this._disabled=!1,this.avatarSize=120,this.isChanged=()=>{if(this.uploadAvatar)return!0;let t=0,s=0,i=0;return this.inputFields.forEach(n=>{n.isValid()&&(n.isChanged()&&++t,n.required&&++i),n.required&&++s}),s===i&&t>0},this.handleChange=()=>{this.nextBtn.classList.toggle("is-visible",this.isChanged())},Nt(this,e),this.peerId||(this.peerId=Wt),this.nextBtn?this.nextBtn.classList.contains("btn-corner")||(this.handleChange=()=>{this.nextBtn.toggleAttribute("disabled",!this.isChanged()||this.disabled)}):this.nextBtn=Cn({icon:"check"}),e.withoutAvatar||(this.avatarElem=vs({middleware:e.middleware,size:this.avatarSize,peerId:this.peerId}),this.avatarElem.node.classList.add("avatar-placeholder"),e.doNotEditAvatar||(this.avatarEdit=new db(t=>{this.uploadAvatar=t,this.handleChange(),this.avatarElem.node.remove()},e.popupOptions),this.avatarEdit.container.append(this.avatarElem.node))),this.inputFields.forEach(t=>{this.listenerSetter.add(t.input)("input",this.handleChange)}),this.handleChange()}get disabled(){return this._disabled}set disabled(e){this._disabled=e,this.inputFields.forEach(t=>t.input.toggleAttribute("disabled",e)),this.handleChange()}lockWithPromise(e,t=!1){this.disabled=!0,e.then(()=>{t&&(this.disabled=!1)},()=>{this.disabled=!1})}}function vS(a,e){const t=document.createElement(e?"div":"textarea");if(e?(t.tabIndex=0,t.contentEditable="true",t.innerHTML=e):t.value=a,t.style.top="0",t.style.left="0",t.style.position="fixed",document.body.appendChild(t),t.focus(),e){const s=window.getSelection();s.removeAllRanges();const i=document.createRange();i.setStartBefore(t.firstChild),i.setEndAfter(t.lastChild),s.addRange(i)}else t.select();try{document.execCommand("copy"),window.getSelection().removeAllRanges()}catch(s){console.error("unable to copy",s)}document.body.removeChild(t)}async function si(a,e){if(!navigator.clipboard){vS(a);return}try{if(!e){await navigator.clipboard.writeText(a);return}await navigator.clipboard.write([new ClipboardItem({"text/plain":new Blob([a],{type:"text/plain"}),"text/html":new Blob([e],{type:"text/html"})})])}catch(t){console.error("clipboard error",t),vS(a,e)}}function $i(a,e,t=!0,s=!0){let i,n,r,o,l=!1;const c=u=>{const h=r,p=o;try{const m=a.apply(null,u);h(m)}catch(m){console.error("debounce error",m),p(m)}},d=(...u)=>{n||(n=new Promise((p,m)=>(r=p,o=m))),i?(clearTimeout(i),l=!0,o(),n=new Promise((p,m)=>(r=p,o=m))):t&&(c(u),l=!1);const h=dm.setTimeout(()=>{s&&(!t||l)&&c(u),i===h&&(i=n=r=o=void 0,l=!1)},e);return i=h,n.catch(as),n};return d.clearTimeout=()=>{i&&(dm.clearTimeout(i),o(),i=n=r=o=void 0,l=!1)},d.isDebounced=()=>!!i,d}function Nv(a){if(a.length<3||a.length>32||!/[a-zA-Z]/.test(a.charAt(0)))return!1;for(let e=0;e<a.length;e++){const t=a.charAt(e);if(!/[a-zA-Z0-9_]/.test(t))return!1}if(a.charAt(a.length-1)==="")return!1;for(let e=1;e<a.length;e++)if(a.charAt(e-1)===""&&a.charAt(e)==="_")return!1;return!0}function tT(a){return a.length>=3&&Nv(a)}class pb extends Yt{constructor(e,t){super(e),this.managers=t,this.checkUsernameDebounced=$i(this.checkUsername.bind(this),150,!1,!0),e.listenerSetter.add(this.input)("input",()=>{const s=this.getValue();if(this.error=void 0,s===this.originalValue||!s.length){this.setState(ra.Neutral),this.options.onChange?.();return}else Nv(s)?this.setState(ra.Neutral):this.setError(this.options.invalidText);if(this.input.classList.contains("error")){this.options.onChange?.();return}this.checkUsernameDebounced(s)})}getValue(){let e=this.value;return this.options.head&&(e=e.slice(this.options.head.length),this.setValueSilently(this.options.head+e)),e}checkUsername(e){if(this.checkUsernamePromise)return;this.error=void 0;let t;this.options.peerId?t=this.managers.appChatsManager.checkUsername(this.options.peerId.toChatId(),e):t=this.managers.appUsersManager.checkUsername(e);const s=this.checkUsernamePromise=t.then(i=>{this.getValue()===e&&(i?this.setState(ra.Valid,this.options.availableText):this.setError(this.options.takenText))},i=>{if(this.getValue()===e)switch(this.error=i,this.error.type){case"USERNAME_PURCHASE_AVAILABLE":{this.setError(this.options.takenText);break}case"USERNAME_INVALID":default:{this.setError(this.options.invalidText);break}}}).then(()=>{this.checkUsernamePromise===s&&(this.checkUsernamePromise=void 0),this.options.onChange?.();const i=this.getValue();i!==e&&this.isValidToChange()&&Nv(i)&&this.checkUsername(i)})}}const ym=a=>"touches"in a?a.touches[0]:a;function yS(a,e){return e?Math.hypot(e.pageX-a.pageX,e.pageY-a.pageY):0}function bS(a,e){return{x:(a.pageX+e.pageX)/2,y:(a.pageY+e.pageY)/2}}const el=document;let e1=!1;Li.addEventListener("toggle",a=>{e1=a});const Sf={passive:!1},Cf=!1,sT={capture:!0,passive:!1};class Qn{constructor(e){this.reset=t=>{this.log("reset"),pt?this.listenerSetter.removeManual(el,"touchmove",this.handleMove,Sf):(this.listenerSetter.removeManual(el,"mousemove",this.handleMove,Cf),this.setCursorTo.style.cursor=""),this.hadMove&&this.onReset?.(t),this.releaseWheelDrag?.clearTimeout(),this.releaseWheelZoom?.clearTimeout(),this.resetValues()},this.handleStart=async t=>{if(this.log("start"),this.isMouseDown){const r=t.touches;r?.length===2&&(this.initialDistance=yS(r[0],r[1]),this.initialTouchCenter=bS(r[0],r[1]));return}const s=ym(t);if(![0,1].includes(Math.max(0,s.button??0))||(s.button===1&&_e(t),UC(t)))return;const i=++this.tempId,n=this.verifyTouchTarget?.(t);if(n!==void 0){let r;if(n instanceof Promise){if(r=await n,this.tempId!==i)return}else r=n;if(!r)return this.reset()}if(this.isMouseDown=!0,this.withDelay&&!pt){const r={...Cf,once:!0},o=Mt(),l=()=>o.resolve(),c=this.listenerSetter.add(el)("mousemove",l,r);if(await Promise.race([ns(300),o]),o.resolve(),this.listenerSetter.remove(c),this.tempId!==i)return}this.xDown=s.clientX,this.yDown=s.clientY,this.eventUp=s,pt?this.listenerSetter.add(el)("touchmove",this.handleMove,Sf):this.listenerSetter.add(el)("mousemove",this.handleMove,Cf),this.onStart&&(this.onStart(),this.hadMove=!0,this.handleMove(s))},this.handleMove=t=>{if(this.xDown===void 0||this.yDown===void 0||e1){this.reset();return}if(this.cancelEvent&&_e(t),this.releaseWheelDrag?.isDebounced()||this.releaseWheelZoom?.isDebounced())return;this.log("move");const s=this.eventUp=ym(t),i=s.clientX,n=s.clientY,r=i-this.xDown+this.xAdded,o=n-this.yDown+this.yAdded;if(!this.hadMove){if(!r&&!o)return;this.setHadMove(t)}const l=t.touches;if(this.onZoom&&this.initialDistance>0&&l.length===2){const c=yS(l[0],l[1]),d=bS(l[0],l[1]),u=d.x-this.initialTouchCenter.x,h=d.y-this.initialTouchCenter.y,m={zoomFactor:c/this.initialDistance,initialCenterX:this.initialTouchCenter.x,initialCenterY:this.initialTouchCenter.y,dragOffsetX:u,dragOffsetY:h,currentCenterX:d.x,currentCenterY:d.y};this.onZoom(m)}this.dispatchOnSwipe(r,o,t)},this.handleWheel=t=>{if(!this.hadMove&&this.verifyTouchTarget){const i=this.verifyTouchTarget(t);if(i!==void 0&&!i){this.reset(t);return}}if(_e(t),this.log("wheel"),this.onDoubleClick&&Object.is(t.deltaX,-0)&&Object.is(t.deltaY,-0)&&t.ctrlKey){this.onWheelCapture(t),this.onDoubleClick({centerX:t.pageX,centerY:t.pageY}),this.reset();return}t.metaKey||t.ctrlKey||t.shiftKey?(this.releaseWheelDrag?.isDebounced()&&this.reset(),this.onWheelZoom(t)):this.handleWheelDrag(t)},this.handleWheelDrag=t=>{this.log("wheel drag"),this.onWheelCapture(t),(!this.isDragCanceled.x||Math.sign(this.initialDragOffset.x)===Math.sign(t.deltaX))&&(this.initialDragOffset.x-=t.deltaX),(!this.isDragCanceled.y||Math.sign(this.initialDragOffset.y)===Math.sign(t.deltaY))&&(this.initialDragOffset.y-=t.deltaY);const{x:s,y:i}=this.initialDragOffset;this.releaseWheelDrag(t),this.dispatchOnSwipe(s,i,t,(n,r)=>{this.isDragCanceled={x:n,y:r}})},this.onWheelCapture=t=>{this.hadMove||(this.log("wheel capture"),this.handleStart(t),this.setHadMove(t),this.initialTouchCenter={x:t.x,y:t.y})},this.onWheelZoom=t=>{if(!this.onZoom)return;this.log("wheel zoom"),this.onWheelCapture(t);const s=t.x-this.initialTouchCenter.x,i=t.y-this.initialTouchCenter.y,n=zt(t.deltaY,-25,25);this.wheelZoom-=n*.01;const r={zoomAdd:this.wheelZoom-1,initialCenterX:this.initialTouchCenter.x,initialCenterY:this.initialTouchCenter.y,dragOffsetX:s,dragOffsetY:i,currentCenterX:t.x,currentCenterY:t.y};this.onZoom(r),this.releaseWheelZoom(t)},Nt(this,e),this.log=Ni("SWIPE-HANDLER"),this.cursor??(this.cursor="grabbing"),this.cancelEvent??(this.cancelEvent=!0),this.listenerOptions??(this.listenerOptions=Sf),this.setCursorTo??(this.setCursorTo=this.element),this.listenerSetter=new $t,this.setListeners(),this.resetValues(),this.tempId=0,e.middleware?.onDestroy(()=>{this.reset(),this.removeListeners()}),this.releaseWheelDrag=$i(this.reset,150,!1),this.releaseWheelZoom=$i(this.reset,150,!1)}setListeners(){pt?(this.withDelay?Er({element:this.element,callback:e=>{_e(e),this.handleStart(e)},listenerSetter:this.listenerSetter,listenerOptions:this.listenerOptions}):this.listenerSetter.add(this.element)("touchstart",this.handleStart,this.listenerOptions),this.onDoubleClick&&this.listenerSetter.add(this.element)("dblclick",e=>{this.onDoubleClick({centerX:e.pageX,centerY:e.pageY})}),this.listenerSetter.add(el)("touchend",this.reset)):(this.listenerSetter.add(this.element)("mousedown",this.handleStart,this.listenerOptions),this.listenerSetter.add(el)("mouseup",this.reset),(this.onZoom||this.onDoubleClick)&&this.listenerSetter.add(this.element)("wheel",this.handleWheel,sT))}removeListeners(){this.log("remove listeners"),this.reset(),this.listenerSetter.removeAll()}setCursor(e=""){this.cursor=e,!pt&&this.hadMove&&this.setCursorTo.style.setProperty("cursor",this.cursor,"important")}add(e,t){this.xAdded=e,this.yAdded=t,this.handleMove({clientX:this.eventUp.clientX,clientY:this.eventUp.clientY,target:this.eventUp.target})}resetValues(){++this.tempId,this.hadMove=!1,this.xAdded=this.yAdded=0,this.xDown=this.yDown=this.eventUp=this.isMouseDown=void 0,this.onZoom&&(this.initialDistance=0,this.initialTouchCenter={x:It.width/2,y:It.height/2},this.initialDragOffset={x:0,y:0},this.isDragCanceled={x:!1,y:!1},this.wheelZoom=1)}setHadMove(e){this.hadMove||(this.log("had move"),this.hadMove=!0,this.setCursorTo.style.setProperty("cursor",this.cursor,"important"),this.onFirstSwipe?.(e))}dispatchOnSwipe(...e){const t=this.onSwipe(...e);t!==void 0&&t&&this.reset()}}class mb{constructor(e){this.onSwipe=(t,s)=>{s=zt(s,this.minY,this.maxY),this.element.style.transform=`translateY(${s}px)`;const i=Math.round(Math.abs(s)/this.elementRect.height),n=this.siblings;this.siblings=[];const r=s<0?"previousElementSibling":"nextElementSibling";let o=this.element[r];for(let l=0;l<i&&this.getSortableTarget(o);++l)this.siblings.push(o),o=o[r];if((n||[]).forEach(l=>{this.siblings.includes(l)||(l.style.transform="")}),this.siblings.forEach(l=>{const c=this.elementRect.height*(s<0?1:-1);l.style.transform=`translateY(${c}px)`}),this.scrollableRect){const l=s,c=l>0,u=(c?this.elementRect.bottom:this.elementRect.top)+l-this.addScrollPos;let h=2;u+(c?0:this.elementRect.height)>=this.scrollableRect.bottom||(u-(c?this.elementRect.height:0)<=this.scrollableRect.top?h*=-1:h=void 0),h!==void 0&&(this.scrollable.scrollPosition+=h)}},this.verifyTouchTarget=t=>this.list.classList.contains("is-reordering")?!1:(this.element=this.getSortableTarget(t.target),!!this.element),this.onScroll=()=>{const t=this.scrollable.scrollPosition,s=this.addScrollPos=t-this.startScrollPos,i=this.scrollable.scrollPositionProperty==="scrollTop";this.swipeHandler.add(i?0:s,i?s:0)},this.onStart=()=>{this.list.classList.add("is-reordering"),this.element.classList.add("is-dragging","no-transition"),this.swipeHandler.setCursor("grabbing"),this.elementRect=this.element.getBoundingClientRect(),this.containerRect=this.list.getBoundingClientRect(),this.minY=this.containerRect.top-this.elementRect.top,this.maxY=this.containerRect.bottom-this.elementRect.bottom,this.addScrollPos=0,this.scrollable&&(this.startScrollPos=this.scrollable.scrollPosition,this.scrollableRect=this.scrollable.container.getBoundingClientRect(),this.scrollable.container.addEventListener("scroll",this.onScroll))},this.onReset=async()=>{const t=this.siblings.length,s=t&&t*(this.siblings[0].previousElementSibling===this.element?1:-1),i=Bn(this.element),n=i+s;this.element.classList.remove("no-transition"),this.element.style.transform=s?`translateY(${s*this.elementRect.height}px)`:"",this.swipeHandler.setCursor(""),this.scrollable&&this.scrollable.container.removeEventListener("scroll",this.onScroll),pt||J(document.body,_e,{capture:!0,once:!0}),wt.isAvailable("animations")&&await ns(250),this.list.classList.remove("is-reordering"),this.element.classList.remove("is-dragging"),di(this.element,this.list,n,i),[this.element,...this.siblings].forEach(r=>{r.style.transform=""}),this.element=this.siblings=this.elementRect=this.containerRect=this.minY=this.maxY=this.startScrollPos=this.addScrollPos=void 0,s&&this.onSort(i,n)},Nt(this,e),this.swipeHandler=new Qn({element:this.list,onSwipe:this.onSwipe,verifyTouchTarget:this.verifyTouchTarget,onStart:this.onStart,onReset:this.onReset,setCursorTo:document.body,middleware:this.middleware,withDelay:!0})}getSortableTarget(e){if(!e)return;let t=Mi(e,this.list);return t&&t.classList.contains("cant-sort")&&(t=void 0),t}}function Rt(a){return new Promise((e,t)=>{const{button:s,checkbox:i,rejectWithReason:n}=a;s.callback=(c,d)=>{e(i||!d?d?!!d.size:void 0:a.checkboxes.map(u=>d.has(u.text)))};const r=Go(a.buttons||[s]),o=r.find(c=>c.isCancel);o.callback=()=>{t(n?"canceled":void 0)},a.buttons=r,a.checkboxes??(a.checkboxes=i&&[i]);const l=ue.createPopup(mi,"popup-confirmation",a);l.addEventListener("closeAfterTimeout",()=>{t(n?"closed":void 0)}),l.show()})}const zp="usernames";class gb extends Fe{constructor(e,t="limit_link",s,i,n){super({title:!0,subtitle:!0,clickable:!0,titleRight:i,subtitleRight:n}),e&&(this.title.classList.add("text-bold"),this.container.classList.add("is-link")),this.container.classList.add(zp+"-username"),this.subtitle.classList.add(zp+"-username-status");const r=this.createMedia("abitbigger");r.classList.add(zp+"-username-icon","avatar-gradient"),s&&(r.dataset.color=s),e&&t==="link_paid"&&this.container.classList.add("is-paid"),r.append(Be(t))}}class fb extends Oe{constructor(e){super({name:"UsernamesProfileHeader",caption:e.peer.pFlags.bot?"UsernamesBotHelp":e.peerId.isUser()?"UsernamesProfileHelp":"UsernamesChannelHelp"});const{peerId:t,peer:s,usernameInputField:i,listenerSetter:n,middleware:r}=e,o=I.managers,l=t.isUser()?void 0:t.toChatId(),c=e.peer.pFlags.bot?t.toUserId():void 0;c&&i.container.classList.add("disable-hover");const d=this,u=document.createElement("div");u.classList.add(zp);let h;const p=new Bg({getIndex:f=>h.length-h.findIndex(v=>v.username===f.id),onDelete:f=>{f.row.container.remove()},onSort:(f,v)=>{di(f.row.container,u,v)},onElementCreate:f=>{const v=h.find(S=>S.username===f.id),y=new gb;y.title.textContent="@"+v.username;const w=!!v.pFlags.editable,b=!!v.pFlags.active;return w&&(y.container.dataset.editable="1"),y.makeSortable(),m(y,b),f.row=y,f},middleware:r}),m=(f,v)=>{f.subtitle.replaceChildren(P(f.container.dataset.editable?c?"UsernameLinkBotUsername":"UsernameLinkEditable":v?"UsernameLinkActive":"UsernameLinkInactive")),f.container.classList.toggle("active",v),f.toggleSorting(v)},g=(f=[])=>{h=f,p.getAll().forEach(v=>{f.some(y=>y.username===v.id)||p.delete(v.id)}),f.forEach(v=>{if(!p.has(v.username))p.add(v.username);else{const y=p.get(v.username);p.update(v.username,y),m(y.row,!!v.pFlags.active)}}),d.container.classList.toggle("hide",!p.getAll().size)};g(s.usernames),n.add(I)("peer_title_edit",async({peerId:f})=>{if(f!==t)return;const v=await o.appPeersManager.getPeer(t);g(v.usernames)}),J(u,async f=>{const v=Mi(f.target,u);if(!v)return;if(v.dataset.editable){c||Ki(i.input,!0,!0);return}const y=v.dataset.username,w=v.classList.contains("active");let b,S;w?(b="UsernameDeactivateLink",S=c?"UsernameDeactivateLinkBotMessage":l?"UsernameDeactivateLinkChannelMessage":"UsernameDeactivateLinkProfileMessage"):(b="UsernameActivateLink",S=c?"UsernameActivateLinkBotMessage":l?"UsernameActivateLinkChannelMessage":"UsernameActivateLinkProfileMessage");try{await Rt({titleLangKey:b,descriptionLangKey:S,button:{langKey:w?"Hide":"Show"}})}catch{return}const _=!w;o.appUsernamesManager.toggleUsername({peerId:t,username:y,active:_}).catch(C=>{C.type==="USERNAMES_ACTIVE_TOO_MUCH"?Rt({titleLangKey:"UsernameActivateErrorTitle",descriptionLangKey:"UsernameActivateErrorMessage",button:{langKey:"OK",isCancel:!0}}).catch(as):console.error("turn username error",C)})}),new mb({list:u,middleware:r,onSort:(f,v)=>{const y=h.splice(f,1)[0];h.splice(v,0,y),p.updateList();const w=h.filter(b=>b.pFlags.active).map(b=>b.username);o.appUsernamesManager.reorderUsernames({peerId:t,order:w})}}),d.content.append(u)}}function Yh(a){return a.username?a.username:a.usernames?.find(s=>s.pFlags.editable)?.username}function vb(){const a=document.createElement("div"),e="https://fragment.com/username/",t=jl(document.createElement("a")),s=P("Username.Purchase",[t]);return s.classList.add("username-purchase-help"),a.append(s,document.createElement("br"),document.createElement("br")),a.classList.add("hide"),{element:a,setUsername:i=>{i&&(t.href=e+i),a.classList.toggle("hide",!i)}}}class bm extends Zt{static getInitArgs(){return{bioMaxLength:I.managers.apiManager.getLimit("bio"),user:I.managers.appUsersManager.getSelf(),userFull:I.managers.appProfileManager.getProfile(I.myId.toUserId())}}async init(e=bm.getInitArgs()){this.container.classList.add("edit-profile-container"),this.setTitle("EditAccount.Title");const t=[],[s,i,n]=await Promise.all([e.bioMaxLength,e.user,e.userFull]);{const r=Xc(this.scrollable,void 0,"Bio.Description"),o=document.createElement("div");o.classList.add("input-wrapper"),this.firstNameInputField=new Yt({label:"EditProfile.FirstNameLabel",name:"first-name",maxLength:70}),this.lastNameInputField=new Yt({label:"Login.Register.LastName.Placeholder",name:"last-name",maxLength:64}),this.bioInputField=new Yt({label:"EditProfile.BioLabel",name:"bio",maxLength:s}),o.append(this.firstNameInputField.container,this.lastNameInputField.container,this.bioInputField.container),t.push(this.firstNameInputField,this.lastNameInputField,this.bioInputField),this.editPeer=new Ou({peerId:I.myId,inputFields:t,listenerSetter:this.listenerSetter,middleware:this.middlewareHelper.get()}),this.content.append(this.editPeer.nextBtn),r.append(this.editPeer.avatarEdit.container,o)}{const r=new Oe({name:"EditAccount.Username",caption:!0}),o=document.createElement("div");o.classList.add("input-wrapper"),this.usernameInputField=new pb({label:"EditProfile.Username.Label",name:"username",plainText:!0,listenerSetter:this.listenerSetter,onChange:()=>{this.editPeer.handleChange();const{error:u}=this.usernameInputField,h=u?.type==="USERNAME_PURCHASE_AVAILABLE";c(h?this.usernameInputField.value:void 0)},availableText:"EditProfile.Username.Available",takenText:"EditProfile.Username.Taken",invalidText:"EditProfile.Username.Invalid"},this.managers),o.append(this.usernameInputField.container);const l=r.caption,{setUsername:c,element:d}=vb();l.append(d,P("UsernameHelp")),t.push(this.usernameInputField),r.content.append(o),this.scrollable.append(r.container)}{const r=new fb({peerId:I.myId,peer:i,listenerSetter:this.listenerSetter,usernameInputField:this.usernameInputField,middleware:this.middlewareHelper.get()});this.scrollable.append(r.container)}J(this.editPeer.nextBtn,()=>{this.editPeer.nextBtn.disabled=!0;const r=[],o=this.managers.appProfileManager.updateProfile(this.firstNameInputField.value,this.lastNameInputField.value,this.bioInputField.value);r.push(o.then(()=>{this.close()},l=>{console.error("updateProfile error:",l)})),this.editPeer.uploadAvatar&&r.push(this.editPeer.uploadAvatar().then(l=>this.managers.appProfileManager.uploadProfilePhoto(l))),this.usernameInputField.isValidToChange()&&r.push(this.managers.appUsersManager.updateUsername(this.usernameInputField.value)),Promise.race(r).finally(()=>{this.editPeer.nextBtn.removeAttribute("disabled")})},{listenerSetter:this.listenerSetter}),this.firstNameInputField.setOriginalValue(i.first_name,!0),this.lastNameInputField.setOriginalValue(i.last_name,!0),this.bioInputField.setOriginalValue(n.about,!0),this.usernameInputField.setOriginalValue(Yh(i),!0),this.editPeer.handleChange()}}class iT extends Bs{async init(){this.container.classList.add("edit-peer-container","group-type-container");const e=await this.managers.appChatsManager.isBroadcast(this.chatId),t=this.chatFull.linked_chat_id;this.setTitle(e?"ChannelType":"GroupType");const s=new Oe({name:e?"ChannelType":"GroupType"}),i=xu(),n=new Fe({radioField:new rn({langKey:e?"ChannelPrivate":"MegaPrivate",name:i,value:"private"}),subtitleLangKey:e?"ChannelPrivateInfo":"MegaPrivateInfo"}),r=new Fe({radioField:new rn({langKey:e?"ChannelPublic":"MegaPublic",name:i,value:"public"}),subtitleLangKey:e?"ChannelPublicInfo":"MegaPublicInfo"}),o=Sd([n,r],U=>{const j=[[u.container],[L]];U==="public"&&j.reverse(),j[0].forEach(q=>q.classList.remove("hide")),j[1].forEach(q=>q.classList.add("hide")),b(),G&&!t&&G.container.classList.toggle("hide",U!=="public")});let l=Ae.getChat(this.chatId);const c={basic:[]},d=(U,j="basic")=>{c[j].push(U)};this.listenerSetter.add(I)("chat_update",U=>{this.chatId===U&&(l=Ae.getChat(this.chatId),c.basic.forEach(j=>j()))}),s.content.append(o);const u=new Oe({}),h=new Fe({title:this.chatFull.exported_invite.link,subtitleLangKey:e?"ChannelPrivateLinkHelp":"MegaPrivateLinkHelp",clickable:()=>{si(this.chatFull.exported_invite.link),Wi(Ne.format("LinkCopied",!0))},listenerSetter:this.listenerSetter}),p=ot("btn-primary btn-transparent danger",{icon:"delete",text:"RevokeLink"});J(p,()=>{ue.createPopup(mi,"revoke-link",{buttons:[{langKey:"RevokeButton",callback:()=>{const U=os([p],!0);this.managers.appProfileManager.getChatInviteLink(this.chatId,!0).then(j=>{U(),h.title.textContent=j})}}],titleLangKey:"RevokeLink",descriptionLangKey:"RevokeAlert"}).show()},{listenerSetter:this.listenerSetter}),u.content.append(h.container,p);const m=new Oe({caption:!0,noDelimiter:!0}),g=document.createElement("div");g.classList.add("input-wrapper");const f="t.me/";let v,y,w;const b=()=>{v=n.radioField.checked&&E!==f||S.isValidToChange()&&S.input.classList.contains("valid"),y=!!O&&O.checkboxField.checked!==H,w=!!$&&$.checkboxField.checked!==D,x.classList.toggle("is-visible",v||y||w);const{error:U}=S,j=U?.type==="USERNAME_PURCHASE_AVAILABLE";_(j?S.getValue():void 0)},S=new pb({label:"SetUrlPlaceholder",name:"group-public-link",plainText:!0,listenerSetter:this.listenerSetter,availableText:"Link.Available",invalidText:"Link.Invalid",takenText:"Link.Taken",onChange:b,peerId:this.chatId.toPeerId(!0),head:f},this.managers),{setUsername:_,element:M}=vb();m.caption.append(M,P(e?"Channel.UsernameAboutChannel":"Channel.UsernameAboutGroup"));const C=new fb({peerId:this.chatId.toPeerId(!0),peer:l,listenerSetter:this.listenerSetter,usernameInputField:S,middleware:this.middlewareHelper.get()}),L=document.createElement("div");L.append(m.container,C.container);const E=f+(Yh(l)||"");g.append(S.container),m.content.append(g);const x=Cn({icon:"check",className:"is-visible"});this.content.append(x);const R=()=>r.radioField.checked?S.getValue():"",B=async()=>{const U=R(),j=await this.managers.appChatsManager.migrateChat(this.chatId);return U?this.managers.appChatsManager.updateUsername(j,U):this.managers.appChatsManager.makeChannelPrivate(j)},N=async()=>{if(!R()){const j=Ae.getChat(this.chatId),q=Yh(j);q&&await Rt({descriptionLangKey:e?"ChannelVisibility.Confirm.MakePrivate.Channel":"ChannelVisibility.Confirm.MakePrivate.Group",descriptionLangArgs:[q],button:{langKey:"OK"}})}};J(x,async()=>{v&&await N();const U=tb(x);try{v&&await B(),(y||w)&&await Promise.all([y&&this.managers.appChatsManager.toggleJoinToSend(this.chatId,O.checkboxField.checked),w&&this.managers.appChatsManager.toggleJoinRequest(this.chatId,$.checkboxField.checked)]),this.close()}catch{U()}},{listenerSetter:this.listenerSetter}),this.scrollable.append(s.container,u.container,L);let G,O,$,H,D;if(!e){const U=G=new Oe({name:"ChannelSettingsJoinTitle",caption:t?"ChannelSettingsJoinToSendInfo":"ChannelSettingsJoinRequestInfo"});O=new Fe({titleLangKey:"ChannelSettingsJoinToSend",checkboxField:new _t({toggle:!0})}),$=new Fe({titleLangKey:"ChannelSettingsJoinRequest",checkboxField:new _t({toggle:!0})});const j=()=>t?O.checkboxField.checked:!L.classList.contains("hide"),q=()=>{const ee=j();$.container.classList.toggle("hide",!ee),!ee&&$.checkboxField.checked&&($.checkboxField.checked=!1)},W=()=>{H=!!l.pFlags.join_to_send,D=!!l.pFlags.join_request,O.checkboxField.setValueSilently(H),$.checkboxField.setValueSilently(D),q(),b()};[O,$].forEach(ee=>{this.listenerSetter.add(ee.checkboxField.input)("change",()=>{O===ee&&q(),b()})}),t||O.container.classList.add("hide"),d(W),W(),U.content.append(O.container,$.container),this.scrollable.append(U.container)}{const U=new Oe({name:"SavingContentTitle",caption:e?"RestrictSavingContentInfoChannel":"RestrictSavingContentInfoGroup"});let j;const q=new Fe({titleLangKey:"RestrictSavingContent",checkboxField:j=new _t({toggle:!0})});this.listenerSetter.add(j.input)("change",()=>{const ee=q.toggleDisability(!0);this.managers.appChatsManager.toggleNoForwards(this.chatId,j.checked).then(()=>{ee()})});const W=()=>{j.setValueSilently(!!l.pFlags.noforwards)};d(W),W(),U.content.append(q.container),this.scrollable.append(U.container)}(E!==f||ji(l).length?r:n).radioField.checked=!0,S.setOriginalValue(E,!0)}}class yb{constructor(e){this.loading=!1,this.loaded=!1,Nt(this,e),e.scrollable.onScrolledBottom=()=>{this.load()}}load(){if(this.loaded)return Promise.resolve();if(this.loading)return this.promise;this.loading=!0,this.promise=this.getPromise().then(e=>{this.loading=!1,this.promise=void 0,e?(this.loaded=!0,this.scrollable.onScrolledBottom=null):this.scrollable.checkForTriggers()},()=>{this.promise=void 0,this.loading=!1})}}function nT(a,e){if(a.default_banned_rights){e=kn(e);const t=a.default_banned_rights.pFlags;for(const s in t)e.pFlags[s]=t[s]}return e}function Cr(a,e,t,s){if(!a||a.pFlags.deactivated&&e!=="view_messages")return!1;const i=t===void 0;if(a.pFlags.creator&&i)return!0;if(a._==="chatForbidden"||a._==="channelForbidden"||a.pFlags.left&&!a.pFlags.megagroup||!t&&(t=a.admin_rights||a.banned_rights||a.default_banned_rights,!t))return!1;let n={};t&&(n=t.pFlags);const r=t._==="chatAdminRights";switch(e){case"embed_links":case"send_games":case"send_gifs":case"send_inline":case"send_media":case"send_messages":case"send_polls":case"send_stickers":case"send_photos":case"send_videos":case"send_roundvideos":case"send_audios":case"send_voices":case"send_docs":case"send_plain":{if(!r&&n[e]||a._==="channel"&&!a.pFlags.megagroup&&!n.post_messages)return!1;break}case"delete_messages":case"manage_call":return!!n[e];case"pin_messages":return r?!!(n[e]||!a.pFlags.megagroup&&n.post_messages):!n[e];case"invite_links":return a._==="chat"?!1:r&&!!n.invite_users;case"change_type":case"delete_chat":return!1;case"change_info":case"invite_users":return r||a.pFlags.broadcast?!!n[e]:!n[e];case"delete_stories":case"edit_stories":case"post_stories":case"add_admins":case"anonymous":case"post_messages":case"edit_messages":return r&&!!n[e];case"ban_users":case"change_permissions":return r&&!!n.ban_users;case"view_participants":return!!(a._==="chat"||!a.pFlags.broadcast||a.pFlags.creator||a.admin_rights);case"create_giveaway":return r&&!!n.post_messages;case"manage_topics":return r?!!n[e]:!n[e]}return!0}function eo(a){return[...new Set(a)]}function Zc(a){return typeof a!="object"?a:a.peer?it(a.peer):a.user_id.toPeerId()}function aT(a){return!!(a&&!a.pFlags.deleted&&a.id.toPeerId()!==Lo)}function t1(a=0){return`index_${a}`}function da(a,e=t1(a.folder_id)){return a?.[e]}async function Dg({container:a,emoji:e,width:t,height:s,assetName:i,middleware:n,managers:r=I.managers,loop:o=!1,autoplay:l=!0}){a||(a=document.createElement("div")),a.classList.add("media-sticker-wrapper");let c;if(i)c=Ns.loadAnimationAsAsset({container:a,loop:o,autoplay:l,width:t,height:s,noCache:!0,middleware:n},i).then(d=>Ns.waitForFirstFrame(d));else if(e){const d=await r.appStickersManager.getAnimatedEmojiSticker(e);d&&(c=ai({doc:d,div:a,loop:o,play:l,width:t,height:s,emoji:e,managers:r,middleware:n}).then(u=>u.render))}return{container:a,promise:c}}const rT=Y("<div class=selector-empty-placeholder><div class=selector-empty-placeholder-title>"),oT=Y("<div class=selector-empty-placeholder-description>");async function s1({middleware:a,title:e,description:t,hide:s,assetName:i="UtyanSearch",width:n=140,height:r=140,isFullSize:o}){const{container:l,promise:c}=await Dg({width:n,height:r,assetName:i,middleware:a,loop:!0});if(!a()||(await c,!a()))return;l.classList.add("selector-empty-placeholder-sticker");let d;return Ft(u=>{a.onClean(u),d=(()=>{const h=rT(),p=h.firstChild;return h.classList.toggle("is-full",!!o),k(h,l,p),k(p,e),k(h,(()=>{const m=V(()=>!!t());return()=>m()&&(()=>{const g=oT();return k(g,t),g})()})(),null),Me(()=>h.classList.toggle("hide",!!s())),h})()}),d}function Wp(a,e,t,s,i,n,r,o){const l=a.canvas.dpr;if(l&&(e*=l,t*=l,s*=l,i*=l),typeof n=="number")l&&(n*=l),n={tl:n,tr:n,br:n,bl:n};else{const c={tl:0,tr:0,br:0,bl:0};for(const d in c)n[d]=n[d]?l?n[d]*l:n[d]:c[d]}a.beginPath(),a.moveTo(e+n.tl,t),a.lineTo(e+s-n.tr,t),a.quadraticCurveTo(e+s,t,e+s,t+n.tr),a.lineTo(e+s,t+i-n.br),a.quadraticCurveTo(e+s,t+i,e+s-n.br,t+i),a.lineTo(e+n.bl,t+i),a.quadraticCurveTo(e,t+i,e,t+i-n.bl),a.lineTo(e,t+n.tl),a.quadraticCurveTo(e,t,e+n.tl,t),a.closePath(),a.fill()}class lT{constructor(){this.font="30pt Helvetica",this.currTime=Date.now(),this.diffTime=0,this.spread=0,this.paused=!1,this.pausedTime=0,this.pauseInterval=850,this.lightSource=0,this.inc=.032,this.lightSpread=.55,this.animations=["slide","slide","slide","slide"],this.currentAnimationIndex=0}keepTime(){this.diffTime=Date.now()-this.currTime,this.currTime=Date.now()}cycleAnimation(){++this.currentAnimationIndex,this.currentAnimationIndex>=this.animations.length&&(this.currentAnimationIndex=0)}animate(){const e=this.animations[this.currentAnimationIndex];if(e==="glow")return this.animateGlow();if(e==="slide")return this.animateSlide();console.log("unknown animation type: "+String(e))}animateGlow(){var e=255,t=68,s=t,i=10,n=800;return()=>{var r=i*(this.diffTime/16.666666666666668);return this.paused?Date.now()-this.pausedTime>n&&(s=t,this.cycleAnimation(),this.paused=!1):(s=parseInt(""+(s+r)),s>=e&&(this.paused=!0,this.pausedTime=Date.now())),"rgb("+s+","+s+","+s+")"}}animateSlide(){var e=this.ctx.createLinearGradient(0,0,this.canvas.width,0),t=this.inc*(this.diffTime/(1e3/60)),s,i,n;if(this.paused){if(Date.now()-this.pausedTime>this.pauseInterval)return this.lightSource=-.6,this.cycleAnimation(),this.paused=!1,this.animateSlide()}else this.lightSource+=t,this.lightSource>1+this.lightSpread&&(this.paused=!0,this.pausedTime=Date.now());n=zt(this.lightSource,0,1),s=zt(this.lightSource-this.lightSpread,0,1),i=zt(this.lightSource+this.lightSpread,0,1);const r=yi.getProperty("background-color-true",this.night),o=yi.getProperty("surface-color",this.night);return e.addColorStop(s,r),e.addColorStop(n,o),e.addColorStop(i,r),e}settings(e={}){this.canvas=e.canvas??document.createElement("canvas"),this.ctx=this.canvas.getContext("2d"),this.font=e.font??this.font,this.lightSpread=e.lightSpread??this.lightSpread,this.inc=e.inc??this.inc,this.animations=e.animations??this.animations,this.text=e.text??this.text,this.fillStyle=e.fillStyle,this.canvas.classList.add("shimmer-canvas")}on(){const{width:e,height:t}=this.canvas;this.keepTime(),this.ctx.clearRect(0,0,e,t),this.font&&(this.ctx.font=this.font),this.ctx.fillStyle=this.animate(),this.ctx.fillRect(0,0,e,t),this.fillStyle&&(this.ctx.fillStyle=this.fillStyle,this.ctx.fillRect(0,0,e,t)),this.text&&this.ctx.fillText(this.text,50,50)}}class i1{constructor(e={}){this.onThemeChange=()=>{this.stopAnimation(),this.startAnimation()},this.onResize=()=>{const{canvas:t}=this,{width:s,height:i,dpr:n}=t;this.updateCanvasSize(),!(t.width===s&&t.height===i&&t.dpr===n)&&(this.stopAnimation(),this.startAnimation())},this.shimmer=new lT,this.shimmer.night=this.night=e.night,this.tempId=0,this.canvas=document.createElement("canvas"),this.canvas.classList.add("dialogs-placeholder-canvas"),this.ctx=this.canvas.getContext("2d"),this.generatedValues=[],this.avatarSize=e.avatarSize??54,this.avatarMarginRight=e.avatarMarginRight??10,this.marginVertical=e.marginVertical??9,this.marginLeft=e.marginLeft??17,this.gapVertical=e.gapVertical??0,this.totalHeight=e.totalHeight??this.avatarSize+this.marginVertical*2,this.lineHeight=10,this.lineBorderRadius=6,this.lineMarginVertical=e.lineMarginVertical??8,this.statusWidth=e.statusWidth??24,this.noSecondLine=e.noSecondLine}attach({container:e,rect:t,getRectFrom:s,onRemove:i,blockScrollable:n}){const{canvas:r}=this;this.detachTime=void 0,this.onRemove=i,this.getRectFrom=typeof s=="function"?s:(s||e).getBoundingClientRect.bind(s||e),(this.blockScrollable=n)&&(n.container.style.overflowY="hidden"),this.updateCanvasSize(t),this.startAnimation(),e.append(r)}detach(e){this.detachTime||(this.availableLength=e,this.detachTime=Date.now(),wt.isAvailable("animations")||this.remove())}removeWithoutUnmounting(){this.stopAnimation(),this.onRemove?.(),this.onRemove=void 0}remove(){this.stopAnimation(),this.canvas.parentElement&&(this.canvas.remove(),this.blockScrollable&&(this.blockScrollable.container.style.overflowY="",this.blockScrollable=void 0)),this.onRemove?.(),this.onRemove=void 0}updateCanvasSize(e=this.getRectFrom()){const{canvas:t}=this,s=t.dpr=window.devicePixelRatio;t.width=e.width*s,t.height=e.height*s,t.style.width=e.width+"px",t.style.height=e.height+"px"}renderDetachAnimationFrame(){const{canvas:e,ctx:t,detachTime:s,length:i,availableLength:n}=this;if(s){if(!wt.isAvailable("animations")){this.remove();return}}else return;const{width:r}=e;t.globalCompositeOperation="destination-out";const o=150,l=15,c=Date.now()-s;let d=!0;for(let u=0;u<i;++u){const h=n<i&&u>=n?l*(n-1):l*u,p=c-h;if(p<=0){d=!1;continue}const m=j_(p,0,1,o);t.beginPath(),t.rect(0,this.dialogHeight*u,r,this.dialogHeight),t.fillStyle=`rgba(0, 0, 0, ${m})`,t.fill(),m<1&&(d=!1)}t.globalCompositeOperation="source-over",d&&this.remove()}renderFrame(){this.shimmer.on(),this.renderDetachAnimationFrame()}startAnimation(){const{canvas:e,shimmer:t}=this,s=++this.tempId,i=this.createPattern();t.settings({canvas:e,fillStyle:i});const n=()=>this.tempId===s;this.renderFrame(),No(()=>n()?(wt.isAvailable("animations")&&this.renderFrame(),n()):!1),I.addEventListener("theme_changed",this.onThemeChange),st.addEventListener("resize",this.onResize)}stopAnimation(){++this.tempId,I.removeEventListener("theme_changed",this.onThemeChange),st.removeEventListener("resize",this.onResize)}createPattern(){const{canvas:e,ctx:t}=this,s=document.createElement("canvas"),i=s.getContext("2d"),n=e.dpr;s.dpr=n,s.width=e.width,s.height=e.height,i.fillStyle=yi.getProperty("surface-color",this.night),i.fillRect(0,0,s.width,s.height),i.fillStyle="#000",i.globalCompositeOperation="destination-out";const r=this.dialogHeight=this.totalHeight*n,o=this.gapVertical*n;let l=0;const c=this.length=Math.ceil(e.height/r);for(let d=0;d<c;++d)this.drawChat(i,d,d*r+l),l+=o;return t.createPattern(s,"no-repeat")}drawChat(e,t,s){let i=this.generatedValues[t];i||(i=this.generatedValues[t]={firstLineWidth:40+Math.random()*100,secondLineWidth:this.noSecondLine?0:120+Math.random()*130,statusWidth:this.statusWidth?this.statusWidth+Math.random()*16:void 0});const{firstLineWidth:n,secondLineWidth:r,statusWidth:o}=i,{canvas:l}=e,{dpr:c}=l;s/=c;const{avatarSize:d,marginVertical:u,lineHeight:h,lineBorderRadius:p,lineMarginVertical:m}=this;let g=this.marginLeft;d&&(gL(e,g,s+u,d/2,!0),g+=d+this.avatarMarginRight),Wp(e,g,s+u+m,n,h,p),r&&Wp(e,g,s+this.totalHeight-u-h-m,r,h,p),o&&Wp(e,l.width/c-24-o,s+u+m,o,h,p)}}function xi(a,e=!0){const t=document.createElement("a");return t.href="#",t.onclick=s=>{e&&_e(s),a(s)},t}function un(a,e=2){if(a===0)return"0";const t=1e3,s=e<0?0:e,i=["","K","M","B","T"],n=Math.floor(Math.log(a)/Math.log(t));return parseFloat((a/Math.pow(t,n)).toFixed(s))+i[n]}async function bb(a){const e={};return await Promise.all(Object.entries(a).map(async([t,s])=>{e[t]=await s})),e}class wn{constructor(e){this.container=document.createElement("div"),this.list=nt.createChatList(),this.chatsContainer=document.createElement("div"),this.selected=new Set,this.freezed=!1,this.folderId=0,this.offsetIndex=0,this.query="",this.loadedWhat={},this.renderedPeerIds=new Set,this.peerType=["dialogs"],this.multiSelect=!0,this.rippleEnabled=!0,this.avatarSize="abitbigger",this.tempIds={},this.selfPresence="Presence.YourChat",this.needSwitchList=!1,this.design="round",this.participants=new Map,this.onInput=()=>{const i=this.input.value;if(this.query===i)return;(this.peerType.includes("contacts")||this.peerType.includes("dialogs"))&&(this.cachedContacts=void 0),this.peerType.includes("dialogs")&&(this.folderId=0,this.offsetIndex=0);for(const o in this.tempIds)++this.tempIds[o];const n=this.list;this.oldList=n,this.list=nt.createChatList(),this.promise=void 0,this.query=i,this.renderedPeerIds.clear(),this.needSwitchList=!0,this.middlewareHelperLoader.clean(),this.loadedWhat={},this.peerType.includes("dialogs")&&(this.loadedWhat.dialogs=!1,this.loadedWhat.archived=!1,this.loadedWhat.contacts=!1),this.peerType.includes("contacts")&&(this.loadedWhat.contacts=!1),this.peerType.includes("channelParticipants")&&(this.loadedWhat.channelParticipants=!1),this.peerType.includes("custom")&&(this.loadedWhat.custom=!1),n.style.position="absolute";const r=n.parentElement?.clientHeight??0;r&&(n.style.overflow="hidden",n.style.height=`${r}px`),r&&this.dialogsPlaceholder?.attach({container:this.section.content,blockScrollable:this.scrollable,getRectFrom:()=>{const o=this.scrollable.container.getBoundingClientRect();return{width:this.section.content.getBoundingClientRect().width,height:o.height}}}),this.emptySearchPlaceholderHideSetter?.(!0),this.getMoreResults()},this.checkForTriggers=()=>{this.scrollable.checkForTriggers()},this.processPlaceholderOnResults=()=>{const i=this.list.childElementCount;if(i)this.dialogsPlaceholder?.detach(i),this.emptySearchPlaceholderHideSetter?.(!0),this.emptySearchPlaceholderQuerySetter?.(this.query);else if(this.emptySearchPlaceholderMiddlewareHelper)this.dialogsPlaceholder?.detach(i),this.emptySearchPlaceholderHideSetter(!1),this.emptySearchPlaceholderQuerySetter(this.query);else{this.emptySearchPlaceholderMiddlewareHelper=Ht();const n=this.emptySearchPlaceholderMiddlewareHelper.get(),[r,o]=K(this.query),[l,c]=K(),[d,u]=K(!1);return this.emptySearchPlaceholderQuerySetter=o,this.emptySearchPlaceholderHideSetter=u,Ft(h=>{n.onClean(h),le(()=>{c(P("RequestJoin.List.SearchEmpty",[je(r())]))})}),s1({middleware:n,title:()=>P("SearchEmptyViewTitle"),description:l,hide:d}).then(h=>{n()&&this.section.content.prepend(h)})}},Nt(this,e),this.checkboxSide??(this.checkboxSide="right"),this.exceptSelf??(this.exceptSelf=!1),this.meAsSaved??(this.meAsSaved=!(this.peerType.length===1&&this.peerType[0]==="channelParticipants")),this.headerSearch??(this.headerSearch=this.multiSelect&&!this.noSearch),this.noShadow??(this.noShadow=!!this.input||!this.sectionCaption),this.excludePeerIds??(this.excludePeerIds=new Set),this.exceptSelf&&this.excludePeerIds.add(I.myId),this.middlewareHelper=e.middleware.create(),this.middlewareHelperLoader=this.middlewareHelper.get().create(),this.noPlaceholder||(this.dialogsPlaceholder=new i1(e.placeholderSizes||{avatarSize:42,avatarMarginRight:18,marginVertical:7,marginLeft:12+(this.design==="square"?48:0),totalHeight:56,gapVertical:e.placeholderElementsGap,statusWidth:0,night:this.night})),this.container.classList.add("selector","selector-"+this.design,"selector-"+this.checkboxSide);const t=(this.renderResultsFunc||this.renderResults).bind(this);if(this.renderResultsFunc=async(i,n)=>{const{needSwitchList:r}=this,o=this.middlewareHelperLoader.get();if(r&&(this.needSwitchList=!1,this.oldList.replaceWith(this.list),this.oldList=void 0),i=i.filter(l=>{if(this.excludePeerIds.has(l))return!1;const c=!this.renderedPeerIds.has(l);return c&&this.renderedPeerIds.add(l),c}),this.filterPeerTypeBy){const l=typeof this.filterPeerTypeBy=="function";if(i=await zn(i,async c=>{if(c.isPeerId()){if(l){const d=await this.managers.appPeersManager.getPeer(c);return this.filterPeerTypeBy(d)}else for(const d of this.filterPeerTypeBy)if(await this.managers.appPeersManager[d](c))return!0;return!1}return!0}),!o())return}await t(i,n),this.promise||this.processPlaceholderOnResults(),this.chatRightsActions?.some(l=>l.startsWith("send_"))&&Promise.all(i.map(async l=>{const c=l.toUserId(),{requirement:d,starsAmount:u}=await bb({requirement:this.managers.appUsersManager.getRequirementToContact(c),starsAmount:this.managers.appPeersManager.getStarsAmount(l)});return{peerId:l,userId:c,requirement:d,requiredStars:u}})).then(l=>{for(const{peerId:c,requirement:d,requiredStars:u}of l){const h=this.getElementByPeerId(c.toPeerId(!1));if(h){if(d?._==="requirementToContactPremium"){const p=Be("premium_lock","selector-premium-lock");h.append(p),h.classList.add("is-premium-locked")}else if(+u){const p=un(+u,1),m=document.createElement("span");m.classList.add("stars-badge-base","dialog-stars-badge");const g=document.createElement("span");g.append(p+""),m.append(Be("star","stars-badge-base__icon"),g),h.append(m)}}}})},!this.noSearch){this.input=document.createElement("input"),this.input.classList.add("selector-search-input"),this.input.type="text",ks(this.input,this.placeholder||"SendMessageTo",void 0,"placeholder");const i=$i(this.onInput,200,!1,!0);this.input.addEventListener("input",i)}if(this.headerSearch){const i=this.searchSection=new Oe({});i.innerContainer.classList.add("selector-search-section"),i.container.classList.add("selector-search-section-container");const n=document.createElement("div");n.classList.add("selector-search-container"),this.selectedContainer=document.createElement("div"),this.selectedContainer.classList.add("selector-search"),this.selectedContainer.append(this.input),n.append(this.selectedContainer),this.selectedScrollable=new tn(n),this.multiSelect&&J(this.selectedContainer,r=>{if(this.freezed)return;let o=r.target;if(o=ne(o,"selector-user"),!o)return;const l=o.dataset.key,c=this.chatsContainer.querySelector('[data-peer-id="'+l+'"]');c?Xs(c):this.remove(l.toPeerId())}),i.content.append(n),this.container.append(i.container)}this.chatsContainer.classList.add("chatlist-container");const s=this.section=new Oe({name:this.sectionNameLangPackKey,caption:this.sectionCaption,noShadow:this.noShadow});this.sectionNameLangPackKey&&(s.content=s.generateContentElement()),this.sectionCaption||(s.content.classList.add("selector-list-section-content"),s.container.classList.add("selector-list-section-container")),s.content.append(this.list),this.chatsContainer.append(s.container),this.scrollable?this.scrollable.append(this.chatsContainer):this.scrollable=new tn(this.chatsContainer),J(this.chatsContainer,i=>{const n=Zd(i.target,"data-peer-id");if(!n||(_e(i),this.freezed))return;let r=n.dataset.peerId;if(r=r.isPeerId()?r.toPeerId():r,r.isPeerId()&&n.classList.contains("is-premium-locked")){qe({peerId:r,onlyFirstName:!0}).then(c=>{$e({langPackKey:"OnlyPremiumCanMessage",langPackArguments:[c,xi(()=>{no(),rs.show()})]})});return}if(this.onSelect){this.onSelect(r);return}if(!this.multiSelect){this.add({key:r});return}if(!(this.selected.has(r)?this.remove(r):this.add({key:r})))return;const l=n.querySelector("input");l.checked=!l.checked}),this.scrollable.onScrolledBottom=()=>{this.getMoreResults()},this.input&&!this.noDelimiter&&this.scrollable.prepend(Fg()),this.listenerSetter=new $t,this.container.append(this.chatsContainer),this.appendTo.append(this.container),this.channelParticipantsUpdateFilter&&this.listenerSetter.add(I)("chat_participant",i=>{const n=i.new_participant,r=i.user_id.toPeerId(!1),o=this.channelParticipantsUpdateFilter(n);o?this.participants.set(r,n):this.participants.delete(r),o?this.renderResultsFunc([r],!1):this.deletePeerId(r)}),e.middleware.onDestroy(()=>{this.destroy()}),setTimeout(()=>{const i=this.getMoreResults();e.onFirstRender&&i.then(()=>{e.onFirstRender()})},0)}static convertPeerTypes(e){const t={bots:"isBot",users:"isRegularUser",groups:"isAnyGroup",channels:"isBroadcast"};return e.map(i=>t[i])}setLimit(e,t){this.limit=e,this.limitCallback=t}destroy(){this.middlewareHelper.destroy(),this.emptySearchPlaceholderMiddlewareHelper?.destroy(),this.listenerSetter.removeAll(),this.dialogsPlaceholder?.removeWithoutUnmounting()}deletePeerId(e){const t=this.list.querySelector(`[data-peer-id="${e}"]`),s=t?.dialogElement;s?s.remove():t?.remove(),this.renderedPeerIds.delete(e),this.promise||this.processPlaceholderOnResults()}clearInput(){this.input.value="",this.onInput()}async renderSaved(){!this.exceptSelf&&!this.offsetIndex&&this.folderId===0&&this.peerType.includes("dialogs")&&(!this.query||await this.managers.appUsersManager.testSelfSearch(this.query))&&await this.renderResultsFunc([I.myId])}getTempId(e){var s;(s=this.tempIds)[e]??(s[e]=0);const t=++this.tempIds[e];return{tempId:t,middleware:()=>this.tempIds[e]===t}}async getMoreDialogs(){if(this.loadedWhat.dialogs&&this.loadedWhat.archived)return;const e=It.height/56*1.25|0,{middleware:t}=this.getTempId("dialogs"),s=this.managers.dialogsStorage.getDialogs({query:this.query,offsetIndex:this.offsetIndex,limit:e,filterId:this.folderId,skipMigrated:!0});s.catch(()=>{t()&&(this.loadedWhat[this.loadedWhat.dialogs?"archived":"dialogs"]=!0)});const i=await s;if(!t())return;let n=i.dialogs;if(n.length){const r=da(n[n.length-1])||0;if(n=n.slice(),tr(n,o=>o.peerId===I.myId),this.chatRightsActions&&(n=await zn(n,o=>this.filterByRights(o.peerId)),!t())||(await this.renderSaved(),!t()))return;this.offsetIndex=r}if(await this.renderResultsFunc(n.map(r=>r.peerId)),i.isEnd)if(this.loadedWhat.dialogs){if(this.loadedWhat.archived=!0,!this.loadedWhat.contacts)return this.getMoreContacts()}else return await this.renderSaved(),t()?(this.loadedWhat.dialogs=!0,this.offsetIndex=0,this.folderId=1,this.getMoreDialogs()):void 0;else if(this.renderedPeerIds.size<e)return this.getMoreDialogs()}async filterByRights(e){const t=Ae.getPeer(e);if(e.isUser())return this.chatRightsActions[0]!=="send_plain"||aT(t);if(this.chatRightsActions.every(s=>Cr(t,s)))return!0}async getMoreContacts(){if(this.loadedWhat.contacts)return;const e=this.peerType.includes("contacts");if(!this.cachedContacts){const{middleware:i}=this.getTempId("contacts"),n=Promise.all([e?this.managers.appUsersManager.getContactsPeerIds(this.query):[],this.query?this.managers.appUsersManager.searchContacts(this.query):void 0]);n.catch(()=>{i()&&(this.loadedWhat.contacts=!0)});const[r,o]=await n;if(!i())return;if(o){let l=e?o.my_results.concat(o.results):o.my_results;if(this.chatRightsActions&&(l=await zn(l,c=>this.filterByRights(c)),!i()))return;this.peerType.includes("dialogs")||(l=l.filter(c=>c.isUser())),this.cachedContacts=eo(r.concat(l))}else this.cachedContacts=r.slice();Vs(this.cachedContacts,I.myId)}const t=It.height/56*1.25|0,s=this.cachedContacts.splice(0,t);await this.renderResultsFunc(s),this.cachedContacts.length||(this.loadedWhat.contacts=!0)}async getMoreChannelParticipants(){if(this.loadedWhat.channelParticipants)return;const e=50;let t;this.channelParticipantsFilter?t=typeof this.channelParticipantsFilter=="function"?this.channelParticipantsFilter(this.query):this.channelParticipantsFilter:t={_:"channelParticipantsSearch",q:this.query};const{middleware:s}=this.getTempId("channelParticipants"),i=this.managers.appProfileManager.getParticipants({id:this.peerId.toChatId(),filter:t,limit:e,offset:this.list.childElementCount});i.catch(()=>{s()&&(this.loadedWhat.channelParticipants=!0)});const n=await i;if(!s())return;const{participants:r}=n,o=r.map(c=>{const d=Zc(c);return this.participants.set(d,c),d});this.exceptSelf&&Vs(o,I.myId),await this.renderResultsFunc(o);const l=n.count??r.length;(this.list.childElementCount>=l||r.length<e)&&(this.loadedWhat.channelParticipants=!0)}async _getMoreCustom(){if(this.loadedWhat.custom)return;const{middleware:e}=this.getTempId("custom"),t=this.getMoreCustom(this.query,e);t.catch(()=>{e()&&(this.loadedWhat.custom=!0)});const s=await t;if(!e())return;const{result:i,isEnd:n}=s;this.exceptSelf&&Vs(i,I.myId),await this.renderResultsFunc(i),n&&(this.loadedWhat.custom=!0)}_getMoreResults(){if(this.peerType.includes("dialogs")&&!this.loadedWhat.archived)return this.getMoreSomething("dialogs");if((this.peerType.includes("contacts")||this.peerType.includes("dialogs"))&&!this.loadedWhat.contacts)return this.getMoreSomething("contacts");if(this.peerType.includes("channelParticipants")&&!this.loadedWhat.channelParticipants)return this.getMoreSomething("channelParticipants");if(this.peerType.includes("custom")&&!this.loadedWhat.custom)return this.getMoreSomething("custom")}getMoreResults(){if(this.promise)return this.promise;const e=this._getMoreResults();if(!e)return this.processPlaceholderOnResults(),Promise.resolve();const t=this.middlewareHelperLoader.get(),s=this.promise=e.catch(i=>{console.error("get more result error",i)}).then(()=>{if(this.promise===s&&(this.promise=void 0),t()){const n=Object.values(this.loadedWhat).every(o=>o),r=this.list.childElementCount;if(n&&!r)return this.dialogsPlaceholder?.detach(r),this.processPlaceholderOnResults();(r||n)&&(this.dialogsPlaceholder?.detach(r),this.emptySearchPlaceholderHideSetter?.(!0))}return this.checkForTriggers(),this.promise});return s}getMoreSomething(e){return{dialogs:this.getMoreDialogs,contacts:this.getMoreContacts,channelParticipants:this.getMoreChannelParticipants,custom:this._getMoreCustom}[e].call(this)}async renderResults(e,t){!this.peerType.includes("dialogs")&&this.loadedWhat.contacts&&(e=await zn(e,i=>this.managers.appUsersManager.isNonContactUser(i)));const s=e.map(async i=>{const n=nt.addDialogNew({peerId:this.getPeerIdFromKey?.(i)??i,container:this.list,rippleEnabled:this.rippleEnabled,avatarSize:this.avatarSize,meAsSaved:this.meAsSaved,append:t,wrapOptions:{middleware:this.middlewareHelperLoader.get()},withStories:this.withStories});this.getPeerIdFromKey&&(n.container.dataset.peerId=i),n.container.dialogElement=n;const{dom:r}=n;if(this.multiSelect){const l=this.selected.has(i);r.containerEl.prepend(this.checkbox(l))}let o;this.getSubtitleForElement&&(o=await this.getSubtitleForElement(i)),o||(o=await this.wrapSubtitle(i)),r.lastMessageSpan.append(o),this.processElementAfter&&await this.processElementAfter(i,n)});return Promise.all(s)}async wrapSubtitle(e){let t;return e.isAnyChat()?t=await ja(e.toChatId()):e===I.myId&&this.meAsSaved?t=P(this.selfPresence):t=qo(await this.managers.appUsersManager.getUser(e.toUserId())),t}checkbox(e){const t=new _t({round:this.design==="round"});return e&&(t.input.checked=e),t.label}static renderEntity({key:e,middleware:t,title:s,avatarSize:i,fallbackIcon:n,meAsSaved:r=!0}){const o=document.createElement("div");o.classList.add("selector-user"),o.middlewareHelper=t.create();const l=document.createElement("div");l.classList.add("selector-user-avatar-container");const c=document.createElement("div");c.classList.add("selector-user-avatar-close"),c.append(Be("close"));const d=vs({middleware:o.middlewareHelper.get(),size:i,isDialog:r});d.node.classList.add("selector-user-avatar"),l.append(d.node,c),o.dataset.key=""+e;const u=[];if(e.isPeerId()){if(s===void 0){const h=new Xt;u.push(h.update({peerId:e.toPeerId(),dialog:r})),s=h.element}d.render({peerId:e}),u.push(d.readyThumbPromise)}else n&&d.setIcon(n);if(s){const h=document.createElement("div");h.classList.add("selector-user-title"),typeof s=="string"?h.innerHTML=s:(St(h,s),h.append(s)),o.append(h)}return o.insertAdjacentElement("afterbegin",l),{element:o,avatar:d,promises:u}}add({key:e,title:t,scroll:s=!0,fireOnChange:i=!0,fallbackIcon:n}){if(this.limit&&this.selected.size>=this.limit)return this.limitCallback?.(),!1;if(this.selected.add(e),!this.multiSelect||!this.input)return i&&this.onChange?.(this.selected.size),!!this.multiSelect;this.query.trim()&&this.clearInput();const r=wn.renderEntity({key:e,middleware:this.middlewareHelper.get(),title:t,avatarSize:32,fallbackIcon:n}),{element:o}=r;return s&&o.classList.add("scale-in"),this.selectedContainer.insertBefore(o,this.input),i&&this.onChange?.(this.selected.size),s&&this.selectedScrollable.scrollIntoViewNew({element:this.input,position:"center"}),r}remove(e,t=!0){if(!this.multiSelect)return!1;if(!this.input)return this.selected.delete(e),t&&this.onChange?.(this.selected.size),!0;const s=this.selectedContainer.querySelector(`[data-key="${e}"]`);s.classList.remove("scale-in"),s.offsetWidth,s.classList.add("scale-out");const i=()=>{this.selected.delete(e),s.remove(),s.middlewareHelper.destroy(),t&&this.onChange?.(this.selected.size)};return wt.isAvailable("animations")?s.addEventListener("animationend",i,{once:!0}):i(),!0}getSelected(){return[...this.selected]}getElementByPeerId(e){return this.chatsContainer.querySelector(`[data-peer-id="${e}"]`)}toggleElementCheckboxByPeerId(e,t){const s=this.getElementByPeerId(e);if(!s)return;const i=s.querySelector("input");i.checked=t===void 0?!i.checked:t}addBatch(e){e.length&&(e.forEach(t=>{this.add({key:t,scroll:!1,fireOnChange:!1}),this.toggleElementCheckboxByPeerId(t,!0)}),this.onChange?.(this.selected.size))}removeBatch(e){e.length&&(e.forEach(t=>{this.remove(t,!1),this.toggleElementCheckboxByPeerId(t,!1)}),this.onChange?.(this.selected.size))}addInitial(e){e?.length&&(this.addBatch(e),this.input&&window.requestAnimationFrame(()=>{this.selectedScrollable.scrollIntoViewNew({element:this.input,position:"center",forceDirection:hm.Static})}))}}async function cT({topic:a,middleware:e}){const t=ii(32,32),s=new Fe({title:je(a.title),clickable:!0});s.container.dataset.peerId=""+a.id,s.container.classList.add("selector-forum-topic");const i=s.createMedia("abitbigger"),n=vs({peerId:a.peerId,threadId:a.id,middleware:e,size:t.width,wrapOptions:{middleware:e,textColor:"primary-text-color",customEmojiSize:t}});return await n.readyThumbPromise,i.append(n.node),s.container}class Rs extends ue{constructor(e){super("popup-forward",{closable:!0,overlayClosable:!0,onBackClick:()=>{this.forumSelector.input.replaceWith(this.selector.input),this.transition(this.selector.container),this.forumNavigationItem&&(Pt.removeItem(this.forumNavigationItem),this.forumNavigationItem=void 0)},body:!0,title:e.titleLangKey??!0});const t=!!e.onMultiSelect;let s;const i=async(r,o)=>{if(s)return;if(e.useTopics&&!Array.isArray(r)&&!o&&await this.managers.appPeersManager.isForum(r)){s=!0,await this.createForumSelector({tabsContainer:n,peerId:r,placeholder:e.placeholder,onSelect:i}),s=void 0;return}const l=e.onSelect||e.onMultiSelect;if(l){const c=l(r,o);if(c instanceof Promise)try{await c}catch{return}}this.selector=null,this.hide()},n=document.createElement("div");n.classList.add("tabs-container"),this.body.append(n),this.selector=new wn({...e,middleware:this.middlewareHelper.get(),appendTo:n,onChange:t?r=>{this.btnConfirm.classList.toggle("is-visible",!!r)}:void 0,onSelect:t?void 0:i,onFirstRender:()=>{this.show(),this.selector.checkForTriggers(),pt||this.selector.input.focus()},multiSelect:t,rippleEnabled:!1,avatarSize:"abitbigger",managers:this.managers,night:this.night,headerSearch:t}),this.selector.container.classList.add("tabs-tab"),this.scrollable=this.selector.scrollable,t?(this.header.after(this.selector.searchSection.container),this.btnConfirm=this.btnConfirmOnEnter=Cn({icon:"check"}),this.body.append(this.btnConfirm),J(this.btnConfirm,()=>{i(this.selector.getSelected())},{listenerSetter:this.listenerSetter}),e.initial&&this.selector.addInitial(e.initial),this.selector.container.classList.add("active")):(e.headerLangPackKey?this.title.append(P(e.headerLangPackKey)):this.title.append(this.selector.input),this.attachScrollableListeners(),this.transition=Sr({content:n,type:"navigation",transitionTime:150,animateFirst:!1,onTransitionEnd:r=>{r?this.selector.clearInput():Array.from(n.children).forEach(o=>{o!==this.selector.container&&(o.middlewareHelper.destroy(),o.remove())})}}),this.transition(this.selector.container))}async createForumSelector({tabsContainer:e,peerId:t,placeholder:s,onSelect:i}){const n=this.middlewareHelper.get().create(),r=n.get(),o=Mt();let l,c;const d=this.forumSelector=new wn({middleware:r,appendTo:e,managers:this.managers,rippleEnabled:!1,night:this.night,multiSelect:!1,headerSearch:!1,placeholder:s,peerType:["custom"],getMoreCustom:async(h,p)=>{c!==h&&(l=void 0,c=h);const m=await this.managers.dialogsStorage.getDialogs({query:h,filterId:t,limit:20,skipMigrated:!0,offsetIndex:l});if(p())return l=da(m.dialogs[m.dialogs.length-1]),{result:m.dialogs.map(g=>g.id),isEnd:m.isEnd}},renderResultsFunc:async(h,p)=>{const m=h.map(async f=>{const v=await this.managers.dialogsStorage.getForumTopic(t,f);return cT({topic:v,middleware:r})}),g=await Promise.all(m);d.list[p?"prepend":"append"](...g)},onSelect:h=>{i(t,h)},placeholderSizes:{avatarSize:32,avatarMarginRight:23,marginVertical:8,marginLeft:17,lineMarginVertical:11,gapVertical:0,totalHeight:48,statusWidth:0,noSecondLine:!0,night:this.night},onFirstRender:()=>{o.resolve()}});d.container.classList.add("tabs-tab"),d.scrollable.attachBorderListeners(),d.container.middlewareHelper=n,await o,this.btnCloseAnimatedIcon.classList.add("state-back"),this.selector.input.replaceWith(d.input),this.transition(d.container);const u=this.forumNavigationItem={type:"popup",onPop:()=>{Xs(this.btnClose)}};Pt.pushItem(this.forumNavigationItem),this.addEventListener("close",()=>{Pt.removeItem(u)})}destroy(){super.destroy(),this.selector?.destroy(),this.selector=void 0}static async createPicker2({peerType:e,filterPeerTypeBy:t,chatRightsActions:s,multiSelect:i,limit:n,limitCallback:r,titleLangKey:o,placeholder:l,exceptSelf:c}){return new Promise((d,u)=>{let h=!1;const p=ue.createPopup(Rs,{peerType:e,placeholder:l||"SelectChat",onSelect:i?void 0:m=>{d(m),h=!0},onMultiSelect:i?m=>{d(m),h=!0}:void 0,filterPeerTypeBy:t,chatRightsActions:s,titleLangKey:o,exceptSelf:c});n&&p.selector.setLimit(n,r),p.addEventListener("close",()=>{h||u()},{once:!0})})}static async createPicker(e=["users","bots","groups","channels"],t){Array.isArray(e)||(e=[]);const s=wn.convertPeerTypes(e),i=["dialogs"];if(e.includes("users")&&i.push("contacts"),!s.length)throw void 0;return this.createPicker2({peerType:i,filterPeerTypeBy:s,chatRightsActions:t})}static createSharingPicker(e){return e.chatRightsActions??(e.chatRightsActions=["send_plain"]),e.placeholder??(e.placeholder="ShareModal.Search.Placeholder"),e.selfPresence??(e.selfPresence="ChatYourSelf"),ue.createPopup(Rs,{...e,peerType:["dialogs","contacts"]})}static createSharingPicker2(e){return new Promise((t,s)=>{let i=!1;Rs.createSharingPicker({...e||{},onSelect:r=>{i=!0,t(r)}}).addEventListener("close",()=>{i||s()})})}static createReplyPicker(){return this.createSharingPicker2({placeholder:"ReplyToDialog",selfPresence:"SavedMessagesInfoQuote"})}static createContactPicker(){return new Promise((e,t)=>{let s=!1;ue.createPopup(Rs,{peerType:["contacts"],placeholder:"Search",onSelect:n=>{s=!0,e(n)}}).addEventListener("close",()=>{s||t()})})}}Di.PopupPickUser=Rs;function hh(a,e,t){const s=e?._==="channelParticipantCreator",i=e?.promoted_by;return!!a.pFlags.creator||!s&&(!i||i===t)}const lg=class lg extends Bs{async init(){this.container.classList.add("edit-peer-container","user-permissions-container"),this.setTitle(this.isAdmin?"EditAdmin":"UserRestrictions");let e;const t=await this.managers.appChatsManager.getChat(this.chatId),s=await this.managers.appChatsManager.isChannel(this.chatId),i=await this.managers.appPeersManager.isAnyGroup(this.chatId.toPeerId(!0)),n=this.participant?._==="channelParticipantCreator",r=hh(t,this.participant,I.myId);let o;this.isAdmin?o=["channelParticipantAdmin","channelParticipantCreator"]:o=["channelParticipantBanned"];{const c=new Oe({name:this.isAdmin?"EditAdminWhatCanDo":"UserRestrictionsCanDo",caption:this.isAdmin?!0:void 0}),d=document.createElement("div");d.classList.add("chatlist-container"),c.content.insertBefore(d,c.title);const u=nt.createChatList({new:!0});d.append(u);const{dom:h}=nt.addDialogNew({peerId:this.userId.toPeerId(!1),container:u,rippleEnabled:!0,avatarSize:"abitbigger",meAsSaved:!1,wrapOptions:{middleware:this.middlewareHelper.get()}});h.lastMessageSpan.append(qo(await this.managers.appUsersManager.getUser(this.userId)));const p={chatId:this.chatId,listenerSetter:this.listenerSetter,appendTo:c.content,participant:o.includes(this.participant._)?this.participant:void 0,chat:t,canEdit:r},m=o.includes(this.participant._)?(this.isAdmin?this.participant.admin_rights:this.participant.banned_rights).pFlags:void 0;if(this.isAdmin){const g=new e8(p),f=g.fields.find(y=>y.flags[0]==="add_admins"),v=()=>{c.caption.replaceChildren(P(r?f.checkboxField.checked?"Channel.Admin.AdminAccess":"Channel.Admin.AdminRestricted":"EditAdminCantEdit"))};v(),this.listenerSetter.add(f.checkboxField.input)("change",v),e=()=>{if(!hh)return;const y=g.takeOut();m&&Pn(m,y.pFlags)||this.managers.appChatsManager.editAdmin(this.chatId,this.participant,y,l?.value)}}else{const g=new fw(p,this.managers);e=()=>{const f=g.takeOut();m&&Pn(m,f.pFlags)||this.managers.appChatsManager.editBanned(this.chatId,this.participant,f)}}this.eventListener.addEventListener("destroy",e,{once:!0}),this.scrollable.append(c.container)}let l;if(this.isAdmin&&i){const c=this.participant._==="channelParticipantCreator"?"Chat.OwnerBadge":"ChatAdmin",d=new Oe({name:"EditAdminRank",caption:"EditAdminRankInfo",captionArgs:[P(c)]}),u=document.createElement("div");u.classList.add("input-wrapper");const h=l=new Yt({name:"rank",placeholder:c,maxLength:16,canBeEdited:r}),p=this.participant.rank;p&&h.setOriginalValue(p,!0),u.append(h.container),d.content.append(u),this.scrollable.append(d.container)}if(this.isAdmin){const c=new Oe({});if(!n&&hh){const d=ot("btn-primary btn-transparent danger",{icon:"deleteuser",text:"Channel.Admin.Dismiss"});J(d,async()=>{const u=os([d],!0);try{await this.managers.appChatsManager.editAdmin(this.chatId,this.participant,{_:"chatAdminRights",pFlags:{}},"")}catch{u();return}this.eventListener.removeEventListener("destroy",e),this.close()},{listenerSetter:this.listenerSetter}),c.content.append(d)}c.content.childElementCount&&this.scrollable.append(c.container)}else{const c=new Oe({});if(this.participant._==="channelParticipantBanned"){const u=ot("btn-primary btn-transparent danger",{icon:"delete",text:"GroupPermission.Delete"});J(u,()=>{const h=os([u],!0);this.managers.appChatsManager.clearChannelParticipantBannedRights(this.chatId,this.participant).then(()=>{this.eventListener.removeEventListener("destroy",e),this.close()},()=>{h()})},{listenerSetter:this.listenerSetter}),c.content.append(u)}const d=ot("btn-primary btn-transparent danger",{icon:"deleteuser",text:"UserRestrictionsBlock"});J(d,async()=>{const u=os([d],!0);try{const h=this.userId.toPeerId();await Rt({peerId:this.chatId.toPeerId(!0),descriptionLangKey:"Permissions.RemoveFromGroup",descriptionLangArgs:[await qe({peerId:h})],titleLangKey:"ChannelBlockUser",button:{langKey:"Remove",isDanger:!0}}),s?await this.managers.appChatsManager.kickFromChannel(this.chatId,this.participant):await this.managers.appChatsManager.kickFromChat(this.chatId,this.participant)}catch{u();return}this.eventListener.removeEventListener("destroy",e),this.close()},{listenerSetter:this.listenerSetter}),c.content.append(d),this.scrollable.append(c.container)}}};lg.openTab=(e,t,s,i)=>{const n=e.createTab(lg);n.participant=s,n.chatId=t,n.userId=Zc(s).toUserId(),n.isAdmin=i,n.open()};let Qh=lg;class $g{constructor(e){Nt(this,e)}createField(e,t){if(e.nestedTo&&!t)return;const s=t&&!this.round,i=Be("down","accordion-icon");let n;this.round&&!s&&e.nested&&(n=document.createElement("div"),n.classList.add("accordion-right-button"));const r=e.row=new Fe({titleLangKey:s?void 0:e.text,titleLangArgs:s?void 0:e.textArgs,checkboxField:e.checkboxField=new _t({text:s?e.text:void 0,textArgs:s?e.textArgs:void 0,checked:e.nested?!1:e.checked,toggle:this.round?void 0:!t,listenerSetter:this.listenerSetter,restriction:this.asRestrictions&&!t,name:e.name,round:this.round}),listenerSetter:this.listenerSetter,subtitleLangKey:e.description,clickable:e.nested?d=>{if(this.round?!Mi(d.target,n)&&d.target!==n:Mi(d.target,r.checkboxField.label)){if(r.checkboxField.input.disabled){const u=r.checkboxField.checked;e.nested.forEach(h=>{h.checkboxField.checked=!u})}else r.checkboxField.checked=!r.checkboxField.checked;return}_e(d),r.container.classList.toggle("accordion-toggler-expanded"),l.classList.toggle("is-expanded"),this.onExpand?.(e)}:void 0,rightContent:n});if(r.container.classList.add("accordion-row"),e.restrictionText){if(!e.nestedTo){const d=e.checkboxField.label.lastElementChild.firstElementChild;d.classList.add("with-lock"),d.append(Be("premium_lock","checkbox-caption-lock"))}e.checkboxField.input.disabled=!0,e.nested||J(e.row.container,d=>{Wi(Ne.format(e.restrictionText,!0))},{listenerSetter:this.listenerSetter})}const o=[r.container];let l,c;if(e.nested){const d=l=document.createElement("div");d.classList.add("accordion"),d.style.setProperty("--max-height",e.nested.length*48+"px");const u=e;e.nested.forEach(h=>{h.nestedTo??(h.nestedTo=u),d.append(...this.createField(h,!0).nodes)}),o.push(d),c=e.nestedCounter=document.createElement("b"),c.classList.add("accordion-counter"),this.setNestedCounter(e),r.container.classList.add("accordion-toggler"),this.round?(n.append(Be(this.rightButtonIcon)," ",c," ",i),r.container.classList.add("accordion-toggler-round")):(r.title.append(" ",c," ",i),r.titleRow.classList.add("with-delimiter")),r.checkboxField.input.disabled=!0,r.checkboxField.setValueSilently(this.getNestedCheckedLength(e)===e.nested.length),e.toggleWith??(e.toggleWith={checked:e.nested,unchecked:e.nested})}if(e.toggleWith||e.nestedTo){const d=e.toggleWith?h=>{const{toggleWith:p,nested:m}=h,g=h.checkboxField.checked,f=g?p.checked:p.unchecked;if(!f)return;this.fields.filter(y=>f.includes(y)).forEach(y=>{y.restrictionText||(y.checkboxField.setValueSilently(g),y.nestedTo&&!m&&this.setNestedCounter(y.nestedTo),y.toggleWith&&d(y))}),h.nested&&this.setNestedCounter(h)}:void 0,u=e.nestedTo?()=>{const h=this.getNestedCheckedLength(e.nestedTo);e.nestedTo.checkboxField.setValueSilently(h===e.nestedTo.nested.length),this.setNestedCounter(e.nestedTo,h)}:void 0;this.listenerSetter.add(e.checkboxField.input)("change",()=>{d?.(e),u?.(),this.onAnyChange?.()})}else this.onAnyChange&&!e.nested&&this.listenerSetter.add(e.checkboxField.input)("change",()=>{this.onAnyChange()});return this.onRowCreation?.(r,e),{row:r,nodes:o}}getNestedCheckedLength(e){return e.nested.reduce((t,s)=>t+ +s.checkboxField.checked,0)}setNestedCounter(e,t=this.getNestedCheckedLength(e)){e.nestedCounter.textContent=this.round?""+e.nested.length:`${t}/${e.nested.length}`}}class wm{constructor(e){this.onIndex=i=>{this.onValue?.(this.steps[i][1]),this.optionsElements.forEach(({container:n},r)=>{n.classList.toggle("active",i>=r),n.classList.toggle("is-chosen",i===r)})},Nt(this,e),this.generateSteps??(this.generateSteps=i=>i.map(this.generateStep));const t=this.container=document.createElement("div");t.classList.add("range-setting-selector","range-steps-selector"),this.middleware.onClean(()=>{this.range.removeListeners()});const s=this.range=new Xl({step:1});s.setListeners(),s.setHandlers({onScrub:this.onIndex}),t.append(s.container)}createOption(e,t,s){const i=document.createElement("div");i.classList.add("range-setting-selector-option");const n=document.createElement("div");return n.classList.add("range-setting-selector-option-text"),n.replaceChildren(e),i.append(n),i.style.left=`${t/s*100}%`,t===0&&!this.noFirstLast?i.classList.add("is-first"):t===s&&(i.style.left="",i.style.right="0",!this.noFirstLast&&i.classList.add("is-last")),{container:i,text:n}}setSteps(e,t){this.optionsElements&&this.optionsElements.forEach(({container:i})=>i.remove());const s=e.length-1;this.range.setMinMax(0,s),this.steps=e,this.optionsElements=e.map(([i],n)=>{const r=this.createOption(i,n,s);return this.range.container.append(r.container),r}),t!==void 0&&this.setIndex(t)}setIndex(e){this.range.setProgress(e),this.onIndex(e)}removeListeners(){this.range.removeListeners()}get value(){return this.steps[this.range.value][1]}}function n1({el:a,onOpen:e,options:t,onClose:s}){(t?.listenerSetter?t.listenerSetter.add(a):a.addEventListener.bind(a))(Eo,n=>{if(!a.classList.contains("btn-menu-toggle")||Hy(n))return!1;if(_e(n),a.classList.contains("menu-open"))Li.close();else{const r=e?.(n);en(r,()=>{const l=a.querySelector(".btn-menu");l&&Li.openBtnMenu(l,s)})}})}function a1(a){return zn(a,e=>e?.verify?e.verify()??!1:!0)}function ki({buttonOptions:a,listenerSetter:e,container:t,direction:s,buttons:i,onOpenBefore:n,onOpen:r,onClose:o,onCloseAfter:l,noIcon:c,icon:d="more"}){a&&(a.asDiv=!0);const u=t??yt(c?void 0:d,a);u.classList.add("btn-menu-toggle");const h=new $t,p=()=>{clearTimeout(g),g=void 0};let m,g,f=0;return n1({el:u,onOpen:async v=>{const y=++f;if(await n?.(v),y!==f)return;if(g){p();return}const w=await a1(i);if(y!==f||!w.length)return;const b=m=await Kh({buttons:w,listenerSetter:h});y===f&&(b.classList.add(s),s==="bottom-center"&&b.style.setProperty("--parent-half-width",t.clientWidth/2+"px"),await r?.(v,b),y===f&&(u.append(b),await hi(),y!==f&&b.remove()))},options:{listenerSetter:e},onClose:()=>{++f,p(),o?.(),g=window.setTimeout(()=>{l?.(),g=void 0,h.removeAll(),i.forEach(v=>{try{v.dispose?.()}catch{}v.element=void 0}),m.remove()},300)}}),u}function fr(a,e,t){const s=[];a=Yc(a);const i=jt(a.text,{entities:a.entities,middleware:e,loadPromises:s});return t?i:Promise.all(s).then(()=>i)}class wS extends Zt{constructor(){super(...arguments),this.renderResults=async e=>{await this.managers.appUsersManager.getContacts();const t=e.map(async s=>{const i=nt.addDialogNew({peerId:s,container:this.selector.list,rippleEnabled:!0,avatarSize:"abitbigger",wrapOptions:{middleware:this.middlewareHelper.get()}});i.container.dialogElement=i;const{dom:n}=i,r=this.selector.selected.has(s);n.containerEl.append(this.selector.checkbox(r));const o=[],l=[...this.dialogsByFilters.entries()].map(async([d,u])=>{if(u.has(s)){const h=document.createElement("span");h.append(await fr(d.title,this.middlewareHelper.get())),o.push(h)}});await Promise.all(l),Yi(o,!1).forEach(d=>{n.lastMessageSpan.append(d)})});await Promise.all(t)},this.onSelectChange=e=>{this.type==="included"&&(this.confirmBtn.style.display=e?"":"none")}}init(e,t,s){this.originalFilter=e,this.filter=kn(this.originalFilter),this.type=t,this.editFolderTab=s,this.content.remove(),this.container.classList.add("included-chatlist-container"),this.confirmBtn=yt("check btn-confirm blue",{noRipple:!0}),this.confirmBtn.style.display="none",this.header.append(this.confirmBtn),J(this.confirmBtn,async()=>{const n=this.selector.getSelected(),r=this.filter.pFlags;if(this.type==="included"&&r)for(const p in r)p.indexOf("exclude_")!==0&&delete r[p];else if(r)for(const p in r)p.indexOf("exclude_")===0&&delete r[p];const o=[];for(const p of n)p.isPeerId()?o.push(p.toPeerId()):this.filter.pFlags[p]=!0;let l;this.type==="included"?l=p=>o.includes(p):l=p=>!o.includes(p),hn(this.filter.pinnedPeerIds,(p,m)=>{l(p)||(this.filter.pinnedPeerIds.splice(m,1),this.filter.pinned_peers.splice(m,1))});const c=this.type==="included"?"excludePeerIds":"includePeerIds",d=this.type==="included"?"exclude_peers":"include_peers",u=this.filter[c],h=this.filter[d];u&&hn(u,(p,m)=>{o.includes(p)&&(u.splice(m,1),h.splice(m,1))}),this.filter[this.type==="included"?"includePeerIds":"excludePeerIds"]=o,this.filter[this.type==="included"?"include_peers":"exclude_peers"]=await Promise.all(o.map(p=>this.managers.appPeersManager.getInputPeerById(p))),this.editFolderTab.setFilter(this.filter,!1),this.close()},{listenerSetter:this.listenerSetter});const i=n=>{this.limit=I.premium?n.dialog_filters_chats_limit_premium:n.dialog_filters_chats_limit_default};return this.listenerSetter.add(I)("app_config",i),this.dialogsByFilters=new Map,Promise.all([this.managers.filtersStorage.getDialogFilters().then(async n=>{await Promise.all(n.filter(r=>!oa.has(r.id)).map(async r=>{const l=(await this.managers.dialogsStorage.getFolderDialogs(r.id)).map(c=>c.peerId);this.dialogsByFilters.set(r,new Set(l))}))}),this.managers.apiManager.getAppConfig().then(n=>{i(n)})])}onOpen(){this.confirmBtn.style.display=this.type==="excluded"?"":"none",this.setTitle(this.type==="included"?"FilterAlwaysShow":"FilterNeverShow");const e=this.filter,t=new Oe({noDelimiter:!0,name:"FilterChatTypes"});t.container.classList.add("folder-categories");let s;this.type==="excluded"?s={exclude_muted:{ico:"mute",text:"ChatList.Filter.MutedChats"},exclude_archived:{ico:"archive",text:"ChatList.Filter.Archive"},exclude_read:{ico:"readchats",text:"ChatList.Filter.ReadChats"}}:s={contacts:{ico:"newprivate",text:"ChatList.Filter.Contacts"},non_contacts:{ico:"noncontacts",text:"ChatList.Filter.NonContacts"},groups:{ico:"group",text:"ChatList.Filter.Groups"},broadcasts:{ico:"newchannel",text:"ChatList.Filter.Channels"},bots:{ico:"bots",text:"ChatList.Filter.Bots"}},this.selector=new wn({middleware:this.middlewareHelper.get(),appendTo:this.container,onChange:this.onSelectChange,peerType:["dialogs"],renderResultsFunc:this.renderResults,placeholder:"Search",sectionNameLangPackKey:"FilterChats",managers:this.managers});const i=document.createDocumentFragment();for(const c in s){const d=ot("btn-primary btn-transparent folder-category-button",{icon:s[c].ico,text:s[c].text});d.dataset.peerId=c,d.append(this.selector.checkbox()),i.append(d)}t.content.append(i);const n=(this.type==="included"?e.includePeerIds:e.excludePeerIds).slice();this.selector.selected=new Set(n);let r=!1;const o=this.selector.add.bind(this.selector);this.selector.add=({key:c,title:d,scroll:u})=>this.selector.selected.size>=this.limit&&r&&!s[c]?(Ja("folderPeers"),!1):o({key:c,title:s[c]?P(s[c].text):void 0,scroll:u,fallbackIcon:s[c]?.ico}),this.selector.scrollable.append(t.container,this.selector.scrollable.container.lastElementChild),this.selector.addInitial(n),r=!0;const l=e.pFlags;if(l)for(const c in l)s.hasOwnProperty(c)&&l[c]&&Xs(t.content.querySelector(`[data-peer-id="${c}"]`))}onCloseAfterTimeout(){return this.selector&&(this.selector.container.remove(),this.selector=null),super.onCloseAfterTimeout()}}function to(a){if(!wt.isAvailable("animations"))return;const e=[{transform:"translateX(0)"},{transform:"translateX(.25rem)"},{transform:"translateX(-.25rem)"},{transform:"translateX(0)"}];a.animate([...e,...e,...e],{duration:300,iterations:1,easing:"ease-in-out"})}class Uu{constructor({buttons:e,button:t,onButtonClick:s,listenerSetter:i,url:n,noRightButton:r,onClick:o}){this.copyLink=(h=this.url)=>{si(h),$e({langPackKey:"LinkCopied"})},this.shareLink=(h=this.url)=>{Rs.createSharingPicker({onSelect:async p=>{const{default:m,PAYMENT_REJECTED:g}=await zo(()=>Promise.resolve().then(()=>o3),void 0,import.meta.url),f=await m.prepareStarsForPayment({messageCount:1,peerId:p});if(f===g)throw new Error;I.managers.appMessagesManager.sendText({peerId:p,text:h,confirmedPaymentResult:f}),Ce.setInnerPeer({peerId:p})}})},this.onButtonClick=s;const l=this.container=document.createElement("div");l.classList.add("invite-link-container");const c=document.createElement("div");c.classList.add("invite-link","rp-overflow");const d=this.textElement=document.createElement("div");d.classList.add("invite-link-text");let u;e?u=ki({buttons:e,direction:"bottom-left",buttonOptions:{noRipple:!0},listenerSetter:i}):r||(u=yt("copy",{noRipple:!0}),J(u,()=>this.copyLink(),{listenerSetter:i})),u&&u.classList.add("invite-link-menu"),!t&&t!==!1&&(t=ot("",{text:"ShareLink"}),this.buttonText=t.lastElementChild,J(t,()=>{this.onButtonClick?this.onButtonClick():this.shareLink()},{listenerSetter:i})),t&&(this.button=t,t.className="btn-primary btn-color-primary invite-link-button"),n&&this.setUrl(n),Ei(c),c.append(...[d,u].filter(Boolean)),l.append(c,t||""),J(c,o||(()=>this.copyLink()),{listenerSetter:i})}setUrl(e){let t=e;t.includes("//")&&(t=e.split("//").slice(1).join("//")),this.textElement.replaceChildren(Oo(t)),this.url=e}}class wb extends Bs{constructor(){super(...arguments),this.isConfirmationNeededOnClose=()=>{if(!this.confirmBtn.classList.contains("hide"))return Rt({descriptionLangKey:"BotWebViewChangesMayNotBeSaved",button:{isDanger:!0,langKey:"BotWebViewCloseAnyway"}})},this.canSelectPeer=e=>!e||!this.chatlistInvite||e._==="user"?!1:!!ji(e).length||Cr(e,"invite_links"),this.onSelectChange=e=>{if(this.updateDescription(e),!this.chatlistInvite)return;const t=[...this.selector.selected],s=this.chatlistInvite.peers.map(n=>it(n)),i=s.length===t.length&&s.every(n=>t.includes(n));this.confirmBtn.classList.toggle("hide",i)},this.renderResults=async e=>{const t=e.map(async s=>{const i=await this.managers.appPeersManager.getPeer(s),n=nt.addDialogNew({peerId:s,container:this.selector.list,rippleEnabled:!0,avatarSize:"abitbigger",meAsSaved:!1,wrapOptions:{middleware:this.middlewareHelper.get()}}),{dom:r}=n;this.elementMap.set(s,n);const o=this.selector.selected.has(s);r.containerEl.append(this.selector.checkbox(o));const l=this.canSelectPeer(i);l||r.containerEl.classList.add("cant-select");let c;i._==="user"?c=P(i.pFlags.bot?"SharedFolder.Cant.ShareBots":"SharedFolder.Cant.ShareUsers"):l?c=await ja(i.id,void 0,i):c=P("SharedFolder.Cant.Share"),r.lastMessageSpan.append(c)});return Promise.all(t).then(()=>{})}}static getInitArgs(){return{animationData:Ns.loadAnimationFromURLManually("Folders_Shared")}}async init(e=wb.getInitArgs()){this.container.classList.add("edit-folder-container","shared-folder-container"),this.caption=document.createElement("div"),this.caption.classList.add("caption"),this.descriptionI18n=new Ne.IntlElement,this.caption.append(this.descriptionI18n.element),this.stickerContainer=document.createElement("div"),this.stickerContainer.classList.add("sticker-container"),this.confirmBtn=yt("check btn-confirm hide blue"),this.header.append(this.confirmBtn),this.elementMap=new Map,this.content.remove(),this.setTitle("SharedFolder.Edit.Title"),this.listenerSetter.add(I)("filter_update",s=>{this.filter.id===s.id&&(this.filter=s)});let t;if(this.chatlistInvite){const s=t=new Oe({name:"InviteLink"}),i=new Uu({buttons:[{icon:"copy",text:"CopyLink",onClick:()=>i.copyLink()},{icon:"delete",className:"danger",text:"DeleteLink",onClick:()=>{this.managers.filtersStorage.deleteExportedInvite(this.filter.id,this.chatlistInvite.url).then(()=>{this.eventListener.dispatchEvent("delete"),this.close()})}}],listenerSetter:this.listenerSetter,url:this.chatlistInvite.url});s.content.append(i.container)}{const s=this.chatsTitleI18n=new Ne.IntlElement;this.selector=new wn({middleware:this.middlewareHelper.get(),appendTo:this.container,onChange:this.onSelectChange,peerType:[],renderResultsFunc:this.renderResults,sectionNameLangPackKey:s.element,sectionCaption:"SharedFolder.Edit.Subtitle",managers:this.managers,noSearch:!0,multiSelect:!0}),this.selector.scrollable.attachBorderListeners(this.container);const n=(this.chatlistInvite?.peers??[]).map(p=>it(p));this.selector.addInitial(n);const r=eo(n.concat(this.filter.includePeerIds)),o=await Promise.all(r.map(p=>this.managers.appPeersManager.getPeer(p))),l=new Map,c=new Map,d=new Map;o.forEach(p=>{const m=p.id.toPeerId(p._!=="user");c.set(p,m),d.set(m,p);let g=0;this.canSelectPeer(p)?this.selector.selected.has(m)&&(g=1):g=-1,l.set(p,g)}),o.sort((p,m)=>l.get(m)-l.get(p)),this.selector.renderResultsFunc(o.map(p=>c.get(p)));const u=this.selector.add.bind(this.selector);this.selector.add=p=>{const m=p.key.toPeerId(),g=this.elementMap.get(m),{container:f}=g;if(f.classList.contains("cant-select")){let v;m.isUser()?v="SharedFolder.Toast.NoPrivate":v=d.get(m).pFlags.broadcast?"SharedFolder.Toast.NoAdminChannel":"SharedFolder.Toast.NoAdminGroup",$e({langPackKey:v}),to(f);return}return u(p)};const h=this.selector.remove.bind(this.selector);this.selector.remove=(...p)=>{const m=p[0].toPeerId();return this.selector.selected.size<=1?(to(this.elementMap.get(m).container),!1):h(...p)}}return J(this.confirmBtn,()=>{const s=os([this.confirmBtn],!0);this.managers.filtersStorage.editExportedInvite(this.filter.id,this.chatlistInvite.url,[...this.selector.selected],this.filter.title.text).then(i=>{this.eventListener.dispatchEvent("edit",i),this.close()},i=>{throw s(),i})},{listenerSetter:this.listenerSetter}),this.selector.scrollable.prepend(...[this.stickerContainer,this.caption,t?.container].filter(Boolean)),Promise.all([this.loadAnimationPromise=e.animationData.then(async s=>{const i=await s({container:this.stickerContainer,loop:!1,autoplay:!1,width:86,height:86});return this.animation=i,Ns.waitForFirstFrame(i)}),fr(this.filter.title,this.middlewareHelper.get()).then(s=>{this.descriptionTitle=document.createElement("span"),this.descriptionTitle.append(s),this.updateDescription()})])}updateDescription(e=this.chatlistInvite?this.chatlistInvite.peers.length:void 0){this.chatlistInvite?(this.descriptionI18n.update({key:"SharedFolder.Edit.Description",args:[this.descriptionTitle,P("Chats",[e])]}),this.chatsTitleI18n.update({key:"ChatsSelected",args:[e]})):(this.descriptionI18n.compareAndUpdate({key:"SharedFolder.NoChats"}),this.chatsTitleI18n.compareAndUpdate({key:"SharedFolder.NoChats.Title"}))}onOpenAfterTimeout(){this.loadAnimationPromise.then(()=>{this.animation.autoplay=!0,this.animation.play()})}}const Sp="popup-chatlist-invite";class Sb extends ue{constructor(e){super("popup-forward "+Sp,{closable:!0,overlayClosable:!0,body:!0,footer:!0,title:!0,withConfirm:!0}),Nt(this,e),this.construct()}async construct(){const e=document.createElement("div");e.classList.add("menu-horizontal-scrollable");const t=document.createElement("nav");t.classList.add("menu-horizontal-div");const{chatlistInvite:s,deleting:i,updating:n}=this,r=s?._==="chatlists.chatlistInviteAlready",o=r&&!!s.missing_peers.length,l=this.filter??(this.filter=r?await this.managers.filtersStorage.getFilter(s.filter_id):void 0);this.title.append(P(i?"SharedFolder.Link.TitleRemove":o?"SharedFolder.Link.TitleAdd":"SharedFolder.Link.Title"));let c;i&&(c=(await this.managers.filtersStorage.getLeaveChatlistSuggestions(this.filter.id)).map(x=>it(x)));const d=()=>{const E=document.createElement("div");E.classList.add("menu-horizontal-div-item");const x=document.createElement("span");return x.classList.add("menu-horizontal-div-item-span"),E.append(x),t.append(E),x};d().append(P("FilterAllChats"));const u=d();u.parentElement.classList.add("active"),u.append(await fr(l?l.title:s.title,this.middlewareHelper.get()),document.createElement("i")),d().append(P("FilterPersonal"));const h=document.createElement("div");h.classList.add("inner-shadow","inner-shadow-inset"),e.append(t,h);const p=document.createElement("div");p.classList.add(Sp+"-description","subtitle");let m,g;i?ks(p,"SharedFolder.Link.DescriptionRemove",[await fr(l.title,this.middlewareHelper.get())]):o?(m=new Ne.IntlElement,g=document.createElement("span"),g.append(await fr(l.title,this.middlewareHelper.get()))):ks(p,r?"SharedFolder.Link.DescriptionAlready":"SharedFolder.Link.Description");const f=new Ne.IntlElement,v=E=>{S&&o&&(E=Math.max(0,E-S.length)),f.update({key:i?"SharedFolder.Link.ChatsRemove":o?"SharedFolder.Link.ChatsAdd":r?"SharedFolder.Link.ChatsAlready":"SharedFolder.Link.Chats",args:[P("Chats",[E])]}),w?.update({key:(y=E===b.length)?"DeselectAll":"SelectAll"}),m?.update({key:"SharedFolder.Link.DescriptionAdd",args:[P("Chats",[E]),g]}),w&&(E&&(M.dataset.badge=""+E),M.classList.toggle("has-badge",!!E)),i&&_.update({key:E?"SharedFolder.Link.Remove":"SharedFolder.Link.TitleRemove"}),i||os([this.btnConfirm],!E)};let y;this.selector=new wn({middleware:this.middlewareHelper.get(),appendTo:this.body,onChange:v,onFirstRender:()=>{this.show(),this.selector.checkForTriggers()},multiSelect:!0,noSearch:!0,sectionNameLangPackKey:f.element,avatarSize:"abitbigger",managers:this.managers,peerType:[],getSubtitleForElement:async E=>{if(S?.includes(E)){const x=await this.managers.appPeersManager.isBroadcast(E);return P(x?"SharedFolder.Link.ChannelAlready":"SharedFolder.Link.ChatAlready")}},processElementAfter:(E,x)=>{S?.includes(E)&&x.dom.containerEl.classList.add("already")}});let w;(!r||o)&&(w=new Ne.IntlElement,w.element.classList.add("sidebar-left-section-name-right"),this.selector.section.title.append(w.element),J(w.element,()=>{y?this.selector.removeBatch(b):this.selector.addBatch(b)},{listenerSetter:this.listenerSetter}));let b;s?b=(o?s.missing_peers:r?s.already_peers:s.peers).map(x=>it(x)):b=l.includePeerIds;let S;if(r&&(S=s.already_peers.map(E=>it(E))),S){const E=this.selector.remove.bind(this.selector);this.selector.remove=(...x)=>{const R=x[0].toPeerId();if(S.includes(R)){const B=this.selector.getElementByPeerId(R);return to(B),!1}return E(...x)}}this.scrollable=this.selector.scrollable,this.attachScrollableListeners(),this.scrollable.prepend(e,p),this.btnConfirm.classList.add(`${Sp}-button`);const _=new Ne.IntlElement({key:i?"SharedFolder.Link.Remove":o?"SharedFolder.Link.Join":r?"OK":"SharedFolder.Link.Title"}),M=_.element;M.classList.add(`${Sp}-button-text`),this.btnConfirm.append(M),this.footer.append(this.btnConfirm),J(this.btnConfirm,()=>{if(r&&!o){this.hide();return}let E;const x=os([this.btnConfirm],!0),R=[...this.selector.selected];n?E=this.managers.filtersStorage.joinChatlistUpdates(this.filter.id,R):s?E=this.managers.filtersStorage.joinChatlistInvite(this.slug,R).catch(B=>{if(B.type==="DIALOG_FILTERS_TOO_MUCH")Ja("folders"),this.hide();else throw B}):E=this.managers.filtersStorage.leaveChatlist(this.filter.id,R),E.then(()=>{this.hide()},B=>{throw x(),B})},{listenerSetter:this.listenerSetter});const C=S?b.concat(S):b,L=i?c:C;this.selector.addInitial(L),this.selector.renderResultsFunc(i?eo(c.concat(C)):C),L.length||v(0),this.body.after(this.footer)}}const dT=12;class vr extends Zt{constructor(){super(...arguments),this.flags={}}static getInitArgs(){return{animationData:Ns.loadAnimationFromURLManually("Folders_2")}}static async deleteFolder(e){const t=await I.managers.filtersStorage.getFilter(e);if(t?._==="dialogFilterChatlist"&&!t.pFlags.has_my_invites){ue.createPopup(Sb,{filter:t,deleting:!0});return}return await Rt({titleLangKey:"ChatList.Filter.Confirm.Remove.Header",descriptionLangKey:t.pFlags.has_my_invites?"RemoveSharedFolder":"ChatList.Filter.Confirm.Remove.Text",button:{langKey:"Delete",isDanger:!0}}),I.managers.filtersStorage.updateDialogFilter({_:"dialogFilter",id:e},!0)}init(e=vr.getInitArgs()){this.container.classList.add("edit-folder-container"),this.caption=document.createElement("div"),this.caption.classList.add("caption"),this.caption.append(P("FilterIncludeExcludeInfo")),this.stickerContainer=document.createElement("div"),this.stickerContainer.classList.add("sticker-container"),this.tempId=0,this.showMoreClicked={},this.confirmBtn=yt("check btn-confirm hide blue");let t=!1;const s={icon:"delete",className:"danger",text:"FilterMenuDelete",onClick:()=>{t||vr.deleteFolder(this.filter.id).then(()=>{this.close()}).finally(()=>{t=!1})}};this.menuBtn=ki({listenerSetter:this.listenerSetter,direction:"bottom-left",buttons:[s]}),this.menuBtn.classList.add("hide"),this.header.append(this.confirmBtn,this.menuBtn);const i=new Oe({}),n=document.createElement("div");n.classList.add("input-wrapper"),this.nameInputField=new Yt({label:"FilterNameHint",maxLength:dT}),n.append(this.nameInputField.container),i.content.append(n);const r=(p,m,g,f,v)=>{const y=new Oe({name:m,caption:v,noDelimiter:!0});y.container.classList.add("folder-list",p);const w=y.generateContentElement();return w.classList.add("folder-categories"),g.forEach((b,S)=>{const _=ot("folder-category-button btn btn-primary btn-transparent"+(S===0?" primary":" disable-hover"),{icon:b.icon,text:b.text,noRipple:b.withRipple?void 0:!0});b.name&&(f[b.name]=_),w.append(_)}),y};this.includePeerIds=r("folder-list-included","FilterInclude",this.includePeerIdsButtons=[{icon:"add",text:"ChatList.Filter.Include.AddChat",withRipple:!0},{text:"ChatList.Filter.Contacts",icon:"newprivate",name:"contacts"},{text:"ChatList.Filter.NonContacts",icon:"noncontacts",name:"non_contacts"},{text:"ChatList.Filter.Groups",icon:"group",name:"groups"},{text:"ChatList.Filter.Channels",icon:"channel",name:"broadcasts"},{text:"ChatList.Filter.Bots",icon:"bots",name:"bots"}],this.flags,"FilterIncludeInfo"),this.excludePeerIds=r("folder-list-excluded","FilterExclude",this.excludePeerIdsButtons=[{icon:"minus",text:"FilterRemoveChats",withRipple:!0},{text:"ChatList.Filter.MutedChats",icon:"mute",name:"exclude_muted"},{text:"ChatList.Filter.Archive",icon:"archive",name:"exclude_archived"},{text:"ChatList.Filter.ReadChats",icon:"readchats",name:"exclude_read"}],this.flags,"FilterExcludeInfo"),this.inviteLinks=r("folder-list-links","InviteLinks",[{icon:"add",text:"SharedFolder.CreateLink",withRipple:!0}],{},"SharedFolder.Description"),this.scrollable.append(this.stickerContainer,this.caption,i.container,this.includePeerIds.container,this.excludePeerIds.container,this.inviteLinks.container),this.toggleExcludedPeers();const o=this.includePeerIds.container.querySelector(".folder-categories"),l=this.excludePeerIds.container.querySelector(".folder-categories");this.inviteLinksCreate=this.inviteLinks.container.querySelector(".btn"),J(o.querySelector(".btn"),()=>{this.slider.createTab(wS).open(this.filter,"included",this)},{listenerSetter:this.listenerSetter}),J(l.querySelector(".btn"),()=>{this.slider.createTab(wS).open(this.filter,"excluded",this)},{listenerSetter:this.listenerSetter});const c=p=>{if(this.nameInputField.input.classList.contains("error"))return;if(!this.nameInputField.value.trim()){this.nameInputField.input.classList.add("error");return}let m=Array.from(o.children).slice(1).reduce((f,v)=>f+ +!v.style.display,0);if(m+=this.filter.include_peers.length,!m){$e({langPackKey:"EditFolder.Toast.ChooseChat"});return}this.confirmBtn.setAttribute("disabled","true");let g;return this.filter.id?(p&&(u=!0),g=this.managers.filtersStorage.updateDialogFilter(this.filter)):g=this.managers.filtersStorage.createDialogFilter(this.filter),g.then(f=>(p&&this.close(),f)).catch(f=>{throw u=!1,d&&(this.updateFilter(d),d=void 0),f.type==="DIALOG_FILTERS_TOO_MUCH"?Ja("folders"):console.error("updateDialogFilter error:",f),f}).finally(()=>{this.confirmBtn.removeAttribute("disabled")})};J(this.confirmBtn,()=>{c(!0)},{listenerSetter:this.listenerSetter});let d,u=!1;this.listenerSetter.add(I)("filter_update",p=>{this.filter.id===p.id&&(u?d=p:this.updateFilter(p))}),this.listenerSetter.add(this.nameInputField.input)("input",()=>{this.filter.title={_:"textWithEntities",text:this.nameInputField.value,entities:[]},this.editCheckForChange()});const h=this.type==="edit"?[this.managers.filtersStorage.reloadMissingPeerIds(this.filter.id,"pinned_peers"),this.managers.filtersStorage.reloadMissingPeerIds(this.filter.id,"include_peers"),this.managers.filtersStorage.reloadMissingPeerIds(this.filter.id,"exclude_peers")]:[];return Promise.all([this.managers.apiManager.getLimit("chatlistInvites"),this.managers.apiManager.getLimit("chatlistInvites",!0),this.loadAnimationPromise=e.animationData.then(async p=>{const m=await p({container:this.stickerContainer,loop:!1,autoplay:!1,width:86,height:86});return this.animation=m,Ns.waitForFirstFrame(m)}),...h]).then(([p,m])=>{this.type==="edit"?(this.setFilter(this.originalFilter,!0),this.onEditOpen()):(this.setInitFilter(),this.onCreateOpen()),this.managers.filtersStorage.getExportedInvites(this.filter.id).catch(g=>{if(g.type==="FILTER_NOT_SUPPORTED")return[];throw g}).then(g=>{const f="usernames",v=this.inviteLinks.generateContentElement(),y=new Map,w=new Map,b=()=>{this.inviteLinksCreate.classList.toggle("hide",y.size>=m)},S=E=>{const x=w.get(E.url);x&&(x.container.remove(),w.delete(E.url),y.delete(x.container),b())},_=(E,x)=>{const R=x.title&&x.title!==this.filter.title.text?je(x.title):x.url.replace(/(.+?):\/\//,""),B=P("SharedFolder.Includes",[P("Chats",[x.peers.length])]);E.title.replaceChildren(R),E.subtitle.replaceChildren(B)},M=E=>{const x=new Fe({title:!0,subtitle:!0,clickable:!0});_(x,E),x.container.classList.add(f+"-username","active");const R=x.createMedia("medium");R.classList.add(f+"-username-icon"),R.append(Be("link")),v.append(x.container),y.set(x.container,E),w.set(E.url,x),b()};let C;Dn({buttons:[{icon:"copy",text:"CopyLink",onClick:()=>si(y.get(C).url)},{icon:"delete",className:"danger",text:"Delete",onClick:()=>{const E=y.get(C);this.managers.filtersStorage.deleteExportedInvite(this.filter.id,E.url).then(()=>{S(E)})}}],listenTo:v,listenerSetter:this.listenerSetter,findElement:E=>ne(E.target,"row"),onOpen:(E,x)=>C=x}),J(this.inviteLinksCreate,async()=>{if(y.size>=p){Ja("chatlistInvites");return}if(!this.filter.title){$e({langPackKey:"SharedFolder.Toast.NeedName"});return}const E=this.filter.pFlags;if(E&&[this.includePeerIdsButtons,this.excludePeerIdsButtons].some(B=>B.some(N=>!!E[N.name]))){$e({langPackKey:"SharedFolder.Toast.NoTypes"});return}if(this.filter.excludePeerIds?.length){$e({langPackKey:"SharedFolder.Toast.NoExcluded"});return}const x=os([this.inviteLinksCreate],!0);try{const R=c(!1);if(!(R instanceof Promise))throw"";const B=await R;this.updateFilter(B),this.type="edit",this.originalFilter=B,this.editCheckForChange()}catch{x();return}this.managers.filtersStorage.exportChatlistInvite({...this.filter,_:"dialogFilterChatlist",pFlags:this.filter._==="dialogFilter"?{has_my_invites:!0}:this.filter.pFlags}).then(R=>{x(),L(R.invite).finally(()=>{M(R.invite)})},R=>{if(x(),R.type==="INVITES_TOO_MUCH"||R.type==="FILTERS_TOO_MUCH"||R.type==="CHATLISTS_TOO_MUCH"){Ja("chatlistInvites");return}else if(R.type==="PEERS_LIST_EMPTY"||R.type==="CHAT_ADMIN_REQUIRED"){L();return}throw R})},{listenerSetter:this.listenerSetter});const L=E=>{const x=w.get(E?.url),R=this.slider.createTab(wb);return R.filter=this.filter,R.chatlistInvite=E,R.eventListener.addEventListener("delete",()=>{S(E)}),R.eventListener.addEventListener("edit",B=>{y.set(x.container,B),_(x,B)}),R.open()};J(v,E=>{const x=ne(E.target,"row"),R=y.get(x);R&&L(R)},{listenerSetter:this.listenerSetter}),g.forEach(M)})})}onOpenAfterTimeout(){this.loadAnimationPromise.then(()=>{this.animation.autoplay=!0,this.animation.play()})}onCreateOpen(){this.setTitle("FilterNew"),this.menuBtn.classList.add("hide"),this.confirmBtn.classList.remove("hide");for(const e in this.flags)this.flags[e].style.display="none"}onEditOpen(){const e=++this.tempId;this.setTitle(this.type==="create"?"FilterNew":"FilterHeaderEdit"),this.type==="edit"&&(this.menuBtn.classList.remove("hide"),this.confirmBtn.classList.add("hide"));const t=this.filter;this.nameInputField.value=ug(t.title.text);const s=t.pFlags;for(const n in this.flags){const r=!!s?.[n];this.flags[n].style.display=r?"":"none"}const i=["includePeerIds","excludePeerIds"].map(async n=>{let r=t[n];if(!r)return;const o=this[n],l=nt.createChatList({ignoreClick:!0}),c=async p=>!!await this.managers.appMessagesManager.getDialogOnly(p)||(p.isUser()?(await this.managers.appUsersManager.getUser(p.toUserId()))._==="user":!1),d=await zn(r,p=>c(p));r.length=0,r.push(...d),r=r.slice();const u=async p=>{const m=r.splice(0,p),g=await zn(m,async y=>y.isUser()?!0:!!await this.managers.appMessagesManager.getDialogOnly(y));if(e!==this.tempId)return;const f=[],v=g.map(y=>{const w=nt.addDialogNew({peerId:y,rippleEnabled:!1,meAsSaved:!0,avatarSize:"small",loadPromises:f,autonomous:!0,wrapOptions:{middleware:this.middlewareHelper.get()}});w.container.dialogElement=w;const{dom:b}=w;return b.lastMessageSpan.parentElement.remove(),b.containerEl});await Promise.all(f),e===this.tempId&&(l.append(...v),h&&(r.length?(h.lastElementChild.replaceWith(P("FilterShowMoreChats",[r.length])),h.classList.remove("hide")):h.remove()))};let h;return r.length&&!this.showMoreClicked[n]&&(h=ot("folder-category-button btn btn-primary btn-transparent hide",{icon:"down"}),h.classList.add("load-more","rp-overflow"),J(h,()=>{this.showMoreClicked[n]=!0,u(1/0)},{listenerSetter:this.listenerSetter}),h.append(P("FilterShowMoreChats",[r.length]))),u(this.showMoreClicked[n]?1/0:4).then(()=>{if(e===this.tempId)return()=>{o.generateContentElement().append(l),h&&r.length&&o.generateContentElement().append(h)}})});return Promise.all(i).then(n=>{e===this.tempId&&(this.toggleExcludedPeers(),this.container&&Array.from(this.container.querySelectorAll(".chatlist, .load-more")).forEach(r=>r.parentElement.remove()),n.forEach(r=>r?.()))})}editCheckForChange(){if(this.type==="edit"){const e=!Pn({...this.originalFilter,updatedTime:0,localId:0},{...this.filter,updatedTime:0,localId:0});this.confirmBtn.classList.toggle("hide",!e),this.menuBtn.classList.toggle("hide",e)}}setFilter(e,t){t?(this.originalFilter=e,this.filter=kn(e)):(this.filter=e,this.onEditOpen(),this.editCheckForChange())}setInitFilter(e){e===void 0?(this.setFilter({_:"dialogFilter",id:0,title:{_:"textWithEntities",text:"",entities:[]},pFlags:{},pinned_peers:[],include_peers:[],exclude_peers:[],pinnedPeerIds:[],includePeerIds:[],excludePeerIds:[]},!0),this.type="create"):(this.setFilter(e,!0),this.type="edit")}toggleExcludedPeers(){this.excludePeerIds.container.classList.toggle("hide",this.filter?._==="dialogFilterChatlist")}updateFilter(e){this.setFilter(e,!1)}}class Cd extends Zt{constructor(){super(...arguments),this.filtersRendered={}}static getInitArgs(){return{animationData:Ns.loadAnimationFromURLManually("Folders_1"),filters:I.managers.filtersStorage.getDialogFilters()}}async renderFolder(e,t,s,i){let n,r="";const o=[];if(e._==="dialogFilterSuggested")n=e.filter,r=e.description;else{n=e;const c=n.pFlags||{};if(Object.keys(c).length===1){let u;c.contacts?u="FilterAllContacts":c.non_contacts?u="FilterAllNonContacts":c.groups?u="FilterAllGroups":c.broadcasts?u="FilterAllChannels":c.bots&&(u="FilterAllBots"),u&&o.push(P(u))}if(!o.length){const u=await this.managers.dialogsStorage.getFolderDialogs(n.id);let h=0,p=0,m=0;await Promise.all(u.map(async g=>{await this.managers.appPeersManager.isAnyGroup(g.peerId)?++m:await this.managers.appPeersManager.isBroadcast(g.peerId)?++p:++h})),h&&o.push(P("Chats",[h])),p&&o.push(P("Channels",[p])),m&&o.push(P("Groups",[m]))}}if(s)n.id!==Fi&&St(s.title,await fr(n.title,this.middlewareHelper.get())),s.subtitle.textContent="",s.subtitle.append(...Yi(o));else{const c=e._==="dialogFilterSuggested";if(s=new Fe({title:n.id===Fi&&!c?P("FilterAllChats"):await fr(n.title,this.middlewareHelper.get()),subtitle:r,clickable:!0,buttonRightLangKey:c?"Add":void 0}),o.length&&s.subtitle.append(...Yi(o)),!c){const d=n.id;if(!this.filtersRendered[n.id]&&n.id!==Fi){const u=vr.getInitArgs();J(s.container,async()=>{const h=await this.managers.filtersStorage.getFilter(d),p=this.slider.createTab(vr);p.setInitFilter(h),p.open(u)},{listenerSetter:this.listenerSetter})}this.filtersRendered[n.id]=s,s.makeSortable()}}const l=s.container;if(i){const c=n.localId;c!==void 0?di(l,l.parentElement||t,c):t&&t.append(l)}return s}init(e=Cd.getInitArgs()){this.container.classList.add("chat-folders-container"),this.setTitle("ChatList.Filter.List.Title"),this.scrollable.container.classList.add("chat-folders"),this.stickerContainer=document.createElement("div"),this.stickerContainer.classList.add("sticker-container");const t=document.createElement("div");t.classList.add("caption"),Rh({element:t,key:"ChatList.Filter.Header"}),this.createFolderBtn=ot("btn-primary btn-color-primary btn-control",{text:"ChatList.Filter.NewTitle",icon:"add"}),this.foldersSection=new Oe({name:"Filters"}),this.foldersSection.container.classList.add("hide"),this.list=document.createElement("div"),this.foldersSection.content.append(this.list),this.suggestedSection=new Oe({name:"FilterRecommended"}),this.suggestedSection.container.classList.add("hide"),this.viewSection=new Oe({name:"FiltersView"});const s=document.createElement("form"),i="theme",n=ci("settings","tabsInSidebar"),r=new Fe({radioField:new rn({langKey:"FiltersOnLeft",name:i,value:"true",valueForState:!0,stateKey:n})}),o=new Fe({radioField:new rn({langKey:"FiltersOnTop",name:i,value:"false",valueForState:!1,stateKey:n})});this.listenerSetter.add(I)("settings_updated",({key:u,value:h})=>{u===n&&(document.body.classList.toggle("has-folders-sidebar",h),Ce.adjustChatPatternBackground(),h||Ri.showCtrlFTip())}),s.append(r.container,o.container),this.viewSection.content.append(s),this.scrollable.append(this.stickerContainer,t,this.createFolderBtn,this.foldersSection.container,this.suggestedSection.container,this.viewSection.container),J(this.createFolderBtn,async()=>{await this.canCreateFolder()?this.slider.createTab(vr).open():Ja("folders")},{listenerSetter:this.listenerSetter});const l=()=>{this.foldersSection.container.classList.toggle("hide",!Object.keys(this.filtersRendered).length)},c=[],d=e.filters.then(async u=>{for(const h of u)h.id!==yn&&await this.renderFolder(h,this.list,void 0,!0);this.toggleAllChats(),l()});return c.push(d),this.listenerSetter.add(I)("filter_update",async u=>{const h=this.filtersRendered[u.id];h?await this.renderFolder(u,null,h):u.id!==yn&&await this.renderFolder(u,this.list,void 0,!0),l(),this.getSuggestedFilters()}),this.listenerSetter.add(I)("filter_delete",u=>{const h=this.filtersRendered[u.id];h&&(this.getSuggestedFilters(),h.container.remove(),delete this.filtersRendered[u.id]),l()}),this.listenerSetter.add(I)("filter_order",u=>{u.filter(h=>!!this.filtersRendered[h]).forEach((h,p)=>{const g=this.filtersRendered[h].container;di(g,g.parentElement,p+1)})}),this.listenerSetter.add(I)("premium_toggle",()=>{this.toggleAllChats()}),this.loadAnimationPromise=e.animationData.then(async u=>{const h=await u({container:this.stickerContainer,loop:!1,autoplay:!1,width:86,height:86});return this.animation=h,Ns.waitForFirstFrame(h)}),c.push(this.loadAnimationPromise),new mb({list:this.list,middleware:this.middlewareHelper.get(),onSort:(u,h)=>{let p=[];for(const m in this.filtersRendered){const g=this.filtersRendered[m],f=Bn(g.container);p[f]=+m}p=p.filter(m=>m!==void 0),I.premium||Vs(p,Fi),this.managers.filtersStorage.updateDialogFiltersOrder(p)},scrollable:this.scrollable}),this.getSuggestedFilters(),Promise.all(c)}onOpenAfterTimeout(){return this.loadAnimationPromise.then(()=>{this.animation.autoplay=!0,this.animation.play()}),super.onOpenAfterTimeout()}toggleAllChats(){this.filtersRendered[Fi].container.classList.toggle("hide",!I.premium)}async canCreateFolder(){const[e,t]=await Promise.all([this.managers.apiManager.getLimit("folders"),this.managers.filtersStorage.getDialogFilters()]);return t.filter(i=>!oa.has(i.id)).length<e}getSuggestedFilters(){return this.managers.filtersStorage.getSuggestedDialogsFilters().then(async e=>{this.suggestedSection.container.classList.toggle("hide",!e.length),Array.from(this.suggestedSection.content.children).slice(1).forEach(t=>t.remove());for(const t of e){const s=await this.renderFolder(t);this.suggestedSection.content.append(s.container);const i=s.buttonRight;J(i,async n=>{if(_e(n),!await this.canCreateFolder()){Ja("folders");return}i.setAttribute("disabled","true");const r=t.filter;r.includePeerIds=[],r.excludePeerIds=[],r.pinnedPeerIds=[],this.managers.filtersStorage.createDialogFilter(r,!0).then(()=>{s.container.remove(),this.suggestedSection.container.classList.toggle("hide",this.suggestedSection.content.childElementCount===1)}).finally(()=>{i.removeAttribute("disabled")})},{listenerSetter:this.listenerSetter})}})}}class r1{constructor(e,t){this.container=e,this.handler=t,this.observeHeaders(),this.observeElements()}observeHeaders(){this.headersObserver=new IntersectionObserver(e=>{for(const t of e){const s=t.boundingClientRect,i=t.target.parentElement,n=t.rootBounds;s.bottom<n.top&&this.handler(!0,i),s.bottom>=n.top&&s.bottom<n.bottom&&this.handler(!1,i)}},{threshold:0,root:this.container})}observeElements(){this.elementsObserver=new IntersectionObserver(e=>{const t=e.filter(i=>i.boundingClientRect.top<i.rootBounds.top).sort((i,n)=>i.boundingClientRect.top-n.boundingClientRect.top)[0];if(!t)return;const s=t.isIntersecting?t.target:t.target.nextElementSibling;this.handler(!0,s)},{root:this.container})}addSentinel(e,t){const s=document.createElement("div");return s.classList.add("sticky_sentinel",t),e.appendChild(s)}observeStickyHeaderChanges(e){const t=this.addSentinel(e,"sticky_sentinel--top");this.headersObserver.observe(t),this.elementsObserver.observe(e)}disconnect(){this.headersObserver.disconnect(),this.elementsObserver.disconnect()}unobserve(e,t){this.elementsObserver.unobserve(e),this.headersObserver.unobserve(t)}}function hT(a){return jt(a,{entities:[HC(a)]})}function o1({listenTo:a,chatInput:e,isPack:t,verifyRecent:s,appendTo:i,isEmojis:n,isGif:r,canHaveEmojiTimer:o,canViewPack:l,onOpen:c,onClose:d,onSend:u}){let h,p;const m=async y=>{const w=await(r?I.managers.acknowledged.appGifsManager.getGifs():I.managers.acknowledged.appStickersManager.getFavedStickersStickers());if(!w.cached)return!1;const b=(await w.result).some(S=>S.id===p.id);return y?!b:b},g=y=>{I.managers.appUsersManager.updateEmojiStatus(y).then(()=>{$e({langPackKey:"SetAsEmojiStatusInfo"})})},f=async y=>{g({_:"emojiStatus",document_id:p.id,until:Qs(!0)+y})};let v=n?[{icon:"copy",text:"Copy",onClick:()=>{p?si(p.stickerEmojiRaw,h.outerHTML):si(Jm(h).emoji)}},{icon:"stickers_face",text:"ViewPackPreview",onClick:()=>{const w=p.attributes.find(b=>b._==="documentAttributeCustomEmoji").stickerset;ue.createPopup(ga,w,!0,e).show()},verify:()=>l},{icon:"smile",text:"SetAsEmojiStatus",onClick:()=>{g({_:"emojiStatus",document_id:p.id})},verify:()=>!!(I.premium&&p)},{icon:"delete",text:"DeleteFromRecent",onClick:()=>I.managers.appEmojiManager.deleteRecentEmoji(Jm(h)),verify:()=>s?.(h)??!1}]:[{icon:"stickers",text:"Context.ViewStickerSet",onClick:()=>ue.createPopup(ga,p.stickerSetInput,!1,e).show(),verify:()=>!t&&!r},{icon:r?"gifs":"favourites",text:r?"SaveToGIFs":"AddToFavorites",onClick:()=>r?I.managers.appGifsManager.saveGif(p.id,!1):I.managers.appStickersManager.faveSticker(p.id,!1),verify:()=>m(!0)},{icon:r?"crossgif":"crossstar",text:r?"Message.Context.RemoveGif":"DeleteFromFavorites",onClick:()=>r?I.managers.appGifsManager.saveGif(p.id,!0):I.managers.appStickersManager.faveSticker(p.id,!0),verify:()=>m(!1)},{icon:"delete",text:"DeleteFromRecent",onClick:()=>I.managers.appStickersManager.saveRecentSticker(p.id,!0),verify:()=>s?.(h)??!1},{icon:"mute",text:"Chat.Send.WithoutSound",onClick:()=>(u?.(),e.emoticonsDropdown.sendDocId({document:p.id,clearDraft:!1,silent:!0,target:h})),verify:()=>!!(e&&e.chat.peerId&&e.chat.peerId!==I.myId)},{icon:"schedule",text:"Chat.Send.ScheduledMessage",onClick:()=>e.scheduleSending(()=>e.sendMessageWithDocument({document:p,target:h})),verify:()=>e&&!!e.chat.peerId&&!e.chat.starsAmount}];return o&&(v=[{text:"SetEmojiStatusUntil1Hour",onClick:()=>f(3600),verify:()=>o},{text:"SetEmojiStatusUntil2Hours",onClick:()=>f(3600*2),verify:()=>o},{text:"SetEmojiStatusUntil8Hours",onClick:()=>f(3600*8),verify:()=>o},{text:"SetEmojiStatusUntil2Days",onClick:()=>f(3600*24*2),verify:()=>o}]),Dn({listenTo:a,appendTo:i,findElement:y=>{if(h=y.target,n){const w=ne(h,"super-emoji");w?h=w.firstElementChild:h=ne(h,"emoji")||ne(h,"custom-emoji")}else r?h=ne(y.target,"gif"):h=ne(y.target,"media-sticker-wrapper");return h},onOpen:async()=>(p=await I.managers.appDocsManager.getDoc(h.dataset.docId),c?.()),onClose:d,buttons:v})}function Cb(a){let e=a.thumb;return e?(e.w=a.w,e.h=a.h):e={_:"photoStrippedSize",bytes:new Uint8Array([1,24,30,197,162,138,40,0,162,138,40,0,162,138,40,0,162,138,40,3]),type:"i",w:1,h:1},{_:"photo",access_hash:"",pFlags:{},date:0,dc_id:0,file_reference:[],id:0,sizes:[e]}}function Vi(a,e=!1,t){if(!a)return;let s;if(a.action)s=a.action.photo;else if(a.media){let i=a.media;const n=i.extended_media;if(i.webpage)i=i.webpage;else if(n){const r=GC(n)[t??0];if(i=r.media,!i)return Cb(r)}s=i.document||i.photo||(e?void 0:i.game||i)}return s}const uT=(()=>{try{return dn&&+navigator.userAgent.match(/ Version\/(\d+)/)[1]<14}catch{return!1}})(),SS=10;class pT extends pn{constructor(){super(...arguments),this.media=new Map,this.scheduled=new Map,this.mediaDetails=new Map,this.waitingMediaForLoad=new Map,this.waitingScheduledMediaForLoad=new Map,this.waitingDocumentsForLoad={},this.playbackRates={voice:1,video:1,audio:1},this.seekBackward=(e,t=this.playingMedia)=>{t&&on(t,Math.max(0,t.currentTime-(e.seekOffset||SS)))},this.seekForward=(e,t=this.playingMedia)=>{t&&on(t,Math.min(t.duration,t.currentTime+(e.seekOffset||SS)))},this.seekTo=(e,t=this.playingMedia)=>{t&&on(t,e.seekTime)},this.onMediaDocumentLoad=async e=>{const t=this.mediaDetails.get(e),s=await this.managers.appDocsManager.getDoc(t.docId);s.type==="audio"&&s.supportsStreaming&&uT&&this.handleSafariStreamable(e);const i=Ae.getCacheContext(s);e.src=i.url,this.playingMedia===e&&(e.playbackRate=this.playbackRate,s.type==="audio"&&(e.loop=this.loop));const n=this.waitingDocumentsForLoad[s.id];n&&(n.delete(e),n.size||delete this.waitingDocumentsForLoad[s.id])},this.onPlay=e=>{const t=e.target,s=this.mediaDetails.get(t),{peerId:i,mid:n}=s,r=this.pip;r&&r.pause();const o=this.getMessageByMedia(t);if(this.playingMedia!==t){this.stop(),this.setMedia(t,o);const c=h=>h.mid===n&&h.peerId===i,d=this.listLoader,u=d.getCurrent();if(!u||!c(u)){let h;for(const p of[!1,!0]){const m=d.getPrevious(p);let g=m.findIndex(c);if(g!==-1?h=-(m.length-g):(g=d.getNext(p).findIndex(c),g!==-1&&(h=g+1)),h!==void 0)break}h?this.go(h,!1):this.setTargets({peerId:i,mid:n})}}setTimeout(()=>{this.playingMedia===t&&(this.dispatchEvent("play",this.getPlayingDetails()),this.pauseMediaInOtherTabs())},0)},this.onPause=e=>{this.dispatchEvent("pause")},this.onEnded=e=>{if(e&&!e.isTrusted)return;this.onPause(e);const t=this.listLoader;(this.lockedSwitchers||!this.round&&t.current&&!t.next.length||!t.getNext(!0).length||!this.next())&&(this.stop(),this.dispatchEvent("stop"))},this.play=()=>this.toggle(!0),this.pause=()=>this.toggle(!1),this.stop=(e=this.playingMedia,t)=>{if(!e)return!1;if(e.paused||e.pause(),on(e,0),md(e,"ended"),e===this.playingMedia){const s=this.mediaDetails.get(e);if(s?.clean){e.src="";const i=s.peerId,n=s.isScheduled?this.scheduled:this.media,r=n.get(i);r&&(r.delete(s.mid),r.size||n.delete(i)),e.remove(),this.mediaDetails.delete(e)}this.playingMedia=void 0,this.playingMediaType=void 0}return t&&this.dispatchEvent("stop"),!0},this.playItem=e=>{const{peerId:t,mid:s}=e,i=this.searchContext.isScheduled;this.getMedia(t,s,i).play(),setTimeout(()=>{this.resolveWaitingForLoadMedia(t,s,i)},0)},this.go=(e,t)=>{const s=this.listLoader;if(!(this.lockedSwitchers||!s))return this.playingMediaType==="audio"?s.goRound(e,t):s.go(e,t)},this.browserPlay=this.bindBrowserCallback(e=>this.toggle(!0,e)),this.browserPause=this.bindBrowserCallback(e=>this.toggle(!1,e)),this.browserStop=this.bindBrowserCallback(e=>this.stop(e)),this.browserSeekBackward=this.bindBrowserCallback((e,t)=>this.seekBackward(t,e)),this.browserSeekForward=this.bindBrowserCallback((e,t)=>this.seekForward(t,e)),this.browserSeekTo=this.bindBrowserCallback((e,t)=>this.seekTo(t,e)),this.browserNext=this.bindBrowserCallback(e=>e||this.next()),this.browserPrevious=this.bindBrowserCallback(e=>e?this.seekToStart(e):this.previous()),this.next=()=>this.go(1),this.previous=()=>{if(!this.seekToStart(this.playingMedia))return this.go(-1)}}construct(e){if(this.managers=e,this.container=document.createElement("div"),this.container.style.cssText="display: none;",document.body.append(this.container),navigator.mediaSession){const i={play:this.browserPlay,pause:this.browserPause,stop:this.browserStop,seekbackward:this.browserSeekBackward,seekforward:this.browserSeekForward,seekto:this.browserSeekTo,previoustrack:this.browserPrevious,nexttrack:this.browserNext};for(const n in i)try{navigator.mediaSession.setActionHandler(n,i[n])}catch{console.warn("MediaSession action is not supported:",n)}}I.addEventListener("document_downloaded",i=>{const n=this.waitingDocumentsForLoad[i];if(n)for(const r of n)this.onMediaDocumentLoad(r)}),I.addEventListener("media_play",()=>{if(this.skipMediaPlayEvent){this.skipMediaPlayEvent=!1;return}!this.pause()&&this.pip&&this.pip.pause()});const t={};["volume","muted","playbackRate","loop","round"].forEach(i=>{const n="_"+i;t[i]={get:()=>this[n],set:r=>{this[n]!==r&&(this[n]=r,this.playingMedia&&(i!=="loop"||this.playingMediaType==="audio")&&i!=="round"&&(this.playingMedia[i]=r),i==="playbackRate"&&this.playingMediaType!==void 0&&(this.playbackRates[this.playingMediaType]=r),this.dispatchPlaybackParams())}}}),Object.defineProperties(this,t),this.addEventListener("play",({doc:i})=>{i.type==="round"&&Ut.toggleMediaPause(!1)}),this.addEventListener("pause",()=>{Ut.toggleMediaPause(!0)})}dispatchPlaybackParams(){this.dispatchEvent("playbackParams",this.getPlaybackParams())}getPlaybackParams(){const{volume:e,muted:t,playbackRate:s,playbackRates:i,loop:n,round:r}=this;return{volume:e,muted:t,playbackRate:s,playbackRates:i,loop:n,round:r}}setPlaybackParams(e){this.playbackRates=e.playbackRates,this._volume=e.volume,this._muted=e.muted,this._playbackRate=e.playbackRate,this._loop=e.loop,this._round=e.round}addMedia(e,t,s){const{peerId:i,mid:n}=e,o=!!e.pFlags.is_scheduled?this.scheduled:this.media;let l=o.get(e.peerId);l||o.set(e.peerId,l=new Map);let c=l.get(n);if(c)return c;const d=Vi(e,!0);l.set(n,c=document.createElement(d.type==="round"||d.type==="video"?"video":"audio")),d.type==="round"&&c.setAttribute("playsinline","true");const u={peerId:i,mid:n,docId:d.id,doc:d,message:e,clean:s,isScheduled:e.pFlags.is_scheduled};this.mediaDetails.set(c,u),c.volume=1,this.container.append(c),c.addEventListener("play",this.onPlay),c.addEventListener("pause",this.onPause),c.addEventListener("ended",this.onEnded),d.type!=="audio"&&e?.pFlags.media_unread&&e.fromId!==I.myId&&c.addEventListener("timeupdate",()=>{this.managers.appMessagesManager.readMessages(i,[n])},{once:!0});const h=Mt();if(t)h.resolve();else{const p=e.pFlags.is_scheduled?this.waitingScheduledMediaForLoad:this.waitingMediaForLoad;let m=p.get(i);m||p.set(i,m=new Map),m.set(n,h)}return h.then(()=>{if(d.supportsStreaming||Ae.getCacheContext(d).url)this.onMediaDocumentLoad(c);else{let p=this.waitingDocumentsForLoad[d.id];p||(p=this.waitingDocumentsForLoad[d.id]=new Set),p.add(c),fs.downloadMediaURL({media:d})}}),c}getMedia(e,t,s){return(s?this.scheduled:this.media).get(e)?.get(t)}handleSafariStreamable(e){e.addEventListener("play",()=>{const t=e.currentTime;e.addEventListener("progress",()=>{on(e,e.duration-1),e.addEventListener("progress",()=>{on(e,t),e.paused||e.play()},{once:!0})},{once:!0})})}resolveWaitingForLoadMedia(e,t,s){const i=s?this.waitingScheduledMediaForLoad:this.waitingMediaForLoad,n=i.get(e);if(!n)return;const r=n.get(t);r&&(r.resolve(),n.delete(t),n.size||i.delete(e))}isSafariBuffering(e){return!!e.safariBuffering}setSafariBuffering(e,t){e.safariBuffering=t}async setNewMediadata(e,t=this.playingMedia){if(document.pictureInPictureElement)return;await ua(t,void 0,!1);const s=Vi(e,!0);if(!s)return;const i=[],n=s.type==="voice"||s.type==="round";let r="",o="";if(s.thumbs?.length){const c=s.thumbs[s.thumbs.length-1];if(!c.bytes){const d=Ae.getCacheContext(s,c.type);d.url?i.push({src:d.url,sizes:`${c.w}x${c.h}`,type:"image/jpeg"}):fs.downloadMediaURL({media:s,thumb:c}).then(()=>{this.playingMedia!==t||!d.url||this.setNewMediadata(e)})}}else if(n){const c=e.fromId||e.peerId;await this.managers.appPeersManager.getPeerPhoto(c),r=await Gr({peerId:c,plainText:!0,onlyFirstName:!1}),o=Ne.format(s.type==="voice"?"AttachAudio":"AttachRound",!0)}if(!n){const c=s.attributes.find(d=>d._==="documentAttributeAudio");r=c?.title??s.file_name,o=c?.performer}i.length||($o?pt?i.push({src:"assets/img/apple-touch-icon-precomposed.png",sizes:"180x180",type:"image/png"}):i.push({src:"assets/img/apple-touch-icon.png",sizes:"180x180",type:"image/png"}):[72,96,144,192,256,384,512].forEach(c=>{const d=`${c}x${c}`;i.push({src:`assets/img/android-chrome-${d}.png`,sizes:d,type:"image/png"})}));const l=new MediaMetadata({title:r,artist:o,artwork:i});navigator.mediaSession.metadata=l}setCurrentMediadata(){const{playingMedia:e}=this;if(!e)return;const t=this.getMessageByMedia(e);this.setNewMediadata(t,e)}getMessageByMedia(e){return this.mediaDetails.get(e)?.message}getPlayingDetails(){const{playingMedia:e}=this;if(!e)return;const t=this.getMessageByMedia(e);if(t)return{doc:Vi(t,!0),message:t,media:e,playbackParams:this.getPlaybackParams()}}pauseMediaInOtherTabs(){this.skipMediaPlayEvent=!0,I.dispatchEvent("media_play")}toggle(e,t=this.playingMedia){return!t||(e===void 0&&(e=t.paused),t.paused!==e)?!1:(e?t.play():t.pause(),!0)}getPlayingMedia(){return this.playingMedia}bindBrowserCallback(e){return s=>{e(this.pip,s)}}seekToStart(e){return e?.currentTime>5?(on(e,0),this.toggle(!0,e),!0):!1}willBePlayed(e){this.willBePlayedMedia=e}setSearchContext(e){return Pn(this.searchContext,e)?!1:(this.searchContext=kn(e),!0)}getSearchContext(){return this.searchContext}setTargets(e,t,s){let i=this.listLoader;i?i.reset():i=this.listLoader=new Rg({loadCount:10,loadWhenLeft:5,processItem:r=>(this.addMedia(r,!1),{peerId:r.peerId,mid:r.mid}),onJump:(r,o)=>{this.playItem(r)},onEmptied:()=>{this.dispatchEvent("stop"),this.stop()}});const n=this.searchContext.folderId===void 0;t?i.setTargets(t,s,n):i.reverse=n,i.setSearchContext(this.searchContext),i.current=e,i.load(!0),i.load(!1)}getPlaybackMediaTypeFromMessage(e){const t=Vi(e,!0);let s="audio";return t?.type&&(t.type==="voice"||t.type==="round"?s="voice":t.type==="video"&&(s="video")),s}setMedia(e,t,s){const i=this.getPlaybackMediaTypeFromMessage(t);this._playbackRate=this.playbackRates[i],this.playingMedia=e,this.playingMediaType=i,s||(this.playingMedia.volume=this.volume,this.playingMedia.muted=this.muted,this.playingMedia.playbackRate=this.playbackRate,i==="audio"&&(this.playingMedia.loop=this.loop)),"mediaSession"in navigator&&this.setNewMediadata(t)}setSingleMedia({media:e,message:t,standalone:s}={}){const i=this.playingMedia,n=this.pause();let r;return e?(r=()=>{const o=this.pip;o&&o.pause(),this.pauseMediaInOtherTabs()},e.paused||r(),e.addEventListener("play",r)):this.pauseMediaInOtherTabs(),this.willBePlayed(void 0),e?this.setMedia(e,t,s):this.playingMedia=void 0,this.toggleSwitchers(!1),this.dispatchEvent("singleMedia",e),(o=n)=>{this.toggleSwitchers(!0),i&&(this.mediaDetails.get(i)?this.setMedia(i,this.getMessageByMedia(i)):this.next()||this.previous()),this.playingMedia===e&&(this.playingMedia=void 0,this.playingMediaType=void 0),e&&e.removeEventListener("play",r),o&&this.play()}}toggleSwitchers(e){this.lockedSwitchers=!e}setPictureInPicture(e){this.pip=e;const t=new $t;t.add(e)("leavepictureinpicture",()=>{this.pip===e&&(this.pip=void 0,t.removeAll())},{once:!0}),t.add(e)("play",s=>{this.playingMedia!==e&&this.pause(),this.pauseMediaInOtherTabs()})}}const rt=new pT;Di.appMediaPlaybackController=rt;let Od;function Dl(a,e){return Od||(Od=document.createElement("canvas").getContext("2d",{alpha:!1})),Od.font!==e&&(Od.font=e),Od.measureText(a).width}const CS="…",Xh=new Map,Zh=new Set;let _f=!1;function l1(){_f||(_f=!0,$s(()=>{_f=!1,mT()}))}function mT(){Zh.forEach(c1),Zh.clear()}window.addEventListener("resize",()=>{for(const[a]of Xh)Zh.add(a);l1()},{capture:!0,passive:!0});function If(a){const e=a.getSize;if(e)return e();const t=a.dataset.sizeType;return t?st.active[t].width:a.getBoundingClientRect().width}function c1(a){let e=Xh.get(a);const t=!e;let{text:s,textLength:i,from:n,multiplier:r,font:o,textWidth:l,elementWidth:c}=e||{};if(t){s=a.textContent,i=s.length,n=50,r=n>0&&n/100;let h=a.dataset.fontSize;h&&+h&&(h+="px"),o=`${a.dataset.fontWeight||fL} ${h||VC} ${Fh}`,l=Dl(s,o),c=If(a),e={text:s,textLength:i,from:n,multiplier:r,font:o,textWidth:l,elementWidth:c},Xh.set(a,e)}const d=If(a),u=t||c!==d;if(!t&&u&&(e.elementWidth=c=d),u)if(l>c){a.setAttribute("title",s);let h=s,p=c;for(;h.length>3;){const m=h.length,g=r&&zt(r*m<<0,1,m-2)||Math.max(m+n-1,1),f=h.substr(0,g).replace(/\s*$/,""),v=h.substr(g+1).replace(/^\s*/,"");if(h=f+v,p=Dl(h+CS,o),p<c){a.textContent=f+CS+v;break}}e.elementWidth=If(a)}else a.removeAttribute("title")}class _b extends HTMLElement{connectedCallback(){Xh.set(this,null),this.dataset.sizeType||this.getSize?c1(this):(Zh.add(this),l1())}disconnectedCallback(){Xh.delete(this),Zh.delete(this)}}customElements.define("middle-ellipsis-element",_b);const _S=7,Ic=class Ic extends Xl{constructor(e={}){super({step:1e3/60/1e3,min:0,max:1,withTransition:e.withTransition,useTransform:e.useTransform},0),this.options=e,this.segments=[],this.activeSegmentIdx=null,this.onHover=t=>{if(this.hoverRAF)return;this.activeSegmentIdx!=null&&this.toggleSegment(this.activeSegmentIdx,!1);const s=this.filledContainer.getBoundingClientRect(),i=t.clientX-s.left,n=this.segments.findIndex(r=>r.left<=i&&i<=r.right);n>=0&&(this.activeSegmentIdx=n,this.toggleSegment(n,!0)),this.updateTimeAndSegment(i,s.width)},this.onPointerOut=()=>{this.toggleSegment(this.activeSegmentIdx,!1),this.activeSegmentIdx=null},this.onLoadedData=()=>{this.setSeekMax(),this.setTimestampsClipPath()},this.onEnded=()=>{this.setProgress()},this.onPlay=()=>{const t=()=>{this.setProgress(),this.progressRAF=this.media.paused?void 0:window.requestAnimationFrame(t)};this.progressRAF&&(window.cancelAnimationFrame(this.progressRAF),this.progressRAF=void 0),this.streamable&&this.setLoadProgress(),t()},this.onTimeUpdate=()=>{this.media.paused&&(this.setProgress(),this.streamable&&this.setLoadProgress())},this.onProgress=t=>{this.setLoadProgress()},this.snapScrubValue=t=>{if(!this.segments?.length)return t;const s=this.segments[this.segments.length-1].right,i=t/this.media.duration*s;for(const n of this.segments)if(n.left-2<=i&&i<=n.left+3)return n.time;return t}}setMedia({media:e,streamable:t,duration:s}){this.media&&this.removeListeners(),t&&!this.filledLoad?(this.filledLoad=document.createElement("div"),this.filledLoad.classList.add("progress-line__filled","progress-line__loaded"),this.container.prepend(this.filledLoad)):this.filledLoad&&this.filledLoad.classList.toggle("hide",!t),this.media=e,this.streamable=t,(!e.paused||e.currentTime>0)&&this.onPlay(),this.setTimestampsClipPath();let i=!1;this.setSeekMax(s),this.setListeners(),this.setHandlers({onMouseDown:()=>{i=!this.media.paused,i&&this.media.pause(),this.options?.onSeekStart?.(),this.container.classList.add("media-progress-line--seeking")},onMouseUp:n=>{i&&Sn(this.media),this.options?.onSeekEnd?.(),this.container.classList.remove("media-progress-line--seeking")}})}initResizeObserver(){this.unobserveResize?.(),this.unobserveResize=Gy(this.filledContainer,()=>{this.setTimestampsClipPath()})}toggleSegment(e,t){const s=this.clipPathSvg.querySelector(`rect:nth-child(${e+1})`);t?s?.setAttribute("data-active","true"):s?.removeAttribute("data-active")}wrapProgressLinesInContainer(){if(this.filledContainer)return;this.container.classList.add("media-progress-line"),this.filledContainer=document.createElement("div"),this.filledContainer.classList.add("media-progress-line__filled-container");const e=document.createElement("div");e.classList.add("media-progress-line__thumb"),this.currentTimeInfoElement=document.createElement("div"),this.currentTimeInfoElement.classList.add("media-progress-line__current-time-info"),this.currentTimeElement=document.createElement("div"),this.currentTimeInfoElement.classList.add("media-progress-line__current-time"),this.currentSegmentElement=document.createElement("div"),this.currentTimeInfoElement.classList.add("media-progress-line__current-segment"),this.currentTimeInfoElement.append(this.currentSegmentElement,this.currentTimeElement),this.filledContainer.append(this.filled,this.filledLoad),this.container.prepend(this.filledContainer),this.container.append(e,this.currentTimeInfoElement),this.container.addEventListener("pointermove",this.onHover),this.container.addEventListener("pointerout",this.onPointerOut),this.initResizeObserver()}clearTimeAndSegment(){this.currentTimeElement.textContent="",this.currentSegmentElement.textContent=""}updateTimeAndSegment(e,t){if(!this.media||!this.currentTimeInfoElement)return;if(e<0||e>t){this.clearTimeAndSegment();return}const s=bn(e/t*this.media.duration|0);if(this.currentTimeElement.textContent=s,this.segments?.length>0){const o=this.segments.find(c=>c.left<=e&&e<=c.right),l=this.options.videoTimestamps?.find(c=>c.time===o.time);this.currentSegmentElement.textContent=Ya(l?.text||"",24,27)}const i=this.currentTimeInfoElement.getBoundingClientRect(),n=Math.min(0,t-(e+i.width/2)),r=Math.max(0,i.width/2-e);this.currentTimeInfoElement.style.setProperty("--current-time-info-x",e+r+n+"px")}setTimestampsClipPath(){if(this.removeClipPathFromDOM(),this.segments=[],!this.options.videoTimestamps?.length)return;this.wrapProgressLinesInContainer();const t=this.filledContainer.getBoundingClientRect().width,s=this.segments=this.getTimestampSegments(t);if(!s?.length)return;const i=1,n=s.map(l=>`<rect x="${(l.left+i).toFixed(2)}" width="${(l.right-l.left-2*i).toFixed(2)}" rx="1" />`);this.usedClipPathId=++Ic.svgClipPathIdSeed;const r=`media-progress-line-clip-path-svg-${Ic.svgClipPathIdSeed}`,o=`media-progress-line-clip-path-${Ic.svgClipPathIdSeed}`;this.removeClipPathFromDOM(),this.clipPathSvg=gr(`
- <svg width="0" height="0" class="media-progress-line-clip-path-svg" id="${r}">
- <clipPath id="${o}">
- ${n.join(`
- `)}
- </clipPath>
- </svg>
- `),document.body.append(this.clipPathSvg),this.filledContainer.style.clipPath=`url(#${o})`}getTimestampSegments(e){const{videoTimestamps:t}=this.options;if(!t?.length||!this.filledContainer)return[];const s=this.media.duration;if(!s)return[];const i=t.map(({time:o})=>o).filter(o=>o>=0&&o<=s).sort((o,l)=>o-l);i[0]!==0&&i.unshift(0),i.push(s);const n=[];let r=0;for(let o=0;o<i.length-1;o++){const l=Math.max(r,i[o]/s*e);let c=i[o+1]/s*e;if(!(c<=l)&&(c=Math.max(c,l+_S),r=c,c+_S>=e&&(c=e),n.push({left:l,right:c,time:i[o]}),c===e))break}return n}removeClipPathFromDOM(){this.clipPathSvg?.remove()}scrub(e){const t=super.scrub(e,this.snapScrubValue);return on(this.media,t),t}setLoadProgress(){if(rt.isSafariBuffering(this.media))return;const e=this.media.buffered,t=e.length,s=this.media.currentTime;let i=0,n=0;for(let o=0;o<t;++o){const l=e.start(o);s>=l&&l>=i&&(i=l,n=e.end(o))}const r=this.max?n/this.max:0;this.filledLoad.style.width=r*100+"%"}setSeekMax(e){const t=this.media.duration||0;(e===void 0||t)&&(e=t),(this.max=e)?this.seek.setAttribute("max",""+this.max):this.media.addEventListener("loadeddata",this.onLoadedData)}setProgress(){if(rt.isSafariBuffering(this.media))return;const e=this.media.currentTime;this.options.onTimeUpdate?.(e),super.setProgress(e),this.container.style.setProperty("--progress",e/this.media.duration+"")}setListeners(){super.setListeners(),this.media.addEventListener("ended",this.onEnded),this.media.addEventListener("play",this.onPlay),this.media.addEventListener("pause",this.onTimeUpdate),this.media.addEventListener("timeupdate",this.onTimeUpdate),this.streamable&&this.media.addEventListener("progress",this.onProgress)}removeListeners(){super.removeListeners(),this.media&&(this.media.removeEventListener("loadeddata",this.onLoadedData),this.media.removeEventListener("ended",this.onEnded),this.media.removeEventListener("play",this.onPlay),this.media.removeEventListener("pause",this.onTimeUpdate),this.media.removeEventListener("timeupdate",this.onTimeUpdate),this.streamable&&this.media.removeEventListener("progress",this.onProgress)),this.container.removeEventListener("pointermove",this.onHover),this.container.removeEventListener("pointerout",this.onPointerOut),this.progressRAF&&(window.cancelAnimationFrame(this.progressRAF),this.progressRAF=void 0)}cleanup(){this.removeClipPathFromDOM(),this.removeListeners(),this.unobserveResize?.(),this.segments=[]}};Ic.svgClipPathIdSeed=0;let Jc=Ic;function Aa(a){return a&&(a.saved_from_name||a.from_name)}function d1(a){return a.fromId?{peerId:a.fromId}:{fromName:Aa(a.fwd_from)}}async function Sm(a){const e=document.createElement("span");e.classList.add("sender-title");const t=a.fromId===I.myId&&a.peerId!==I.myId;if(e.append(t?P("FromYou"):await qe({...d1(a),dialog:a.peerId===I.myId})),await I.managers.appPeersManager.isAnyGroup(a.peerId)||t){const s=await qe({peerId:a.peerId});e.append(" ➝ ",s)}return e}function Ib(a){const e=document.createElement("span");return e.classList.add("sent-time"),e.append(Au(new Date(a.date*1e3))),e}I.addEventListener("messages_media_read",({mids:a,peerId:e})=>{a.forEach(t=>{const s=`[data-mid="${t}"][data-peer-id="${e}"]`;Array.from(document.querySelectorAll(`audio-element.is-unread${s}, .media-round.is-unread${s}`)).forEach(i=>{i.classList.remove("is-unread")})})});function gT(a){a instanceof Uint8Array||(a=new Uint8Array(a));const t=a.length*8/5|0;if(!t)return new Uint8Array([]);let s;try{const i=new DataView(a.buffer);s=new Uint8Array(t);for(let n=0;n<t;n++){const r=n*5/8|0,o=n*5%8,l=i.getUint16(r,!0);s[n]=l>>o&31}}catch{s=new Uint8Array([])}return s}function fT(a,e){const n=(st.isMobile,23),r=st.isMobile?152:190,o=st.isMobile?190:256,l=zt(e/60*o,r,o),c=Math.max(...a),d=a.length,u=Math.min(l/4|0,d);let h=0;const p=n-4;let m="";for(let v=0,y=0,w=0;v<d;++v){const b=a[v]||0;if(w+u>=d){w=w+u-d,w<(u+1)/2&&h<b&&(h=b);const S=Math.max((h*p+(c+1)/2)/(c+1),4),_=`<rect class="audio-waveform-bar" x="${y}" y="${n-S}" width="2" height="${S}" rx="1" ry="1"></rect>`;m+=_,y+=4,w<(u+1)/2?h=0:h=b}else h<b&&(h=b),w+=u}let g,f;return m&&(g=document.createElement("div"),g.classList.add("audio-waveform"),f=document.createElementNS("http://www.w3.org/2000/svg","svg"),f.classList.add("audio-waveform-bars"),f.setAttributeNS(null,"width",""+l),f.setAttributeNS(null,"height",""+n),f.setAttributeNS(null,"viewBox",`0 0 ${l} ${n}`),f.insertAdjacentHTML("beforeend",m),g.append(f)),{svg:f,container:g,availW:l}}async function vT(a){a.classList.add("is-voice");const e=a.message,t=Vi(e);e.pFlags.out&&a.classList.add("is-out");let s=t.attributes.find(p=>p._==="documentAttributeAudio")?.waveform||new Uint8Array([]);s=gT(s.slice(0,63));const{svg:i,container:n,availW:r}=fT(s,t.duration);let o;n&&(o=n.cloneNode(!0),o.classList.add("audio-waveform-fake"),n.classList.add("audio-waveform-background"));const l=document.createElement("div");l.classList.add("audio-waveform-container"),n&&l.append(n,o);const c=document.createElement("div");if(c.classList.add("audio-time"),a.append(l,c),a.customAudioToTextButton)a.classList.add("can-transcribe"),a.append(a.customAudioToTextButton);else if(a.transcriptionState!==void 0){a.classList.add("can-transcribe");const p=document.createElement("div");p.classList.add("audio-to-text-button");const m=Be("transcribe"),g=document.createElement("div");g.classList.add("loader"),g.innerHTML='<svg class="audio-transcribe-outline" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 24"><rect class="audio-transcribe-outline-rect" fill="transparent" stroke-width="3" stroke-linejoin="round" rx="6" ry="6" stroke="var(--message-primary-color)" stroke-dashoffset="1" stroke-dasharray="32,68" width="32" height="24"></rect></svg>',p.append(m),p.onclick=()=>{const f=(ne(a,"document-wrapper")||ne(a,"quote-text")).querySelector(".audio-transcribed-text");if(a.transcriptionState===0)if(f)f.classList.remove("hide"),m.classList.remove(zr("transcribe")),m.classList.add(zr("up")),a.transcriptionState=2;else{const v=a.message;if(v.pFlags.is_outgoing)return;a.transcriptionState=1,!g.parentElement&&p.append(g),hi().then(()=>{a.transcriptionState===1&&g.classList.add("active")}),a.managers.appMessagesManager.transcribeAudio(v).catch(as)}else a.transcriptionState===2&&(f.classList.add("hide"),m.classList.remove(zr("up")),m.classList.add(zr("transcribe")),a.transcriptionState=0)},a.append(p)}let d=i,u;return d||(u=new Jc,l.append(u.container)),()=>{let p=a.audio;const m=()=>{Wl(()=>p?(g(),!p.paused):!1,a)},g=()=>{o&&(o.style.width=p.currentTime/p.duration*100+"%")};(!p.paused||p.currentTime>0&&p.currentTime!==p.duration)&&g();const f=vL(g);return a.addAudioListener("timeupdate",f),a.addAudioListener("ended",f),a.addAudioListener("play",m),d&&a.readyPromise.then(()=>{let v=!1,y=!1;d.addEventListener("mouseleave",b=>{v&&(a.togglePlay(void 0,!0),v=!1),y=!1}),d.addEventListener("mousemove",b=>{y=!0,v&&w(b)}),d.addEventListener("mousedown",b=>{b.preventDefault(),b.button===0&&(p.paused||a.togglePlay(void 0,!1),w(b),v=!0)}),d.addEventListener("mouseup",b=>{y&&v&&(a.togglePlay(void 0,!0),v=!1)}),J(d,b=>{_e(b),p.paused||w(b)});function w(b){let S;if(b instanceof MouseEvent)S=b.offsetX;else{const M=b.target.getBoundingClientRect();S=b.targetTouches[0].pageX-M.left}const _=S/r*p.duration;on(p,_)}},as),!d&&u.setMedia({media:p,streamable:t.supportsStreaming,duration:t.duration}),()=>{d?.remove(),d=null,p=null}}}async function yT(a){const e=a.withTime,t=a.message,s=Vi(t),i=s.type==="voice"||s.type==="round",n=document.createElement("div");n.classList.add("audio-description");const r=s.attributes.find(h=>h._==="documentAttributeAudio");if(!i){const h=[];r?.performer&&h.push(je(r.performer)),e?h.push(gs(t.date)):h.length||h.push(ur(s.size)),a.showSender&&h.push(await Sm(t)),n.append(" • ",...Kl(h," • "))}a.insertAdjacentHTML("beforeend",`
- <div class="audio-details">
- <div class="audio-title"></div>
- <div class="audio-subtitle"><div class="audio-time"></div></div>
- </div>`);const l=a.querySelector(".audio-title"),c=new _b;c.dataset.fontWeight=a.dataset.fontWeight,c.dataset.fontSize=a.dataset.fontSize,c.dataset.sizeType=a.dataset.sizeType,c.getSize=a.getSize,i?c.append(await Sm(t)):Qt(c,je(r?.title??s.file_name)),l.append(c),a.showSender&&l.append(Ib(t));const d=a.querySelector(".audio-subtitle");return d.append(n),()=>{let h=!1,p=new Jc;p.setMedia({media:a.audio,streamable:s.supportsStreaming,duration:s.duration}),a.addAudioListener("ended",()=>{a.classList.remove("audio-show-progress"),d.lastChild.replaceWith(n),h=!1});const m=()=>{h||(a.classList.add("audio-show-progress"),h=!0,p&&d.lastChild.replaceWith(p.container))};return a.addAudioListener("play",m),(!a.audio.paused||a.audio.currentTime>0)&&m(),()=>{p.removeListeners(),p.container.remove(),p=null}}}function Pf(a=!0){const e=new Kn({cancelable:!0,tryAgainOnFail:a});return e.construct(),a||(e.circle.setAttributeNS(null,"r","23"),e.totalLength=143.58203125),e}const h1=(a,e)=>{let t,s;const i=!a.classList.contains("search-super-item"),n=ne(a,i?"bubbles-inner":"tabs-tab");if(n){const r=':not([data-is-outgoing="1"])',o=`.audio:not(.is-voice)${r}`;let l;if(a.matches(o)?l=[o]:l=[`.audio.is-voice${r}`,`.media-round${r}`],i){const p=".bubble:not(.webpage) ";l=l.map(m=>p+m)}const c=l.join(", ");let d=Array.from(n.querySelectorAll(c));d=d.filter(p=>p===a||p.matches(':not([data-to-be-skipped="1"])'));const u=d.indexOf(a),h=d.map(p=>({peerId:p.dataset.peerId.toPeerId(),mid:+p.dataset.mid}));t=h.slice(0,u),s=h.slice(u+1)}return(s.length&&s[0].mid<e||t.length&&t[t.length-1].mid>e)&&([t,s]=[s.reverse(),t.reverse()]),[t,s]};class Pb extends HTMLElement{constructor(){super(...arguments),this.withTime=!1,this.voiceAsMusic=!1,this.showSender=!1,this.listenerSetter=new $t}async render(){this.classList.add("audio"),this.managers=I.managers,this.dataset.mid=""+this.message.mid,this.dataset.peerId=""+this.message.peerId;const e=Vi(this.message),t=e.type==="voice",s=!this.voiceAsMusic&&t,i=this.message.pFlags.is_outgoing,n=this.uploadingFileName??this.message?.uploadingFileName?.[0],r=()=>{const p=this.audio&&this.audio.readyState>=this.audio.HAVE_CURRENT_DATA?this.audio.duration:e.duration;return bn(p|0)};this.innerHTML=`
- <div class="audio-toggle audio-ico">
- <div class="audio-play-icon">
- <div class="part one" x="0" y="0" fill="#fff"></div>
- <div class="part two" x="0" y="0" fill="#fff"></div>
- </div>
- </div>`;const o=this.firstElementChild,l=document.createElement("div");l.classList.add("audio-download"),e.type!=="audio"&&this.message&&this.message.pFlags.media_unread&&this.classList.add("is-unread"),n&&(this.classList.add("is-outgoing"),this.append(l));const d=await(s||this.shouldWrapAsVoice?vT(this):yT(this)),u=this.querySelector(".audio-time");u.textContent=r();const h=this.onLoad=p=>{this.onLoad=void 0;const m=this.audio??(this.audio=rt.addMedia(this.message,p)),g=this.readyPromise=Mt();this.audio.readyState>=this.audio.HAVE_CURRENT_DATA?g.resolve():this.addAudioListener("canplay",()=>g.resolve(),{once:!0}),this.onTypeDisconnect=d();const f=()=>bn(m.currentTime|0)+(s?" / "+r():""),v=()=>{u.innerText=f(),o.classList.toggle("playing",!m.paused)};(!m.paused||m.currentTime>0&&m.currentTime!==m.duration)&&v();const y=w=>{this.togglePlay(w)};o.addEventListener("click",y),this.addAudioListener("ended",()=>{o.classList.remove("playing"),u.innerText=r()}),this.addAudioListener("timeupdate",()=>{!m.currentTime&&m.paused||rt.isSafariBuffering(m)||(u.innerText=f())}),this.addAudioListener("pause",()=>{o.classList.remove("playing")}),this.addAudioListener("play",v)};if(e.thumbs?.length){const p=[],m=await Bi({photo:e,message:null,container:o,boxWidth:48,boxHeight:48,loadPromises:this.loadPromises,withoutPreloader:!0,lazyLoadQueue:this.lazyLoadQueue});o.style.width=o.style.height="",m.images.thumb&&p.push(m.images.thumb),m.images.full&&p.push(m.images.full),this.classList.add("audio-with-thumb"),p.forEach(g=>g.classList.add("audio-thumb"))}if(i){if(n){this.classList.add("downloading"),this.preloader=Pf(!1);const p=fs.getUpload(n);this.preloader.attachPromise(p),this.dataset.isOutgoing="1",this.preloader.attach(l,!1),p.then(()=>{this.classList.remove("downloading"),l.classList.add("downloaded"),setTimeout(()=>{l.remove()},200)})}}else{let p=this.preloader;const m=e.type!=="audio";h(m);const g=this.load=(f,v)=>{if(this.load=void 0,!this.audio.src){if(rt.resolveWaitingForLoadMedia(this.message.peerId,this.message.mid,this.message.pFlags.is_scheduled),this.onDownloadInit(f),!p)if(e.supportsStreaming){this.classList.add("corner-download");let y;const w=()=>{const S=Pf(!1),_=Mt();_.notifyAll({done:75,total:100}),_.catch(()=>{this.audio.pause(),rt.willBePlayed(void 0)}),_.cancel=()=>{_.cancel=as,_.reject(Vo("CANCELED"))},S.attach(l,!1,_),y=this.addAudioListener("pause",()=>{_.cancel()},{once:!0}),this.onDownloadInit(f)},b=this.addAudioListener("play",w);this.readyPromise.then(()=>{this.listenerSetter.remove(b),y&&this.listenerSetter.remove(y)})}else{p=Pf(),f||(this.readyPromise=Mt());const y=()=>{this.onDownloadInit(f);const w=fs.downloadMediaURL({media:e});return f||w.then(()=>{this.readyPromise.resolve()}),p.attach(l,!1,w),{download:w}};p.setDownloadFunction(y),y()}this.classList.contains("corner-download")?o.append(l):this.append(l),this.classList.add("downloading"),this.readyPromise.then(()=>{this.classList.remove("downloading"),l.classList.add("downloaded"),setTimeout(()=>{l.remove()},200),!v&&rt.willBePlayedMedia===this.audio&&(Sn(this.audio),rt.willBePlayed(void 0))})}};this.audio?.src||(m?g(!1):J(o,()=>{g(!0)},{once:!0,listenerSetter:this.listenerSetter}))}}onDownloadInit(e){e&&(rt.willBePlayed(this.audio),dn&&!this.audio.autoplay&&(this.audio.autoplay=!0))}togglePlay(e,t=this.audio.paused){e&&_e(e),t?(this.setTargetsIfNeeded(),Sn(this.audio)):this.audio.pause()}setTargetsIfNeeded(){const e=!!this.searchContext;if(rt.setSearchContext(this.searchContext||{peerId:Wt,inputFilter:{_:"inputMessagesFilterEmpty"},useSearch:!1})){const t=this.dataset.toBeSkipped?this.audio.parentElement:this,[s,i]=e?h1(t,this.message.mid):[];rt.setTargets({peerId:this.message.peerId,mid:this.message.mid},s,i)}}playWithTimestamp(e){this.load?.(!0),on(this.audio,e),this.togglePlay(void 0,!0)}get addAudioListener(){return this.listenerSetter.add(this.audio)}disconnectedCallback(){setTimeout(()=>{this.isConnected||(this.onTypeDisconnect&&(this.onTypeDisconnect(),this.onTypeDisconnect=null),this.readyPromise&&this.readyPromise.reject(),this.listenerSetter&&(this.listenerSetter.removeAll(),this.listenerSetter=null),this.preloader&&(this.preloader=null))},100)}}customElements.define("audio-element",Pb);class Mb extends pn{constructor(){super(!1),this.hideControls=(e=!1)=>{if(e){this.hideControlsTimeout||(this.hideControlsTimeout=window.setTimeout(this.hideControls,3e3));return}clearTimeout(this.hideControlsTimeout),this.hideControlsTimeout=0;const t=this.element.classList.contains("show-controls");if(this.controlsLocked!==!1){if(this.canHideControls&&!this.canHideControls()||!t||this.controlsLocked)return}else if(!t)return;this.dispatchEvent("toggleControls",!1),this.element.classList.remove("show-controls")},this.showControls=(e=!0)=>{(this.canShowControls?.()??!0)&&(this.hideControlsTimeout?(clearTimeout(this.hideControlsTimeout),this.hideControlsTimeout=0):!this.element.classList.contains("show-controls")&&this.controlsLocked!==!1&&(this.dispatchEvent("toggleControls",!0),this.element.classList.add("show-controls")),!(!e||this.controlsLocked)&&(this.hideControlsTimeout=window.setTimeout(this.hideControls,3e3)))},this.toggleControls=e=>{const t=this.element.classList.contains("show-controls");if(e===void 0)t?this.hideControls():this.showControls();else{if(e===t)return;e===!1?this.hideControls():this.showControls()}},this.hideControlsTimeout=0}setup(e){Nt(this,e);const{listenerSetter:t,element:s}=this;pt?t.add(s)("click",i=>{this.ignoreClickClassName&&ne(i.target,this.ignoreClickClassName)||this.toggleControls()}):(t.add(s)("mousemove",()=>{this.showControls()}),t.add(s)("mouseenter",()=>{this.showControls(!1)}),t.add(s)("mouseleave",i=>{if(i.relatedTarget&&this.showOnLeaveToClassName&&ne(i.relatedTarget,this.showOnLeaveToClassName)){this.showControls(!1);return}this.hideControls()}))}lockControls(e){this.controlsLocked!==e&&(this.controlsLocked=e,this.element.classList.toggle("disable-hover",e===!1),this.toggleControls(e))}}const Mf="player-volume",cg=class cg extends Xl{constructor(e){super({step:.01,min:0,max:1,vertical:e.vertical},1),this.setVolume=({volume:s,muted:i,eventType:n})=>{let r;!s||i?r=0:s>.5?r=3:s>0&&s<.25?r=1:r=2,Wo(this.btn,cg.ICONS[r]).classList.add(Mf+"__icon"),this.media&&(this.media.volume=s,this.media.muted=i),this.mousedown||this.setProgress(i?0:s),n&&this.onVolumeChange?.(n)},this.setGlobalVolume=s=>{const{volume:i,muted:n}=rt;return this.setVolume({volume:i,muted:n,eventType:s})},Nt(this,e),this.setListeners(),this.setHandlers({onScrub:s=>{const i=Math.max(Math.min(s,1),0);this.useGlobalVolume&&this.modifyGlobal(()=>{rt.muted=!1,rt.volume=i}),this.setVolume({volume:i,muted:!1,eventType:"click"})}});const t=this.btn=document.createElement("div");t.classList.add("btn-icon",Mf),J(t,s=>{ne(s.target,Mf+"__icon")&&this.onMuteClick(s)},{listenerSetter:this.listenerSetter}),this.useGlobalVolume?(this.listenerSetter.add(rt)("playbackParams",s=>{this.ignoreGlobalEvents||this.setVolume({...s,eventType:"global"})}),this.useGlobalVolume==="no-init"?this.setVolume({volume:rt.volume,muted:this.media.muted}):this.setGlobalVolume()):this.media&&this.setVolume({volume:this.media.volume,muted:this.media.muted}),t.append(this.container)}removeListeners(){super.removeListeners(),this.onVolumeChange=void 0}modifyGlobal(e){this.ignoreGlobalEvents=!0,e(),this.ignoreGlobalEvents=!1}onMuteClick(e){e&&_e(e);const t=rt.muted;this.useGlobalVolume&&this.modifyGlobal(()=>{rt.muted=!t}),this.setVolume({volume:this.media?.volume??rt.volume,muted:!(this.media?.muted??t),eventType:"click"})}};cg.ICONS=["volume_off","volume_mute","volume_down","volume_up"];let Cm=cg;function bT({width:a=0,height:e=0,image:t}={}){const s=document.createElement("canvas");s.width=a,s.height=e;const i=s.captureStream();i.getVideoTracks()[0].enabled=!0;const n=s.getContext("2d");return t&&(n.drawImage(t,0,0,a,e),n.globalAlpha=.5,n.fillStyle="#000"),n.fillRect(0,0,a,e),i}function uh(a){const e=[480,720,1080],t=(e[1]-e[0])/2;if(a<e[0]+t)return e[0];const s=(e[2]-e[1])/2;return a<e[1]+s?e[1]:e[2]}const wT=Y("<span class=btn-menu-item-with-auxiliary-text><span class=btn-menu-item-auxiliary-text>"),ST=Y('<svg class=quality-levels-switch-button__hd-icon width=14 height=10 viewBox="0 0 14 10"fill=none xmlns=http://www.w3.org/2000/svg><rect width=14 height=10 rx=2 fill=currentColor></rect><path fill-rule=evenodd clip-rule=evenodd d="M3.5 2.5C3.5 2.08579 3.16421 1.75 2.75 1.75C2.33579 1.75 2 2.08579 2 2.5V5V7.5C2 7.91421 2.33579 8.25 2.75 8.25C3.16421 8.25 3.5 7.91421 3.5 7.5V5.75H5V7.5C5 7.91421 5.33579 8.25 5.75 8.25C6.16421 8.25 6.5 7.91421 6.5 7.5V5V2.5C6.5 2.08579 6.16421 1.75 5.75 1.75C5.33579 1.75 5 2.08579 5 2.5V4.25H3.5V2.5ZM8.25 1.75C7.83579 1.75 7.5 2.08579 7.5 2.5V7.5C7.5 7.91421 7.83579 8.25 8.25 8.25H9.75C11.2688 8.25 12.5 7.01878 12.5 5.5V4.5C12.5 2.98122 11.2688 1.75 9.75 1.75H8.25ZM9.75 6.75H9V3.25H9.75C10.4404 3.25 11 3.80964 11 4.5V5.5C11 6.19036 10.4404 6.75 9.75 6.75Z"fill=black>');function CT(a){const[e,t]=K([]),[s,i]=K(),[n,r]=K(!1),o={loadQualityLevels:async()=>{r(!0)},isMenuOpen:()=>l().classList.contains("menu-open")};a.controlsRef(o),le(()=>{n()&&(async()=>{const c=await PT(a.video,i);t(c)})()}),le(()=>{if(n()){e().forEach(d=>d.icon=void 0);const c=e().find(d=>d.id===(s()||"auto"));c&&(c.icon="check")}});const l=V(()=>ki({icon:`settings ${a.skin}__button checkable-button-menu quality-levels-switch-button`,buttons:e(),direction:"top-left"}));return le(()=>{l()?.append(MT())}),le(()=>{const c=s()===1080;l()?.querySelector(".tgico")?.replaceWith(Be(c?"settings_clipped_corner":"settings")),l()?.classList.toggle("quality-levels-switch-button--is-hd",c)}),T(Js,{get when(){return e().length>0},get children(){return l()}})}function _T(a){const e=document.createElement("div");let t;const s=wi(()=>T(CT,ni({controlsRef:i=>{t=i}},a)),e);return{element:e,get controls(){return t},dispose:s}}function u1(a,e){return(()=>{const t=wT(),s=t.firstChild;return k(t,()=>P(a),s),k(s,e),t})()}function IT(a){return u1(`Hls.ResolutionHeightName${a}`,`${a}p`)}async function PT(a,e){const t=yL.get(a);if(!t)return[];const s=Mt(),{default:i}=await zo(()=>import("./hls-I6_10gPe.js"),[],import.meta.url);t.levels&&t.levels.length>0?s.resolve(t.levels):t.on(i.Events.MANIFEST_PARSED,(c,d)=>{s.resolve(d.levels)});const n=await s,o=Array.from(new Set(n.map(c=>uh(c.height)))).sort((c,d)=>d-c).map(c=>{const d=n.filter(h=>uh(h.height)===c).sort((h,p)=>h.bitrate-p.bitrate),u=()=>{let h=d[0];for(const m of d)m.bitrate<t.bandwidthEstimate&&(h=m);const p=n.indexOf(h);t.currentLevel=p,e(c)};return{id:c,emptyIcon:!0,regularText:IT(c),onClick:u}});return[{id:"auto",text:"Hls.ResolutionHeightAuto",emptyIcon:!0,onClick:()=>{t.currentLevel=-1,e()}},...o]}function MT(){return ST()}const LT=[.5,1,1.5,2,3],ET=5,kT={0:"geometric_digit_0",1:"geometric_digit_1",2:"geometric_digit_2",3:"geometric_digit_3",4:"geometric_digit_4",5:"geometric_digit_5",6:"geometric_digit_6",7:"geometric_digit_7",8:"geometric_digit_8",9:"geometric_digit_9",x:"geometric_letter_x",".":"geometric_dot"};function TT(a){const[e,t]=K(rt.playbackRate||1),s={setPlayBackRate:t,changeRateByAmount:r=>{const o=e()+r;o<1?t(.5):t(Math.min(ET,Math.round(o-.01))),rt.playbackRate=e()},isMenuOpen:()=>n.classList.contains("menu-open")};a.controlsRef(s);const i=LT.map(r=>({id:r.toFixed(1),emptyIcon:!0,onClick:()=>{rt.playbackRate=r,t(r)},text:r===1?"PlaybackRateNormal":void 0,regularText:r!==1?r+"x":void 0}));le(()=>{i.forEach(o=>o.icon=void 0);const r=i.find(o=>o.id===e().toFixed(1));r&&(r.icon="check")}),le(()=>{const r="playback-speed-icon-floating";n.querySelector(`.${r}`)?.remove();const l=e().toFixed(1).replace(/\.0$/,"x").split("").map(d=>({char:d==="."?"dot":d,icon:kT[d]})).filter(Boolean),c=document.createElement("span");c.classList.add(r),c.append(...l.map(({char:d,icon:u})=>Be(u,"geometric-font-icon",`geometric-font-icon--${d}`))),n.append(c)});const n=ki({icon:`mediaspeed_empty ${a.skin}__button`,buttons:i,direction:"top-left",onOpen:()=>{a.onMenuToggle?.(!0)},onClose:()=>{a.onMenuToggle?.(!1)}});return le(()=>{n?.classList.add("checkable-button-menu","playback-rate-button-menu")}),n}function xT(a){const e=document.createElement("div");let t;const s=wi(()=>T(TT,ni({controlsRef:i=>{t=i}},a)),e);return{element:e,get controls(){return t},dispose:s}}const AT=Y("<span>"),hs=a=>{const[,e]=wa(a,["icon"]);return(()=>{const t=AT();return so(t,ni(e,{get class(){return Ge("tgico",a.class)}}),!1,!0),k(t,()=>zC(a.icon)),t})()},RT=Y("<div class=speed-drag-handler__speed><div class=speed-drag-handler__speed-number>x</div><div class=speed-drag-handler__speed-arrows>"),FT=Y("<div class=speed-drag-handler__speed-tip><div class=speed-drag-handler__speed-tip-arrows></div><div class=speed-drag-handler__speed-tip-description>"),BT=Y('<svg width=8 height=11 viewBox="0 0 8 11"fill=none xmlns=http://www.w3.org/2000/svg><path opacity=0.7 d="M0 1.5V9.5C0 10.324 0.940764 10.7944 1.6 10.3L6.93333 6.3C7.46667 5.9 7.46667 5.1 6.93333 4.7L1.6 0.7C0.940764 0.205573 0 0.675955 0 1.5Z"fill=currentColor>'),DT=2,$T=200,NT=1500,OT=1/100,Lf=.2,IS=5,UT=.2;function HT(a){const[e,t]=K(rt.playbackRate),[s,i]=K(!1),[n,r]=K(!0),[o,l]=K([0,0]),c={isChangingSpeed:()=>s()};a.controlsRef(c);let d;const u=new $t;Jt(()=>{let p,m=0,g=1,f=0;function v(){const y=a.video.getBoundingClientRect();pi(()=>{i(!0),l([p[0]-y.left,p[1]-y.top])}),f&&(rt.playbackRate=Math.min(g+f,IS)),window.setTimeout(()=>{if(!d)return;const w=d.getBoundingClientRect();w.left<y.left||w.top<y.top||w.right>y.right||w.bottom>y.bottom?r(!0):r(!1),setTimeout(()=>{n()||r(!0)},NT)},0)}u.add(a.video)("pointerdown",y=>{a.video.paused||(p=[y.clientX,y.clientY],g=rt.playbackRate,!Gi&&PS(g,1)&&(f=1),Gi&&(f=g),m=window.setTimeout(()=>{v()},$T))}),u.add(window)("pointermove",y=>{if(!p||Gi)return;const w=y.clientX-p[0],b=g+f,S=w*OT;let _;if(b<1){const C=Math.min((1-b)/Lf,S);_=b+C*Lf+Math.max(0,S-C)}else b+S<1?_=1-(1-b-S)*Lf:_=b+S;if(_=zt(_,UT,IS),PS(rt.playbackRate,_)||(rt.playbackRate=_),!p||n())return;Math.hypot(w,y.clientY-p[1])>DT&&(r(!0),window.clearTimeout(m),i(!0))}),u.add(window)("pointerup",()=>{p&&(window.clearTimeout(m),pi(()=>{r(!0),i(!1),l([0,0])}),p=void 0,f&&(rt.playbackRate=g),f=0)}),u.add(rt)("playbackParams",()=>{t(rt.playbackRate)})}),le(()=>{s()&&(a.onShowSpeed(),a.video&&(a.video.dataset.startedChangingSpeed="true",a.video.dataset.wasChangingSpeed="true",setTimeout(()=>{delete a.video.dataset.startedChangingSpeed},100)),ze(()=>{a.onHideSpeed(),a.video&&setTimeout(()=>{delete a.video.dataset.wasChangingSpeed},100)}))}),ze(()=>{u.removeAll()});const h=()=>e().toFixed(1).replace(/\.0$/,"");return T(Js,{get when(){return s()},get children(){return[(()=>{const p=RT(),m=p.firstChild,g=m.firstChild,f=m.nextSibling;return k(m,h,g),k(f,T(MS,{}),null),k(f,T(MS,{class:"speed-drag-handler__speed-arrow-right-last"}),null),Me(()=>e()!=null?p.style.setProperty("--animation-duration-multiplier",e()):p.style.removeProperty("--animation-duration-multiplier")),p})(),(()=>{const p=FT(),m=p.firstChild,g=m.nextSibling,f=d;return typeof f=="function"?Ue(f,p):d=p,k(m,T(hs,{icon:"arrow_prev"}),null),k(m,T(hs,{icon:"arrow_next"}),null),k(g,()=>P("PlaybackRateDragTip")),Me(v=>{const y=!n()&&!Gi,w=o()[0]+"px",b=o()[1]+"px";return y!==v._v$&&p.classList.toggle("speed-drag-handler__speed-tip--visible",v._v$=y),w!==v._v$2&&((v._v$2=w)!=null?p.style.setProperty("--left",w):p.style.removeProperty("--left")),b!==v._v$3&&((v._v$3=b)!=null?p.style.setProperty("--top",b):p.style.removeProperty("--top")),v},{_v$:void 0,_v$2:void 0,_v$3:void 0}),p})()]}})}function GT(a){const e=document.createElement("div");let t;const s=wi(()=>T(HT,ni({controlsRef:i=>{t=i}},a)),e);return{element:e,get controls(){return t},dispose:s}}function PS(a,e){return a.toFixed(1)===e.toFixed(1)}function MS(a){return(()=>{const e=BT();return Me(()=>Es(e,"class",Ge("speed-drag-handler__speed-arrow-right",a.class))),e})()}class p1 extends Mb{constructor({video:e,container:t,play:s=!1,streamable:i=!1,duration:n,live:r,width:o,height:l,videoTimestamps:c,onPlaybackRateMenuToggle:d,onPip:u,onPipClose:h,listenKeyboardEvents:p,useGlobalVolume:m,onVolumeChange:g,onFullScreen:f,onFullScreenToPip:v,shouldEnableSoundOnClick:y}){if(super(),this._inPip=!1,this._onPip=w=>{this._inPip=w,this.wrapper.style.visibility=w?"hidden":"",this.onPip?.(w)},this.onEnterPictureInPictureLeave=w=>{const b=()=>{clearTimeout(_),this.onPipClose?.()},S=this.listenerSetter.add(w.target)("pause",b,{once:!0}),_=setTimeout(()=>{this.listenerSetter.remove(S)},this.debouncePipTime)},this.onEnterPictureInPicture=w=>{this.debouncedPip(!0),this.listenerSetter.add(w.target)("leavepictureinpicture",this.onEnterPictureInPictureLeave,{once:!0})},this.onLeavePictureInPicture=()=>{this.debouncedPip(!1)},this.requestPictureInPicture=async()=>{if(this.video.duration){this.isFullScreen()&&this.onFullScreenToPip?.(),this.video.requestPictureInPicture(),this.checkInteraction();return}if(!this.emptyPipVideo){const{width:w,height:b}=this;this.emptyPipVideo=document.createElement("video"),this.emptyPipVideo.autoplay=!0,this.emptyPipVideo.muted=!0,this.emptyPipVideo.playsInline=!0,this.emptyPipVideo.style.position="absolute",this.emptyPipVideo.style.visibility="hidden",document.body.prepend(this.emptyPipVideo),this.emptyPipVideo.srcObject=bT({width:w,height:b,image:this.emptyPipVideoSource}),this.addPipListeners(this.emptyPipVideo)}await ua(this.emptyPipVideo),this.emptyPipVideo.requestPictureInPicture(),ua(this.video).then(()=>{document.pictureInPictureElement===this.emptyPipVideo&&(document.exitPictureInPicture(),this.video.requestPictureInPicture())})},this.video=e,this.video.classList.add("ckin__video"),this.wrapper=t??document.createElement("div"),this.wrapper.classList.add("ckin__player"),this.live=r,this.canPause=!r,this.canSeek=!r,this._width=o,this._height=l,this.onPlaybackRateMenuToggle=d,this.onPip=u,this.onPipClose=h,this.onVolumeChange=g,this.onFullScreen=f,this.onFullScreenToPip=v,this.listenKeyboardEvents=p,this.hadContainer=!!t,this.useGlobalVolume=m,this.shouldEnableSoundOnClick=y,this.video.playbackRate=rt.playbackRate,this.listenerSetter=new $t,this.setup({element:this.wrapper,listenerSetter:this.listenerSetter,canHideControls:()=>!(this.video.paused||this.playbackRateButton?.controls.isMenuOpen()||this.qualityLevelsButton?.controls.isMenuOpen()),canShowControls:()=>!this.speedDragHandler?.controls.isChangingSpeed(),showOnLeaveToClassName:"media-viewer-caption",ignoreClickClassName:"ckin__controls"}),this.hadContainer||(e.parentNode.insertBefore(this.wrapper,e),this.wrapper.appendChild(e)),this.skin="default",this.stylePlayer(n),this.skin==="default"&&!r){const w=this.controls=this.wrapper.querySelector(".default__controls.ckin__controls");this.gradient=this.controls.previousElementSibling,this.progress=new Jc({videoTimestamps:c,onSeekStart:()=>{this.wrapper.classList.add("is-seeking")},onSeekEnd:()=>{this.wrapper.classList.remove("is-seeking")}}),this.progress.setMedia({media:e,streamable:i,duration:n}),w.prepend(this.progress.container)}s?e.play().catch(w=>{w.name==="NotAllowedError"&&(e.muted=!0,e.autoplay=!0,Sn(e))}).finally(()=>{this.setIsPlaying(!this.video.paused)}):this.setIsPlaying(!this.video.paused)}get width(){return this.video.videoWidth||this._width}get height(){return this.video.videoHeight||this._height}setIsPlaying(e){this.isPlaying!==e&&(this.isPlaying=e,this.toggleActivity(e),!(this.live&&!e)&&(this.wrapper.classList.toggle("is-playing",e),this.toggles.forEach(t=>{t.replaceChildren(Be(e?"pause":"play"))})))}stylePlayer(e){const{wrapper:t,video:s,skin:i,listenerSetter:n,live:r}=this;t.classList.add(i),r&&t.classList.add(`${i}-live`);const o=this.buildControls();t.insertAdjacentHTML("beforeend",o);let l;const c=[],d=[];if(i==="default"){if(this.canPause){const v=this.mainToggle=ot(`${i}__button--big toggle`,{noRipple:!0,icon:"play"});t.firstElementChild.after(v)}const u=t.querySelector(".left-controls");if(r)this.toggles=[];else{const v=yt(` ${i}__button toggle`,{noRipple:!0});u.prepend(v),this.toggles=[v]}const h=t.querySelector(".right-controls");r||(this.playbackRateButton=xT({skin:this.skin,onMenuToggle:this.onPlaybackRateMenuToggle})),!Gi&&document.pictureInPictureEnabled&&(this.pipButton=yt(`pip ${i}__button`,{noRipple:!0}));const p=yt(` ${i}__button`,{noRipple:!0});h.append(...[this.playbackRateButton?.element,this.createQualityLevelsButton(),this.pipButton,p].filter(Boolean));const m=t.querySelector(".ckin__time-elapsed");l=t.querySelector(".ckin__time-duration");const g=this.volumeSelector=new Cm({listenerSetter:n,vertical:!1,media:s,useGlobalVolume:this.useGlobalVolume,onVolumeChange:this.onVolumeChange});g.btn.classList.remove("btn-icon"),m?m.parentElement.before(g.btn):u.lastElementChild.before(g.btn),this.toggles.forEach(v=>{J(v,()=>{this.togglePlay()},{listenerSetter:this.listenerSetter})}),this.pipButton&&(J(this.pipButton,this.requestPictureInPicture,{listenerSetter:this.listenerSetter}),this.debouncePipTime=20,this.debouncedPip=$i(this._onPip,this.debouncePipTime,!1,!0),this.addPipListeners(s)),pt||(this.canPause&&J(s,()=>{this.checkInteraction()||s.dataset.wasChangingSpeed||this.togglePlay()},{listenerSetter:this.listenerSetter}),this.listenKeyboardEvents&&n.add(document)("keydown",v=>{if(vn.overlaysActive>1||document.pictureInPictureElement===s||this.listenKeyboardEvents==="fullscreen"&&!this.isFullScreen())return;const{key:y,code:w}=v;let b=!0;if(w==="KeyF")this.toggleFullScreen();else if(w==="KeyM")rt.muted=!rt.muted;else if(w==="Space"&&this.canPause)this.togglePlay();else if(v.altKey&&(w==="Equal"||w==="Minus")&&this.canSeek){const S=w==="Equal"?1:-1;this.playbackRateButton.controls.changeRateByAmount(S)}else t.classList.contains("ckin__fullscreen")&&(y==="ArrowLeft"||y==="ArrowRight")&&this.canSeek?y==="ArrowLeft"?rt.seekBackward({action:"seekbackward"}):rt.seekForward({action:"seekforward"}):b=!1;if(b)return _e(v),!1})),this.canPause&&(this.speedDragHandler=GT({video:this.video,onShowSpeed:()=>{this.hideControls()},onHideSpeed:()=>{this.showControls()}}),this.wrapper.append(this.speedDragHandler.element),n.add(s)("contextmenu",v=>{v.preventDefault()})),n.add(s)("dblclick",()=>{pt||this.toggleFullScreen()}),J(p,()=>{this.toggleFullScreen()},{listenerSetter:this.listenerSetter}),pg(t,()=>this._onFullScreen(p),n),this._onFullScreen(p,!0),m&&n.add(s)("timeupdate",()=>{!s.paused&&!this.isPlaying&&(console.warn("video: fixing missing play event"),md(s,"play")),m.textContent=bn(s.currentTime|0)});const f=()=>{t.classList.add("played"),!pt&&!r&&c.push(()=>{this.hideControls(!0)}),Vs(c,f)};this.hadContainer&&f(),c.push(f),d.push(()=>{this.showControls(!1)}),n.add(rt)("playbackParams",()=>{this.video.dataset.startedChangingSpeed||this.playbackRateButton.controls.setPlayBackRate(rt.playbackRate)}),r&&(this.liveEl=P("Rtmp.MediaViewer.Live"),this.liveEl.classList.add("controls-live"),u.prepend(this.liveEl))}n.add(s)("play",()=>{this.setIsPlaying(!0),c.forEach(u=>u())}),n.add(s)("pause",()=>{this.setIsPlaying(!1),d.forEach(u=>u())}),l&&(s.duration||e?l.textContent=bn(Math.round(s.duration||e)):ua(s).then(()=>{l.textContent=bn(Math.round(s.duration))}))}createQualityLevelsButton(){return this.qualityLevelsButton=_T({skin:this.skin,video:this.video}),this.qualityLevelsButton.element}async loadQualityLevels(){this.qualityLevelsButton?.controls.loadQualityLevels()}checkInteraction(){return this.shouldEnableSoundOnClick?.()?(this.volumeSelector.setVolume({volume:1,muted:!1}),!0):!1}addPipListeners(e){this.listenerSetter.add(e)("enterpictureinpicture",this.onEnterPictureInPicture),this.listenerSetter.add(e)("leavepictureinpicture",this.onLeavePictureInPicture)}togglePlay(e=this.video.paused){this.video[e?"play":"pause"]()}buildControls(){const e=this.skin;if(e==="default"){const t=this.live?`
- <span class="left-controls-watching"></span>
- `:`
- <time class="ckin__time-elapsed">0:00</time>
- <span> / </span>
- <time class="ckin__time-duration">0:00</time>
- `;return`
- <div class="${e}__gradient-bottom ckin__controls"></div>
- <div class="${e}__controls ckin__controls">
- <div class="bottom-controls night">
- <div class="left-controls">
- <div class="ckin__time">
- ${t}
- </div>
- </div>
- <div class="right-controls"></div>
- </div>
- </div>`}}cancelFullScreen(){bL()===this.wrapper&&this.toggleFullScreen()}toggleFullScreen(){const e=this.wrapper;if(Vy){const t=this.video;t.webkitEnterFullscreen(),t.enterFullscreen();return}pa()?Bh():(zy(e),this.checkInteraction())}toggleActivity(e){Ae.invokeVoid("toggleUninteruptableActivity",{activity:"UsingVideoPlayer",active:e})}isFullScreen(){return pa()}_onFullScreen(e,t){const s=pa();this.wrapper.classList.toggle("ckin__fullscreen",s),s?(e.replaceChildren(Be("smallscreen")),e.setAttribute("title","Exit Full Screen")):(e.replaceChildren(Be("fullscreen")),e.setAttribute("title","Full Screen")),!t&&this.onFullScreen?.(s)}dimBackground(){this.wrapper.classList.add("dim-background")}setTimestamp(e){on(this.video,e),this.togglePlay(!0)}cleanup(){super.cleanup(),this.listenerSetter.removeAll(),this.progress?.removeListeners(),this.volumeSelector?.removeListeners(),this.qualityLevelsButton?.dispose(),this.playbackRateButton?.dispose(),this.speedDragHandler?.dispose(),this.onPlaybackRateMenuToggle=this.onPip=this.onVolumeChange=this.onFullScreen=this.onFullScreenToPip=this.shouldEnableSoundOnClick=void 0,this.progress?.cleanup(),this.toggleActivity(!1)}unmount(){[this.mainToggle,this.gradient,this.controls].forEach(e=>{e.remove()})}setupLiveMenu(e){this.liveMenuButton=ki({direction:"top-left",buttons:e,buttonOptions:{noRipple:!0}}),this.wrapper.querySelector(".right-controls").prepend(this.liveMenuButton)}updateLiveViewersCount(e){this.wrapper.querySelector(".left-controls-watching").replaceChildren(P("Rtmp.Watching",[hb(Math.max(1,e))]))}get inPip(){return this._inPip}}const VT=50*1024*1024,zT=!1;let Ha=0;st.addEventListener("changeScreen",(a,e)=>{if(e===fn.mobile||a===fn.mobile){const t=Array.from(document.querySelectorAll(".media-round .progress-ring")),s=st.active.round.width,i=s/2,n=i-7;Ha=2*Math.PI*n,t.forEach(r=>{r.setAttributeNS(null,"width",""+s),r.setAttributeNS(null,"height",""+s);const o=r.firstElementChild;o.setAttributeNS(null,"cx",""+i),o.setAttributeNS(null,"cy",""+i),o.setAttributeNS(null,"r",""+n),o.style.strokeDasharray=Ha+" "+Ha,o.style.strokeDashoffset=""+Ha})}});let Ud=!1;async function Xa({doc:a,altDoc:e,container:t,message:s,boxWidth:i,boxHeight:n,withTail:r,isOut:o,middleware:l,lazyLoadQueue:c,noInfo:d,group:u,onlyPreview:h,noPreview:p,withoutPreloader:m,loadPromises:g,noPlayButton:f,photoSize:v,videoSize:y,searchContext:w,autoDownload:b,managers:S=I.managers,noAutoplayAttribute:_,ignoreStreaming:M,canAutoplay:C,useBlur:L,observer:E,setShowControlsOn:x,uploadingFileName:R,onGlobalMedia:B,onLoad:N}){const G=a.supportsStreaming&&!M;!G&&e&&!h&&!wL&&(a=e,e=void 0),a.type==="gif"&&t&&(t.classList.add("media-gif-wrapper"),t.dataset.docId=""+a.id);const O=b?.video;let $=O===0;const H=!(i&&n);C??(C=(a.type!=="video"||a.size<=VT&&!H)&&(a.type==="gif"?wt.isAvailable("gif"):wt.isAvailable("video")));let D,U,j=!1,q,W;if(!d&&t){D=document.createElement("span"),D.classList.add("video-time"),t.append(D);let fe=!1;a.type!=="gif"?(D.innerText=bn(a.duration,!1),!f&&a.type!=="round"&&(C&&!$?(E&&zT&&(j=!0,W=l,q=Ht(),l=q.get()),D.append(Be("nosound","video-time-icon"))):fe=!0)):(D.innerText="GIF",!C&&!f&&(fe=!0,$=void 0)),fe&&(U=ot("btn-circle video-play position-center",{icon:"largeplay",noRipple:!0}),t.append(U))}const ee={};if(a.mime_type==="image/gif"){const fe=await Bi({photo:a,message:s,container:t,boxWidth:i,boxHeight:n,withTail:r,isOut:o,lazyLoadQueue:c,middleware:l,withoutPreloader:m,loadPromises:g,autoDownloadSize:O,size:v,managers:S,useBlur:L,uploadingFileName:R});return ee.thumb=fe,ee.loadPromise=fe.loadPromises.full,ee}let z;const Z=Do({middleware:l,pip:j});if(Z.classList.add("media-video"),Z.muted=!0,a.type==="round"){const fe=document.createElement("div");fe.classList.add("media-round","z-depth-1"),fe.dataset.mid=""+s.mid,fe.dataset.peerId=""+s.peerId,fe.message=s;const Xe=st.active.round,Ye=Xe.width/2,Ze=3.5,Je=Ye-Ze*2;fe.innerHTML=`<svg class="progress-ring" width="${Xe.width}" height="${Xe.width}" style="transform: rotate(-90deg);">
- <circle class="progress-ring__circle" stroke="white" stroke-opacity="0.3" stroke-width="${Ze}" cx="${Ye}" cy="${Ye}" r="${Je}" fill="transparent"/>
- </svg>`;const tt=fe.firstElementChild.firstElementChild;Ha||(Ha=2*Math.PI*Je),tt.style.strokeDasharray=Ha+" "+Ha,tt.style.strokeDashoffset=""+Ha,s.pFlags.media_unread&&fe.classList.add("is-unread");const Ee=document.createElement("canvas");Ee.classList.add("video-round-canvas"),Ee.width=Ee.height=a.w,fe.prepend(Ee,D),fe.append(Z),t?.append(fe);const ve=Ee.getContext("2d"),Qe=()=>{const A=fe.message,F=rt.addMedia(A,!$);B?.(F);const Q=()=>{(Ce.chat.setPeerPromise||Promise.resolve()).finally(()=>{mr(F)||(F.removeEventListener("play",xe),F.removeEventListener("timeupdate",he),F.removeEventListener("pause",lt),F.removeEventListener("ended",mt))})},X=()=>{ve.drawImage(F,0,0);const at=Ha-F.currentTime/F.duration*Ha;return tt.style.strokeDashoffset=""+at,!F.paused},ge=()=>{if(F.duration){if(!mr(F)){Q();return}F.paused&&X(),D.firstChild.nodeValue=bn(F.duration-F.currentTime,!1)}},he=fa(()=>{$s(ge)},1e3,!1),Le=Be("nosound","video-time-icon"),Se=at=>{fe.classList.toggle("is-paused",at),at?D.append(Le):Le.remove()},xe=()=>{Z.classList.add("hide"),Se(!1),Wl(X,Ee),z?.preloader&&z.preloader.classList.contains("manual")&&z.onClick()},lt=()=>{if(!mr(F)){Q();return}Se(!0)},mt=()=>{Z.classList.remove("hide"),Se(!0),on(Z,0),D.firstChild.nodeValue=bn(F.duration,!1),F.currentTime&&on(F,0)};F.addEventListener("play",xe),F.addEventListener("timeupdate",he),F.addEventListener("pause",lt),F.addEventListener("ended",mt),J(Ee,at=>{if(_e(at),z&&!z.detached&&z.onClick(),F.paused){const kt=!!w;if(rt.setSearchContext(w||{peerId:Wt,inputFilter:{_:"inputMessagesFilterEmpty"},useSearch:!1})){const[Us,Ts]=kt?h1(fe,A.mid):[];rt.setTargets({peerId:A.peerId,mid:A.mid},Us,Ts)}Sn(F)}else F.pause()}),F.paused?F.duration&&F.currentTime!==F.duration&&F.currentTime>0?(X(),ge(),Z.classList.add("hide")):lt():xe()};s.pFlags.is_outgoing?(fe.onLoad=Qe,fe.dataset.isOutgoing="1"):Qe()}else _||(Z.autoplay=!0);let de;if(s||h){if(de=await Bi({photo:a,message:s,container:t,boxWidth:i,boxHeight:n,withTail:r,isOut:o,lazyLoadQueue:c,middleware:l,withoutPreloader:!0,loadPromises:g,autoDownloadSize:b?.photo,size:v,managers:S,useBlur:L,canHaveVideoPlayer:j,uploadingFileName:R}),ee.thumb=de,!C&&a.type!=="gif"||h)return ee.loadPromise=de.loadPromises.full,ee;if(r){const fe=(de.images.thumb||de.images.full).parentElement;Z.width=+fe.getAttributeNS(null,"width"),Z.height=+fe.getAttributeNS(null,"height"),fe.append(Z)}}else if(!p){const fe=zh({photo:a,cacheContext:{},useBlur:L||!0});if(fe){const Xe=fe.image;Xe.classList.add("media-poster"),t?.append(Xe),ee.thumb={loadPromises:{thumb:fe.loadPromise,full:Promise.resolve()},images:{thumb:Xe,full:null},preloader:null,aspecter:null},g?.push(fe.loadPromise),ee.loadPromise=fe.loadPromise}}if(h)return ee;const ie=()=>{(de?.aspecter||t).append(Z)};!Z.parentElement&&t&&Z.poster&&ie();let oe,ae;const ke=()=>{oe=Ae.getCacheContext(a,y?.type),e&&(ae=Ae.getCacheContext(e,y?.type))};ke(),R??(R=s?.uploadingFileName?.[0]),R?(z=new Kn({attachMethod:"prepend",isUpload:!0}),z.attachPromise(fs.getUpload(R)),z.attach(t,!1),$=void 0):!oe.downloaded&&!G&&!m?z=new Kn({attachMethod:"prepend"}):G&&!m&&(z=new Kn({cancelable:!1,attachMethod:"prepend"}));const re=Mt();if(Z.addEventListener("error",fe=>{WC(fe)||(Z.error.code!==4&&console.error("Error "+Z.error.code+"; details: "+Z.error.message),z&&!R&&z.detach(),re.isFulfilled||re.resolve())},{once:!0}),a.type==="video"&&D){const fe=()=>{Z.duration&&(D.firstChild.nodeValue=bn(Z.duration-Z.currentTime,!1))},Xe=fa(()=>{$s(fe)},1e3,!1);Z.addEventListener("timeupdate",Xe),U&&Z.addEventListener("timeupdate",()=>{lm.mutateElement(U,()=>{U.remove()})},{once:!0})}Z.muted=!0,Z.loop=!0,_||(Z.autoplay=!0);let ce=$&&de?.preloader?.loadFunc;const Ie=async()=>{z&&$&&!m&&(z.construct(),z.setManual()),ke();let fe=Promise.resolve();if(z&&!R||m)if(!oe.downloaded&&!G){const Xe=fe=fs.downloadMediaURL({media:a,queueId:c?.queueId,onlyCache:$,thumb:y});z&&z.attach(t,!1,Xe)}else G&&($?fe=Promise.reject(Vo("NO_AUTO_DOWNLOAD")):!oe.downloaded&&z&&(z.attach(t,!1,null),Z.addEventListener(dn?"timeupdate":"canplay",()=>{z.detach()},{once:!0})));return!$&&ce&&(ce(),ce=null),$=void 0,fe.then(async()=>{if(l&&!l()){re.resolve();return}a.type==="round"&&rt.resolveWaitingForLoadMedia(s.peerId,s.mid,s.pFlags.is_scheduled),ke();const Xe=Je=>{if(console.error("video load error",Z,Je),D){D.classList.add("is-error");const tt=D.querySelector(".video-time-icon"),ht=Be("sendingerror","video-time-icon");tt?tt.replaceWith(ht):D.append(ht)}re.reject(Je)},Ye=ua(Z),Ze=mg(Z,Ye);if(Ze.catch(Xe),Ye.then(()=>{u&&Ut.addAnimation({animation:Z,group:u,observeElement:Z,type:"video",locked:j}),z&&!R&&z.detach(),!Z.parentElement&&t&&!Z.poster&&ie(),e?(Ze.then(()=>{Z.pause(),re.resolve()}),on(Z,1e-4)):re.resolve(),Ve?.(),N?.()},Xe),e&&ae){const Je=[{context:oe,type:'video/mp4; codecs="hev1"',width:a.w},{context:ae,type:'video/mp4; codecs="avc1.64001E"',width:e.w}].map(({context:tt,type:ht,width:Ee})=>{const ve=document.createElement("source");return ve.src=tt.url,ve.width=Ee,ve});Z.append(...Je),Z.load()}else Ka(Z,oe.url)},as),{download:fe,render:Promise.all([fe,re])}};z&&!R&&z.setDownloadFunction(Ie),t&&(t.preloader=z),a.type==="gif"&&!C?J(t,fe=>{_e(fe),U.remove(),Ie()},{capture:!0,once:!0}):ee.loadPromise=c?(c.push({div:t,load:()=>Ie().then(({render:fe})=>fe)}),Promise.resolve()):(await Ie()).render,ee.thumb&&await ee.thumb.loadPromises.thumb,Z&&(ee.video=Z);const Ve=j?()=>{Z.mini=!0,Z.pause();const fe=Ee=>{Ee.isIntersecting||Xe(),!Ee.isIntersecting&&Z.muted};t.classList.add("media-video-container","media-video-mini"),E.observe(Z,fe);const Xe=()=>{Ye.clearTimeout(),!(!Ze||!l()||pa()||Ze.inPip)&&(Ze.unmount(),Ze.cleanup(),Ze=void 0,x.classList.remove("show-controls"))},Ye=$i(Xe,1e3,!1,!0);let Ze,Je;t.onMiniVideoMouseMove=Ee=>{if(Ze)return;const ve=F=>{F?Je=Mt():Je?.resolve()},Qe=F=>{if(A&&A--)return;const Q=Ut.getAnimations(Z)[0];Ut.toggleItemLock(Q,F),ve(F)};let A=0;Ze=new p1({video:Z,container:t,duration:Z.duration,streamable:!0,listenKeyboardEvents:"fullscreen",useGlobalVolume:"no-init",onVolumeChange:F=>{const Q=!Z.volume||Z.muted;let X;Q?X=Ud=!1:F==="click"&&(X=Ud=!0),X!==Ud&&X!==void 0&&rt.dispatchEvent("toggleVideoAutoplaySound",X)},onFullScreen:F=>{Qe(F),vn.isDarkOverlayActive=F},onFullScreenToPip:()=>{A=2},onPip:Qe}),Ze.volumeSelector.setVolume({muted:!Ud,volume:Z.volume}),Ze.addEventListener("toggleControls",F=>{x.classList.toggle("show-controls",F),F?Ye.clearTimeout():Ye()})};const tt=Ee=>{Ze||(Z.muted=rt.muted,Z.volume=rt.volume)},ht=Ee=>{Ze||(Z.muted=Ud?Ee.muted:!0,Z.playbackRate=Ee.playbackRate,Z.volume=Ee.volume)};rt.addEventListener("toggleVideoAutoplaySound",tt),rt.addEventListener("playbackParams",ht),l.onClean(()=>{E.unobserve(Z,fe),delete t.onMiniVideoMouseMove,rt.removeEventListener("toggleVideoAutoplaySound",tt),rt.removeEventListener("playbackParams",ht)}),W.onClean(async()=>{await Je,q.destroy()})}:void 0;return ee}let Ef=!1;function _d({listenTo:a,listenerSetter:e,selector:t,findTarget:s,getTextColor:i}){if(pt)return;const n=(o,l)=>{let c;if(s)c=s(o);else{const d=t||".media-sticker-wrapper, .media-gif-wrapper";c=o.target.closest(d)}return c&&(!l||Mi(c,a))?c:void 0},r=I.managers;e.add(a)("mousedown",o=>{if(Ef||o.buttons>1||o.button!==0)return;let l=n(o);if(!l)return;const c=l.dataset.docId;if(!c)return;const d="sticker-viewer",u="STICKER-VIEWER",h=200,p=200,m=Ut.getOnlyOnePlayableGroup(),g=Ht();let f,v,y=!1;const w=async({mediaContainer:C,doc:L,middleware:E,lockGroups:x,isSwitching:R})=>{const B=L.type==="gif",N=B?void 0:ql(L),G=C.getBoundingClientRect(),O=ii(L.w,L.h),$=N?280:B?Math.min(480,It.height-200):360,H=ii($,$),D=G.width===G.height?H:O.aspectFitted(H),U=ne(C,"bubble"),j=U?U.classList.contains("is-out"):!0,q=document.createElement("div");q.classList.add(d+"-transformer"),q.middlewareHelper=E.create(),E=q.middlewareHelper.get();const W=document.createElement("div");W.classList.add(d+"-sticker"),W.style.width=D.width+"px",W.style.height=D.height+"px";const ee=document.createElement("div");if(ee.classList.add(d+"-emoji"),ee.append(je(L.stickerEmojiRaw)),N){const fe=($*KC-$)/3*(j?1:-1);q.classList.add("has-effect"),q.style.setProperty("--translateX",`${fe}px`),ee.style.setProperty("--translateX",`${-fe}px`)}const z=ne(C,"scrollable"),Z=Ko(C,z,!0,G);(Z.overflow.vertical||Z.overflow.horizontal)&&W.classList.add("is-overflow");const de=C.getBoundingClientRect(),ie=de.width/D.width,oe=de.height/D.height,ae=de.left-(It.width-de.width)/2,ke=de.top-(It.height-de.height)/2;q.style.transform=`translate(${ae}px, ${ke}px) scale(${ie}, ${oe})`,R&&q.classList.add("is-switching"),q.append(W,ee),f.append(q);const re=L.attributes.find(fe=>fe._==="documentAttributeCustomEmoji"),ce=B?await Xa({doc:L,container:W,group:u,boxWidth:D.width,boxHeight:D.height,canAutoplay:!0,middleware:E,noInfo:!0}).then(async fe=>(await fe.loadPromise,fe.video)):await ai({doc:L,div:W,group:u,width:D.width,height:D.height,play:!1,loop:!0,middleware:E,managers:r,needFadeIn:!1,isOut:j,withThumb:!1,relativeEffect:!0,loopEffect:!0,textColor:re&&re.pFlags.text_color?i?.()||du:void 0}).then(({render:fe})=>fe);if(!E())return;f.parentElement||document.body.append(f);const Ie=Array.isArray(ce)?ce[0]:ce,Ve=Ie instanceof Up?new Promise(fe=>Ie.addEventListener("firstFrame",fe,{once:!0})):Promise.resolve();if(await Promise.all([Ve,hi()]),await ns(0),!!E()){if(x&&(Ut.setOnlyOnePlayableGroup(u),Ut.checkAnimations2(!0)),Ie instanceof Up){const fe=C instanceof Wy?C.player:Ns.getAnimation(C);if(fe){if(Ie.curFrame=fe.curFrame,Ie.play(),await new Promise(Xe=>{let Ye=0;const Ze=()=>{++Ye===2&&(Xe(),Ie.removeEventListener("enterFrame",Ze))};Ie.addEventListener("enterFrame",Ze)}),!E())return;Ie.pause()}}else if(Ie instanceof HTMLVideoElement){const fe=C.querySelector("video");fe&&(Ie.currentTime=fe.currentTime)}return{ready:()=>{(Ie instanceof Up||Ie instanceof HTMLVideoElement)&&Sn(Ie),N&&Xs(W)},transformer:q}}},b=window.setTimeout(async()=>{document.removeEventListener("mousemove",_),f=document.createElement("div"),f.classList.add(d),Ef=!0;const C=g.get(),L=await r.appDocsManager.getDoc(c);if(!C())return;let E;try{if(E=await w({doc:L,mediaContainer:l,middleware:C,lockGroups:!0}),!E)return}catch{return}if(y)return;const{ready:x,transformer:R}=E;v=R,Dt({element:f,className:"is-visible",forwards:!0,duration:h,onTransitionEnd:()=>{C()&&x()}}),document.addEventListener("mousemove",S)},125),S=async C=>{const L=n(C,!0);if(!L||l===L)return;const E=L.dataset.docId;if(!E)return;l=L,g.clean();const x=g.get(),R=await r.appDocsManager.getDoc(E);if(!x())return;let B;try{if(B=await w({doc:R,mediaContainer:l,middleware:x,isSwitching:!0}),!B)return}catch($){console.error("sticker viewer error",$);return}const{ready:N,transformer:G}=B,O=v;Dt({element:O,className:"is-switching",forwards:!0,duration:p,onTransitionEnd:()=>{O.remove(),O.middlewareHelper.destroy()}}),v=G,Dt({element:G,className:"is-switching",forwards:!1,duration:p,onTransitionEnd:()=>{x()&&N()}})},_=C=>{Mi(C.target,l)||M()},M=()=>{y=!0,clearTimeout(b),f&&(Dt({element:f,className:"is-visible",forwards:!1,duration:h,onTransitionEnd:()=>{f.remove(),Ut.setOnlyOnePlayableGroup(m),Ut.checkAnimations2(!1),g.destroy(),Ef=!1}}),J(document.body,_e,{capture:!0,once:!0})),document.removeEventListener("mousemove",_),document.removeEventListener("mousemove",S),document.removeEventListener("mouseup",M,{capture:!0})};document.addEventListener("mousemove",_),document.addEventListener("mouseup",M,{once:!0,capture:!0})})}const kf="STICKERS-POPUP";class ga extends ue{constructor(e,t,s=Ce.chat?.input){super("popup-stickers",{closable:!0,overlayClosable:!0,body:!0,scrollable:!0,title:!0,footer:!0}),this.stickerSetInput=e,this.isEmojis=t,this.chatInput=s,this.onStickersClick=async o=>{if(!this.chatInput.chat.peerId)return;const l=ne(o.target,"sticker-set-sticker")||ne(o.target,"custom-emoji");if(!l)return;const c=l.dataset.docId;let d;if(this.isEmojis&&(d={docId:c,emoji:l.dataset.stickerEmoji},!this.chatInput.emoticonsDropdown.canUseEmoji(d,!0)))return;(this.isEmojis?this.chatInput.onEmojiSelected(d,!1):await Ce.chat.input.sendMessageWithDocument({document:c,target:l}))&&this.hide()},this.title.append(P("Loading")),this.updateAdded={},Gn.setIgnoreMouseOut("popup",!0),this.addEventListener("close",()=>{Gn.setIgnoreMouseOut("popup",!1),Ut.setOnlyOnePlayableGroup()}),this.appendTo=this.scrollable.container,this.appendTo.classList.add("is-loading"),Yn(this.appendTo,!0);const i=ot("btn-primary btn-primary-transparent disable-hover",{noRipple:!0,text:"Loading"});this.footer.append(i),_d({listenTo:this.appendTo,listenerSetter:this.listenerSetter});const n=o=>{const l=this.sets.findIndex(d=>d.id===o.id);if(l===-1)return;this.sets[l]=o;const c=this.updateAdded[o.id];c?.(!!o.installed_date),this.updateButton()};this.listenerSetter.add(I)("stickers_installed",n),this.listenerSetter.add(I)("stickers_deleted",n);const r=o=>{const l=tp(this.container,o);if(l)return this.addEventListener("closeAfterTimeout",l),this.hide(),!1};this.container.addEventListener("click",r,{capture:!0}),this.middlewareHelper.onDestroy(()=>{this.container.removeEventListener("click",r,{capture:!0})}),this.loadStickerSet()}createStickerSetElements(e){const t=document.createElement("div");t.classList.add("sticker-set");let s,i;e&&(s=new Fe({title:jt(e.title),subtitle:P(e.pFlags.emojis?"EmojiCount":"Stickers",[e.count]),buttonRight:!0}),i=r=>{St(s.buttonRight,P(r?"Stickers.SearchAdded":"Stickers.SearchAdd")),s.buttonRight.classList.toggle("active",r)},i(!!e.installed_date),t.append(s.container));const n=document.createElement("div");return n.classList.add("sticker-set-stickers"),t.append(n),{container:t,headerRow:s,updateAdded:i,itemsContainer:n}}async loadStickerSet(){const e=this.middlewareHelper.get(),s=GC(this.stickerSetInput).map(g=>this.managers.appStickersManager.getStickerSet(g));let i=await Promise.all(s);if(!e())return;let n=i[0];if(i.length===1&&!n){$e({langPackKey:this.isEmojis?"AddEmojiNotFound":"StickerSet.DontExist"}),this.hide();return}i=i.filter(Boolean),n=i[0],this.sets=i.map(g=>g.set);const r=this.isEmojis??(this.isEmojis=!!n.set.pFlags.emojis);J(this.appendTo,this.onStickersClick,{listenerSetter:this.listenerSetter});const{destroy:o}=o1({listenTo:this.appendTo,chatInput:this.chatInput,isPack:!0,isEmojis:r,onSend:()=>this.hide()});this.addEventListener("close",o),Ut.setOnlyOnePlayableGroup(kf);const l=new sr,c=[],d=i.map(async g=>{const{container:f,itemsContainer:v,headerRow:y,updateAdded:w}=this.createStickerSetElements(i.length>1?g.set:void 0);y&&J(y.buttonRight,()=>{this.managers.appStickersManager.toggleStickerSet(g.set)},{listenerSetter:this.listenerSetter}),this.updateAdded[g.set.id]=w;let b;const S=g.documents.filter(_=>_?._==="document");if(r){const _=ab({docIds:S.map(M=>M.id),loadPromises:c,animationGroup:kf,customEmojiSize:st.active.esgCustomEmoji,middleware:e});Array.from(_.children).slice(1).forEach(M=>{const C=document.createElement("span");C.classList.add("super-emoji","super-emoji-custom"),M.replaceWith(C),C.append(M)}),b=[_],v.classList.replace("sticker-set-stickers","super-emojis"),v.classList.add("is-emojis")}else b=await Promise.all(S.map(async _=>{const M=document.createElement("div");M.classList.add("sticker-set-sticker");const C=st.active.popupSticker.width;return await ai({doc:_,div:M,lazyLoadQueue:l,group:kf,play:!0,loop:!0,width:C,height:C,withLock:!0,loadPromises:c,middleware:e}),M}));return v.append(...b.filter(Boolean)),f}),u=await Promise.all(d);await Promise.all(c);const h=this.button=ot("",{noRipple:!0});this.updateButton(),J(h,()=>{const g=os([h],!0);this.managers.appStickersManager.toggleStickerSets(i.map(f=>f.set)).then(()=>{this.hide()}).catch(()=>{g()})},{listenerSetter:this.listenerSetter}),i.length===1?Qt(this.title,jt(n.set.title)):Qt(this.title,P("Emoji"));const p=[{icon:"copy",text:"CopyLink",onClick:()=>{const g=`https://t.me/${this.isEmojis?"addemoji":"addstickers"}/`,f=i.map(v=>g+v.set.short_name).join(`
- `);si(f)}}];_n&&p.push({icon:"download",text:"MediaViewer.Context.Download",onClick:async()=>{for(const g of i)for(const f of g.documents)fs.downloadToDisc({media:f}),await ns(100)}});const m=ki({listenerSetter:this.listenerSetter,buttons:p,direction:"bottom-left"});this.title.after(m),this.footer.textContent="",this.footer.append(h),this.appendTo.classList.remove("is-loading"),this.appendTo.textContent="",this.appendTo.append(...u),this.scrollable.onAdditionalScroll()}updateButton(){const{sets:e,isEmojis:t}=this;let s,i;if(e.length===1){const n=e[0];i=P(t?"EmojiCount":"Stickers",[n.count]),s=!n.installed_date}else{const n=e.filter(o=>o.installed_date);let r;e.length===n.length?(s=!1,r=e.length):(s=!0,r=e.length-n.length),i=P("EmojiPackCount",[r])}this.button.className=s?"btn-primary btn-color-primary":"btn-primary btn-primary-transparent danger",St(this.button,P(s?"AddStickersCount":"RemoveStickersCount",[i]))}}const Ur={Stickers:{getElementMediaSize:()=>st.active.esgSticker,padding:3*2,gapX:4,gapY:4,itemsClassName:"super-stickers"},Emoji:{getElementMediaSize:()=>X9,padding:16,gapX:4,gapY:0,itemsClassName:"super-emojis"},GIF:{getElementMediaSize:()=>ii(124,124),padding:4,gapX:2,gapY:2,itemsClassName:"emoticons-gifs"}};class WT{constructor(e){const t=document.createElement("div");t.classList.add("emoji-category");const s=document.createElement("div");s.classList.add("category-items");let i;e.title&&(i=document.createElement("div"),i.classList.add("category-title"),i.append(e.title));let n,r;e.noMenuTab||(n=yt(void 0,{noRipple:!0}),n.classList.add("menu-horizontal-div-item"),r=document.createElement("div"),r.classList.add("menu-horizontal-div-item-padding"),n.append(r)),i&&t.append(i),t.append(s),this.elements={container:t,title:i,items:s,menuTab:n,menuTabPadding:r},this.id=e.id,this.items=[],this.getContainerSize=e.getContainerSize,this.getElementMediaSize=e.styles.getElementMediaSize,this.gapX=e.styles.gapX??0,this.gapY=e.styles.gapY??0,this.middlewareHelper=e.middleware?e.middleware.create():Ht()}setCategoryItemsHeight(e=this.items.length){const{width:t}=this.getContainerSize(),s=this.getElementMediaSize().width;let i=t/s;this.gapX&&(i-=Math.floor(i-1)*this.gapX/s),i=Math.floor(i);const n=Math.ceil(e/i);let r=n*s;this.gapY&&(r+=(n-1)*this.gapY),this.elements.items.style.minHeight=r+"px"}}function Lb(a,e){const t=Ot(a),{onChange:s}=e;let i=new Set(e.appear?void 0:t);const n=new WeakSet,[r,o]=K([],{equals:!1}),[l]=CL(),c=e.exitMethod==="remove"?as:h=>{o(p=>(p.push(...h),p));for(const p of h)n.delete(p)};let d;return e.exitMethod==="remove"?d=as:e.exitMethod==="keep-index"?d=h=>h.elements.splice(h.previousIndex,0,h.element):e.exitMethod==="keep-relative"?d=h=>{let p;h.side==="start"?p=h.previousIndex:p=h.elements.length,h.elements.splice(p,0,h.element)}:d=h=>h.elements.push(h.element),V(h=>{const p=r(),m=a();if(m[SL],Ot(l))return l(),h;if(p.length){const g=h.filter(f=>!p.includes(f));return p.length=0,s({list:g,added:[],removed:[],unchanged:g,finishRemoved:c}),g}return Ot(()=>{const g=new Set(m),f=m.slice(),v=[],y=[],w=[];for(const _ of m)(i.has(_)?w:v).push(_);const b={elements:f,previousElements:h,side:"start"};let S=!v.length;for(let _=0;_<h.length;++_){const M=h[_];g.has(M)?b.side="end":(n.has(M)||(y.push(M),n.add(M)),b.element=M,b.previousIndex=_,d(b)),S&&M!==f[_]&&(S=!1)}return!y.length&&S?h:(s({list:f,added:v,removed:y,unchanged:w,finishRemoved:c}),i=g,f)})},e.appear?[]:t.slice())}function KT(a){return typeof a!="function"?()=>a:a}function jT(a){const e=yd(()=>a.children).toArray,t=a.itemClassName?i=>{i.forEach(n=>{n.classList.add(a.itemClassName)})}:void 0;return t?.(e()),Lb(e,{exitMethod:"keep-index",appear:a.appear,onChange:({added:i,removed:n,finishRemoved:r})=>{const o=a.animationOptions;wt.isAvailable("animations")||(o.duration=0),t?.(i);const l=KT(a.keyframes);let c=!1,d=!1;a.mode==="replacement"?(c=!!n.length,d=!!i.length):a.mode==="remove"?d=!!n.length:a.mode==="add-remove"&&(c=!!i.length,d=!!n.length),queueMicrotask(()=>{if(c){const p=i.map(m=>l(m));i.forEach((m,g)=>{m.animate(p[g],o)})}if(!d){r(n);return}const u=n.map(p=>l(p).slice().reverse()),h=[];n.forEach((p,m)=>{const g=p.animate(u[m],o);h.push(g.finished)}),Promise.all(h).then(()=>r(n))})}})}const qT={"cross-fade":[{opacity:0},{opacity:1}],"grow-width":a=>{const{clientWidth:e}=a;return[{width:0,opacity:0},{width:e+"px",opacity:1}]}};function YT(a){return T(jT,{animationOptions:{duration:200,easing:"cubic-bezier(.4, .0, .2, 1)"},get keyframes(){return a.keyframes},get mode(){return a.mode||"replacement"},itemClassName:"animated-item",get appear(){return a.appear},get children(){return a.children}})}function Yo(a){return T(Ru,{component:YT,get keyframes(){return qT[a.type]},get mode(){return a.mode},get appear(){return a.appear},get children(){return a.children}})}const QT="_Viewer_13e91_41",XT="_isInvisible_13e91_53",ZT="_isFull_13e91_60",JT="_ViewerBackground_13e91_60",ex="_isReady_13e91_63",tx="_ViewerStoryContainer_13e91_68",sx="_fromLeft_13e91_79",ix="_current_13e91_82",nx="_fromRight_13e91_90",ax="_ViewerStory_13e91_68",rx="_fadeIn_13e91_148",ox="_small_13e91_151",lx="_hideOnSmall_13e91_155",cx="_hold_13e91_158",dx="_ViewerStoryContentMediaContainer_13e91_162",hx="_ViewerStoryInfo_13e91_168",ux="_focused_13e91_174",px="_ViewerStorySlides_13e91_177",mx="_ViewerStorySlidesSlide_13e91_186",gx="_ViewerStoryHeader_13e91_205",fx="_ViewerStoryHeaderAvatar_13e91_217",vx="_ViewerStoryHeaderName_13e91_224",yx="_ViewerStoryHeaderTime_13e91_224",bx="_ViewerStoryHeaderSecondary_13e91_232",wx="_hasRepost_13e91_242",Sx="_ViewerStoryHeaderLeft_13e91_247",Cx="_ViewerStoryHeaderRight_13e91_247",_x="_ViewerStoryHeaderInfo_13e91_261",Ix="_ViewerStoryHeaderRow_13e91_265",Px="_ViewerStoryHeaderRepost_13e91_272",Mx="_ViewerStoryHeaderRepostTitle_13e91_282",Lx="_ViewerStoryPrivacy_13e91_287",Ex="_ViewerStoryContent_13e91_162",kx="_ViewerStoryContentItem_13e91_310",Tx="_ViewerStoryContentMedia_13e91_162",xx="_ViewerStoryFooter_13e91_323",Ax="_ViewerStoryFooterLeft_13e91_342",Rx="_ViewerStoryFooterRight_13e91_342",Fx="_ViewerStoryFooterIcon_13e91_346",Bx="_ViewerStoryFooterIconIcon_13e91_350",Dx="_ViewerStoryFooterReaction_13e91_354",$x="_isReacted_13e91_363",Nx="_isMe_13e91_376",Ox="_isChangelog_13e91_379",Ux="_ViewerStoryShadow_13e91_383",Hx="_hasCaption_13e91_389",Gx="_ViewerStoryInfoAvatar_13e91_407",Vx="_ViewerStoryInfoName_13e91_411",zx="_ViewerStoryCaption_13e91_424",Wx="_hasReply_13e91_448",Kx="_ViewerStoryCaptionText_13e91_451",jx="_ViewerStoryCaptionTextCell_13e91_460",qx="_ViewerStoryMediaArea_13e91_465",Yx="_ViewerStoryMediaAreaReaction_13e91_475",Qx="_ViewerStoryMediaAreaReactionBubbles_13e91_481",Xx="_dark_13e91_489",Zx="_ViewerStoryMediaAreaReactionBubble_13e91_481",Jx="_ViewerStoryMediaAreaReactionInner_13e91_508",e2="_hasCount_13e91_519",t2="_ViewerStoryMediaAreaReactionCount_13e91_525",s2="_ViewerStoryMediaAreas_13e91_541",i2="_ViewerStoryReactions_13e91_548",n2="_ViewerStoryRepost_13e91_577",a2="_ViewerStoryRepostSmall_13e91_582",r2="_ViewerClose_13e91_775",o2="_noSound_13e91_785",He={Viewer:QT,isInvisible:XT,isFull:ZT,ViewerBackground:JT,isReady:ex,ViewerStoryContainer:tx,fromLeft:sx,current:ix,fromRight:nx,ViewerStory:ax,fadeIn:rx,small:ox,hideOnSmall:lx,hold:cx,ViewerStoryContentMediaContainer:dx,ViewerStoryInfo:hx,focused:ux,ViewerStorySlides:px,ViewerStorySlidesSlide:mx,ViewerStoryHeader:gx,ViewerStoryHeaderAvatar:fx,ViewerStoryHeaderName:vx,ViewerStoryHeaderTime:yx,ViewerStoryHeaderSecondary:bx,hasRepost:wx,ViewerStoryHeaderLeft:Sx,ViewerStoryHeaderRight:Cx,ViewerStoryHeaderInfo:_x,ViewerStoryHeaderRow:Ix,ViewerStoryHeaderRepost:Px,ViewerStoryHeaderRepostTitle:Mx,ViewerStoryPrivacy:Lx,ViewerStoryContent:Ex,ViewerStoryContentItem:kx,ViewerStoryContentMedia:Tx,ViewerStoryFooter:xx,ViewerStoryFooterLeft:Ax,ViewerStoryFooterRight:Rx,ViewerStoryFooterIcon:Fx,ViewerStoryFooterIconIcon:Bx,ViewerStoryFooterReaction:Dx,isReacted:$x,isMe:Nx,isChangelog:Ox,ViewerStoryShadow:Ux,hasCaption:Hx,ViewerStoryInfoAvatar:Gx,ViewerStoryInfoName:Vx,ViewerStoryCaption:zx,hasReply:Wx,ViewerStoryCaptionText:Kx,ViewerStoryCaptionTextCell:jx,ViewerStoryMediaArea:qx,ViewerStoryMediaAreaReaction:Yx,ViewerStoryMediaAreaReactionBubbles:Qx,dark:Xx,ViewerStoryMediaAreaReactionBubble:Zx,ViewerStoryMediaAreaReactionInner:Jx,hasCount:e2,ViewerStoryMediaAreaReactionCount:t2,ViewerStoryMediaAreas:s2,ViewerStoryReactions:i2,ViewerStoryRepost:n2,ViewerStoryRepostSmall:a2,ViewerClose:r2,noSound:o2};function l2(a,e){return e*(--a*a*a+1)}class m1 extends Yt{constructor(e){super(e),this.input.addEventListener("input",()=>{this.updateInnerHTML(),this.onFakeInput()}),this.input.classList.add("scrollable","scrollable-y","no-scrollbar"),this.inputFake=document.createElement("div"),this.inputFake.contentEditable="true",this.inputFake.tabIndex=-1,this.inputFake.className=this.input.className+" input-field-input-fake"}onFakeInput(e=!0,t){const{scrollHeight:s}=this.inputFake;t??(t=!this.input.isContentEditable);const i=+this.input.style.height.replace("px","");if(i===s)return;const r=t?0:Math.round(50*Math.log(Math.abs(s-i)));this.input.style.transitionDuration=`${r}ms`,e&&(this.onChangeHeight?.(s),this.input.style.height=s?s+"px":"",this.input.oldHeight=this.input.newHeight,this.input.newHeight=s,Array.from(this.input.querySelectorAll(".quote-like")).forEach(l=>{const c=l.scrollHeight,d=getComputedStyle(l),u=parseFloat(d.lineHeight),h=parseFloat(d.paddingTop),p=parseFloat(d.paddingBottom),m=(c-h-p)/u;l.classList.toggle("can-send-collapsed",m>3)}));const o="is-changing-height";Dt({element:this.input,className:o,forwards:!0,duration:r,onTransitionEnd:()=>{this.input.classList.remove(o),this.input.oldHeight=this.input.newHeight}})}updateInnerHTML(e=this.input.innerHTML){e=e.replace(/<custom-emoji-renderer-element.+\/custom-emoji-renderer-element>/,"").replace(/(<custom-emoji-element.+?>).+?\/custom-emoji-element>/g,"$1</custom-emoji-element>"),this.inputFake.innerHTML=e}setValueSilently(e,t){super.setValueSilently(e,t),this.updateInnerHTML(),t||this.onFakeInput()}}(function(a,e){typeof exports=="object"&&typeof module=="object"?module.exports=e():typeof define=="function"&&define.amd?define([],e):typeof exports=="object"?exports.Recorder=e():a.Recorder=e()})(typeof self<"u"?self:void 0,function(){return function(a){var e={};function t(s){if(e[s])return e[s].exports;var i=e[s]={i:s,l:!1,exports:{}};return a[s].call(i.exports,i,i.exports,t),i.l=!0,i.exports}return t.m=a,t.c=e,t.d=function(s,i,n){t.o(s,i)||Object.defineProperty(s,i,{enumerable:!0,get:n})},t.r=function(s){typeof Symbol<"u"&&Symbol.toStringTag&&Object.defineProperty(s,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(s,"__esModule",{value:!0})},t.t=function(s,i){if(1&i&&(s=t(s)),8&i||4&i&&typeof s=="object"&&s&&s.__esModule)return s;var n=Object.create(null);if(t.r(n),Object.defineProperty(n,"default",{enumerable:!0,value:s}),2&i&&typeof s!="string")for(var r in s)t.d(n,r,function(o){return s[o]}.bind(null,r));return n},t.n=function(s){var i=s&&s.__esModule?function(){return s.default}:function(){return s};return t.d(i,"a",i),i},t.o=function(s,i){return Object.prototype.hasOwnProperty.call(s,i)},t.p="",t(t.s=0)}([function(a,e,t){(function(s){var i=s.AudioContext||s.webkitAudioContext,n=function(r){if(!n.isRecordingSupported())throw new Error("Recording is not supported in this browser");r||(r={}),this.state="inactive",this.config=Object.assign({bufferLength:4096,encoderApplication:2049,encoderFrameSize:20,encoderPath:"encoderWorker.min.js",encoderSampleRate:48e3,maxFramesPerPage:40,mediaTrackConstraints:!0,monitorGain:0,numberOfChannels:1,recordingGain:1,resampleQuality:3,streamPages:!1,reuseWorker:!1,wavBitDepth:16},r),this.encodedSamplePosition=0};n.isRecordingSupported=function(){return i&&s.navigator&&s.navigator.mediaDevices&&s.navigator.mediaDevices.getUserMedia&&s.WebAssembly},n.prototype.clearStream=function(){this.stream&&(this.stream.getTracks?this.stream.getTracks().forEach(function(r){r.stop()}):this.stream.stop(),delete this.stream),this.audioContext&&this.closeAudioContext&&(this.audioContext.close(),delete this.audioContext)},n.prototype.encodeBuffers=function(r){if(this.state==="recording"){for(var o=[],l=0;l<r.numberOfChannels;l++)o[l]=r.getChannelData(l);this.encoder.postMessage({command:"encode",buffers:o})}},n.prototype.initAudioContext=function(r){return r&&r.context?(this.audioContext=r.context,this.closeAudioContext=!1):(this.audioContext=new i,this.closeAudioContext=!0),this.audioContext},n.prototype.initAudioGraph=function(){this.encodeBuffers=function(){delete this.encodeBuffers},this.scriptProcessorNode=this.audioContext.createScriptProcessor(this.config.bufferLength,this.config.numberOfChannels,this.config.numberOfChannels),this.scriptProcessorNode.connect(this.audioContext.destination),this.scriptProcessorNode.onaudioprocess=r=>{this.encodeBuffers(r.inputBuffer)},this.monitorGainNode=this.audioContext.createGain(),this.setMonitorGain(this.config.monitorGain),this.monitorGainNode.connect(this.audioContext.destination),this.recordingGainNode=this.audioContext.createGain(),this.setRecordingGain(this.config.recordingGain),this.recordingGainNode.connect(this.scriptProcessorNode)},n.prototype.initSourceNode=function(r){return r&&r.context?s.Promise.resolve(r):s.navigator.mediaDevices.getUserMedia({audio:this.config.mediaTrackConstraints}).then(o=>(this.stream=o,this.audioContext.createMediaStreamSource(o)))},n.prototype.loadWorker=function(){this.encoder||(this.encoder=new s.Worker(this.config.encoderPath))},n.prototype.initWorker=function(){var r=(this.config.streamPages?this.streamPage:this.storePage).bind(this);return this.recordedPages=[],this.totalLength=0,this.loadWorker(),new Promise((o,l)=>{var c=d=>{switch(d.data.message){case"ready":o();break;case"page":this.encodedSamplePosition=d.data.samplePosition,r(d.data.page);break;case"done":this.encoder.removeEventListener("message",c),this.finish()}};this.encoder.addEventListener("message",c),this.encoder.postMessage(Object.assign({command:"init",originalSampleRate:this.audioContext.sampleRate,wavSampleRate:this.audioContext.sampleRate},this.config))})},n.prototype.pause=function(r){if(this.state==="recording"){if(this.state="paused",r&&this.config.streamPages){var o=this.encoder;return new Promise((l,c)=>{var d=u=>{u.data.message==="flushed"&&(o.removeEventListener("message",d),this.onpause(),l())};o.addEventListener("message",d),o.postMessage({command:"flush"})})}return this.onpause(),Promise.resolve()}},n.prototype.resume=function(){this.state==="paused"&&(this.state="recording",this.onresume())},n.prototype.setRecordingGain=function(r){this.config.recordingGain=r,this.recordingGainNode&&this.audioContext&&this.recordingGainNode.gain.setTargetAtTime(r,this.audioContext.currentTime,.01)},n.prototype.setMonitorGain=function(r){this.config.monitorGain=r,this.monitorGainNode&&this.audioContext&&this.monitorGainNode.gain.setTargetAtTime(r,this.audioContext.currentTime,.01)},n.prototype.start=function(r){if(this.state==="inactive")return this.initAudioContext(r),this.initAudioGraph(),this.encodedSamplePosition=0,this.initWorker().then(()=>this.initSourceNode(r)).then(o=>{this.sourceNode=o,this.state="recording",this.onstart(),this.encoder.postMessage({command:"getHeaderPages"}),this.sourceNode.connect(this.monitorGainNode),this.sourceNode.connect(this.recordingGainNode)})},n.prototype.stop=function(){if(this.state!=="inactive"){this.state="inactive",this.monitorGainNode.disconnect(),this.scriptProcessorNode.disconnect(),this.recordingGainNode.disconnect(),this.sourceNode.disconnect(),this.clearStream();var r=this.encoder;return new Promise(o=>{var l=c=>{c.data.message==="done"&&(r.removeEventListener("message",l),o())};r.addEventListener("message",l),r.postMessage({command:"done"}),this.config.reuseWorker||r.postMessage({command:"close"})})}return Promise.resolve()},n.prototype.destroyWorker=function(){this.state==="inactive"&&this.encoder&&(this.encoder.postMessage({command:"close"}),delete this.encoder)},n.prototype.storePage=function(r){this.recordedPages.push(r),this.totalLength+=r.length},n.prototype.streamPage=function(r){this.ondataavailable(r)},n.prototype.finish=function(){if(!this.config.streamPages){var r=new Uint8Array(this.totalLength);this.recordedPages.reduce(function(o,l){return r.set(l,o),o+l.length},0),this.ondataavailable(r)}this.onstop(),this.config.reuseWorker||delete this.encoder},n.prototype.ondataavailable=function(){},n.prototype.onpause=function(){},n.prototype.onresume=function(){},n.prototype.onstart=function(){},n.prototype.onstop=function(){},a.exports=n}).call(this,t(1))},function(a,e){var t;t=function(){return this}();try{t=t||new Function("return this")()}catch{typeof window=="object"&&(t=window)}a.exports=t}])});function yr(a,e){let t;const s=a.reply_to,i=a.saved_peer_id&&it(a.saved_peer_id);return i?t=i:s?._==="messageReplyHeader"&&(!e||s.pFlags.forum_topic)?t=s.reply_to_top_id||s.reply_to_msg_id:e&&(a._==="messageService"&&a.action?._==="messageActionTopicCreate"?t=a.mid:t=Tu),t}function Ov(a,e,t,s){return t?Tl(a,e,t):(Vs(a,e),(s?a.push(e):a.unshift(e))-1)}class c2{constructor(e,t,s){this.container=document.createElement("div"),this.container.classList.add("bubbles-group"),this.chat=e,this.groups=t,this.items=[],this.dateTimestamp=s,this.offset=0,this.middlewareHelper=e.bubbles.getMiddleware().create()}getAvatarOptions(e){const t=e.fwd_from,s=e.fwdFromId,i=Aa(t),n=e.from_id&&e.from_id._==="peerChannel"&&e.fromId===s,r=this.chat.peerId,o=(t&&r===Lo&&!i||n?s:e.fromId)||Wt;return{peerId:o,peerTitle:o===Wt?i:void 0}}destroyAvatar(){this.avatar&&(this.avatarContainer.remove(),this.avatarLoadPromise=this.avatar=this.avatarContainer=void 0,--this.offset)}createAvatar(e,t){return this.avatarLoadPromise?this.avatarLoadPromise:e._==="messageService"?void 0:(this.avatarContainer=document.createElement("div"),this.avatarContainer.classList.add("bubbles-group-avatar-container"),++this.offset,this.avatar=vs({middleware:this.middlewareHelper.get(),size:40,lazyLoadQueue:this.chat.bubbles.lazyLoadQueue,...t||this.getAvatarOptions(e)}),this.avatar.node.classList.add("bubbles-group-avatar","user-avatar"),this.avatarLoadPromise=this.avatar.readyThumbPromise,this.avatarContainer.append(this.avatar.node),this.container.append(this.avatarContainer),this.avatarLoadPromise)}get firstTimestamp(){return this.firstItem.timestamp}get firstMid(){return this.firstItem.mid}get firstItem(){return this.items[this.items.length-1]}get lastTimestamp(){return this.lastItem.timestamp}get lastMid(){return this.lastItem.mid}get lastItem(){return this.items[0]}updateClassNames(){const e=this.items,t=e.length;if(!t)return;const s=e[t-1].bubble;if(e.length===1){s.classList.add("is-group-first","is-group-last");return}else s.classList.remove("is-group-last"),s.classList.add("is-group-first");for(let n=1,r=t-1;n<r;++n)e[n].bubble.classList.remove("is-group-last","is-group-first");const i=e[0].bubble;i.classList.remove("is-group-first"),i.classList.add("is-group-last")}insertItem(e){const{items:t}=this;Ov(t,e,this.groups.sortGroupItemsKey,this.groups.reverse=e.reverse),e.group=this,t.length===1&&this.groups.insertGroup(this)}removeItem(e){Vs(this.items,e),this.items.length||Vs(this.groups.groups,this),e.group=void 0}mount(e){if(!this.groups.groups.includes(this)||!this.items.length){debugger;this.mounted&&this.onItemUnmount();return}const{offset:t,items:s}=this,{length:i}=s;hn(s,(n,r)=>{this.mountItem(n,i-1-r,t)}),e&&this.updateClassNames(),this.onItemMount()}mountItem(e,t=this.items.indexOf(e),s=this.offset){e.mounted||(di(e.bubble,this.container,s+t),e.mounted=!0)}unmountItem(e){e.mounted&&(e.bubble.remove(),e.mounted=!1,this.onItemUnmount())}onItemMount(){if(this.mounted)return;const e=this.dateContainer=this.chat.bubbles.getDateContainerByTimestamp(this.dateTimestamp/1e3),t=this.groups.groups.filter(r=>r.dateTimestamp===this.dateTimestamp),s=t.length,i=t.indexOf(this),n=t.slice(i+1).reduce((r,o)=>r+(o.mounted?0:1),0);di(this.container,e.container,lP+s-1-i-n),++e.groupsLength,this.mounted=!0,this.groups?.updateGroupsClassNames()}onItemUnmount(){this.mounted&&(this.items.length?this.updateClassNames():(this.container.remove(),this.dateContainer&&--this.dateContainer.groupsLength,this.dateContainer=void 0,this.chat.bubbles.deleteEmptyDateGroups(),this.mounted=!1,this.middlewareHelper.clean(),this.groups?.updateGroupsClassNames()))}}class d2{constructor(e){this.chat=e,this.itemsArr=[],this.itemsMap=new Map,this.groups=[],this.newGroupDiff=121,e.type!==we.Search&&(this.sortItemsKey=e.type===we.Scheduled?"timestamp":"mid",this.sortGroupsKey=e.type===we.Scheduled?"lastTimestamp":"lastMid",this.sortGroupItemsKey="groupMid")}removeItem(e){e.group?.removeItem(e),this.removeItemFromCache(e)}removeAndUnmountBubble(e){const t=this.getItemByBubble(e);if(!t){const d=e.parentElement;return d&&(d.classList.contains("bubbles-group")?d.remove():e.remove()),!1}const s=this.itemsArr,i=s.indexOf(t),n=this.getSiblingsAtIndex(i,s),r=t.group;this.removeItem(t);const o=new Set;r&&(r.unmountItem(t),o.add(r));const[l,c]=n;if(l&&c&&this.canItemsBeGrouped(l,c)&&l.group!==c.group){const d=c.group;this.f(c.group.items),d.onItemUnmount(),o.add(l.group),this.groupUngrouped()}return this.mountUnmountGroups(Array.from(o)),!0}mountUnmountGroups(e){const[t,s]=qc(e,i=>!!i.items.length);s.forEach(i=>{i.onItemUnmount()}),t.forEach(i=>{i.mount(!0)})}f(e,t=0,s=e.length){for(;t<s;++t){const i=e[t];i.mounted=!1,i.group.removeItem(i),--s,--t}}getItemByBubble(e){return this.itemsMap.get(e)}get firstGroup(){return this.groups[this.groups.length-1]}get lastGroup(){return this.groups[0]}changeBubbleMessage(e,t){const s=this.getItemByBubble(e);s&&(s.mid=t.mid,s.message=t,s.groupMid=this.generateGroupMid(t,s.dateTimestamp),Vs(this.itemsArr,s),this.insertItemToArray(s,this.itemsArr))}changeItemBubble(e,t){this.itemsMap.delete(e.bubble),e.bubble=t,this.itemsMap.set(t,e)}changeBubbleByBubble(e,t){const s=this.getItemByBubble(e);s&&this.changeItemBubble(s,t)}canItemsBeGrouped(e,t){const s=this.chat.isOutMessage(e.message);return t.fromId===e.fromId&&e.dateTimestamp===t.dateTimestamp&&Math.abs(t.timestamp-e.timestamp)<=this.newGroupDiff&&!e.single&&!t.single&&s===this.chat.isOutMessage(t.message)&&(!this.chat.isAllMessagesForum||yr(e.message,!0)===yr(t.message,!0))&&(!s||e.message.fromId===I.myId)&&e.message.peerId===t.message.peerId&&e.message.post_author===t.message.post_author}getSiblingsAtIndex(e,t){return[t[e-1],t[e+1]]}findGroupSiblingByItem(e,t){t=t.slice();const s=this.insertItemToArray(e,t);return this.findGroupSiblingInItems(e,t,s)}findGroupSiblingInItems(e,t,s=t.indexOf(e),i=t.length){const n=t[s-1];let r;if(n?.group&&this.canItemsBeGrouped(e,n))r=n;else for(let o=s+1;o<i;++o){const l=t[o];if(this.canItemsBeGrouped(e,l))l.group&&(r=l);else break}return r}addItemToGroup(e,t){t.insertItem(e),this.addItemToCache(e)}insertItemToArray(e,t){return Ov(t,e,this.sortItemsKey,this.reverse=e.reverse)}insertGroup(e){return Ov(this.groups,e,this.sortGroupsKey,this.reverse)}updateGroupsClassNames(){this.groups.forEach((e,t,s)=>{e.container.classList.toggle("bubbles-group-last",t===0),e.container.classList.toggle("bubbles-group-first",t===s.length-1)})}addItemToCache(e){this.insertItemToArray(e,this.itemsArr),this.itemsMap.set(e.bubble,e)}removeItemFromCache(e){Vs(this.itemsArr,e),this.itemsMap.delete(e.bubble)}getMessageFromId(e){let t=e.fromId;return t===I.myId&&e.peerId===I.myId&&e.fwdFromId===t&&(t=t.toPeerId(!0)),t}generateGroupMid(e,t){const{mid:s,date:i}=e;return this.chat.type===we.Scheduled?+`${(i*1e3-t)/1e3}.${+(""+s).replace(".","")}`:s}createItem(e,t,s){const i=!(t._==="message"||t.action&&ew.has(t.action._)),{mid:n,date:r}=t,{dateTimestamp:o}=this.chat.bubbles.getDateForDateContainer(r);return{mid:n,groupMid:this.generateGroupMid(t,o),fromId:this.getMessageFromId(t),bubble:e,timestamp:r,dateTimestamp:o,mounted:!1,single:i,message:t,reverse:s}}splitSiblingsOnGrouping(e){const[t,s]=e,i=t?.group;if(s?.group,!i)return;const n=i.items,r=n.indexOf(t)+1,o=n.length;if(r===o)return;const l=[i];return this.f(n,r,o),l}prepareForGrouping(e,t,s){if(this.getItemByBubble(e))return;const n=this.createItem(e,t,s);this.addItemToCache(n)}groupUngrouped(){const e=this.itemsArr,t=e.length,s=new Set;for(let i=0;i<t;++i){const n=e[i];if(n.group)continue;let r=!0;const o=this.getSiblingsAtIndex(i,e),d=this.findGroupSiblingInItems(n,e,i,t)?.group??(r=!1,new c2(this.chat,this,n.dateTimestamp));if(s.add(d),d.insertItem(n),!r){const u=this.splitSiblingsOnGrouping(o);u&&u.forEach(h=>s.add(h))}}return s}cleanup(){this.itemsArr=[],this.groups=[],this.itemsMap.clear()}}class Ng extends ue{constructor(e,t,s={}){if(super("popup-date-picker",{body:!0,overlayClosable:!0,buttons:s.noButtons?[]:[{langKey:"JumpToDate",callback:()=>{this.onPick&&this.onPick(this.selectedDate.getTime()/1e3|0)}},{langKey:"Cancel",isCancel:!0}],title:!0,...s}),this.onPick=t,this.options=s,this.onPrevClick=n=>{this.selectedMonth.setMonth(this.selectedMonth.getMonth()-1),this.setMonth(),this.selectedMonth.getTime()===this.minMonth.getTime()&&this.prevBtn.setAttribute("disabled","true"),this.nextBtn.removeAttribute("disabled")},this.onNextClick=n=>{this.selectedMonth.setMonth(this.selectedMonth.getMonth()+1),this.setMonth(),this.selectedMonth.getTime()===this.maxMonth.getTime()&&this.nextBtn.setAttribute("disabled","true"),this.prevBtn.removeAttribute("disabled")},this.onDateClick=n=>{const r=n.target;if(!r.dataset.timestamp)return;if(this.selectedEl){if(this.selectedEl===r)return;this.selectedEl.classList.remove("active")}this.selectedEl=r,r.classList.add("active");const o=+r.dataset.timestamp;this.selectedDate=new Date(o),this.setTitle(),this.setTimeTitle()},this.minDate=s.minDate||new Date("2013-08-01T00:00:00"),e<this.minDate&&e.setFullYear(this.minDate.getFullYear(),this.minDate.getMonth(),this.minDate.getDate()),this.controlsDiv=document.createElement("div"),this.controlsDiv.classList.add("date-picker-controls"),this.prevBtn=yt("down date-picker-prev",{noRipple:!0}),J(this.prevBtn,this.onPrevClick,{listenerSetter:this.listenerSetter}),this.nextBtn=yt("down date-picker-next",{noRipple:!0}),J(this.nextBtn,this.onNextClick,{listenerSetter:this.listenerSetter}),this.monthTitle=document.createElement("div"),this.monthTitle.classList.add("date-picker-month-title"),this.controlsDiv.append(this.prevBtn,this.monthTitle,this.nextBtn),this.monthsContainer=document.createElement("div"),this.monthsContainer.classList.add("date-picker-months"),J(this.monthsContainer,this.onDateClick,{listenerSetter:this.listenerSetter}),this.body.append(this.controlsDiv,this.monthsContainer),s.withTime){this.timeDiv=document.createElement("div"),this.timeDiv.classList.add("date-picker-time");const n=document.createElement("div");n.classList.add("date-picker-time-delimiter"),n.append(":");const r=(o,l,c,d)=>{const u=""+o;this.listenerSetter.add(l.input)("input",h=>{let p=l.value.replace(/\D/g,"");p.length>2?p=p.slice(0,2):(p.length===1&&+p[0]>+u[0]||p.length===2&&+p>o)&&(p.length===2&&d&&d(+p[1]),p="0"+p[0]),l.setValueSilently(p),c(p.length)})};this.hoursInputField=new Yt({plainText:!0}),this.minutesInputField=new Yt({plainText:!0}),r(23,this.hoursInputField,o=>{o===2&&this.minutesInputField.input.focus(),this.setTimeTitle()},o=>{this.minutesInputField.value=(o+this.minutesInputField.value).slice(0,2)}),r(59,this.minutesInputField,o=>{o||this.hoursInputField.input.focus(),this.setTimeTitle()}),this.selectedDate=e,this.hoursInputField.setValueSilently(("0"+e.getHours()).slice(-2)),this.minutesInputField.setValueSilently(("0"+e.getMinutes()).slice(-2)),e.setHours(0,0,0,0),this.timeDiv.append(this.hoursInputField.container,n,this.minutesInputField.container),J(this.btnConfirm,()=>{this.onPick&&(this.selectedDate.setHours(+this.hoursInputField.value||0,+this.minutesInputField.value||0,0,0),this.onPick(this.selectedDate.getTime()/1e3|0)),this.hide()},{listenerSetter:this.listenerSetter}),this.body.append(this.timeDiv),this.prevBtn.classList.add("primary"),this.nextBtn.classList.add("primary")}const i=document.createElement("div");i.classList.add("popup-centerer"),i.append(this.container),this.element.append(i),e.setHours(0,0,0,0),this.selectedDate=e,this.maxDate=s.maxDate||new Date,this.maxDate.setHours(0,0,0,0),this.selectedMonth=new Date(this.selectedDate),this.selectedMonth.setDate(1),this.maxMonth=new Date(this.maxDate),this.maxMonth.setDate(1),this.minMonth=new Date(this.minDate),this.minMonth.setHours(0,0,0,0),this.minMonth.setDate(1),this.selectedMonth.getTime()===this.minMonth.getTime()&&this.prevBtn.setAttribute("disabled","true"),this.selectedMonth.getTime()===this.maxMonth.getTime()&&this.nextBtn.setAttribute("disabled","true"),s.noTitle&&(this.setTitle=()=>{}),this.setTimeTitle(),this.setTitle(),this.setMonth()}setTimeTitle(){}setTitle(){this.title.replaceChildren(new Ne.IntlDateElement({date:this.selectedDate,options:{day:"numeric",month:"long",weekday:"short"}}).element)}renderElement(e,t=""){const s=document.createElement("button");return s.classList.add("btn-icon","date-picker-month-date"),e&&s.setAttribute("disabled","true"),t&&s.append(t),s}setMonth(){const e=new Date(this.selectedMonth),t={year:"numeric",month:this.timeDiv&&st.isMobile?"short":"long"};this.monthTitle.replaceChildren(new Ne.IntlDateElement({date:e,options:t}).element),this.month?.remove(),this.month=document.createElement("div"),this.month.classList.add("date-picker-month");const s=new Date,i=s.getDay();i!==1&&s.setHours(-24*(i-1));for(let c=0;c<7;++c){const d=this.renderElement(!0,new Ne.IntlDateElement({date:s,options:{weekday:"narrow"}}).element);d.classList.remove("date-picker-month-date"),d.classList.add("date-picker-month-day"),this.month.append(d),s.setDate(s.getDate()+1)}let n=e.getDay()-1;n===-1&&(n=6);const r=new Date(e.getTime());r.setDate(r.getDate()-n-1);for(let c=0;c<n;++c)this.options.showOverflowMonths?(r.setDate(r.getDate()+1),this.month.append(this.renderElement(!0,""+r.getDate()))):this.month.append(this.renderElement(!0));do{const c=e.getDate(),d=this.renderElement(e>this.maxDate||e<this.minDate,""+c);d.dataset.timestamp=""+e.getTime(),e.getTime()===this.selectedDate.getTime()&&(this.selectedEl=d,d.classList.add("active")),this.month.append(d),e.setDate(c+1)}while(e.getDate()!==1);const o=this.month.childElementCount%7;if(this.options.showOverflowMonths&&o)for(let c=o;c<7;++c)this.month.append(this.renderElement(!0,""+e.getDate())),e.setDate(e.getDate()+1);const l=Math.ceil(this.month.childElementCount/7);this.container.dataset.lines=""+l,this.monthsContainer.append(this.month)}}class kr extends Rs{constructor(e,t,s=["send_plain"],i){super({peerType:["dialogs","contacts"],onSelect:!e&&t?t:async(n,r)=>{if(t){const o=t(n);o instanceof Promise&&await o}if(n===I.myId){let o=0;for(const l in e){const c=e[l];o+=c.length,this.managers.appMessagesManager.forwardMessages({peerId:n,fromPeerId:l.toPeerId(),mids:c})}$e({langPackKey:o>0?"FwdMessagesToSavedMessages":"FwdMessageToSavedMessages"});return}await Ce.setInnerPeer({peerId:n,threadId:r}),Ce.chat.input.initMessagesForward(e)},placeholder:"ShareModal.Search.ForwardPlaceholder",chatRightsActions:s,selfPresence:"ChatYourSelf",useTopics:!i})}static async create(...e){const[t]=e,s=Object.keys(t).map(r=>t[r].map(l=>I.managers.appMessagesManager.getMessageByPeer(r.toPeerId(),l))),i=await Promise.all(va(s)),n=new Set;i.forEach(r=>{if(!r)return;const o=Vi(r);let l;if(!o)r.viaBotId?l="send_inline":l="send_plain";else if(o._==="webPage")l="embed_links";else if(o._==="photo")l="send_photos";else if(o._==="game")l="send_games";else switch(o.type){case"audio":l="send_audios";break;case"gif":l="send_gifs";break;case"round":l="send_roundvideos";break;case"sticker":l="send_stickers";break;case"voice":l="send_voices";break;case"video":l="send_videos";break;default:l="send_docs";break}l&&n.add(l)}),ue.createPopup(kr,e[0],e[1],Array.from(n))}}const Tf=(a,e={})=>{const t=e.monthAsNumber?".":" ",s=("0"+a.getHours()).slice(-2)+":"+("0"+a.getMinutes()).slice(-2)+(e.noSeconds?"":":"+("0"+a.getSeconds()).slice(-2)),i=a.getFullYear();return(e.leadingZero?("0"+a.getDate()).slice(-2):a.getDate())+t+(e.monthAsNumber?("0"+(a.getMonth()+1)).slice(-2):_L[a.getMonth()])+t+(""+i).slice(e.shortYear?2:0)+(e.noTime?"":", "+s)};class Og{constructor(e,t){this.className=e,this.fill=t,this.container=document.createElement("div"),this.container.className=e,this.border=document.createElement("div"),this.border.classList.add(e+"-border"),this.content=document.createElement("div"),this.content.classList.add(e+"-content"),this.title=document.createElement("div"),this.title.classList.add(e+"-title"),Xr(this.title),this.subtitle=document.createElement("div"),this.subtitle.classList.add(e+"-subtitle"),Xr(this.subtitle),this.content.append(this.title,this.subtitle),this.container.append(this.border,this.content)}}const lo=32;async function Eb(a){a.loadPromises||(a.loadPromises=[]);const{titleEl:e,subtitleEl:t,mediaEl:s,message:i,loadPromises:n,animationGroup:r,middleware:o,lazyLoadQueue:l,replyHeader:c}=a;let{storyItem:d,quote:u}=a,h=a.title;if(h!==void 0)typeof h=="string"&&(h=Ya(h,140),h=je(h)),St(e,h);else if(a.isStoryExpired){const y=Be("bomb","expired-story-icon");e.append(y,P("ExpiredStory"))}const p=c?._==="messageReplyHeader";p&&c.quote_text&&(u??(u={text:c.quote_text,entities:c.quote_entities}));let m=d?.media||i?.media||p&&c.reply_media;m?._==="messageMediaStory"&&(d=m.story,m=d?.media);let g=!1,f=!1;const v=s?Array.from(s.children).slice():[];if(m&&s){m=m.webpage||m;const y=m.photo,w=m.document;if(y||w&&w.thumbs?.length)if(w?.type==="sticker")await ai({doc:w,div:s,lazyLoadQueue:l||void 0,group:r,width:lo,height:lo,middleware:o,loadPromises:n}),g=!0;else if(w?.type==="gif"&&w.video_thumbs)g=!0,await Xa({doc:w,container:s,boxWidth:lo,boxHeight:lo,lazyLoadQueue:l||void 0,noPlayButton:!0,noInfo:!0,middleware:o,loadPromises:n,withoutPreloader:!0,videoSize:w.video_thumbs[0],group:r});else{const b=y||w;f=w?.type==="round";try{await Bi({photo:b,container:s,boxWidth:lo,boxHeight:lo,size:ha(b,lo,lo),middleware:o,lazyLoadQueue:l,noBlur:!0,withoutPreloader:!0,loadPromises:n}),g=!0}catch{}}}if(a.subtitle!==void 0){let y=a.subtitle;typeof y=="string"&&(y=Ya(y,140),y=je(y)),St(t,y||"")}else if(d&&a.storyItem)t.replaceChildren(P("Story"));else if(a.isStoryExpired){const y=Be("bomb","expired-story-icon");t.replaceChildren(y,P("ExpiredStory"))}else if(u){const y=jt(Ya(u.text,200),{...a,noLinebreaks:!0,entities:u.entities,noLinks:!0});t.replaceChildren(y)}else if(i){const y=await To(a);t.replaceChildren(y)}return Promise.all(n).then(()=>{o&&!o()||(v.forEach(y=>y.remove()),s&&s.classList.toggle("is-round",f))}),g}class g1 extends Og{constructor(e){super(e,async t=>{this.mediaEl||(this.mediaEl=document.createElement("div"),this.mediaEl.classList.add(this.className+"-media"));const s=await Eb({...t,titleEl:this.title,subtitleEl:this.subtitle,mediaEl:this.mediaEl});t.isStoryExpired&&this.container.classList.add("is-expired-story"),this.container.classList.toggle("is-media",s),s?this.content.prepend(this.mediaEl):this.mediaEl.remove()}),this.className=e}}async function kb({docId:a,middleware:e,useHighlightingColor:t,colorAsOut:s,container:i,color:n,positions:r,canvasWidth:o,canvasHeight:l,emojiSize:c,onCacheStatus:d}){let u;if(typeof a=="object")u=a;else{const p=await I.managers.acknowledged.appEmojiManager.getCustomEmojiDocument(a);p.cached||d?.(!1),u=await p.result}const h=document.createElement("div");return ai({doc:u,div:h,middleware:e,width:c,height:c,static:!0,withThumb:!1,exportLoad:2,useCache:!1}).then(({load:p,downloaded:m})=>(d?.(m),p())).then(p=>{const m=p[0];return m.naturalWidth?m:(console.warn("should wait for image size",m),ns(100).then(()=>m))}).then(p=>{const m=document.createElement("canvas");m.classList.add("emoji-pattern-canvas"),m.style.width=`${o}px`,m.style.height=`${l}px`;const g=m.getContext("2d"),f=m.dpr=window.devicePixelRatio;return m.width=o*f,m.height=l*f,r.forEach(([v,y,w,b])=>{g.globalAlpha=b,g.drawImage(p,v*f,y*f,w*f,w*f)}),g.globalAlpha=1,t?n="#ffffff":s&&(n=yi.getProperty("message-out-primary-color")),IL(g,n,0,0,m.width,m.height),i&&i.prepend(m),m}).catch(as)}function Hu(a){const e=new g1("reply"),t=e.fill(a);e.container.classList.add("quote-like","quote-like-hoverable","quote-like-border"),Xr(e.container),e.border.remove(),Ei(e.container,void 0,void 0,!0),a.isQuote&&(e.container.classList.add("quote-like-icon"),e.container.classList.add("reply-multiline")),a.noBorder&&e.container.classList.remove("quote-like-border");const{setColorPeerId:s}=a;if(s!==void 0){Ce.setPeerColorToElement({peerId:s,element:e.container,messageHighlighting:a.useHighlightingColor,colorAsOut:a.colorAsOut});const i=Ae.getPeer(s),n=i?.color?.background_emoji_id;n&&kb({docId:n,container:e.container,middleware:a.middleware,color:jC(i)[0],colorAsOut:a.colorAsOut,useHighlightingColor:a.useHighlightingColor,positions:[[104.5,34.5,12,.35],[9.3,33.3,10.4,.2],[51.3,.3,10.4,.2],[.6,7.6,12.8,.1],[28.9,12.9,15.2,.2],[65.5,18.5,12,.25],[48.9,37.9,15.2,.25],[91.9,7.9,15.2,.3]],canvasWidth:117,canvasHeight:54,emojiSize:16}).then(r=>{a.middleware&&!a.middleware()||r.classList.add("reply-background-canvas")})}return{container:e.container,fillPromise:t}}const f1="stacked-avatars",v1=f1+"-avatar",h2=v1+"-container";class Zl{constructor(e){this.lazyLoadQueue=e.lazyLoadQueue,this.avatarSize=e.avatarSize,this.middlewareHelper=e.middleware.create(),this.container=document.createElement("div"),this.container.classList.add(f1),this.container.style.setProperty("--avatar-size",e.avatarSize+"px")}render(e,t=[]){const s=this.container.children;return e=e.slice().reverse(),e.length>3&&(e=e.slice(-3)),e.forEach((i,n)=>{let r=s[n];r?r.middlewareHelper.clean():(r=document.createElement("div"),r.classList.add(h2),r.middlewareHelper=this.middlewareHelper.get().create());const o=vs({middleware:r.middlewareHelper.get(),size:this.avatarSize,isDialog:!1,lazyLoadQueue:this.lazyLoadQueue,peerId:i});o.node.classList.add(v1),t?.push(o.readyThumbPromise),r.replaceChildren(o.node),r.parentNode||this.container.append(r),r.classList.toggle("is-first",n===0)}),Array.from(s).slice(e.length).forEach(i=>{i.middlewareHelper.destroy(),i.remove()}),Promise.all(t)}}const y1="replies-element";I.addEventListener("replies_updated",a=>{Array.from(document.querySelectorAll(y1+`[data-post-key="${a.peerId}_${a.mid}"]`)).forEach(e=>{e.message=a,e.render()})});class b1 extends HTMLElement{constructor(){super(),this.updated=!1,this.managers=I.managers}init(){this.render(),this.dataset.postKey=this.message.peerId+"_"+this.message.mid,this.classList.add("replies","replies-"+this.type)}render(){const e=this.message.replies;if(this.type==="footer"){let t;this.firstElementChild&&(t=this.firstElementChild),e?.recent_repliers?(t&&!t.classList.contains("replies-footer-avatars")&&(this.replaceChildren(),t=null),this.stackedAvatars||(this.stackedAvatars=new Zl({lazyLoadQueue:this.lazyLoadQueue,avatarSize:30,middleware:this.middlewareHelper.get()}),this.stackedAvatars.container.classList.add("replies-footer-avatars")),t=this.stackedAvatars.container,this.stackedAvatars.render(e.recent_repliers.map(n=>it(n)),this.loadPromises)):(t&&!t.classList.contains(zr("comments"))&&(t.remove(),t=null),t||(t=Be("comments","replies-footer-icon","replies-footer-icon-comments"))),t.parentElement||this.prepend(t),this.text||(this.text=new Ne.IntlElement);const s=this.text;if(e?e.replies?s.compareAndUpdate({key:"Comments",args:[e.replies]}):s.compareAndUpdate({key:"LeaveAComment"}):s.compareAndUpdate({key:"ViewInChat"}),e){let n=!1;e.replies&&e.read_max_id!==void 0&&e.max_id!==void 0&&(n=e.read_max_id<e.max_id),this.classList.toggle("is-unread",n)}let i=this.children[1];if(!i){i=document.createElement("span"),i.classList.add("replies-footer-text");const n=Be("next","replies-footer-icon","replies-footer-icon-next"),r=document.createElement("div");Ei(r),this.append(i,n,r)}St(i,s.element)}else this.classList.add("bubble-beside-button"),this.innerHTML=`<span class="replies-beside-text">${e?.replies?un(e.replies,0):""}</span>`,this.prepend(Be("commentssticker"));e&&!this.updated&&!this.message.pFlags.is_outgoing&&(this.managers.appMessagesManager.subscribeRepliesThread(this.message.peerId,this.message.mid),this.managers.appMessagesManager.updateMessage(this.message.peerId,this.message.mid,"replies_updated"),this.updated=!0),this.loadPromises&&(this.loadPromises=void 0)}}customElements.define(y1,b1);const u2=" ",LS=()=>{const a=document.createElement("i");return a.classList.add("time-edited","time-part"),ks(a,"EditedMessage"),a},ES=(a,e)=>e?OC(a.getTime()/1e3|0,{combined:!0}).dateEl:Ny(a),kS=a=>{const e=document.createElement("span");if(e.classList.add("time-effect"),a.onlyElement)return e;const t=Mt();return e.dataset.effectId=""+a.docId,I.managers.acknowledged.appReactionsManager.getAvailableEffect(a.docId).then(async s=>{s.cached||t.resolve();const i=await s.result;if(!i){t.resolve();return}const n=[];ai({doc:await I.managers.appDocsManager.getDoc(i.static_icon_id),div:e,middleware:a.middleware,loadPromises:n,width:12,height:12}),Promise.all(n).then(async()=>{s.cached&&t.resolve();const{doc:r,thumb:o}=await w1(i);fs.downloadMedia({media:r,thumb:o})})}),a.loadPromises?.push(t),e},w1=async a=>{const e=!a.effect_animation_id,t=await I.managers.appDocsManager.getDoc(e?a.effect_sticker_id:a.effect_animation_id);return{isPremiumEffect:e,doc:t,thumb:ql(t)}},S1=({e:a,isOut:e,element:t,middleware:s,scrollable:i,effectId:n})=>{if(t.dataset.playing){a&&_e(a);return}t.dataset.playing="1",I.managers.appReactionsManager.getAvailableEffect(n).then(async r=>{const{doc:o,thumb:l}=await w1(r);if(!s())return;const{animationDiv:c}=Dh({doc:o,middleware:s,side:e?"right":"left",size:240,target:t,play:!0,scrollable:i,fullThumb:ql(o),addOffsetX:40,onUnmount:()=>{delete t.dataset.playing}});e===!1&&c.classList.add("reflect-x")}),a&&_e(a)},p2=({timeEffect:a,bubble:e,e:t,scrollable:s})=>{const i=a.dataset.effectId;return S1({element:a,isOut:e.classList.contains("is-out"),e:t,scrollable:s,effectId:i,middleware:e.middlewareHelper.get()})};var bc;(a=>{a.setTime=e=>{const{chatType:t,message:s,groupedMessagesCount:i}=e,n=!("action"in s),r=s.peerId===I.myId&&!e.isOut,o=[];let l=s.date;r&&n&&s.fwd_from&&(l=s.fwd_from.saved_date||s.fwd_from.date||l);const c=new Date(l*1e3);let d,u;const h=n&&s.fwd_from,p=ES(c,r);if(n){if(s.views){const w=document.createElement("span");w.classList.add("post-views"),w.textContent=un(s.views,1);const b=Be("channelviews","time-icon","time-part","time-icon-views");o.push(w,b)}const y=e.chat.getPostAuthor(s);if(y){const w=document.createElement("span");w.classList.add("time-post-author"),Qt(w,je(y)),w.insertAdjacentHTML("beforeend",'<span class="time-post-author-comma">,'+u2+"</span>"),o.push(w)}if(s.edit_date&&t!==we.Scheduled&&!s.pFlags.edit_hide&&o.unshift(d=LS()),t!==we.Pinned&&s.pFlags.pinned){const w=Be("pinnedchat","time-icon","time-pinned","time-part");o.unshift(w)}if(s.effect&&(u=kS({onlyElement:!0}),o.push(u)),s.paid_message_stars&&e.chat.isAnyGroup){const w=document.createElement("span");w.classList.add("inline-message-stars"),w.append(Jr(+s.paid_message_stars*Math.max(i||0,1)),Be("star")),o.push(w)}}p&&o.push(p);let m=Tf(new Date(s.date*1e3));n&&(m+=(s.edit_date&&!s.pFlags.edit_hide?`
- Edited: ${Tf(new Date(s.edit_date*1e3))}`:"")+(h?`
- Original: ${Tf(new Date(h.saved_date||h.date*1e3))}`:""));const g=document.createElement("span");g.classList.add("time"),g.append(...o);const f=document.createElement("div");f.classList.add("time-inner"),m&&(f.title=m);let v=o;return d&&(v[v.indexOf(d)]=LS()),u&&(v[v.indexOf(u)]=kS({docId:s.effect,middleware:e.middleware,loadPromises:e.loadPromises})),v=v.map(y=>y instanceof HTMLElement&&!y.classList.contains("i18n")&&!y.classList.contains("reactions")&&!y.classList.contains("time-effect")?y.cloneNode(!0):y),p&&(v[v.length-1]=ES(c,r)),f.append(...v),g.append(f),g},a.renderReplies=({bubble:e,bubbleContainer:t,message:s,messageDiv:i,loadPromises:n,lazyLoadQueue:r,middleware:o})=>{const l=!e.classList.contains("sticker")&&!e.classList.contains("emoji-big")&&!e.classList.contains("round"),c=new b1;return c.message=s,c.type=l?"footer":"beside",c.loadPromises=n,c.lazyLoadQueue=r,c.middlewareHelper=o.create(),c.init(),t.append(c),l},a.setReply=async({chat:e,bubble:t,bubbleContainer:s,message:i,appendCallback:n,middleware:r,lazyLoadQueue:o,needUpdate:l,isStandaloneMedia:c,isOut:d,fromUpdate:u})=>{const h=!s;h&&(s=t.querySelector(".bubble-content"));const p=h?s.querySelector(".reply"):null,m=i.reply_to;if(!m){p?.remove(),t.classList.remove("is-reply");return}const g=m._==="messageReplyStoryHeader",f=g?it(m.peer):m.reply_to_peer_id?it(m.reply_to_peer_id):i.peerId,v=!g&&Ae.getMessageByPeer(f,i.reply_to_mid),y=g&&await I.managers.acknowledged.appStoriesManager.getStoryById(f,m.story_id);let w,b=!1,S,_,M;if(u||(g?l.push(M={replyToPeerId:f,replyStoryId:m.story_id,mid:i.mid,peerId:i.peerId}):l.push(M={replyToPeerId:f,replyMid:i.reply_to_mid,mid:i.mid,peerId:i.peerId}),r.onClean(()=>{Vs(l,M)})),g)y.cached?(S=f,w=new Xt({peerId:S,dialog:!1,onlyFirstName:!1,plainText:!1}).element):(I.managers.appMessagesManager.fetchMessageReplyTo(i),w=P("Loading"));else if(!v)m.reply_from?(b=!0,S=it(m.reply_from?.from_id||m.reply_to_peer_id),w=new Xt({peerId:S||void 0,dialog:!1,onlyFirstName:!1,plainText:!1,fromName:Aa(m.reply_from)}).element):(I.managers.appMessagesManager.fetchMessageReplyTo(i),w=P("Loading"));else{b=!!m.reply_from;const x=v.fwdFromId;S=i.fwdFromId&&i.fwdFromId===x?i.fwdFromId:x||v.fromId,_=i.fwdFromId&&i.fwdFromId===x?void 0:v.fromId,w=new Xt({peerId:S,dialog:!1,onlyFirstName:!1,plainText:!1,fromName:S?void 0:Aa(v.fwd_from)}).element}if(!g&&m.reply_from){const x=document.createDocumentFragment();let R;if(m.reply_from.channel_post)x.append(R=Be("newchannel_filled","with-margin"),w);else if(m.reply_to_peer_id){const B=new Xt({peerId:it(m.reply_to_peer_id),dialog:!1,onlyFirstName:!1,plainText:!1}).element;x.append(w," ",R=Be("group_filled")," ",B)}else x.append(R=Be("newprivate_filled","with-margin"),w);R&&(R.classList.add("inline-icon","reply-title-icon"),w=x)}const C=g&&y.cached&&!await y.result,{container:L,fillPromise:E}=Hu({title:w,animationGroup:e.animationGroup,message:v||(b?{_:"message",pFlags:{},id:0,date:0,message:"",peer_id:void 0,media:m.reply_media}:void 0),isStoryExpired:C,storyItem:y?.cached&&await y.result,setColorPeerId:_||S,textColor:"primary-text-color",isQuote:g?void 0:m.pFlags.quote,middleware:r,lazyLoadQueue:o,replyHeader:m,useHighlightingColor:c,colorAsOut:d,canTranslate:v&&!b?!v.pFlags.out:void 0});if(await E,p){const x=["floating-part","mb-shorter"],R=p.classList;x.forEach(B=>{R.contains(B)&&L.classList.add(B)}),p.replaceWith(L)}else n(L);return t.classList.add("is-reply"),L}})(bc||(bc={}));class TS extends Zt{async init(e){this.container.id="poll-results-container",this.container.classList.add("chatlist-container"),this.resultsDiv=document.createElement("div"),this.resultsDiv.classList.add("poll-results"),this.scrollable.append(this.resultsDiv);const t=await this.managers.appPollsManager.getPoll(e.media.poll.id);this.setTitle(t.poll.pFlags.quiz?"PollResults.Title.Quiz":"PollResults.Title.Poll");const s=document.createElement("h3"),i=Yc(t.poll.question);Qt(s,jt(i.text,{entities:i.entities,middleware:this.middlewareHelper.get()}));const n=t.results.results.map(o=>o.voters/t.results.total_voters*100);_1(n);const r=document.createDocumentFragment();t.results.results.forEach((o,l)=>{if(!o.voters)return;const c=document.createElement("hr"),d=t.poll.answers[l],u=document.createElement("div");u.classList.add("poll-results-answer");const h=document.createElement("div"),p=Yc(d.text);Qt(h,jt(p.text,{entities:p.entities,middleware:this.middlewareHelper.get()}));const m=document.createElement("div");m.innerText=Math.round(n[l])+"%",u.append(h,m);const g=nt.createChatList();g.classList.add("poll-results-voters"),nt.setListClickListener({list:g,onFound:()=>{Gs.onCloseBtnClick()},withContext:void 0,autonomous:!0}),g.style.minHeight=Math.min(o.voters,4)*48+"px",r.append(c,u,g);let f,v=4,y=!1,w=Math.max(0,o.voters-4);const b=()=>{y||(y=!0,this.managers.appPollsManager.getVotes(e,d.option,f,v).then(_=>{_.votes.forEach(M=>{const{dom:C}=nt.addDialogNew({peerId:it(M.peer),container:g,rippleEnabled:!1,meAsSaved:!1,avatarSize:"small",withStories:!1,wrapOptions:{middleware:this.middlewareHelper.get()}});C.lastMessageSpan.parentElement.remove()}),f&&(w=Math.max(0,w-_.votes.length),w&&S.lastElementChild.replaceWith(P("PollResults.LoadMore",[Math.min(20,w)]))),f=_.next_offset,v=20,(!w||!_.votes.length)&&S.remove()}).finally(()=>{y=!1}))},S=ot("poll-results-more btn btn-primary btn-transparent",{icon:"down"});S.addEventListener("click",b),S.append(P("PollResults.LoadMore",[Math.min(20,w)])),r.append(S),b()}),this.resultsDiv.append(s,r),Gs.toggleSidebar(!0).then(()=>{})}}const m2=Y('<div><div class="tooltip-part tooltip-background"></div><span class="tooltip-part tooltip-notch"></span><div class="tooltip-part tooltip-text">'),g2=Y("<div>"),f2=Y("<div class=tooltip-subtitle>"),v2=Y('<div class="tooltip-part tooltip-right">'),xf=new Tg(void 0,!0);function Ra({element:a,class:e,container:t=a.parentElement,vertical:s,textElement:i,subtitleElement:n,paddingX:r=0,offsetY:o=0,centerVertically:l,onClose:c,icon:d,auto:u,mountOn:h=document.body,relative:p,lighter:m,rightElement:g}){const f=!p&&t.getBoundingClientRect(),v=!p&&a.getBoundingClientRect(),y=h===document.body;let w;return Ft(b=>{const[S,_]=K(),M=()=>{const B={"max-width":Math.min(f.width-r*2,320)+"px"},N=S();if(!N)return B;const G=Math.min(f.left+r,f.right),O=Math.max(f.left,f.right-Math.min(f.width,N.width)-r),$=v.left+(v.width-N.width)/2,H=zt($,G,O),D=12;s==="top"?B.top=(l?v.top+v.height/2:v.top)-N.height-D+o+"px":B.top=v.bottom+D+"px",B.left=H+"px";const U=v.left+(v.width-19)/2;return B["--notch-offset"]=U-H+"px",B};let C;const L=(()=>{const B=m2(),N=B.firstChild,G=N.nextSibling,O=G.nextSibling,$=C;return typeof $=="function"?Ue($,B):C=B,k(O,d&&T(hs,{icon:d,class:"tooltip-icon"}),null),k(O,n?[(()=>{const H=g2();return k(H,i),H})(),(()=>{const H=f2();return k(H,n),H})()]:i,null),k(B,g&&(()=>{const H=v2();return k(H,g),H})(),null),Me(H=>{const D=Ge("tooltip","tooltip-"+s,d&&"tooltip-with-icon",e,m&&"tooltip-lighter"),U=!p&&M();return D!==H._v$&&be(B,H._v$=D),H._v$2=Ii(B,U,H._v$2),H},{_v$:void 0,_v$2:void 0}),B})();T(gd,{mount:h,children:L}),Jt(()=>{!p&&_(C.getBoundingClientRect()),C.classList.add("mounted"),Dt({element:C,className:"is-visible",duration:200,useRafs:2,forwards:!0})});let E=!1;const x=B=>{B||(E=!0,clearTimeout(R),Dt({element:C,className:"is-visible",duration:200,forwards:!1,onTransitionEnd:()=>{c?.(),b()}}))};w=()=>{E||(y?xf.close():x(!1))};const R=u?window.setTimeout(w,3e3):0;y&&Promise.resolve().then(()=>{xf.open(h),xf.addEventListener("toggle",x,{once:!0})})}),{close:w}}let xS=0;const y2=9,hc=10,C1=340,AS=C1/hc,_1=a=>{const e=a.reduce((t,s)=>t+Math.round(s),0);if(e>100){const t=e-100,s=a.length;for(let i=0;i<t;++i){let n=-1,r=1;for(let o=0;o<s;++o){const l=a[o]%1;l>=.5&&l<r&&(r=l,n=o)}if(n===-1)return;a[n]-=r}}else if(e<100){const t=100-e,s=a.length;for(let i=0;i<t;++i){let n=-1,r=0;for(let o=0;o<s;++o){const l=a[o]%1;l<.5&&l>r&&(r=l,n=o)}if(n===-1)return;a[n]+=1-r}}};I.addEventListener("poll_update",({poll:a,results:e})=>{Array.from(document.querySelectorAll(`poll-element[poll-id="${a.id}"]`)).forEach(s=>{s._poll=a,s._results=e,s.isClosed=!!a.pFlags.closed,s.performResults(e,a.chosenIndexes)})});st.addEventListener("resize",()=>{$l.setMaxLength(),$l.resizePolls()});st.addEventListener("changeScreen",()=>{$l.setMaxLength()});const Af=(a,e,t)=>{a.classList.remove("active"),clearTimeout(t),setTimeout(()=>{e?.(),a.remove(),vo===a&&ph===e&&mh===t&&(vo=ph=null,mh=0)},200)};let vo,ph,mh,RS=!1;const Gu=a=>{vo&&Af(vo,ph,mh);const e=document.createElement("div");e.classList.add("quiz-hint","from-"+a.from),a.class&&e.classList.add(a.class);const t=document.createElement("div");t.classList.add("quiz-hint-container");let s;a.title&&(s=document.createElement("div"),s.classList.add("quiz-hint-title"),s.append(a.title),t.classList.add("has-title"));const i=document.createElement("div");i.classList.add("quiz-hint-text");let n;a.textRight&&(n=document.createElement("div"),n.classList.add("quiz-hint-text-right"),n.append(a.textRight),t.classList.add("has-right-text")),t.append(...[a.icon&&Be(a.icon,"quiz-hint-icon"),s,i,n].filter(Boolean)),e.append(t),Qt(i,a.textElement),a.appendTo.append(e),e.offsetLeft,e.classList.add("active");const r=()=>{Af(e,a.onHide,o)};vo=e,ph=a.onHide;const o=mh=a.duration&&window.setTimeout(r,a.duration);return a.canCloseOnPeerChange??(a.canCloseOnPeerChange=!0),a.canCloseOnPeerChange||(e.dataset.dontCloseOnPeerChange="1"),RS||(RS=!0,Ce.addEventListener("peer_changed",()=>{vo&&vo.dataset.dontCloseOnPeerChange!=="1"&&Af(vo,ph,mh)})),{hide:r}},vl=class vl extends HTMLElement{constructor(){super(...arguments),this.isClosed=!1,this.isQuiz=!1,this.isRetracted=!1,this.isPublic=!1,this.isMultiple=!1,this.chosenIndexes=[],this.chosingIndexes=[],this.sentVote=!1,this.clickHandler=e=>{const t=ne(e.target,"poll-answer");if(!t)return;_e(e);const s=+t.dataset.index;if(!this.canVote){const n=this.results.results[s];Ra({element:t,container:t.parentElement,vertical:"top",textElement:P("Chat.Poll.TotalVotes1",[n.voters]),offsetY:12,auto:!0});return}if(this.isMultiple){t.classList.toggle("is-chosing");const i=this.chosingIndexes.indexOf(s);i!==-1?this.chosingIndexes.splice(i,1):this.chosingIndexes.push(s)}else this.sendVotes([s])}}static setMaxLength(){const e=It.width<=360?It.width-120:st.active.poll.width;this.MAX_LENGTH=e+y2+this.MAX_OFFSET+-13.7}static resizePolls(){if(!this.MAX_LENGTH)return;Array.from(document.querySelectorAll("poll-element.is-voted")).forEach(t=>{t.svgLines.forEach((s,i)=>{t.setLineProgress(i,1)})})}async render(){this.listenerSetter=new $t,this.middlewareHelper.get().onClean(()=>{this.listenerSetter.removeAll()}),xS||(xS=document.getElementById("poll-line").getTotalLength(),vl.setMaxLength());const{poll:e,results:t}=this;this.message.pFlags.is_scheduled&&this.classList.add("disable-hover");let s;e.pFlags&&(this.isPublic=!!e.pFlags.public_voters,this.isQuiz=!!e.pFlags.quiz,this.isClosed=!!e.pFlags.closed,this.isMultiple=!!e.pFlags.multiple_choice,this.isClosed?(s="Chat.Poll.Type.Closed",this.classList.add("is-closed")):this.isQuiz?s=this.isPublic?"Chat.Poll.Type.Quiz":"Chat.Poll.Type.AnonymousQuiz":s=this.isPublic?"Chat.Poll.Type.Public":"Chat.Poll.Type.Anonymous"),this.classList.toggle("is-multiple",this.isMultiple);const i=e.answers.map((o,l)=>{const c=`
- <div class="poll-answer" data-index="${l}">
- <div class="circle-hover">
- <div class="animation-ring"></div>
- <svg class="progress-ring">
- <circle class="progress-ring__circle" cx="13" cy="13" r="9"></circle>
- </svg>
- </div>
- <div class="poll-answer-percents"></div>
- <div class="poll-answer-text"></div>
- <svg version="1.1" class="poll-line" style="display: none;" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 485.9 35" xml:space="preserve">
- <use href="#poll-line"></use>
- </svg>
- </div>
- `,d=$u(c);if(this.isMultiple){const h=document.createElement("span");h.classList.add("poll-answer-selected"),h.append(Be("check")),d.firstElementChild.firstElementChild.append(h)}const u=document.createElement("span");return u.classList.add("poll-answer-selected"),d.firstElementChild.append(u),d});if(this.innerHTML=`
- <div class="poll-title"></div>
- <div class="poll-desc">
- <div class="poll-type"></div>
- <div class="poll-avatars"></div>
- </div>
- `,this.append(...i),Qt(this.firstElementChild,this.wrapSomeText(e.question)),Array.from(this.querySelectorAll(".poll-answer-text")).forEach((o,l)=>{const c=this.wrapSomeText(e.answers[l].text);Qt(o,c)}),this.descDiv=this.firstElementChild.nextElementSibling,this.typeDiv=this.descDiv.firstElementChild,this.avatarsDiv=this.descDiv.lastElementChild,s&&this.typeDiv.append(P(s)),this.isQuiz&&(this.classList.add("is-quiz"),e.close_period&&e.close_date)){const o=document.createElement("div");o.classList.add("poll-time"),this.descDiv.append(o);const l=document.createElementNS("http://www.w3.org/2000/svg","svg");l.classList.add("poll-quiz-timer"),this.quizTimer=l;const c=2,d=7,u=2*Math.PI*d,h=document.createElementNS("http://www.w3.org/2000/svg","circle");h.classList.add("poll-quiz-timer-circle"),h.setAttributeNS(null,"cx","16"),h.setAttributeNS(null,"cy","16"),h.setAttributeNS(null,"r",""+d),h.setAttributeNS(null,"stroke-width",""+c),l.append(h),this.descDiv.append(l);const p=e.close_period*1e3,m=(e.close_date-await I.managers.timeManager.getServerTimeOffset())*1e3;this.quizInterval=window.setInterval(()=>{const g=Date.now(),f=(m-g)/p,v=(m-g)/1e3+1|0;o.textContent=bn(v),v<=5&&(o.style.color="#ee545c",h.style.stroke="#ee545c"),h.style.strokeDashoffset=u+f*u,h.style.strokeDasharray=`${u} ${u}`,g>=m&&(clearInterval(this.quizInterval),o.replaceChildren(),h.style.strokeDashoffset=u,this.quizInterval=0,setTimeout(()=>{this.managers.appPollsManager.getResults(this.message)},3e3))},1e3)}this.answerDivs=Array.from(this.querySelectorAll(".poll-answer")),this.svgLines=Array.from(this.querySelectorAll(".poll-line")),this.numberDivs=Array.from(this.querySelectorAll(".poll-answer-percents"));const n=document.createElement("div");n.classList.add("poll-footer"),this.viewResults=document.createElement("div"),this.viewResults.className="poll-footer-button poll-view-results hide",this.viewResults.append(P("Chat.Poll.ViewResults")),this.votersCountDiv=document.createElement("div"),this.votersCountDiv.className="poll-votes-count",n.append(this.viewResults,this.votersCountDiv),this.append(n),J(this.viewResults,o=>{_e(o),Gs.isTabExists(TS)||Gs.createTab(TS).open(this.message)},{listenerSetter:this.listenerSetter}),Ei(this.viewResults),this.isMultiple&&(this.sendVoteBtn=document.createElement("div"),this.sendVoteBtn.classList.add("poll-footer-button","poll-send-vote"),this.sendVoteBtn.append(P("Chat.Poll.SubmitVote")),Ei(this.sendVoteBtn),e.chosenIndexes.length||this.votersCountDiv.classList.add("hide"),J(this.sendVoteBtn,o=>{_e(o),this.chosingIndexes.length&&this.sendVotes(this.chosingIndexes).then(()=>{this.chosingIndexes.length=0,this.answerDivs.forEach(l=>{l.classList.remove("is-chosing")})})},{listenerSetter:this.listenerSetter}),n.append(this.sendVoteBtn));const{canVote:r}=this;(!r||this.isPublic)&&this.performResults(t,e.chosenIndexes,!1),r&&this.setVotersCount(t),J(this,this.clickHandler,{listenerSetter:this.listenerSetter})}get poll(){return this._poll||this.message.media.poll}get results(){return this._results||this.message.media.results}get canVote(){return!(this.poll.chosenIndexes.length||this.isClosed)}wrapSomeText(e,t,s=this.middlewareHelper.get()){return typeof e!="string"&&(t=e.entities,e=e.text),this.translatableParams?Nu({...this.translatableParams,middleware:s,textWithEntities:{_:"textWithEntities",text:e,entities:t}}):jt(e,{...this.richTextOptions,entities:t})}initQuizHint(e){if(e.solution&&e.solution_entities){const t=document.createElement("div");if(t.classList.add("poll-hint"),t.append(Be("tip")),this.descDiv.append(t),J(t,s=>{_e(s),t.classList.add("active");const i=Ht();Gu({textElement:this.wrapSomeText(e.solution,e.solution_entities,i.get()),appendTo:Ce.chat.bubbles.container,from:"top",duration:pt?5e3:7e3,icon:"info2",onHide:()=>{i.destroy(),t.classList.remove("active")}})},{listenerSetter:this.listenerSetter}),this.sentVote){const s=e.results.find(i=>i.pFlags.correct);s&&!s.pFlags.chosen&&Xs(t)}}}sendVotes(e){if(this.sendVotePromise)return this.sendVotePromise;const t=this.answerDivs.filter((s,i)=>e.includes(i));return t.forEach(s=>{s.classList.add("is-voting")}),this.classList.add("disable-hover"),this.sentVote=!0,this.sendVotePromise=this.managers.appPollsManager.sendVote(this.message,e).then(()=>{t.forEach(s=>{s.classList.remove("is-voting")}),this.classList.remove("disable-hover")}).catch(()=>{this.sentVote=!1}).finally(()=>{this.sendVotePromise=null})}performResults(e,t,s=!0){if(wt.isAvailable("animations")||(s=!1),this.isQuiz&&(e.results?.length||this.isClosed)&&(this.answerDivs.forEach((n,r)=>{const l=!!e.results[r].pFlags.correct;n.classList.toggle("is-correct",l)}),this.initQuizHint&&(this.initQuizHint(e),this.initQuizHint=null),this.quizInterval&&(clearInterval(this.quizInterval),this.quizInterval=0),this.quizTimer?.parentElement&&this.quizTimer.remove(),this.descDiv.querySelector(".poll-time")?.remove()),this.isClosed&&(this.classList.add("is-closed"),St(this.typeDiv,P("Chat.Poll.Type.Closed"))),(this.chosenIndexes.length!==t.length||this.isClosed)&&(this.isRetracted=this.chosenIndexes.length&&!t.length,this.chosenIndexes=t.slice()),this.chosenIndexes.length||this.isRetracted||this.isClosed){const i=e.results.map(n=>e.total_voters?n.voters/e.total_voters*100:0);this.classList.toggle("no-transition",!s),s&&Dt({element:this,className:"",forwards:!this.isRetracted,duration:340}),$s(()=>{this.setResults(this.isRetracted?this.percents:i,this.chosenIndexes,s),this.percents=i,this.isRetracted=!1})}if(this.setVotersCount(e),this.isPublic){this.isMultiple||(this.viewResults.classList.toggle("hide",!e.total_voters||!this.chosenIndexes.length),this.votersCountDiv.classList.toggle("hide",!!this.chosenIndexes.length));const i=(e.recent_voters||[]).map(r=>it(r)),n=new Zl({avatarSize:16,middleware:this.middlewareHelper.get()});n.render(i),St(this.avatarsDiv,n.container)}if(this.isMultiple){const i=!!this.chosenIndexes.length,n=this.isClosed||i,r=!this.isPublic||!e.total_voters||!i&&!this.isClosed;this.sendVoteBtn.classList.toggle("hide",n),this.viewResults.classList.toggle("hide",r),this.votersCountDiv.classList.toggle("hide",!n||!r)}}setResults(e,t,s){this.svgLines.forEach(o=>o.style.display=""),this.answerDivs.forEach((o,l)=>{const c=t.includes(l);o.classList.toggle("is-chosen",c);const d=o.lastElementChild;let u;o.classList.contains("is-correct")||!this.isQuiz&&c?u=Be("check"):c&&(u=Be("close")),d.replaceChildren(u)});const i=Math.max(...e);if(this.maxPercents=e.map(o=>o/i),this.isRetracted)this.svgLines.forEach((o,l)=>{this.setLineProgress(l,-1)});else{const o=()=>{this.svgLines.forEach((l,c)=>{this.setLineProgress(c,1)})};s?$s(o):o()}e=e.slice(),_1(e);let n;const r=o=>{e.forEach((l,c)=>{const d=n(l,o);this.numberDivs[c].innerText=d+"%"})};if(this.isRetracted)if(n=(o,l)=>Math.round(o/hc*l),s)for(let o=hc-1,l=0;o>=0;--o,++l)setTimeout(()=>{r(o)},AS*l);else r(0);else if(n=(o,l)=>Math.round(o/hc*(l+1)),s)for(let o=0;o<hc;++o)setTimeout(()=>{r(o)},AS*o);else r(hc-1);if(this.isRetracted){s&&this.classList.add("is-retracting"),this.classList.remove("is-voted");const o=()=>{this.svgLines.forEach(l=>l.style.display="none")};s?setTimeout(()=>{this.classList.remove("is-retracting"),o()},C1):o()}else this.classList.add("is-voted")}setVotersCount(e){const t=e.total_voters||0;let s;const i=[t];this.isClosed?this.isQuiz?s=t?"Chat.Quiz.TotalVotes":"Chat.Quiz.TotalVotesResultEmpty":s=t?"Chat.Poll.TotalVotes1":"Chat.Poll.TotalVotesResultEmpty":this.isQuiz?s=t?"Chat.Quiz.TotalVotes":"Chat.Quiz.TotalVotesEmpty":s=t?"Chat.Poll.TotalVotes1":"Chat.Poll.TotalVotesEmpty",St(this.votersCountDiv,P(s,i))}setLineProgress(e,t){const s=this.svgLines[e];t===-1?(s.style.strokeDasharray="",s.style.strokeDashoffset=""):(s.style.strokeDasharray=t*this.maxPercents[e]*vl.MAX_LENGTH+", 485.9",s.style.strokeDashoffset=""+t*vl.MAX_OFFSET)}};vl.MAX_OFFSET=-46.5,vl.MAX_LENGTH=0;let $l=vl;customElements.define("poll-element",$l);function b2(a,e){const t=a.length;if(t!==e.length){const i=t-e.length;return i<0?-1:i>0?1:0}const s=15;for(let i=0;i<t;i+=s){const n=+a.slice(i,i+s),r=+e.slice(i,i+s),o=n-r;if(o)return o}return 0}function w2(a,e){if(a.toExponential){const t=a-e;return t<0?-1:t>0?1:0}return b2(a,e)}var uc=(a=>(a[a.None=0]="None",a[a.Top=1]="Top",a[a.Bottom=2]="Bottom",a[a.Both=3]="Both",a))(uc||{});class ed{constructor(){this.sliceConstructor=ed.getSliceConstructor(this),this.compareValue??(this.compareValue=w2);const e=this.constructSlice();this.slices=[e]}static getSliceConstructor(e){return class extends Array{constructor(){super(...arguments),this.end=0}isEnd(s){if((this.end&s)===s)return!0;let i=!1;if(s===1){const n=e.last;i=n.end&s?this.includes(n[n.length-1]):!1}else if(s===2){const n=e.first;i=n.end&s?this.includes(n[0]):!1}else if(s===3)return this.isEnd(1)&&this.isEnd(2);return i&&this.setEnd(s),i}getEnds(){return{top:this.isEnd(1),bottom:this.isEnd(2),both:this.isEnd(3)}}setEnd(s){this.end|=s}unsetEnd(s){this.end&=~s}splice(s,i,...n){const r=super.splice(s,i,...n);if(!this.length){const o=e.slices,l=o.indexOf(this);l!==-1&&(o.length===1?this.unsetEnd(3):o.splice(l,1))}return r}}}constructSlice(...e){const t=new this.sliceConstructor(e.length);for(let s=0,i=e.length;s<i;++s)t[s]=e[s];return t}insertSlice(e,t=!0){if(!e.length)return;const s=this.slices[0];if(!s.length)return s.push(...e),s;const i=e[e.length-1],n=e[0];let r,o=-1,l=-1,c=0;for(;c<this.slices.length&&(r=this.slices[c],o=r.indexOf(i),l=r.indexOf(n),!(l!==-1&&o!==-1));++c)if(l!==-1||o!==-1)break;if(!(l!==-1&&o!==-1))if(l!==-1){const d=e.slice(r.length-l);r.push(...d)}else if(o!==-1){const d=e.slice(0,e.length-o-1);r.unshift(...d)}else{let d=0;for(const u=this.slices.length;d<u;++d){const h=this.slices[d];if(this.compareValue(e[0],h[0])===1)break}this.slices.splice(d,0,this.constructSlice(...e)),c=d}if(t)return this.flatten(c)}flatten(e){if(this.slices.length>=2)for(let t=0,s=this.slices.length;t<s-1;++t){const i=this.slices[t],n=this.slices[t+1];i.indexOf(n[0])!==-1&&(i.setEnd(n.end),this.slices.splice(t+1,1),t<e&&--e,--s,--t,this.insertSlice(n,!1))}return this.slices[e]}get first(){return this.slices[0]}get last(){return this.slices[this.slices.length-1]}get slice(){return this.first}get length(){return this.slice.length}findSlice(e){for(let t=0,s=this.slices.length;t<s;++t){const i=this.slices[t],n=i.indexOf(e);if(n!==-1)return{slice:i,index:n}}}findOffsetInSlice(e,t){for(let s=0;s<t.length;++s)if(this.compareValue(e,t[s])>=0)return{slice:t,offset:e===t[s]?s+1:s}}findSliceOffset(e){let t;for(let s=0;s<this.slices.length;++s){t=this.slices[s];const i=this.findOffsetInSlice(e,t);if(i)return{...i,sliceIndex:s}}if(t?.isEnd(1))return{slice:t,offset:t.length,sliceIndex:this.slices.length-1}}sliceMe(e,t,s){let i=this.slice,n=0,r=0;if(e){const m=this.findSliceOffset(e);if(!m)return;i=m.slice,n=r=m.offset}else if(!i.isEnd(2))return;const o=Math.max(r+t,0),l=r+t+s,c=i.slice(o,l),d=t<0?s+t:s,u=Math.abs(t),h=i.length-r>=d||(i.isEnd(1)?(c.setEnd(1),!0):!1),p=r-u>=0||(i.isEnd(2)?(c.setEnd(2),!0):!1);return{slice:c,offsetIdOffset:n,fulfilled:0|(h&&p?3:(h?1:0)|(p?2:0))}}unshift(...e){let t=this.first;t.length?t.isEnd(2)||(t=this.constructSlice(),t.setEnd(2),this.slices.unshift(t)):t.setEnd(2),t.unshift(...e)}push(...e){let t=this.last;t.length?t.isEnd(1)||(t=this.constructSlice(),t.setEnd(1),this.slices.push(t)):t.setEnd(1),t.push(...e)}delete(e){const t=this.findSlice(e);return t?(t.slice.splice(t.index,1),!0):!1}deleteSlice(e){Vs(this.slices,e)}toJSON(){const t={slices:this.slices.map(s=>({values:s.slice(),isEnd:s.getEnds()}))};return JSON.stringify(t)}static fromJSON(e){const t=JSON.parse(e),s=new ed;return t.slices.forEach(i=>{const n=s.insertSlice(i.values)||s.first;i.isEnd.top&&n.setEnd(1),i.isEnd.bottom&&n.setEnd(2)}),s}}Di&&(Di.SlicedArray=ed);function S2(a){a.style.display="none",a.offsetLeft,a.style.display=""}function I1(a){let e=!1,t=!1;return new Qn({...a,verifyTouchTarget:s=>!ne(s.target,"progress-line")&&!UC(s)&&(a.verifyTouchTarget?a.verifyTouchTarget(s):!0),onSwipe:(s,i,n)=>{if(s*=-1,i*=-1,!e&&Math.abs(i)>20)return!0;if(Math.abs(s)>Math.abs(i))_e(n),e=!0;else if(!e&&Math.abs(i)>Math.abs(s))return!0;return t=!0,a.onSwipe(s,i,n)},onReset:()=>{t&&a.onReset?.(),e=t=!1},cancelEvent:!1})}var Ct=(a=>(a[a.MESSAGE=0]="MESSAGE",a[a.PRIVATE_POST=1]="PRIVATE_POST",a[a.STICKER_SET=2]="STICKER_SET",a[a.JOIN_CHAT=3]="JOIN_CHAT",a[a.VOICE_CHAT=4]="VOICE_CHAT",a[a.USER_PHONE_NUMBER=5]="USER_PHONE_NUMBER",a[a.INVOICE=6]="INVOICE",a[a.EMOJI_SET=7]="EMOJI_SET",a[a.ATTACH_MENU_BOT=8]="ATTACH_MENU_BOT",a[a.WEB_APP=9]="WEB_APP",a[a.ADD_LIST=10]="ADD_LIST",a[a.STORY=11]="STORY",a[a.BOOST=12]="BOOST",a[a.PREMIUM_FEATURES=13]="PREMIUM_FEATURES",a[a.GIFT_CODE=14]="GIFT_CODE",a[a.BUSINESS_CHAT=15]="BUSINESS_CHAT",a[a.STARS_TOPUP=16]="STARS_TOPUP",a[a.SHARE=17]="SHARE",a[a.UNIQUE_STAR_GIFT=18]="UNIQUE_STAR_GIFT",a))(Ct||{});function C2(a){return{_:"reactionEmoji",emoticon:a.reaction}}function Wn(a,e){return typeof a!=typeof e?!1:([a,e]=[a,e].map(t=>t._==="availableReaction"?C2(t):t),Pn(a,e))}function Tb(a){return a+(window.devicePixelRatio>1?"@2x":"")}const P1=Y("<div>"),_2=Y("<div><div>"),I2=Y("<hr>"),P2=Y("<div class=sidebar-left-section-name-right>"),gh="sidebar-left-section",M1=a=>(()=>{const e=P1(),t=a.ref;return typeof t=="function"?Ue(t,e):a.ref=e,k(e,()=>a.children),Me(()=>be(e,Ge(gh+"-content",a.class))),e})(),FS=a=>T(M1,{ref(e){const t=a.captionRef;typeof t=="function"?t(e):a.captionRef=e},class:gh+"-caption",get children(){return V(()=>typeof a.caption=="string")()?P(a.caption,a.captionArgs):a.caption}}),Ms=a=>{const[,e]=wa(a,["name","nameArgs","nameRight","caption","captionArgs","captionOld","captionRef","noDelimiter","fakeGradientDelimiter","noShadow","class"]);return(()=>{const t=_2(),s=t.firstChild,i=a.ref;return typeof i=="function"?Ue(i,t):a.ref=t,so(t,ni({get class(){return Ge(gh+"-container",a.class)}},e),!1,!0),k(s,(()=>{const n=V(()=>!!a.fakeGradientDelimiter);return()=>n()?Fg():(()=>{const r=V(()=>!a.noDelimiter);return()=>r()&&I2()})()})(),null),k(s,T(M1,{get children(){return[V(()=>V(()=>!!a.name)()&&(()=>{const n=P1();return k(n,(()=>{const r=V(()=>typeof a.name=="string");return()=>r()?P(a.name,a.nameArgs):a.name})(),null),k(n,(()=>{const r=V(()=>!!a.nameRight);return()=>r()&&(()=>{const o=P2();return k(o,()=>a.nameRight),o})()})(),null),Me(()=>be(n,Ge("sidebar-left-h2",gh+"-name"))),n})()),V(()=>a.children)]}}),null),k(s,(()=>{const n=V(()=>!!(a.caption&&a.captionOld));return()=>n()&&T(FS,a)})(),null),k(t,(()=>{const n=V(()=>!!(a.caption&&!a.captionOld));return()=>n()&&T(FS,a)})(),null),Me(()=>be(s,Ge(gh,a.noShadow&&"no-shadow",a.fakeGradientDelimiter?"with-fake-delimiter":a.noDelimiter&&"no-delimiter"))),t})()};function Uo(a,e){return a.reduce((t,s)=>t+s,e)}function _m(a){const e={},t={};return s=>{var n;const i="_"+s;return(n=typeof s=="string"?e:t)[i]??(n[i]=a(s))}}function Ug(a){return a.replace(/\D/g,"")}const BS={visa:/^4/,mastercard:/^(51|52|53|54|55|222|23|24|25|26|27)/,amex:/^(34|37)/,discover:/^(60|64|65)/,diners:/^(30|38|39)/,diners14:/^(36)/,jcb:/^(35)/,unionpay:/^(62[0-6,8-9]|627[0-6,8-9]|6277[0-7,9]|62778[1-9]|81)/,elo:/^(5067|509|636368|627780)/,mir:/^(2\d+)/},xb={visa:{minLength:16,maxLength:16,cvcMaxLength:3,cvcMinLength:null},mastercard:{minLength:16,maxLength:16,cvcMaxLength:3,cvcMinLength:null},amex:{minLength:15,maxLength:15,cvcMaxLength:4,cvcMinLength:3},unionpay:{minLength:13,maxLength:19,cvcMaxLength:3,cvcMinLength:null},diners:{minLength:16,maxLength:16,cvcMaxLength:3,cvcMinLength:null},diners14:{minLength:14,maxLength:14,cvcMaxLength:3,cvcMinLength:null},discover:{minLength:16,maxLength:16,cvcMaxLength:3,cvcMinLength:null},jcb:{minLength:16,maxLength:16,cvcMaxLength:3,cvcMinLength:null},elo:{minLength:16,maxLength:16,cvcMaxLength:3,cvcMinLength:null},mir:{minLength:16,maxLength:16,cvcMaxLength:3,cvcMinLength:null},unknown:{minLength:16,maxLength:16,cvcMaxLength:4,cvcMinLength:3}},Vu=_m((a="")=>{const e=Object.keys(BS),t=Ug(a);let s,i=0;return e.forEach(n=>{const r=BS[n],o=t.match(r);if(o){const l=o[0];l&&l.length>i&&(s=n,i=l.length)}}),s||"unknown"});function M2(a){return a==="diners14"?"diners":a}function L1(a=""){const e=Vu(a);return M2(e)}class Hg{constructor(e,t,s){this.scrollable=e,this.query=t,this.reverse=s}get container(){return this.scrollable.container}getSaved(){return{scrollHeight:this.scrollHeight,scrollTop:this.scrollTop,clientHeight:this.clientHeight}}findElements(){if(!this.query)return[];const{container:e}=this,t=e.getBoundingClientRect(),s=Array.from(e.querySelectorAll(this.query)),i=[];for(const n of s){const r=n.getBoundingClientRect();if(Ko(n,e,void 0,r,t))i.push({element:n,rect:r});else if(i.length)break}if(!i.length){const n=s[0];n&&i.push({element:n,rect:n.getBoundingClientRect()})}return i}replaceSaved(e,t){if(!this.elements)return;const s=this.elements.findIndex(({element:i})=>e===i);s!==-1&&(this.elements[s].element=t)}findAndSetElements(){this.elements=this.findElements()}save(){this.findAndSetElements(),this._save()}_save(){const{scrollTop:e,scrollHeight:t,clientHeight:s}=this.container;this.scrollHeight=t,this.scrollTop=e,this.clientHeight=s,this.scrollHeightMinusTop=this.reverse?t-e:e}onRestore(e){this.scrollable.onSizeChange()}setScrollTop(e,t){this.scrollable.setScrollPositionSilently(this.scrollTop=e),dn&&$s(()=>{this.scrollTop===e&&this.scrollable.setScrollPositionSilently(this.scrollTop=e)}),this.onRestore(t)}restore(e){const{scrollPosition:t,scrollSize:s}=this.scrollable;if(this.scrollHeight=s,!this.elements.length){this.setScrollTop(this.reverse?s:0,e);return}let i;if(i=this.elements[this.elements.length-1],!i?.element?.parentElement&&(this.findAndSetElements(),i=this.elements[this.elements.length-1],!i)){this._restore(e);return}const{element:n,rect:r}=i,l=n.getBoundingClientRect().bottom-r.bottom;this.setScrollTop(t+l,e)}_restore(e){const{scrollHeightMinusTop:t,scrollable:s}=this,i=this.scrollHeight,n=this.reverse?i-t:t;this.setScrollTop(n,e)}}Di&&(Di.ScrollSaver=Hg);function Cp(a,e,t){const s=new Array(a);return s.fill(e),t?s.map(t):s}const L2=65248,E2=/[0-9]/g;function k2(a){return String.fromCharCode(a.charCodeAt(0)-L2)}function E1(a){return a.replace(E2,k2)}function k1(a,e){return{type:"optional",result:a,consumed:e}}function Im(a,e,t){return{type:"required",result:a,consumed:e,partial:t}}function T2(a,e){return{type:"formatting",result:a,consumed:e}}function Gg(a,e){return t=>{const s=new RegExp("^".concat(a.source.replace(/^\^/,""))),i=t.match(s),n=e?k1:Im;if(i){const r=i[0];return n(r,i.index+r.length)}return n("",t.length)}}function x2(a){const e=Gg(/\w/)(a);return e.result?Im(e.result.toUpperCase(),e.consumed):e}const A2=Gg(/1[0-2]|0?[1-9]|0/);function R2(a){return Gg(/[0-9]/)(E1(a))}const Io={digit:R2,capitalCharacter:x2,month:a=>{const e=A2(E1(a)),t=Ug(e.result);return["0","1"].includes(e.result)&&a.length===1||e.result==="0"&&a.length>=2?Im(e.result,a.length,!0):Im(t.length===1?"0"+t:t,e.consumed)},formattingCharacter:a=>e=>{const t=a===e[0]?1:0;return T2(a,t)},optionalPattern:a=>e=>{const t=Gg(a,!0)(e);return t.result?t:k1("",0)}},Ps=Io.digit,nc=Io.capitalCharacter,td=Io.formattingCharacter(" "),F2=Io.optionalPattern(/\d\d/),B2=[Ps,Ps,Ps,Ps,td,Ps,Ps,Ps,Ps,Ps,Ps,td,Ps,Ps,Ps,Ps,Ps],D2=[Ps,Ps,Ps,Ps,td,Ps,Ps,Ps,Ps,Ps,Ps,td,Ps,Ps,Ps,Ps],$2=new Set(["DZ","AR","AM","AU","AT","AZ","PT","BD","BY","BE","BA","BR","BN","BG","CA","IC","CN","CO","HR","CY","CZ","DK","EC","GB","EE","FO","FI","FR","GE","DE","GR","GL","GU","GG","NL","HU","IN","ID","IL","IT","JP","JE","KZ","KR","FM","KG","LV","LI","LT","LU","MK","MG","PT","MY","MH","MQ","YT","MX","MN","ME","NL","NZ","GB","NO","PK","PH","PL","FM","PT","PR","RE","RU","SA","SF","RS","SG","SK","SI","ZA","ES","LK","SX","VI","VI","SE","CH","TW","TJ","TH","TU","TN","TR","TM","VI","UA","GB","US","UY","UZ","VA","VN","GB","FM"]),N2=_m(a=>{const e=[];for(let t=0,s=0;t<a;)s===4?(e.push(td),s=0):(e.push(Ps),++t,++s);return e});function O2(a){const e=Vu(a);if(e==="amex")return B2;if(e==="diners14")return D2;const{minLength:t,maxLength:s}=xb[e],i=Ug(a).length,n=Math.min(Math.max(t,i),s);return N2(n)}const fh={cardNumber:O2,cardExpiry:()=>[Io.month,Io.formattingCharacter("/"),Ps,Ps,F2],cardCvc:a=>fh.cardCvcFromBrand(Vu(a)),cardCvcFromBrand:_m(a=>{const e=xb[a],{cvcMinLength:t,cvcMaxLength:s}=e,i=Cp(t||s,Ps);if(t&&t<s){const n=s-t,r=Io.optionalPattern(/\d/);n&&i.push(...Cp(n,r))}return i}),postalCodeFromCountry:_m(a=>{switch(a){case"US":return Cp(5,Ps);case"CA":return fv?null:[nc,nc,nc,td,nc,nc,nc];default:const e=Cp(10,Io.optionalPattern(/\d/));return $2.has(a)&&(e[0]=Ps),e}})};function _p(a){return Uo(a.map(e=>e.length),0)}function U2(a,e,t={},s){const i=a(e);if(!i)return{value:e,selection:null,autocorrectComplete:!!e};const n=i.length,r=[],o=[];let l=0,c=0,d=t.selectionStart===0?0:null,u=t.selectionEnd===0?0:null;const h=()=>{d===null&&c+1>=t.selectionStart&&(d=_p(r)+(s?o.length:0)),u===null&&c+1>=t.selectionEnd&&(u=_p(r)+(s?o.length:0))},p=m=>{m>0&&(h(),c+=m)};for(;l<n;){const m=i[l],g=m(e.slice(c)),{type:f,result:v,consumed:y}=g;if(f==="required")if(v){if(r.push(...o,v),o.length=0,++l,g.partial){p(e.length-c);break}p(y)}else{if(!y)break;p(1)}else if(f==="optional")v&&(r.push(...o,v),o.length=0,p(y)),++l;else if(f==="formatting"){if(!s&&c>=e.length)break;o.push(v),++l,p(y)}}return s&&r.push(...o),{value:r.join(""),selection:{selectionStart:d===null||e.length&&t.selectionStart===e.length?_p(r):d,selectionEnd:u===null||e.length&&t.selectionEnd===e.length?_p(r):u},autocorrectComplete:l===n}}function H2(a){const{value:e,getPattern:t,deleting:s,input:i}=a,n=!s&&!!e.length,r=U2(t,e,{selectionStart:i?i.selectionStart:0,selectionEnd:i?i.selectionEnd:0},n),{value:o,selection:l}=r;return{value:o,meta:{autocorrectComplete:r.autocorrectComplete,empty:!o},selection:l}}const Ab="",G2=new RegExp(Ab,"g");function Jh(a){return a?{type:"invalid",code:a}:null}function V2(a){const t=a.length%2;let s=0;for(let i=a.length-1;i>=0;--i){const n=t===i%2;let r=a.charCodeAt(i)-48;n&&(r*=2),r>9&&(r-=9),s+=r}return!(s%10)}function z2(a,e,t){const s=t.date||new Date,i=a<100?s.getFullYear()%100:s.getFullYear(),n=s.getMonth()+1;return isNaN(a)||isNaN(e)?t?.ignoreIncomplete?null:"incomplete":a-i<0?"invalid_expiry_year_past":a-i>50?"invalid_expiry_year":!(a-i)&&e<n?"invalid_expiry_month_past":null}function W2(a){const e=Ug(a),t=Vu(a);return{sanitized:e,brand:t,minLength:xb[t].minLength}}function K2(a,e,t){return a.length>=e?V2(a)||Vu(a)==="mir"?null:Jh("invalid"):t?null:Jh("incomplete")}function j2(a,e={}){const{sanitized:t,minLength:s}=W2(a);return K2(t,s,e.ignoreIncomplete)}function DS(a,e={}){const t=a.replace(G2,"").split(/ ?\/ ?/),[s,i=""]=t,[n,r]=[s,i].map(l=>+l),o=i.length===2?r%100:r;return i.length<2||i.length===3?e.ignoreIncomplete?null:Jh("incomplete"):Jh(z2(o,n,e))}function q2(a,e,t={}){return a.meta.autocorrectComplete||t.ignoreIncomplete?null:Jh("incomplete")}const Uv=new WeakMap;window.addEventListener("message",a=>{const e=Uv.get(a.source);e&&e(JSON.parse(a.data))});class T1 extends pn{constructor({url:e,sandbox:t,allow:s,onLoad:i}){super(!1),this.onTelegramWebViewEvent=({eventType:r,eventData:o})=>{o===""&&(o=void 0),this.dispatchEvent(r,o)};const n=this.iframe=document.createElement("iframe");n.src=e,t&&n.setAttribute("sandbox",t),s&&(n.allow=s),i&&(this.onLoad=i,n.addEventListener("load",i,{once:!0}))}onMount(){Uv.set(this.iframe.contentWindow,this.onTelegramWebViewEvent)}destroy(){this.cleanup(),Uv.delete(this.iframe.contentWindow),this.iframe.removeEventListener("load",this.onLoad)}dispatchWebViewEvent(e,t){this.lastDispatchedWebViewEvent?.type!==e&&(this.lastDispatchedWebViewEvent={type:e,count:0}),++this.lastDispatchedWebViewEvent.count,this.iframe.contentWindow.postMessage(JSON.stringify({eventType:e,eventData:t}),"*")}}function x1(a){const e=new T1({...a,sandbox:"allow-forms allow-scripts allow-same-origin allow-modals"}),{iframe:t}=e;return t.allow="payment",t.classList.add("payment-verification"),e}class Y2 extends ue{constructor(e,t){super("popup-payment popup-payment-verification",{closable:!0,overlayClosable:!0,body:!0,title:"Checkout.WebConfirmation.Title"}),this.url=e,this.openPathAfter=t,this.d()}d(){const e=this.telegramWebView=x1({url:this.url});e.addEventListener("web_app_open_tg_link",t=>{this.dispatchEvent("finish"),this.hide(),this.openPathAfter&&Ce.openUrl("https://t.me"+t.path_full)}),this.body.append(e.iframe),this.show(),e.onMount()}destroy(){return this.telegramWebView.destroy(),super.destroy()}}class pl extends Yt{constructor(e){super(e),this.options=e,this.onKeyDown=t=>{this.lastKeyDown=t.key,this.options.onKeyDown?.(t)},this.onInput=()=>{const t=this.value,s=this.lastKeyDown==="Backspace"&&(this.lastTransformed&&this.lastTransformed.value.length||0)-t.length===1,i=this.lastTransformed=H2({value:t,getPattern:this.options.formatMethod,deleting:s,input:this.input}),n=i.value;n!==t&&(this.setValueSilently(n),i.selection&&(this.input.selectionStart=i.selection.selectionStart,this.input.selectionEnd=i.selection.selectionEnd)),this.validateNew(n,{ignoreIncomplete:!0}),this.options.onChange?.(i)},this.onBlur=()=>{const t=this.lastTransformed?.value;t&&this.validateNew(t)},this.validate=()=>this.validateNew(),this.input.addEventListener("keydown",this.onKeyDown),this.input.addEventListener("input",this.onInput),this.input.addEventListener("blur",this.onBlur)}update(){this.onInput()}validateNew(e=this.lastTransformed?.value??"",t={},s){let i;if(this.options.validateMethod?i=this.options.validateMethod?.(e,t):i=q2(this.lastTransformed,e,t),i?.code){const n=this.options.errorKeys?.[i.code];return!s&&this.setState(ra.Error,n),!1}return!s&&this.setState(ra.Neutral),!0}}function A1(a,e){const t=()=>{const s=a.every(i=>"validateNew"in i?i.validateNew(void 0,void 0,!0):i.isValid());e(s)};return a.forEach(s=>{if(s instanceof pl){const i=s.options.onChange;s.options.onChange=(...n)=>{i?.(...n),t()},"update"in s&&s.update()}else s.input.addEventListener("input",t)}),{validate:t}}function R1(a,e){let t,s;return(a||e)&&(a&&(t=new ZE({noPhoneCodes:!0,onCountryChange:()=>{s?.update()},required:!0,autocomplete:"country"})),e&&(s=new pl({label:"PaymentShippingZipPlaceholder",plainText:!0,inputMode:"numeric",autocomplete:"postal-code",formatMethod:()=>{const{country:i}=t.getSelected(),n=i?.iso2;return fh.postalCodeFromCountry(n&&n.toUpperCase())}}))),{countryInputField:t,postcodeInputField:s}}const $S=new Set(["stripe","smartglocal"]);class Q2 extends ue{constructor(e,t,s){if(super("popup-payment popup-payment-card",{closable:!0,overlayClosable:!0,body:!0,scrollable:$S.has(e.native_provider),title:"PaymentCardInfo"}),this.paymentForm=e,this.user=t,this.savedCard=s,$S.has(e.native_provider))this.d();else{const i=this.telegramWebView=x1({url:e.url});i.addEventListener("payment_form_submit",n=>{const r={title:n.title,save:!1};this.dispatchEvent("finish",{token:n.credentials,card:r}),this.hide(),e.pFlags.can_save_credentials&&Rt({titleLangKey:"PaymentCardSavePaymentInformation",descriptionLangKey:"PaymentCardSavePaymentInformationInfoLine1",button:{langKey:"Save"}}).then(()=>{r.save=!0},as)}),this.body.append(i.iframe),this.show(),i.onMount()}}destroy(){return this.telegramWebView?.destroy(),super.destroy()}d(){const e=this.savedCard,t=new Oe({name:"PaymentInfo.Card.Title",noDelimiter:!0,noShadow:!0}),s=JSON.parse(this.paymentForm.native_params.data);let i,n=0,r;const o=C=>{if(i===C)return;const L=++n;i=C;const E=B1(C);if(!E){r&&(r.remove(),r=void 0);return}const x=new Image;x.classList.add("input-field-icon"),Vn(x,E,!1).then(()=>{n===L&&(r?r.replaceWith(x):l.container.append(x),r=x)})},l=new pl({label:"PaymentCardNumber",plainText:!0,inputMode:"numeric",autocomplete:"cc-number",formatMethod:fh.cardNumber,validateMethod:j2,errorKeys:{invalid:"PaymentCard.Error.Invalid",incomplete:"PaymentCard.Error.Incomplete"},onChange:C=>{o(L1(C.value)),h.update()}});let c;s.need_cardholder_name&&(c=new Yt({label:"Checkout.NewCard.CardholderNamePlaceholder",maxLength:255,required:!0,autocomplete:"cc-name"}));const d=bd(this.user.phone),u=new pl({label:"SecureId.Identity.Placeholder.ExpiryDate",plainText:!0,inputMode:"numeric",autocomplete:"cc-exp",formatMethod:fh.cardExpiry,validateMethod:d.country.iso2==="RU"?(C,L)=>DS(C,{...L||{},date:new Date(2022,0,1)}):DS});u.input.addEventListener("input",()=>{let C=u.value;if(C.length<5)return;const L=C.split("/");L[1].length===4&&(C=[L[0],L[1].slice(2)].join("/"),u.setValueSilently(C))},{capture:!0});const h=new pl({labelText:"CVC",plainText:!0,inputMode:"numeric",autocomplete:"cc-csc",name:"cvc",formatMethod:()=>fh.cardCvc(l.value)});new PL(h.container,h.input);const p=[l,u,h,c].filter(Boolean);p.forEach(C=>{const L=E=>{if(!C.value&&E.key==="Backspace"){const x=p[p.indexOf(C)-1];x&&Ki(x.input,!0)}};if(C instanceof pl){C.options.onKeyDown=L;const E=C.options.onChange;C.options.onChange=x=>{if(E?.(x),document.activeElement===C.input&&x.meta.autocorrectComplete)for(let R=p.indexOf(C),B=p.length;R<B;++R){const N=p[R];if(N instanceof pl?!N.validateNew(void 0,void 0,!0):!N.value){Ki(N.input,!0);break}}}}else C.input.addEventListener("keydown",L)});const m=document.createElement("div");m.classList.add("input-fields-row"),m.append(u.container,h.container);const g=document.createElement("form");g.append(...[l.container,m,c?.container].filter(Boolean)),t.content.append(g);let f;const{countryInputField:v,postcodeInputField:y}=R1(s.need_country,s.need_zip);(s.need_country||s.need_zip)&&(f=new Oe({name:"PaymentInfo.Billing.Title",noDelimiter:!0,noShadow:!0}),f.content.append(...[v,y].filter(Boolean).map(C=>C.container)));const w=!!this.paymentForm.pFlags.can_save_credentials,b=new _t({text:"PaymentCardSavePaymentInformation",checked:!!w}),S=new Fe({checkboxField:b,subtitleLangKey:w?"PaymentCardSavePaymentInformationInfoLine1":"Checkout.2FA.Text"});w||S.container.classList.add("is-disabled"),(f||t).content.append(S.container),this.scrollable.append(...[t,f].filter(Boolean).map(C=>C.container));const _=sd({key:"PaymentInfo.Done",onClick:async()=>{const C={cardNumber:l.value,expiryFull:u.value,expiryMonth:u.value.split("/")[0],expiryYear:u.value.split("/")[1],cvc:h.value,cardholderName:c?.value,country:v?.value,zip:y?.value,save:b?.checked},L=this.paymentForm.native_provider;let E;if(L==="stripe"){const x=new URL("https://api.stripe.com/v1/tokens");x.search=new URLSearchParams({"card[number]":C.cardNumber,"card[exp_month]":C.expiryMonth,"card[exp_year]":C.expiryYear,"card[cvc]":C.cvc,"card[address_zip]":C.zip,"card[address_country]":C.country,"card[name]":C.cardholderName}).toString(),E=await(await fetch(x.toString(),{method:"POST",credentials:"same-origin",headers:{"Content-Type":"application/x-www-form-urlencoded",Authorization:`Bearer ${s.publishable_key}`}})).json()}else if(L==="smartglocal"){const x={card:{number:C.cardNumber.replace(/[^\d]+/g,""),expiration_month:C.expiryMonth,expiration_year:C.expiryYear,security_code:C.cvc.replace(/[^\d]+/g,"")}};E={type:"card",token:(await(await fetch("https://tgb.smart-glocal.com/cds/v1/tokenize/card",{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json","X-PUBLIC-TOKEN":s.public_token},body:JSON.stringify(x)})).json()).data.token}}this.dispatchEvent("finish",{token:E,card:C}),this.hide()}}),M=[l,c,u,h,v,y].filter(Boolean);A1(M,C=>{_.disabled=!C}),e&&(l.value=e.cardNumber,u.value=e.expiryFull,h.value=e.cvc,c&&(c.value=e.cardholderName),v&&(v.value=e.country),y&&(y.value=e.zip)),this.body.append(this.btnConfirmOnEnter=_),this.show(),l.validateNew(void 0,void 0,!0)||Ki(l.input)}}class X2 extends ue{constructor(e,t){super("popup-payment popup-payment-card-confirmation",{closable:!0,overlayClosable:!0,body:!0,scrollable:!0,title:"Checkout.PasswordEntry.Title"});const s=new Oe({noDelimiter:!0,noShadow:!0,caption:"Checkout.PasswordEntry.Text",captionArgs:[e]}),i=new gg({labelText:t.hint});s.content.append(i.container),this.scrollable.append(s.container);const n=()=>{r.disabled=!i.value,i.setState(ra.Neutral)};i.input.addEventListener("input",n);const r=sd({key:"Checkout.PasswordEntry.Pay",onClick:async()=>{try{const o=await this.managers.passwordManager.getInputCheckPassword(i.value,t),l=await this.managers.apiManager.invokeApi("account.getTmpPassword",{password:o,period:60});this.dispatchEvent("finish",l),this.hide()}catch(o){throw o.type==="PASSWORD_HASH_INVALID"&&(o.handled=!0,i.setError("PASSWORD_HASH_INVALID")),o}}});this.body.append(this.btnConfirmOnEnter=r),n(),this.show(),Ki(i.input)}}function F1(a){return a?a.match(ML):null}class Z2 extends ue{constructor(e,t,s){super("popup-payment popup-payment-shipping",{closable:!0,overlayClosable:!0,body:!0,scrollable:!0,title:"PaymentShippingInfo"}),this.paymentForm=e,this.inputInvoice=t,this.focus=s,this.d()}d(){const t=this.paymentForm.invoice,s=this.paymentForm.saved_info;let i,n,r,o,l,c,d;if(t.pFlags.shipping_address_requested){i=new Oe({name:"PaymentShippingAddress",noDelimiter:!0,noShadow:!0}),n=new Yt({label:"PaymentShippingAddress1Placeholder",maxLength:64,required:!0}),r=new Yt({label:"PaymentShippingAddress2Placeholder",maxLength:64}),o=new Yt({label:"PaymentShippingCityPlaceholder",maxLength:64,required:!0}),l=new Yt({label:"PaymentShippingStatePlaceholder",maxLength:64});const b=R1(!0,!0);c=b.countryInputField,d=b.postcodeInputField,i.content.append(...[n,r,o,l,c,d].filter(Boolean).map(S=>S.container))}let u,h,p,m;if([t.pFlags.name_requested,t.pFlags.email_requested,t.pFlags.phone_requested].includes(!0)){u=new Oe({name:"PaymentShippingReceiver",noDelimiter:!0,noShadow:!0});const b=()=>{const _=p.value,M=F1(_);return!(!M||M[0].length!==_.length)},S=()=>!!m.value.match(/\d/);t.pFlags.name_requested&&(h=new Yt({label:"PaymentShippingName",maxLength:256,required:!0})),t.pFlags.email_requested&&(p=new Yt({label:"PaymentShippingEmailPlaceholder",maxLength:64,required:!0,validate:b})),t.pFlags.phone_requested&&(m=new v_({required:!0,validate:S})),u.content.append(...[h,p,m].filter(Boolean).map(_=>_.container))}const g=new _t({text:"PaymentShippingSave",checked:!0}),f=new Fe({checkboxField:g,subtitleLangKey:"PaymentShippingSaveInfo"});(u||i).content.append(f.container),this.scrollable.append(...[i,u].filter(Boolean).map(b=>b.container));const v=sd({key:"PaymentInfo.Done",onClick:async()=>{const b=c&&c.getSelected().country,S={_:"paymentRequestedInfo",shipping_address:b&&{_:"postAddress",street_line1:n.value,street_line2:r.value,city:o.value,state:l.value,country_iso2:b?.iso2,post_code:d.value},name:h?.value,email:p?.value,phone:m?.value};try{const _=await this.managers.appPaymentsManager.validateRequestedInfo(this.inputInvoice,S,g?.checked);this.dispatchEvent("finish",{shippingAddress:S,requestedInfo:_}),this.hide()}catch(_){const C={ADDRESS_STREET_LINE1_INVALID:n,ADDRESS_STREET_LINE2_INVALID:r,ADDRESS_COUNTRY_INVALID:c,ADDRESS_CITY_INVALID:o,ADDRESS_STATE_INVALID:l,ADDRESS_POSTCODE_INVALID:d,REQ_INFO_NAME_INVALID:h,REQ_INFO_EMAIL_INVALID:p,REQ_INFO_PHONE_INVALID:m}[_.type];throw C&&(C.setError(),_.handled=!0),_}}});if(this.body.append(this.btnConfirmOnEnter=v),s){const b=s.shipping_address;b&&(n.value=b.street_line1,r.value=b.street_line2,o.value=b.city,l.value=b.state,c.selectCountryByIso2(b.country_iso2),d.value=b.post_code),s.name&&h&&(h.value=s.name),s.email&&p&&(p.value=s.email),s.phone&&m&&(m.value=s.phone)}const{validate:y}=A1([n,r,o,l,c,d,h,p,m].filter(Boolean),b=>{v.disabled=!b});y(),this.show();let w;this.focus?w={name:h,email:p,phone:m}[this.focus]:w=n,w&&Ki(w.input)}}class J2 extends ue{constructor(e,t,s){super("popup-payment popup-payment-shipping-methods",{closable:!0,overlayClosable:!0,body:!0,scrollable:!0,title:"PaymentShippingMethod"}),this.paymentForm=e,this.requestedInfo=t,this.shippingOption=s,this.d()}d(){const e=new Oe({name:"PaymentCheckoutShippingMethod",noDelimiter:!0,noShadow:!0}),t=this.requestedInfo.shipping_options.map(r=>new Fe({radioField:new rn({text:r.title,name:"shipping-method",value:r.id}),subtitle:qi(Uo(r.prices.map(({amount:o})=>+o),0),this.paymentForm.invoice.currency)}));let s;const i=Sd(t,r=>{s=r});this.shippingOption?t.find(r=>r.radioField.input.value===this.shippingOption.id).radioField.checked=!0:t[0].radioField.checked=!0,e.content.append(i),this.scrollable.append(e.container);const n=sd({key:"PaymentInfo.Done",onClick:()=>{this.dispatchEvent("finish",this.requestedInfo.shipping_options.find(r=>r.id===s)),this.hide()}});this.body.append(this.btnConfirmOnEnter=n),this.show()}}const Cl=a=>{const e=new Xt,[t]=ma(()=>a.peerId,async s=>{if(await e.update({peerId:s,dialog:!1,onlyFirstName:a.onlyFirstName}),a.onClick){const i=J(e.element,a.onClick);ze(i)}return!0});return V(()=>t()&&e.element)},eA="_table_1l42t_1",tA="_cell_1l42t_12",sA="_key_1l42t_19",iA="_boldKey_1l42t_23",nA="_value_1l42t_27",aA="_peer_1l42t_33",rA="_anonymous_1l42t_41",oA="_button_1l42t_55",Ga={table:eA,cell:tA,key:sA,boldKey:iA,value:nA,peer:aA,anonymous:rA,button:oA};function Za(a={}){return T(Ru,{ref(e){const t=a.ref;typeof t=="function"?t(e):a.ref=e},get component(){return a.asLink?"a":a.asDiv?"div":"button"},get class(){return a.class},get disabled(){return a.disabled},get onClick(){return a.onClick},get children(){return[V(()=>V(()=>!!a.icon)()&&T(hs,{get icon(){return a.icon},class:"button-icon"})),V(()=>V(()=>!!a.text)()?P(a.text,a.textArgs):a.children),V(()=>V(()=>!!a.iconAfter)()&&T(hs,{get icon(){return a.iconAfter},class:"button-icon"}))]}})}const lA=Y("<table>"),cA=Y("<tr><td></td><td><div>"),dA=Y("<tr><td colspan=2>"),hA=Y("<div>"),uA=Y("<div class=popup-star-gift-info-anonymous><img src=assets/img/anon_paid_reaction.png alt=Anonymous>"),pA=Ge(Ga.cell,Ga.key);function Rb(a){return(()=>{const e=lA();return k(e,T(Cs,{get each(){return a.content},children:([t,s])=>(()=>{const i=cA(),n=i.firstChild,r=n.nextSibling,o=r.firstChild;return be(i,Ga.row),k(n,()=>P(t)),be(o,Ga.value),k(o,s),Me(l=>{const c=Ge(pA,a.cellClass),d=Ge(Ga.cell,a.cellClass);return c!==l._v$&&be(n,l._v$=c),d!==l._v$2&&be(r,l._v$2=d),l},{_v$:void 0,_v$2:void 0}),i})()}),null),k(e,(()=>{const t=V(()=>!!a.footer);return()=>t()&&(()=>{const s=dA(),i=s.firstChild;return be(s,Ga.row),k(i,()=>a.footer),Me(()=>be(i,a.footerClass??Ge(Ga.cell,a.cellClass))),s})()})(),null),Me(()=>be(e,Ge(Ga.table,a.boldKey&&Ga.boldKey,a.class))),e})()}function Pm(a){const e=Ot(()=>jn({peerId:a.peerId,size:24}));return(()=>{const t=hA();return Lr(t,"click",a.onClick,!0),be(t,Ga.peer),k(t,(()=>{const s=V(()=>a.peerId===Wt);return()=>s()?[uA(),V(()=>P("StarGiftHiddenUser"))]:[V(()=>e.element),T(Cl,{get peerId(){return a.peerId}})]})()),t})()}function Kp(a){return T(Za,ni(a,{class:Ga.button}))}Fs(["click"]);function hr(a){if(typeof a!="number"&&typeof a!="string")return+a.amount+ +a.nanos/1e9;const e=+a%1*1e9;return{_:"starsAmount",amount:Math.abs(+a|0),nanos:e}}const mA=Y("<span class=popup-stars-pay-boosts>"),gA=Y("<span>"),fA=Y("<div class=popup-stars-pay-padding><div class=popup-stars-pay-images><div class=popup-stars-pay-avatar></div></div><div class=popup-stars-title>"),NS=Y("<div>"),vA=Y("<div class=popup-stars-pay-tos>"),yA=_n&&!1;class bA extends ue{constructor(e){super("popup-stars popup-stars-pay",{closable:!0,overlayClosable:!0,body:!0,scrollable:!0,footer:!0,withConfirm:!0,title:!0}),Nt(this,e),this.footer.classList.add("abitlarger"),this.result="cancelled";let t=yA;const s=this.onConfirm=async()=>{const{paymentForm:i}=this;if(this.isReceipt||!i&&!this.chatInvite&&!this.subscription){this.hide();return}const n=Yn(this.btnConfirm),r=os([this.btnConfirm],!0);this.result="pending";let o;t?(t=!1,o=Promise.reject(Vo("BALANCE_TOO_LOW"))):this.subscription?o=this.managers.appPaymentsManager.changeStarsSubscription(this.subscription.id,!this.subscription.pFlags.canceled):o=this.managers.appPaymentsManager.sendStarsForm(this.inputInvoice,i?.form_id||this.chatInvite.subscription_form_id);try{await o,this.result="paid",this.hide()}catch(l){let c=!1;l.type==="BALANCE_TOO_LOW"?ue.createPopup(ba,{itemPrice:i?+i.invoice.prices[0].amount:this.chatInvite?+this.chatInvite.subscription_pricing.amount:+this.subscription.pricing.amount,paymentForm:i,onTopup:async()=>{await this.reloadForm(),s()},onCancel:()=>{this.result="cancelled",this.hide()},purpose:this.purpose}):l.type==="FORM_EXPIRED"?(await this.reloadForm(),c=!0):this.result="failed",r(),n.remove(),c&&s()}};J(this.btnConfirm,s,{listenerSetter:this.listenerSetter})}get form(){return this.paymentForm||this.transaction}hide(){return this.dispatchEvent("finish",this.result),super.hide()}async reloadForm(){this.paymentForm&&(this.paymentForm=await this.managers.appPaymentsManager.getPaymentForm(this.inputInvoice))}setPaymentForm(e){this.paymentForm=e,this.isReceipt=!!this.transaction||e?._==="payments.paymentReceiptStars",this.isOutGift=!!this.transaction&&!this.transaction.id,this.construct()}_construct(e,t,s,i){const n=this,r=this;!this.isReceipt&&(!this.subscription||Qs(!0)>this.subscription.until_date)&&this.header.append(Vg()),this.footer.append(this.btnConfirm),this.body.after(this.footer);let o;if(this.paymentForm?o=this.paymentForm.invoice.prices[0].amount:this.chatInvite?o=this.chatInvite.subscription_pricing.amount:this.subscription?o=this.subscription.pricing.amount:o=hr(this.transaction.stars),this.isReceipt)this.btnConfirm.append(P("OK"));else if(this.chatInvite){this.btnConfirm.append(P("Stars.Subscribe.Button"));const w=P("Stars.Subscribe.Terms");w.classList.add("popup-footer-caption"),this.btnConfirm.after(w)}else if(this.subscription){if(this.subscription.pFlags.canceled?this.btnConfirm.append(P("Stars.Subscription.Renew")):(this.btnConfirm.className="btn-primary btn-secondary btn-primary-transparent danger",this.btnConfirm.append(P("Stars.Subscription.Cancel"))),this.subscription.until_date>Qs(!0)&&qC(this.peerId.toChatId()).pFlags.left){const b=document.createElement("button");b.classList.add("btn-primary","btn-color-primary"),b.append(P("Stars.Subscription.Fulfill")),b.style.marginTop=".5rem",J(b,async()=>{const S=os([this.btnConfirm,b],!0);try{await this.managers.appPaymentsManager.fulfillStarsSubscription(this.subscription.id),l(()=>{Ce.setInnerPeer({peerId:this.peerId})})}catch(_){console.error("fulfill error",_),S()}},{listenerSetter:this.listenerSetter}),this.btnConfirm.after(b)}}else this.btnConfirm.append(P("Stars.ConfirmPurchaseButton",[o])),Wo(this.btnConfirm,"star");const l=(w,b)=>{_e(b),this.hide(),ue.getPopups(ba)?.[0]?.hide(),this.hideWithCallback(w)};let c=!1,d,u;if(this.transaction&&this.transaction.pFlags.gift){d=P(this.isOutGift?"StarsGiftSent":"StarsGiftReceived"),u=document.createDocumentFragment();const w=tI(l),b=new Xt;b.update({peerId:this.peerId,wrapOptions:{middleware:this.middlewareHelper.get()}}),u.append(P(this.isOutGift?"ActionGiftStarsSubtitle":"ActionGiftStarsSubtitleYou",[b.element])," ",w)}else if(this.transaction?.extended_media)d=P("StarMediaPurchase");else if(this.paidMedia){const[w,b]=qc(this.paidMedia.extended_media,M=>M._==="messageExtendedMedia"?M.media._!=="messageMediaDocument":M.video_duration===void 0),S=P("Stars.Unlock.Photos",[w.length]),_=P("Stars.Unlock.Videos",[b.length]);d=P("StarsConfirmPurchaseTitle"),u=P(this.peerId.isUser()?"Stars.Unlock.FromBot":"Stars.Unlock",[w.length&&b.length?P("Stars.Unlock.Media",[S,_]):(w.length||b.length)===1?P(w.length?"Stars.Unlock.Photo":"Stars.Unlock.Video"):w.length?S:_,t,P("Stars.Unlock.Stars",[o])])}else this.transaction&&this.transaction.pFlags.reaction?d=P("StarsReactionTitle"):this.transaction?.giveaway_post_id?(d=P(this.transaction.id?"StarsGiveawayPrizeReceived":"Stars",[hr(this.transaction.stars)]),this.transaction.id||(u=(()=>{const w=mA();return k(w,T(hs,{icon:"boost"}),null),k(w,()=>P("BoostingBoostsCountTitle",[n.boost.multiplier||1]),null),w})(),c=!0)):this.form._==="payments.paymentFormStarGift"?(d=P("StarsConfirmPurchaseTitle"),u=P("StarGiftConfirmPurchaseText",[o])):this.transaction&&!this.form.title?d=P(this.transaction.subscription_period?"Stars.Subscription.Title":"Stars.TopUp"):this.chatInvite?(d=P("Stars.Subscribe.Title"),t.style.display="inline",u=P("Stars.Subscribe.Description",[t,P("Stars.Unlock.Stars",[o])])):this.subscription?(d=P("Stars.Subscription"),u=P("Stars.Subscription.Fee",[zg({stars:o})]),u.classList.add("secondary")):this.transaction?.paid_messages?(d=P("PaidMessages.FeeForMessages",[this.transaction.paid_messages]),!this.transaction.pFlags.refund&&+o>0&&(u=P("PaidMessages.YouReceiveWithCommissionNotice"),Promise.resolve(Ae.getAppConfig()).then(w=>{Ne.weakMap.get(u).compareAndUpdate({key:"PaidMessages.YouReceiveWithCommissionNotice",args:[Math.round(w.stars_paid_message_commission_permille/10)]})}))):(d=this.isReceipt?je(this.form.title):P("StarsConfirmPurchaseTitle"),u=this.isReceipt?je(this.form.description):P("StarsConfirmPurchaseText",[o,je(this.paymentForm.title),t]));const h=this.transaction?.id??this.paymentForm?.transaction_id,p=()=>{si(h),$e({langPackKey:"StarsTransactionIDCopied"})},m=i&&YC(i);m&&(m.textContent=i.replace("https://",""),m.onclick=w=>l(()=>Ce.openUrl(i),w));const g=w=>Pm({peerId:w,onClick:()=>{l(()=>{Ce.setInnerPeer({peerId:w,stack:this.message?{peerId:this.message.peerId,mid:this.message.mid}:void 0})})}}),f=(this.isReceipt||this.subscription)&&g(this.peerId),v=h&&(()=>{const w=gA();return w.$$click=p,k(w,()=>jt(h,{entities:[{_:"messageEntityCode",length:h.length,offset:0}]})),w})();let y;if(this.subscription)y=[["Stars.Subscription",f],["Stars.Subscription.Subscribed",gs(this.subscription.until_date-this.subscription.pricing.period)],["Stars.Subscription.Renews",gs(this.subscription.until_date)]];else if(this.transaction?.giveaway_post_id)m.replaceChildren(P("BoostingGiveaway")),y=[["BoostingFrom",f],this.transaction.id&&["BoostingTo",g(I.myId)],[this.transaction.id?"BoostingGift":"Giveaway.Prize",P("Stars",[hr(this.transaction.stars)])],["BoostingReason",m],this.transaction.id&&["StarsTransactionID",v],["StarsTransactionDate",gs(this.form.date,void 0,!0)]];else if(this.transaction&&this.transaction.pFlags.gift)y=[[this.isOutGift?"BoostingTo":"BoostingFrom",f],["StarsTransactionDate",gs(this.form.date,void 0,!0)]];else if(this.isReceipt){const w=this.transaction?.paid_messages&&!this.transaction.pFlags.refund&&this.transaction.starref_amount&&this.transaction.stars&&+o>0&&hr(this.transaction.starref_amount)+hr(this.transaction.stars);y=[this.peerId?[this.transaction?.subscription_period?"Stars.Subscription":"BoostingTo",f]:["Stars.Via",t],w&&["PaidMessages.FullPrice",T(zv,{reverse:!0,noSign:!0,inline:!0,stars:w})],this.transaction&&(this.transaction.extended_media||this.transaction.pFlags.reaction)&&m&&[this.transaction.pFlags.reaction?"Message":"StarsTransactionMedia",m],["StarsTransactionID",v],["StarsTransactionDate",gs(this.form.date,void 0,!0)]]}return(()=>{const w=fA(),b=w.firstChild,S=b.firstChild,_=b.nextSibling;return k(w,e,b),S.$$click=async()=>{if(!r.isReceipt||!r.transaction.extended_media)return;const M=r.transaction.extended_media,C=M.map(x=>x.photo||x.document),L=await r.managers.appMessagesManager.generateStandaloneOutgoingMessage(r.peerId);L.media={_:"messageMediaPaidMedia",extended_media:M.map(x=>({_:"messageExtendedMedia",media:x})),stars_amount:0},L.id=An(r.transaction.msg_id),L.mid=r.transaction.msg_id;const E=C.map((x,R)=>({element:null,mid:0,peerId:0,index:R,message:L}));E[0].element=s,new zl(!0).setSearchContext({peerId:0,inputFilter:{_:"inputMessagesFilterEmpty"},useSearch:!1}).openMedia({message:L,target:E[0].element,fromRight:0,reverse:!1,prevTargets:[],nextTargets:E.slice(1)})},k(S,s),k(_,d),k(w,(()=>{const M=V(()=>!!(y&&!r.subscription&&!c));return()=>M()&&T(zv,{get stars(){return r.transaction?o:-+o},get isRefund(){return!!r.transaction?.pFlags?.refund},get noSign(){return r.isOutGift}})})(),null),k(w,u&&(()=>{const M=NS();return k(M,u),Me(()=>be(M,Ge("popup-stars-subtitle",y&&!r.subscription&&!r.boost&&"mt"))),M})(),null),k(w,y&&[T(Rb,{class:"popup-stars-pay-table",get content(){return y.filter(Boolean)}}),(()=>{const M=vA();return k(M,()=>P("Stars.TransactionTOS")),M})(),V((()=>{const M=V(()=>!!r.subscription);return()=>M()&&(()=>{const C=NS();return k(C,()=>P(r.subscription.pFlags.canceled?"Stars.Subscription.Cancelled":"Stars.Subscription.Active",[gs(r.subscription.until_date)])),Me(()=>be(C,Ge("popup-stars-pay-tos","popup-stars-pay-tos2",r.subscription.pFlags.canceled&&"danger"))),C})()})())],null),w})()}async construct(){this.chatInvite||this.paymentForm?._==="payments.paymentFormStarGift"?this.peerId=Wt:this.paymentForm?this.peerId=this.paymentForm.bot_id.toPeerId(!1):this.subscription?this.peerId=it(this.subscription.peer):this.transaction.peer._==="starsTransactionPeer"&&(this.peerId=it(this.transaction.peer.peer));const[e,{title:t,media:s},i]=await Promise.all([(async()=>{const n=document.createElement("img");return n.classList.add("popup-stars-image"),await Vn(n,`assets/img/${Tb(this.boost?"stars":"stars_pay")}.png`),n})(),(async()=>{const n=await sI({transaction:this.transaction,middleware:this.middlewareHelper.get(),size:90,paidMedia:this.paidMedia,paidMediaPeerId:this.message?this.message.fwdFromId||this.message.fromId:this.peerId,chatInvite:this.chatInvite,subscription:this.subscription,photo:this.form._==="payments.paymentFormStarGift"?void 0:this.form?.photo});return this.boost?n.media=void 0:this.transaction&&(this.transaction.pFlags.gift||this.transaction.giveaway_post_id)?n.media=await Dg({width:128,height:128,assetName:"Gift3",middleware:this.middlewareHelper.get(),loop:!1,autoplay:wt.isAvailable("stickers_chat")}).then(async({container:o,promise:l})=>(o.classList.add("popup-stars-pay-sticker"),await l,o)):n.media.classList.add("popup-stars-pay-item"),n})(),(async()=>{if(!this.transaction||!this.transaction.extended_media&&!this.transaction.pFlags.reaction&&!this.transaction.giveaway_post_id||!this.peerId||this.peerId.isUser())return;const n=this.peerId.toChatId(),r=An(this.transaction.msg_id||this.transaction.giveaway_post_id);return`https://t.me/c/${n}/${r}`})()]);this.body.classList.toggle("is-receipt",this.isReceipt),this.appendSolid(()=>this._construct(e,t,s,i)),this.noShowIfStars?this.onConfirm():this.show()}}Fs(["click"]);const wA=!0,SA="assets/img/",CA=["amex","card","diners","discover","jcb","mastercard","visa","unionpay","mir","logo"];function B1(a){if(CA.includes(a))return`${SA}${a}.svg`}function sd(a){const e=a.textEl??new Ne.IntlElement({key:a.key??"PaymentInfo.Done"}),t=e.key,s=ot("btn-primary btn-color-primary payment-item-pay");return s.append(e.element),J(s,async()=>{const i=a.onClick();if(!(i instanceof Promise))return;const n=Yn(s),r=os([s],!0);e.compareAndUpdate({key:"PleaseWait"});try{await i}catch(o){o.handled||console.error("payment button error",o),r(),e.compareAndUpdate({key:t}),n.remove()}}),s}class D1{constructor(e={}){this.options=e;const t=this.input=document.createElement("input");t.type="tel",t.classList.add("input-clear");const s=t instanceof HTMLInputElement?1:2,i=()=>{if(o){--o;return}o=s,Ki(t)},n=()=>{setTimeout(()=>{o=s,Ki(t),document.addEventListener("selectionchange",i)},0)},r=()=>{t.addEventListener("focus",n,{once:!0}),document.removeEventListener("selectionchange",i)};let o;t.addEventListener("focusout",r),r()}get value(){return this.input.value}set value(e){this.input.value=e,this.onValue()}onValue(){document.activeElement===this.input&&Ki(this.input),this.setWidth()}setWidth(){const e=Dl(this.value,this.options?.fontWeight?`${this.options.fontWeight} ${VC} ${Fh}`:$h);this.input.style.width=e+"px"}}class Ln extends ue{constructor(e){super("popup-payment",{closable:!0,overlayClosable:!0,body:!0,scrollable:!0,title:!0}),Nt(this,e),this.result="cancelled",this.tipButtonsMap=new Map}hide(){return this.dispatchEvent("finish",this.result),super.hide()}setPaymentForm(e){this.paymentForm=e,this.d().catch(t=>{console.error("payment popup error",t),this.hide()})}async d(){this.element.classList.add("is-loading"),this.show();let e=!1;const t=()=>{e||(this.result="paid",e=!0,at&&at.hide(),this.hide())},{paymentForm:s,message:i}=this;if(s._==="payments.paymentFormStarGift")throw new Error("not implemented");i&&this.listenerSetter.add(I)("payment_sent",({peerId:et,mid:te})=>{i.peerId===et&&i.mid===te&&t()});const n=i?.media,r=this.isReceipt??(n?!!n.receipt_msg_id||n.extended_media?._==="messageExtendedMedia":s._==="payments.paymentReceipt"),o=n?n.pFlags.test:s.invoice.pFlags.test,l=s._==="payments.paymentFormStars",c=n?n.photo:s.photo,d=n?n.title:s.title,u=n?n.description:s.description;ks(this.title,r?"PaymentReceipt":"PaymentCheckout"),o&&this.title.append(" (Test)");const h="payment-item",p=document.createElement("div");p.classList.add(h);const m=h+"-details",g=document.createElement("div");g.classList.add(m);let f;if(c){f=document.createElement("div"),f.classList.add(m+"-photo","media-container-contain");const et=c.attributes.find(se=>se._==="documentAttributeImageSize"),te=ii(100,100);if(et){const ye=ii(et.w,et.h).aspectFitted(te);f.style.width=ye.width+"px",f.style.height=ye.height+"px"}Bi({photo:c,container:f,boxWidth:te.width,boxHeight:te.height,size:{_:"photoSizeEmpty",type:""}}),g.append(f)}const v=m+"-lines",y=document.createElement("div");y.classList.add(v);const w=document.createElement("div");w.classList.add(v+"-title");const b=document.createElement("div");b.classList.add(v+"-description");const S=document.createElement("div");S.classList.add(v+"-bot-name"),y.append(w,b,S),Qt(w,je(d)),Qt(b,je(u));const _=new Xt;S.append(_.element),g.append(y),p.append(g),this.scrollable.append(p);const M=document.createElement("div");M.classList.add(h+"-preloader-container"),Yn(M,!0),this.scrollable.append(M);const C=this.inputInvoice;let L=s.saved_info||s.info;const E=s.saved_credentials?.[0];let[x,R,B]=await Promise.all([!r&&L&&this.managers.appPaymentsManager.validateRequestedInfo(C,L).catch(et=>{console.error("validateRequestedInfo",et,L)}),E&&this.managers.passwordManager.getState(),qe({peerId:l?Wt:s.provider_id.toPeerId()})]);await _.update({peerId:s.bot_id.toPeerId()}),M.remove(),this.element.classList.remove("is-loading");const N=(et,te)=>qi(et,O,te,wA,!0),{invoice:G}=s,O=G.currency,$=G.pFlags.recurring&&!r,H=!!G.terms_url;await _.update({peerId:s.bot_id.toPeerId()});const D=$||H?await qe({peerId:s.bot_id.toPeerId()}):void 0;M.remove(),this.element.classList.remove("is-loading");const U=()=>{const et=document.createElement("div");et.classList.add(j+"-price");const te=document.createElement("span"),se=document.createElement("span");return et.append(te,se),{label:et,left:te,right:se}},j=h+"-prices",q=document.createElement("div");q.classList.add(j);const W=et=>et.map(te=>{const{amount:se,label:ye}=te,Te=U();Te.left.append(je(ye));const Pe=N(se);return Te.right.textContent=Pe,Te.label}),ee=W(G.prices);let z=()=>0,Z=0;const de=()=>ke+z()+Z,ie=()=>{const et=N(de());ae.right.textContent=et,oe.compareAndUpdate({key:"PaymentCheckoutPay",args:[et]})},oe=new Ne.IntlElement,ae=U();ae.label.classList.add("is-total"),ks(ae.left,"PaymentTransactionTotal");const ke=Uo(G.prices.map(({amount:et})=>+et),0),re=G.max_tip_amount!==void 0&&!r||!!s.tip_amount;if(re){const et=h+"-tips",te=C_[O];z=()=>+Te.value.replace(/\D/g,"");const se=Ke=>{Ke=Math.min(+Ke,+G.max_tip_amount);const Bt=N(Ke,!0);Te.value=Bt,We?.();const bt=this.tipButtonsMap.get(Ke);bt&&bt.classList.add("active"),ie()},ye=U();ks(ye.left,r?"PaymentTip":"PaymentTipOptional");const Te=new D1({fontWeight:500}),{input:Pe}=Te;Pe.classList.add("input-clear",et+"-input"),ye.right.append(Pe),r?ye.label.classList.add("disable-hover"):ye.label.style.cursor="text",ye.label.addEventListener("mousedown",Ke=>{Mi(Ke.target,Pe)||Ki(Pe)}),Pe.addEventListener("input",()=>{se(z())});const De=[te.native||te.symbol,te.space_between?" ":""];te.symbol_left||De.reverse(),ye.right[te.symbol_left?"prepend":"append"](De.join("")),ee.push(ye.label);let We;if(r)se(s.tip_amount);else{const Ke=document.createElement("div");Ke.classList.add(et);const Bt=et+"-tip",bt=G.suggested_tip_amounts.map(ct=>{const Tt=ot(Bt,{noRipple:!0});return Tt.textContent=N(ct),this.tipButtonsMap.set(+ct,Tt),Tt});We=()=>{const ct=Ke.querySelector(".active");ct&&ct.classList.remove("active")},J(Ke,ct=>{const Tt=ne(ct.target,Bt);if(!Tt)return;let ft=0;if(Tt.classList.contains("active"))Tt.classList.remove("active");else{We(),Tt.classList.add("active");for(const[Kt,es]of this.tipButtonsMap)if(es===Tt){ft=Kt;break}}se(ft)}),se(0),Ke.append(...bt),ee.push(Ke)}}else ie();ee.push(ae.label),q.append(...ee),p.append(q);const ce=async(et,te)=>{const se=document.createElement("img");se.classList.add("media-photo"),await Vn(se,B1(te));let ye=et.media;ye?St(ye,se):(ye=et.createMedia("small"),ye.classList.add("media-container-cover"),ye.append(se)),et.container.classList.remove("row-with-icon")},Ie=et=>{et.titleLangKey&&(et.subtitleLangKey=et.titleLangKey),et.noWrap=!0;const te=new Fe(et);return te.container.classList.add(h+"-row"),et.titleLangKey&&te.subtitle.classList.add("hide"),te},Ve=(et,te)=>{if(et.title.textContent=te,!te){const se=Ne.weakMap.get(et.subtitle.firstElementChild);et.title.append(P(se.key))}et.subtitle.classList.toggle("hide",!te)},fe=et=>{let te,se,ye;"title"in et?(te=et.title.split(" ").shift(),se=et.title,ye=et.icon):(te=L1(et.cardNumber),se=te+" *"+et.cardNumber.split(" ").pop()),Je.container.querySelector(`.${zr("card_outline")}`)?.remove(),ce(Je,ye||te.toLowerCase()),Ve(Je,se)},Xe=async()=>{ue.createPopup(Q2,s,await this.managers.appUsersManager.getSelf(),Ye).addEventListener("finish",({token:et,card:te})=>{Ze=et,Ye=te,fe(te)})};let Ye,Ze;const Je=Ie({titleLangKey:"PaymentCheckoutMethod",clickable:r?void 0:Xe,icon:"card_outline"});Je.container.classList.add(h+"-method-row"),E?fe(E):s.credentials_title&&fe({title:s.credentials_title});const tt=Ie({title:B,subtitleLangKey:"PaymentCheckoutProvider"}),ht=vs({middleware:this.middlewareHelper.get(),size:32,peerId:l?Wt:s.provider_id.toPeerId()});tt.createMedia("small").append(ht.node);let Ee,ve,Qe,A,F,Q,X,ge;const he=G.pFlags.shipping_address_requested?et=>{if(!et){F.subtitle.classList.add("hide"),St(F.title,P("PaymentShippingAddress"));return}const te=et.shipping_address;Ve(Ee,[te.city,te.street_line1,te.street_line2].filter(Boolean).join(", ")),F.container.classList.toggle("hide",!x?.shipping_options&&!r)}:void 0,Le=et=>{he&&he?.(et),ve&&Ve(ve,et.name),Qe&&Ve(Qe,et.email),A&&Ve(A,et.phone&&"+"+bd(et.phone).formatted)};if(r||(X=et=>{ue.createPopup(Z2,s,C,et).addEventListener("finish",({shippingAddress:te,requestedInfo:se})=>{x=se,L=s.saved_info=te,Le(te)})}),G.pFlags.shipping_address_requested){const et=ye=>{const Te=new Hg(this.scrollable,void 0,!0);if(Te.save(),te&&te.forEach(De=>De.remove()),!ye){Z=0,ie(),Te.restore(),this.onContentUpdate();return}Q=ye,Ve(F,ye.title),Z=Uo(ye.prices.map(({amount:De})=>+De),0),te=W(ye.prices);let Pe=ae.label;re&&(Pe=Pe.previousElementSibling,r||(Pe=Pe.previousElementSibling)),te.forEach(De=>Pe.parentElement.insertBefore(De,Pe)),ie(),Te.restore(),this.onContentUpdate()};Ee=Ie({icon:"location",titleLangKey:"PaymentShippingAddress",clickable:!r&&X.bind(null,void 0)});let te;F=Ie({icon:"shipping",titleLangKey:"PaymentCheckoutShippingMethod",clickable:!r&&(ge=()=>{ue.createPopup(J2,s,x,Q).addEventListener("finish",ye=>{et(ye)})})}),F.container.classList.add("hide");const se=s.shipping;se&&et(se)}G.pFlags.name_requested&&(ve=Ie({icon:"newprivate",titleLangKey:"PaymentCheckoutName",clickable:!r&&X.bind(null,"name")})),G.pFlags.email_requested&&(Qe=Ie({icon:"mention",titleLangKey:"PaymentShippingEmailPlaceholder",clickable:!r&&X.bind(null,"email")})),G.pFlags.phone_requested&&(A=Ie({icon:"phone",titleLangKey:"PaymentCheckoutPhoneNumber",clickable:!r&&X.bind(null,"phone")})),L&&Le(L);const Se=[Je,tt,Ee,F,ve,Qe,A].filter(Boolean),xe=($||H)&&new _t({text:$?"Payments.Recurrent.Accept":"Payments.Terms.Accept",textArgs:[jt(G.terms_url),D]}),lt=xe&&Ie({checkboxField:xe}),mt=xe?[document.createElement("hr"),lt.container]:[];this.scrollable.append(...[document.createElement("hr"),...Se.map(et=>et.container),...mt].filter(Boolean));let at,kt;const Us=()=>{const et=G.pFlags.name_requested&&!L?.name?"name":G.pFlags.email_requested&&!L?.email?"email":G.pFlags.phone_requested&&!L?.phone?"phone":void 0;if(G.pFlags.shipping_address_requested)if(x){if(!Q&&x.shipping_options){ge();return}}else{X();return}else if(et){X(et);return}if(!Ye&&!kt){if(!E){Xe();return}Promise.resolve(R??this.managers.passwordManager.getState()).then(te=>{ue.createPopup(X2,E.title,te).addEventListener("finish",se=>{R=void 0,kt=se,Xs(zs);const ye=se.valid_until-Qs(!0)-5;setTimeout(()=>{kt===se&&(kt=void 0)},ye*1e3)})});return}return Promise.resolve().then(async()=>{const te=kt?{_:"inputPaymentCredentialsSaved",id:E.id,tmp_password:kt.tmp_password}:{_:"inputPaymentCredentials",data:{_:"dataJSON",data:JSON.stringify(Ze.token?Ze:{type:Ze.type,id:Ze.id})},pFlags:{save:Ye.save||void 0}};try{this.result="pending";const se=await this.managers.appPaymentsManager.sendPaymentForm(C,s.form_id,x?.id,Q?.id,te,z());se._==="payments.paymentResult"?t():(at=ue.createPopup(Y2,se.url,!n?.extended_media),at.addEventListener("finish",()=>{at=void 0,t()}),await new Promise((ye,Te)=>{at.addEventListener("close",()=>{if(at=void 0,e)ye();else{const Pe=Vo(void 0,"payment not finished");Pe.handled=!0,Te(Pe),this.result="failed"}})}))}catch(se){throw se.type==="BOT_PRECHECKOUT_TIMEOUT"?($e({langPackKey:"Error.AnError"}),se.handled=!0):se.type==="TMP_PASSWORD_INVALID"?(R=kt=void 0,Xs(zs),se.handled=!0):this.result="failed",se}})},Ts=()=>{zs.disabled=!!(xe&&!xe.checked)};let zs;r?zs=sd({onClick:()=>this.hide(),key:"Done"}):zs=sd({onClick:Us,textEl:oe}),Ts(),xe&&xe.input.addEventListener("change",Ts),this.body.append(this.btnConfirmOnEnter=zs),this.onContentUpdate()}static async create(e){let t;!e.paymentForm&&!e.transaction&&!e.noPaymentForm?e.isReceipt?t=I.managers.appPaymentsManager.getPaymentReceipt(e.message.peerId,e.message.media.receipt_msg_id||e.inputInvoice.msg_id):t=I.managers.appPaymentsManager.getPaymentForm(e.inputInvoice):t=Promise.resolve(e.paymentForm);const s=await t,i=e.noPaymentForm||e.transaction||e.giftAction||s._==="payments.paymentFormStars"||s._==="payments.paymentReceiptStars"||s._==="payments.paymentFormStarGift"?bA:Ln,n=ue.createPopup(i,e);return n.setPaymentForm(s),n}}const[_A,Hv]=K(),[IA,eu]=K(0),PA=()=>I.managers.appPaymentsManager.getStarsStatus(!0).then(a=>Hv(hr(a.balance)));function $1(a){return Ft(e=>{a.onClean(e);const t=Jl();return t()!==void 0?t():new Promise(s=>{Or(()=>s(t()))(t)})})}let Gv;function N1(){return Gv||T_(()=>N1.name,()=>(PA(),I.addEventListener("stars_balance",({balance:a,fulfilledReservedStars:e})=>{pi(()=>{Hv(a),e&&eu(t=>Math.max(0,t-e))})}),ze(()=>{I.removeEventListener("stars_balance",Hv)}),V(()=>+_A()-+IA())))()}function Jl(){return Gv??(Gv=Ft(()=>N1()))}const MA=Y("<div>");let OS=!1;const LA=()=>{if(OS)return;const a=[];tu.forEach((e,t)=>{const s=[...e.keys()],i=I.managers.appStoriesManager.getStoriesById(t,s,!0).then(()=>{s.forEach(n=>{e.get(n).mounted||(e.delete(n),e.size||tu.delete(t))})});a.push(i)}),Promise.all(a).then(()=>{OS=!1})},tu=new Map;window.wrappedStories=tu;setInterval(LA,3e5);const zu=a=>{const[e,t]=K(),[s,i]=K(),[n,r]=K(!1);let o=tu.get(a.peerId);o||tu.set(a.peerId,o=new Map);let l=o.get(a.storyItem.id);l||o.set(a.storyItem.id,l={mounted:0}),++l.mounted,ze(()=>{--l.mounted});const c=bl(a.storyItem.media),d=ui().get();let u;const h=(()=>{const f=MA(),v=u;return typeof v=="function"?Ue(v,f):u=f,so(f,ni(()=>a.containerProps||{}),!1,!1),f})(),p=(f,v)=>{[f.images.thumb,f.images.full].filter(Boolean).forEach(y=>{y.classList.add(v)})},m={photo:f=>{const v=f.document||f.photo,y=Bi({...a,container:u,photo:v,middleware:d,...a.forPreview&&{...a.noAspecter&&{size:ha(v,150,200)},useRenderCache:!1},...a.forViewer&&{size:ha(v,1/0,1/0),noFadeIn:!0},withoutPreloader:!a.withPreloader});return y.then(async w=>{d()&&(a.childrenClassName&&p(w,a.childrenClassName),await w.loadPromises.thumb,d()&&(t(w.images.thumb),r(!0),await w.loadPromises.full,d()&&i(w.images.full)))}),y},video:f=>{const v=f.document,y=f.alt_documents?.[0],w=Xa({...a,container:u,doc:v,altDoc:y,middleware:d,...a.forViewer&&{noInfo:!0,noAutoplayAttribute:!0},...a.forPreview&&{...a.noAspecter&&{photoSize:ha(v,200,200,!1)},onlyPreview:!0},withoutPreloader:!a.withPreloader});return w.then(async b=>{if(!d()||(a.childrenClassName&&(b?.thumb&&p(b.thumb,a.childrenClassName),b?.video&&b.video.classList.add(a.childrenClassName)),b?.thumb&&await b.thumb.loadPromises.thumb,!d()))return;b?.thumb&&t(b.thumb.images.full||b.thumb.images.thumb),r(!0);const S=b?.video;S&&a.forViewer&&(S.loop=!1,S.muted=!0,dn&&S.load()),await b?.loadPromise,d()&&i(S)}),w}};let g;switch(c._){case"messageMediaPhoto":{g=m.photo(c);break}case"messageMediaDocument":{g=m.video(c);break}}return{container:h,div:u,media:s,mediaResult:g,thumb:e,ready:n}},EA=a=>{let{loadPromises:e}=a;e&&delete a.loadPromises;const t=e&&Mt();e?.push(t),e=void 0;const[s,i]=K(void 0,{equals:!1}),[n,r]=K();return I.managers.acknowledged.appStoriesManager.getStoryById(a.peerId,a.storyId).then(async l=>{l.cached||t?.resolve();const c=await l.result;i(c)}),le(Vt(()=>s(),l=>{if(!l){a.onExpiredStory?.(),t.resolve();return}ze(()=>{t?.reject()});const{container:c,ready:d}=zu({...a,storyItem:l,forPreview:!0});le(Vt(()=>d(),()=>{t?.resolve(),r(c)},{defer:!0}))},{defer:!0})),n},kA=Y("<span class=statistics-overview-item-value-description>"),TA=Y("<span>"),xA=Y("<div class=statistics-overview-item><div class=statistics-overview-item-value></div><div class=statistics-overview-item-name>"),AA=Y("<div class=statistics-overview>"),RA=Y("<div class=statistics-chart>"),FA=Y("<div>"),BA={growth_graph:"GrowthChartTitle",followers_graph:"FollowersChartTitle",mute_graph:"Notifications",top_hours_graph:"TopHoursChartTitle",views_by_source_graph:"ViewsBySourceChartTitle",new_followers_by_source_graph:"NewFollowersBySourceChartTitle",languages_graph:"LanguagesChartTitle",interactions_graph:"InteractionsChartTitle",iv_interactions_graph:"IVInteractionsChartTitle",reactions_by_emotion_graph:"ReactionsByEmotionChartTitle",story_interactions_graph:"StoryInteractionsChartTitle",story_reactions_by_emotion_graph:"StoryReactionsByEmotionChartTitle"},DA={growth_graph:"GrowthChartTitle",members_graph:"GroupMembersChartTitle",new_members_by_source_graph:"NewMembersBySourceChartTitle",languages_graph:"MembersLanguageChartTitle",messages_graph:"MessagesChartTitle",actions_graph:"ActionsChartTitle",top_hours_graph:"TopHoursChartTitle",weekdays_graph:"TopDaysOfWeekChartTitle"},O1={views_graph:"ViewsAndSharesChartTitle",reactions_by_emotion_graph:"ReactionsByEmotionChartTitle"},$A=O1,NA={followers:"FollowersChartTitle",enabled_notifications:"EnabledNotifications",views_per_post:"ViewsPerPost",views_per_story:"ViewsPerStory",shares_per_post:"SharesPerPost",shares_per_story:"SharesPerStory",reactions_per_post:"ReactionsPerPost",reactions_per_story:"ReactionsPerStory"},OA={members:"MembersOverviewTitle",messages:"MessagesOverview",viewers:"ViewingMembers",posters:"PostingMembers"},U1={views:"StatisticViews",public_shares:"PublicShares",reactions:"Reactions",private_shares:"PrivateShares"},UA=U1;let HA,H1;function GA(){return HA??(HA=zo(()=>import("./chart-BIax9IsQ.js"),__vite__mapDeps([0,1]),import.meta.url).then(a=>{H1=a.default}))}function VA(a){return a.substring(a.indexOf("#"))}const Oa=(a,e)=>({_:"statsAbsValueAndPrev",current:a,previous:0,approximate:e}),id=(a={})=>K({rendered:[],values:[],left:0,count:0,...a},{equals:!1}),Mm=(a,e,t,s="PollResults.LoadMore")=>{const i=ot("btn btn-primary btn-transparent primary",{icon:"down",text:s,textArgs:[a]});return J(i,()=>{e(i)},{listenerSetter:t}),i},zA=({value:a,title:e,includeZeroValue:t,describePercentage:s})=>{const i=a._==="statsPercentValue";let n;if(i)n=`${(a.part/a.total*100).toFixed(2)}%`,s&&(n=[V(()=>`≈${a.part} `),(()=>{const o=kA();return k(o,n),o})()]);else{if(n=un(a.current,1),a.approximate&&(n="≈"+n),!a.current&&!a.previous&&!t)return;if(a.current!==a.previous&&a.previous){const r=a.current-a.previous,o=Math.abs(r),l=`${r>0?"+":"-"}${un(o,1)}`,c=+(Math.abs(1-a.current/a.previous)*100).toFixed(2),d=`${l} (${c}%)`;n=[n," ",(()=>{const u=TA();return k(u,d),Me(()=>be(u,Ge("statistics-overview-item-value-description",r>0?"green":"red"))),u})()]}}return(()=>{const r=xA(),o=r.firstChild,l=o.nextSibling;return k(o,n),k(l,()=>P(e)),r})()},G1=a=>(()=>{const e=AA();return k(e,T(Cs,{get each(){return a.items},children:zA})),e})();class Wu extends Bs{constructor(){super(...arguments);ro(this,"renderPeer",async t=>{const s=t._==="message"?t.peerId:t.user_id.toPeerId(!1),i=[],{dom:n}=nt.addDialogNew({peerId:s,container:!1,rippleEnabled:!0,avatarSize:"abitbigger",loadPromises:i,wrapOptions:{middleware:this.middlewareHelper.get()},meAsSaved:!1});let r;return t._==="message"?(r=[await ja(s.toChatId()),P("Views",[un(t.views,1)])],n.listEl.dataset.mid=""+t.mid):t._==="statsGroupTopPoster"?r=[t.messages&&P("messages",[t.messages]),t.avg_chars&&P("CharactersPerMessage",[P("Characters",[t.avg_chars])])]:t._==="statsGroupTopAdmin"?r=[t.deleted&&P("Deletions",[t.deleted]),t.banned&&P("Bans",[t.banned]),t.kicked&&P("Restrictions",[t.kicked])]:r=[t.invitations&&P("Invitations",[t.invitations])],r=r.filter(Boolean),r.length&&n.lastMessageSpan.replaceChildren(...Yi(r,!1)),await Promise.all(i),{container:n.listEl,peerId:s}});ro(this,"renderPublicForward",async t=>{if(t._==="publicForwardMessage"){const n=t.message;return this.renderRecentPost({_:"postInteractionCountersMessage",forwards:n.forwards,msg_id:n.mid,views:n.views,reactions:n.reactions?n.reactions.results.reduce((r,o)=>r+o.count,0):0},n.peerId,n)}const s=t.story;if(!s)return;const i=s.views;return this.renderRecentPost({_:"postInteractionCountersStory",forwards:i?.forwards_count||0,story_id:s.id,views:i?.views_count||0,reactions:i?.reactions_count||0},it(t.peer),void 0,s)})}onOpenAfterTimeout(){this.openPromise.resolve()}_construct(t,s,i,n,r,o){const l=this,c=new Ne.IntlDateElement({options:{}}),d=(C,L={})=>{L.displayYear??(L.displayYear=!0),L.isMonthShort??(L.isMonthShort=!0);const E=new Date(C);return c.update({date:E,options:{weekday:L.displayWeekDay?L.isShort?"short":"long":void 0,year:L.displayYear?"numeric":void 0,hour:L.displayHours?"2-digit":void 0,minute:L.displayHours?"2-digit":void 0,month:L.isMonthShort?"short":"long",day:"numeric"}}),c.element.textContent},u=C=>{const L=new Date(C);return c.update({date:L,options:{hour:"2-digit",minute:"2-digit"}}),c.element.textContent},h=()=>{const C=yi.getProperty("surface-color"),L=yi.getProperty("primary-color"),E=yi.getProperty("secondary-color"),x=Pa(C),R=Jd(Pa(E),Jd(Pa(L),x,.1),.2),B=Jd(Pa(E),Jd(Pa(L),x,.3),.4);return{primary:yi.getProperty("primary-color"),secondary:yi.getProperty("secondary-color"),background:C,backgroundRgb:x,text:yi.getProperty("primary-text-color"),dates:yi.getProperty("secondary-text-color"),grid:`rgba(${Pa(yi.getProperty("secondary-text-color")).join(", ")}, 0.2)`,axis:{x:yi.getProperty("secondary-text-color"),y:yi.getProperty("secondary-text-color")},barsSelectionBackground:`rgba(${x.join(", ")}, 0.5)`,miniMask:`rgba(${R.join(", ")}, 0.6)`,miniFrame:`rgb(${B.join(", ")})`}};let p=h();this.listenerSetter.add(I)("theme_changed",()=>{p=h()});const m=this.isBroadcast?BA:this.isMegagroup?DA:this.isStory?$A:O1,g=Object.keys(m).map(C=>{const L=this.stats[C];return L&&{statsGraph:L,title:m[C],percentage:C==="languages_graph"}}).filter(Boolean),f=({statsGraph:C,title:L,percentage:E})=>{Jt(()=>{let G=JSON.parse(C.json.data);const O=(j,q)=>{for(const W in j.colors){const ee=j.colors[W];j.colors[W]=VA(ee)}if(q)for(const W in j.types)j.types[W]==="bar"&&(j.types[W]="area");return j};G=O(G,E);const $={getLabelDate:d,getLabelTime:u,tooltipOnHover:!0},H=C.zoom_token,D=H1.render({container:N,data:{...G,...$,x_on_zoom:H?async j=>{const q=await this.managers.appStatisticsManager.loadAsyncGraph(H,j,this.dcId);if(q._!=="statsGraphError")return{...O(JSON.parse(q.json.data),E),...$}}:void 0},settings:{darkMode:Ls.isNight(),ALL_LABEL:Ne.format("Chart.Tooltip.All",!0),DATES_SIDE:"left",DATES_WEIGHT:"normal",DATES_FONT_SIZE:14,ZOOM_TEXT:Ne.format("ZoomOut",!0),FONT:{family:Fh,bold:"500",normal:"400"},COLORS:p}}),U=()=>{[["primary-color",p.primary],["background-color",p.background],["background-color-rgb",p.backgroundRgb.join(", ")],["text-color",p.text],["secondary-color",p.secondary],["font-family",Fh]].forEach(([q,W])=>{D.$wrapper.style.setProperty(`--tchart-${q}`,W)})};U(),this.listenerSetter.add(I)("theme_changed",()=>{D.setDarkMode(Ls.isNight(),{...p}),U()})});const x=document.createElement("div"),R=document.createElement("div");x.classList.add("statistics-title");const B=P(L);B.classList.add("statistics-title-text"),x.append(B);let N;return T(Ms,{name:x,nameRight:R,get children(){const G=RA(),O=N;return typeof O=="function"?Ue(O,G):N=G,G}})},v=this.stats._==="stats.broadcastStats"?NA:this.isMegagroup?OA:this.isStory?UA:U1,y=Object.keys(v).map(C=>{const L=this.stats[C];return L&&{value:L,title:v[C]}}).filter(Boolean),w=(C,L)=>Kl([C,L].map(E=>new Ne.IntlDateElement({date:new Date(E*1e3),options:{month:"short",day:"numeric",year:"numeric"}}).element)," — "),b=this.stats.period,S=["TopMembers","TopAdmins","TopInviters"];let _;const M=[o&&T(Ms,{get children(){return o.container}}),T(Ms,{name:"StatisticOverview",get nameRight(){return b&&w(b.min_date,b.max_date)},get children(){return T(G1,{items:y})}}),T(Cs,{each:g,children:f}),V((()=>{const C=V(()=>!!t.length);return()=>C()&&T(Ms,{ref(L){const E=_;typeof E=="function"?E(L):_=L},name:"RecentPosts",get children(){return t.map(({container:L})=>L)}})})()),T(Cs,{each:[s,i,n],children:(C,L)=>{if(!C.length)return;C=C.slice();const E=nt.createChatList();E.append(...C.splice(0,10).map(({container:R})=>R));let x;return C.length&&(x=Mm(C.length,()=>{x.remove(),E.append(...C.map(({container:R})=>R))},l.listenerSetter)),T(Ms,{get name(){return S[L()]},get nameRight(){return b&&w(b.min_date,b.max_date)},get children(){return[E,x]}})}}),V((()=>{const C=V(()=>!!r().count);return()=>C()&&T(Ms,{name:"PublicSharesCount",get nameArgs(){return[r().count]},get children(){return[(()=>{const L=FA();return Ue(E=>{nt.setListClickListener({list:E,onFound:x=>{if(x.dataset.storyId)return Fo({target:()=>x.querySelector(".avatar"),peerId:x.dataset.peerId.toPeerId(),id:+x.dataset.storyId}),!1},withContext:void 0,autonomous:void 0,openInner:!0})},L),k(L,()=>r().rendered),L})(),V(()=>V(()=>!!r().loadMore)()&&Mm(r().count-r().rendered.length,L=>{const E=os(L,!0);r().loadMore().finally(()=>E())},l.listenerSetter))]}})})())];if(_){const C=new Map;t.forEach(({container:R,postInteractionCounters:B})=>{C.set(R,B)});const L=R=>ne(R.target,"statistics-post");let E;const x=()=>{this.slider.createTab(Wu).open(this.chatId,E.msg_id,E.story_id)};J(_,R=>{E=C.get(L(R)),E&&x()},{listenerSetter:this.listenerSetter}),Dn({buttons:[{icon:"statistics",text:"ViewStatistics",onClick:x},{icon:"message",text:"Message.Context.Goto",onClick:()=>{Ce.setInnerPeer({peerId:this.chatId.toPeerId(!0),lastMsgId:E.msg_id})},verify:()=>E._==="postInteractionCountersMessage"},{icon:"stories",text:"ViewStory",onClick:()=>{Fo({peerId:this.chatId.toPeerId(!0),id:E.story_id})},verify:()=>E._==="postInteractionCountersStory"}],listenTo:_,listenerSetter:this.listenerSetter,findElement:R=>{const B=L(R);return E=C.get(B),B},middleware:this.middlewareHelper.get()})}return M}async renderRecentPost(t,s=this.chatId.toPeerId(!0),i,n,r){const o=document.createDocumentFragment(),l=[["reactions",t.reactions],["reply",t.forwards]];!r&&l.forEach(([p,m])=>{if(!m)return;const g=Be(p,"statistics-post-counter-icon");p==="reply"&&g.classList.add("icon-reflect");const f=document.createElement("span");f.classList.add("statistics-post-counter"),f.append(g,un(m,1)),o.append(f)});const c=new Fe({title:!0,titleRight:r?void 0:P("Views",[ln(t.views)]),subtitle:!0,subtitleRight:r?void 0:o,clickable:!0,noWrap:!0,asLink:!!(i||n)}),{container:d}=c;d.classList.add("statistics-post"),c.title.classList.add("statistics-post-title");const u=this.middlewareHelper.get(),h=document.createElement("div");if(h.classList.add("statistics-post-media"),i||n){const{node:p,readyThumbPromise:m,setStoriesSegments:g}=vs({middleware:u,size:42,isDialog:!0,peerId:s});c.container.dataset.peerId=""+s,n?(g([{length:1,type:"unread"}]),c.container.dataset.storyId=""+n.id):c.container.dataset.mid=""+i.mid,h.append(p),await m,c.title.append(await qe({peerId:s})),c.subtitle.append(gs(i?.date||n?.date)),c.applyMediaElement(h,"abitbigger")}else if(t._==="postInteractionCountersMessage"){if(d.classList.add("statistics-post-message"),i||(i=this.messages.get(t.msg_id)),!await Eb({titleEl:c.subtitle,title:gs(i.date),subtitleEl:c.title,message:i,mediaEl:h,middleware:u,withoutMediaType:!0})){const{node:m,readyThumbPromise:g}=vs({middleware:u,peerId:s,size:42});h.append(m),await g}c.applyMediaElement(h,"abitbigger")}else{d.classList.add("statistics-post-story"),n||(n=this.stories.get(t.story_id)),c.title.append(P("Story")),c.subtitle.append(gs(n.date));const p=document.createElement("div");p.classList.add("avatar-stories-simple","is-unread"),h.append(p),await Ft(m=>{u.onDestroy(m);const{ready:g,div:f}=zu({storyItem:n,peerId:this.chatId.toPeerId(!0),forPreview:!0,noInfo:!0,withPreloader:!1,noAspecter:!0}),v=Mt();return le(()=>{g()&&(h.append(f),v.resolve())}),v}),c.applyMediaElement(h,"abitbigger")}return{container:d,postInteractionCounters:t}}async loadStats(){const t=this.chatId.toPeerId(!0),s=this.managers.appStatisticsManager,i=100,n=this.isBroadcast?s.getBroadcastStats:this.isMegagroup?s.getMegagroupStats:this.isStory?s.getStoryStats:s.getMessageStats,r=this.isMessage?this.managers.appMessagesManager.reloadMessages(t,this.mid):void 0,o=this.isMessage?s.getMessagePublicForwards({peerId:t,mid:this.mid,limit:i}):void 0,l=this.isStory?this.managers.appStoriesManager.getStoryById(t,this.storyId):void 0,c=this.isStory?s.getStoryPublicForwards({peerId:t,id:this.storyId,limit:i}):void 0,{stats:d,dcId:u}=await n({peerId:t,dark:Ls.isNight(),storyId:this.storyId,mid:this.mid});this.stats=d,this.dcId=u;const h=[];for(const S in d){const _=d[S];if(_._==="statsGraphAsync"){const M=s.loadAsyncGraph(_.token,void 0,u).then(C=>{if(C._==="statsGraphError"){delete d[S];return}d[S]=C});h.push(M)}else _._==="statsGraphError"&&delete d[S]}const p=d.recent_posts_interactions||[];p.forEach(S=>{let _;S._==="postInteractionCountersMessage"?_=this.managers.appMessagesManager.reloadMessages(t,S.msg_id).then(M=>{if(!M){Vs(p,S);return}this.messages.set(M.mid,M)}):_=this.managers.appStoriesManager.getStoryById(t,S.story_id).then(M=>{if(!M){Vs(p,S);return}this.stories.set(M.id,M)}),h.push(_)});const m=Promise.all([r,o,l,c]).then(async([S,_,M,C])=>{const[L,E]=id();if(!S&&!M)return L;if(S){this.messages.set(S.mid,S);const x=_.count;d.views=Oa(S.views),d.reactions=Oa(S.reactions?S.reactions.results.reduce((N,G)=>N+G.count,0):0),d.public_shares=Oa(x),d.private_shares=Oa(S.forwards-x,!0),E(N=>(N.count=x,N));let R;const B=async N=>{R=N.next_offset;const G=N.forwards.map(this.renderPublicForward),O=await Promise.all(G);E($=>($.rendered.push(...O.map(({container:H})=>H)),$.loadMore=R?()=>s.getMessagePublicForwards({peerId:t,mid:this.mid,limit:i,offset:R}).then(B):void 0,$))};await B(_)}else{const x=C.count,R=M.views;d.views=Oa(R.views_count),d.reactions=Oa(R.reactions_count||0),d.public_shares=Oa(x),d.private_shares=Oa(Math.abs((R.forwards_count||0)-x),!0),E(G=>(G.count=x,G));let B;const N=async G=>{B=G.next_offset;const O=G.forwards.map(this.renderPublicForward),$=await Promise.all(O);E(H=>(H.rendered.push(...$.map(({container:D})=>D)),H.loadMore=B?()=>s.getStoryPublicForwards({peerId:t,id:M.id,limit:i,offset:B}).then(N):void 0,H))};await N(C)}return L});h.push(m);const g=d.top_posters||[],f=d.top_admins||[],v=d.top_inviters||[],y=g.map(this.renderPeer),w=f.map(this.renderPeer),b=v.map(this.renderPeer);return Promise.all(h).then(()=>{const S=p.map(C=>this.renderRecentPost(C)),_=this.isMessage?this.renderRecentPost({_:"postInteractionCountersMessage",msg_id:this.mid,forwards:0,reactions:0,views:0},void 0,void 0,void 0,!0):void 0,M=[Promise.all(S),Promise.all(y),Promise.all(w),Promise.all(b),m,_];return Promise.all(M)})}async init(t,s,i){this.container.classList.add("statistics-container"),this.chatId=t,this.mid=s,this.storyId=i,this.messages=new Map,this.stories=new Map,this.openPromise=Mt(),s?this.isMessage=!0:i?this.isStory=!0:(this.isBroadcast=await this.managers.appChatsManager.isBroadcast(t),this.isMegagroup=await this.managers.appChatsManager.isMegagroup(t)),this.setTitle(this.isBroadcast?"Statistics":this.isMegagroup?"GroupStats.Title":this.isStory?"StoryStatistics":"PostStatistics");const n=Promise.all([GA(),this.openPromise,this.loadStats()]),[r,o]=K(!1),l=await s1({title:()=>P("LoadingStats"),description:()=>P("LoadingStatsDescription"),assetName:"StatsEmoji",middleware:this.middlewareHelper.get(),hide:r,isFullSize:!0});this.scrollable.append(l),n.then(async([c,d,u])=>{const h=document.createElement("div");this.scrollable.append(h);const p=wi(()=>this._construct(...u),h);if(this.eventListener.addEventListener("destroy",p),wt.isAvailable("animations")){const m=[{opacity:"1"},{opacity:"0"}],g={duration:200,fill:"forwards",easing:"ease-in-out"},f=[l.animate(m,g),h.animate(m.slice().reverse(),g)];await Promise.all(f.map(v=>v.finished))}o(!0)})}}const WA=()=>{const a=new Date;return a.setHours(0,0,0,0),a},V1=()=>{const a=new Date;return a.setFullYear(a.getFullYear()+1),a.setDate(a.getDate()-1),a},KA=(a,e)=>{const t=a.getTime()>V1().getTime()?new Date:a;return e&&t.setMinutes(t.getMinutes()+e),t};class Fb extends Ng{constructor(e){if(super(KA(e.initDate,e.canSendWhenOnline!==void 0?10:void 0),e.onPick,{noButtons:!0,noTitle:!0,closable:!0,withConfirm:!0,minDate:e.minDate??WA(),maxDate:e.maxDate??V1(),withTime:!0,showOverflowMonths:!0,confirmShortcutIsSendShortcut:!0,title:!0}),this.canSendWhenOnline=e.canSendWhenOnline,this.isCustomButtonText=!!e.btnConfirmLangKey,this.element.classList.add("popup-schedule"),this.header.append(this.controlsDiv),this.title.replaceWith(this.monthTitle),this.body.append(this.btnConfirm),e.canSendWhenOnline){const t=ot("btn-primary btn-secondary btn-primary-transparent primary popup-schedule-secondary",{text:"Schedule.SendWhenOnline"});this.body.append(t),J(t,()=>{e.onPick(Nh),this.hide()})}e.btnConfirmLangKey&&(this.btnConfirm.replaceChildren(P(e.btnConfirmLangKey)),this.btnConfirm.classList.add("text-uppercase"))}setTimeTitle(){if(super.setTimeTitle(),!(this.btnConfirm&&this.selectedDate)||this.isCustomButtonText)return;let e;const t=[],s=new Date;s.setHours(0,0,0,0);const i={minute:"2-digit",hour:"2-digit"},n=new Date(this.selectedDate.getTime());if(n.setHours(+this.hoursInputField.value,+this.minutesInputField.value),this.selectedDate.getTime()===s.getTime())e="Schedule.SendToday";else{e="Schedule.SendDate";const r={month:"short",day:"numeric"};n.getFullYear()!==s.getFullYear()&&(r.year="numeric"),t.push(new Ne.IntlDateElement({date:n,options:r}).element)}t.push(new Ne.IntlDateElement({date:n,options:i}).element),this.btnConfirm.replaceChildren(P(e,t))}}const Ku=a=>{const{callback:e,onEnd:t}=a,s=sb(()=>a.children);return le(()=>{const{dispose:i,element:n}=Ei(s(),e,t,!0);ze(()=>{i(),n.remove()})}),a.children},jA=Y("<div dir=auto>"),US=Y("<div>"),qA=Y("<div class=row-right>");function En(a={}){const e=h=>{if(h.part)return(()=>{const p=jA();return k(p,()=>h.part),Me(()=>be(p,Ge("row-"+h.class,s()&&"no-wrap"))),p})()},t=h=>{const p=T(e,{get class(){return h.class},get part(){return h.left}});return h.right?(()=>{const m=US();return k(m,p,null),k(m,T(e,{get class(){return`${h.class} row-${h.class}-right${h.rightSecondary?` row-${h.class}-right-secondary`:""}`},get part(){return h.right}}),null),Me(()=>be(m,Ge("row-row",`row-${h.class}-row`))),m})():p},s=()=>a.noWrap,i=T(t,{class:"title",get left(){return a.title},get right(){return a.titleRight||a.checkboxFieldToggle},get rightSecondary(){return a.titleRightSecondary}}),n=T(t,{class:"subtitle",get left(){return a.subtitle},get right(){return a.subtitleRight}}),r=LL(()=>a.rightContent),o=()=>!!(a.checkboxField||a.checkboxFieldToggle||a.radioField),l=()=>!!(a.clickable||o()),c=()=>!!(!a.noRipple&&l()),d=()=>!!(a.havePadding||a.icon||a.checkboxField||a.radioField||a.media),u=T(Ru,{ref(h){const p=a.ref;typeof p=="function"?p(h):a.ref=h},get component(){return V(()=>!!a.asLink)()?"a":a.asLabel||o()?"label":"div"},get classList(){return{row:!0,"no-subtitle":!n,"no-wrap":a.noWrap,"row-with-icon":!!a.icon,"row-with-padding":d(),[`row-clickable hover-${a.color?a.color+"-":""}effect`]:l(),"is-disabled":a.disabled,"is-fake-disabled":a.fakeDisabled,"row-grid":!!r(),"with-midtitle":!!a.midtitle,...a.classList||{}}},get onClick(){return typeof a.clickable!="boolean"&&a.clickable},get children(){return[i,V(()=>V(()=>!!a.midtitle)()&&T(t,{class:"midtitle",get left(){return a.midtitle}})),n,V(()=>V(()=>!!a.icon)()&&T(hs,{get icon(){return a.icon},get class(){return Ge("row-icon",...a.iconClasses||[])}})),V(()=>a.checkboxField||a.radioField),V(()=>V(()=>!!r())()&&(()=>{const h=qA();return k(h,r),h})()),V(()=>V(()=>!!a.media)()&&(()=>{const h=US();return k(h,()=>a.media),Me(()=>be(h,Ge("row-media",a.mediaSize&&`row-media-${a.mediaSize}`))),h})())]}});return V((()=>{const h=V(()=>!!c());return()=>h()?T(Ku,{children:u}):u})())}const YA=Y("<span class=popup-boosts-badge>"),QA=Y("<span class=popup-boosts-button-text>"),z1=Y("<span>"),XA=Y('<span class="primary is-flex"> '),Rf=Y("<form>"),ZA=Y('<span class="popup-boosts-stars-amount text-bold"> '),JA=Y('<div class=popup-boosts-additional-row><div class=popup-boosts-additional-row-count></div><input class="input-clear popup-boosts-additional-row-input">'),e3=Y("<div class=popup-boosts-star-container><img class=popup-boosts-star>"),t3=Y("<div class=popup-boosts-title>"),s3=Y("<div class=popup-boosts-subtitle>"),W1=a=>(()=>{const e=YA();return k(e,T(hs,{icon:"boost",class:"popup-boosts-badge-icon"}),null),k(e,()=>a.boosts,null),e})(),K1=a=>{let e,t;(()=>{const s=QA(),i=e;return typeof i=="function"?Ue(i,s):e=s,k(s,()=>P(a.langKey(),a.langArgs?.())),s})(),(()=>{const s=z1(),i=t;return typeof i=="function"?Ue(i,s):t=s,k(s,T(hs,{icon:"boost",class:"popup-boosts-button-badge-icon"}),null),k(s,()=>a.boosts(),null),Me(()=>be(s,Ge("popup-boosts-button-badge",!a.boosts()&&"hide"))),s})(),a.button.classList.add("popup-boosts-button"),a.button.append(e,t)};class HS extends ue{constructor(e,t,s){super("popup-boosts",{closable:!0,overlayClosable:!0,body:!0,scrollable:!0,title:"BoostsViaGifts.Title",floatingHeader:!0,footer:!0,withConfirm:!0}),this.peerId=e,this.prepaidGiveaway=t,this.onCreated=s,this.construct()}_construct(){const e=this,t=this,s=this,[i,n]=K(10),[r,o]=K(Qs(!0)+3*86400),[l,c]=K([this.peerId]),[d,u]=K([]),[h,p]=K(this.prepaidGiveaway?._==="prepaidStarsGiveaway"),[m,g]=K(this.starsOptions?.[0]),[f,v]=K(m()&&m().winners[0]),[y,w]=K(!1),[b,S]=K(),[_,M]=K(),[C,L]=K(),[E,x]=K(!1),[R,B]=K(!1),[N,G]=K(""),[O,$]=K(!0),H=V(()=>!!this.prepaidGiveaway),D=V(()=>h()?f().users:i()),U=V(()=>h()?m().yearly_boosts:D()*(this.appConfig.giveaway_boosts_per_premium??1));let j;H()?n(this.prepaidGiveaway.quantity):(j=new wm({generateStep:Ee=>[""+Ee,Ee],onValue:Ee=>{h()?v(m().winners.find(ve=>ve.users===Ee)):n(Ee)},middleware:this.middlewareHelper.get(),noFirstLast:!0}),le(()=>{if(h()){const A=m().winners.map(ge=>ge.users),F=j.generateSteps(A),Q=Ot(f);let X=A.findIndex(ge=>ge>=Q.users);X===-1?X=A.length-1:A[X]!==Q.users&&(X=Math.max(0,X-1)),j.setSteps(F,X);return}const Ee=[1,3,5,7,10,25,50,100].filter(A=>this.premiumGiftCodeOptions.some(F=>F.users===A)),ve=j.generateSteps(Ee),Qe=Ot(i);j.setSteps(ve,Ee.indexOf(Qe))}));const q={round:!0,asRadio:!0},W=new Fe({titleLangKey:"Ends",titleRightSecondary:!0,clickable:()=>{const Ee=new Date(Date.now()+(this.appConfig.giveaway_period_max??604800)*1e3),ve=new Date(r()*1e3);new Fb({initDate:ve,onPick:A=>{o(A)},btnConfirmLangKey:"Save",maxDate:Ee}).show()},listenerSetter:this.listenerSetter});W.titleRight.classList.add("primary"),le(()=>{W.titleRight.replaceChildren(gs(r()))});const ee=Ee=>{n(d().length),w(Ee),this.scrollable.updateThumb()};let z,Z,de,ie;if(this.prepaidGiveaway)Z=Q1({giveaway:this.prepaidGiveaway,appConfig:this.appConfig});else{const Ee=new Fe({titleLangKey:"BoostingPremium",subtitle:!0,clickable:X=>{if(h()){p(!1);return}_e(X),ue.createPopup(Rs,{peerType:["channelParticipants"],peerId:this.peerId,onMultiSelect:he=>{u(he),ee(!0),A.checkboxField.setValueSilently(!0)},placeholder:"SearchPlaceholder",exceptSelf:!0,titleLangKey:"Giveaway.Type.Specific.Modal.SelectUsers",initial:d()}).selector.setLimit(this.subscribersLimit,()=>{$e({langPackKey:"Giveaway.MaximumSubscribers",langPackArguments:[this.subscribersLimit]})})},checkboxField:new _t({...q,checked:!h(),name:"giveaway-type"}),listenerSetter:this.listenerSetter}),ve=Ee.createMedia("abitbigger"),Qe=jn({size:42});Qe.set({icon:"gift_premium",color:"premium"}),ve.append(Qe.node),de=Ee.container;const A=new Fe({titleLangKey:"BoostingStars",subtitleLangKey:"BoostsViaGifts.CreateSubtitle",clickable:X=>{p(!0)},checkboxField:new _t({...q,checked:h(),name:"giveaway-type"}),listenerSetter:this.listenerSetter});le(()=>{const X=d(),ge=!(!X.length||X.length>2);if(Ee.subtitle.classList.toggle("is-flex",!ge),!ge)Ee.subtitle.replaceChildren(P(X.length>2?"Recipient":"BoostsViaGifts.CreateSubtitle",[X.length]),oe());else{Ee.subtitle.classList.remove("is-flex");const he=X.map(Le=>new Xt({peerId:Le}).element);Ee.subtitle.replaceChildren(...Yi(he,!1))}}),Ee.subtitle.classList.add("primary");const F=A.createMedia("abitbigger"),Q=jn({size:42});Q.set({icon:"star",color:"stars"}),F.append(Q.node),ie=A.container,ie.classList.add("popup-boosts-type"),de.classList.add("popup-boosts-type","popup-boosts-specific")}const oe=()=>Be("next","popup-boosts-specific-next"),ae=xi(()=>{rs.show()});let ke;le(()=>{const Ee=i(),ve=new Map;this.premiumGiftCodeOptions.forEach((F,Q,X)=>{const ge=F.months;if(ve.has(ge))return;const he=X.filter(xe=>xe.months===ge).sort((xe,lt)=>xe.users-lt.users),Le=he.findIndex(xe=>xe.users>=Ee),Se=he[Le]||he[he.length-1];ve.set(ge,Se)});const Qe=[...ve.values()].sort((F,Q)=>Q.months-F.months),A=HM({periodOptions:Qe,onOption:F=>{ke=Qe.indexOf(F),M(F)},checked:ke,users:Ee,discountInTitle:!0});S(A)});const re=ot("btn btn-primary btn-transparent primary",{icon:"add",text:"AddChannel"});J(re,async()=>{const Ee=os(re,!0),ve=ue.createPopup(Rs,{filterPeerTypeBy:["isBroadcast"],onMultiSelect:F=>{c([this.peerId,...F])},placeholder:"SearchPlaceholder",titleLangKey:"AddChannels",initial:l().filter(F=>F!==this.peerId),excludePeerIds:new Set([this.peerId])});ve.selector.setLimit(this.channelsLimit,()=>{$e({langPackKey:"BoostingSelectUpToWarningChannelsPlural",langPackArguments:[this.channelsLimit]})}),ve.addEventListener("closeAfterTimeout",()=>Ee(),{once:!0});const Qe=ve.selector.add.bind(ve.selector);let A;ve.selector.add=F=>{const Q=F.key.toPeerId(),X=Ae.getChat(Q.toChatId());return!ji(X)[0]&&A!==Q&&ve.selector.getSelected().length<this.channelsLimit?(Rt({titleLangKey:"BoostingGiveawayPrivateChannel",descriptionLangKey:"BoostingGiveawayPrivateChannelWarning",button:{langKey:"Add"}}).then(()=>{A=Q,ve.selector.add({key:Q}),ve.selector.toggleElementCheckboxByPeerId(Q,!0),A=void 0}),!1):Qe(F)}},{listenerSetter:this.listenerSetter});const ce=()=>(()=>{const Ee=XA(),ve=Ee.firstChild;return k(Ee,()=>P(C()?"BoostingFromCountriesCount":"BoostingFromAllCountries",[C()?.length]),ve),k(Ee,oe,null),Ee})(),Ie=Ee=>{if(!ne(Ee.target,"row").querySelector(".checkbox-field-input").checked)return;let A;const F=ue.createPopup(Rs,{peerType:["custom"],renderResultsFunc:X=>{X.forEach(ge=>{const he=A.get(ge),Le=vv(he.iso2),Se=document.createDocumentFragment(),xe=document.createElement("span");xe.classList.add("selector-countries-emoji"),xe.append(je(Le)),Se.append(xe," ",P(he.default_name));const lt=new Fe({title:Se,clickable:!0,havePadding:!0});lt.container.append(F.selector.checkbox(F.selector.selected.has(ge))),lt.container.dataset.peerId=""+ge,F.selector.list.append(lt.container)})},placeholder:"Search",onMultiSelect:X=>{L(X)},getMoreCustom:async X=>{const ge=JE(X,!0);return A=new Map,{result:ge.map(he=>(A.set(he.iso2,he),he.iso2)),isEnd:!0}},titleLangKey:"BoostingSelectCountry",checkboxSide:"left",noPlaceholder:!0}),Q=F.selector.add.bind(F.selector);F.selector.add=({key:X,scroll:ge})=>{const he=Ne.countriesList.find(Se=>Se.iso2===X),Le=Q({key:X,title:P(he.default_name),scroll:ge});return Fy(Le)&&Le.avatar.render({peerTitle:vv(he.iso2)}),Le},F.selector.searchSection.container.classList.add("is-countries"),F.selector.container.classList.add("is-countries"),F.selector.addInitial(C()),F.selector.setLimit(this.countriesLimit,()=>{$e({langPackKey:"BoostingSelectUpToWarningCountriesPlural",langPackArguments:[this.countriesLimit]})})},Ve=[V((()=>{const Ee=V(()=>!!(!H()&&h()));return()=>Ee()&&T(Ms,{name:"BoostingStarsOptions",caption:"BoostingStarsOptionsInfo",captionOld:!0,get children(){const ve=Rf();return k(ve,T(Cs,{get each(){return e.starsOptions},children:Qe=>{const A=new _t({...q,checked:m()===Qe,name:"giveaway-stars-quantity"}),F=V(()=>{const Q=Qe.winners.find(X=>X.users===f().users);if(Q)return P("BoostingStarOptionPerUser",[Jr(+Q.per_user_stars)])});return T(En,{classList:{"popup-boosts-stars-row":!0},get title(){return(()=>{const Q=ZA(),X=Q.firstChild;return k(Q,T(eI,{get stars(){return+Qe.stars},size:18}),X),k(Q,()=>P("Stars",[Jr(+Qe.stars)]),null),Q})()},get subtitle(){return F()},get rightContent(){return qi(Qe.amount,Qe.currency)},get checkboxField(){return A.label},noRipple:!0,clickable:()=>{g(Qe)}})}})),ve}})})()),V((()=>{const Ee=V(()=>!H());return()=>Ee()&&T(Ms,{get name(){return h()?"BoostingStarsQuantityPrizes":"BoostsViaGifts.Quantity"},get nameRight(){return V(()=>!h())()&&T(W1,{get boosts(){return U()}})},get caption(){return h()?"BoostingStarsQuantityPrizesInfo":"BoostsViaGifts.QuantitySubtitle"},captionOld:!0,get children(){return j.container}})})()),T(Ms,{name:"BoostsViaGifts.Channels",get children(){return[T(Cs,{get each(){return l()},children:(Ee,ve)=>{const Qe=new Xt;Qe.update({peerId:Ee}),Qe.element.classList.add("text-bold");let A;(()=>{const Q=z1(),X=A;return typeof X=="function"?Ue(X,Q):A=Q,k(Q,(()=>{const ge=V(()=>ve()===0);return()=>ge()&&P("BoostsViaGifts.ChannelSubscription",[U()])})(),null),k(Q,(()=>{const ge=V(()=>ve()!==0);return()=>ge()&&ja(Ee.toChatId(),void 0,void 0,!0)})(),null),Q})();const F=new Fe({title:Qe.element,subtitle:A,...Ee!==e.peerId&&{clickable:Q=>{F.openContextMenu(Q)},contextMenu:{buttons:[{icon:"delete",danger:!0,text:"Remove",onClick:()=>{c(Q=>Q.filter(X=>X!==Ee))}}]}}});return F.container.classList.add("popup-boosts-channel"),F.createMedia("abitbigger").append(jn({peerId:Ee,size:42}).node),F.container}}),re]}}),T(Ms,{name:"BoostsViaGifts.Users",caption:"BoostsViaGifts.UsersSubtitle",captionOld:!0,get children(){const Ee=Rf();return k(Ee,()=>new Fe({titleLangKey:"AllSubscribers",clickable:ve=>(x(!1),Ie(ve)),checkboxField:new _t({...q,checked:!0,name:"giveaway-users"}),subtitle:ce(),listenerSetter:e.listenerSetter}).container,null),k(Ee,()=>new Fe({titleLangKey:"OnlyNewSubscribers",clickable:ve=>(x(!0),Ie(ve)),checkboxField:new _t({...q,name:"giveaway-users"}),subtitle:ce(),listenerSetter:e.listenerSetter}).container,null),Ee}})],fe=(()=>{const Ee=JA(),ve=Ee.firstChild,Qe=ve.nextSibling;return k(ve,D),Qe.$$input=A=>{const F=A.target;let Q=F.value;const X=Q.length>128;X&&(F.value=Q=Q.slice(0,128)),G(Q),X&&to(F)},Ue(A=>{ks(A,"BoostsViaGifts.AdditionalPrizeLabel",void 0,"placeholder")},Qe),Ee})(),Xe=[T(Ms,{get caption(){return V(()=>!!R())()?"BoostsViaGifts.AdditionalPrizesSubtitle":h()?"BoostingStarsGiveawayAdditionPrizeHint":"BoostsViaGifts.AdditionalPrizesSubtitleOff"},get captionArgs(){return V(()=>!!R())()?V(()=>!!h())()?[P(N()?"BoostsViaGifts.AdditionalStarsPrizesDetailedWith":"BoostsViaGifts.AdditionalStarsPrizesDetailed",[m().stars,D(),N()].filter(Boolean))]:[P(N()?"BoostsViaGifts.AdditionalPrizesDetailedWith":"BoostsViaGifts.AdditionalPrizesDetailed",[i(),N(),Zr(_().months,!0)].filter(Boolean))]:void 0},captionOld:!0,get children(){return[V(()=>new Fe({titleLangKey:"BoostsViaGifts.AdditionalPrizes",clickable:()=>{B(Ee=>!Ee)},checkboxField:new _t({toggle:!0,checked:Ot(R)}),listenerSetter:t.listenerSetter}).container),V(()=>R()&&fe)]}}),T(Ms,{caption:"BoostsViaGifts.ShowWinnersSubtitle",captionOld:!0,get children(){return new Fe({titleLangKey:"BoostsViaGifts.ShowWinners",clickable:()=>{$(Ee=>!Ee)},checkboxField:new _t({toggle:!0,checked:Ot(O)}),listenerSetter:t.listenerSetter}).container}}),T(Ms,{name:"BoostsViaGifts.End",get caption(){return h()?"BoostsViaGifts.Stars.EndSubtitle":"BoostsViaGifts.EndSubtitle"},get captionArgs(){return[D()]},captionOld:!0,get children(){return W.container}})],Ye=[T(Ms,{noDelimiter:!0,get children(){return[(()=>{const Ee=e3(),ve=Ee.firstChild,Qe=z;return typeof Qe=="function"?Ue(Qe,ve):z=ve,Ee})(),(()=>{const Ee=t3();return k(Ee,()=>P("BoostsViaGifts.Title")),Ee})(),(()=>{const Ee=s3();return k(Ee,()=>P(H()&&s.prepaidGiveaway._==="prepaidGiveaway"?"BoostingGetMoreBoosts":"BoostingGetMoreBoosts2")),Ee})(),V(()=>H()&&Z),V(()=>V(()=>!H())()&&(()=>{const Ee=Rf();return k(Ee,de,null),k(Ee,ie,null),Ee})())]}}),V(()=>!y()&&Ve),V((()=>{const Ee=V(()=>!H()&&!h());return()=>Ee()&&T(Ms,{name:"BoostsViaGifts.Duration",caption:"BoostsViaGifts.DurationSubtitle",captionArgs:[ae],captionOld:!0,get children(){return b()}})})()),V(()=>!y()&&Xe)];Ka(z,`assets/img/premiumboostsstar${window.devicePixelRatio>1?"@2x":""}.png`),K1({button:this.btnConfirm,langKey:()=>"BoostsViaGifts.Start",boosts:U}),this.footer.append(this.btnConfirm),this.body.after(this.footer),this.footer.classList.add("abitlarger");const Ze=async()=>{const Ee=await Promise.all(l().map(Qe=>this.managers.appPeersManager.getInputPeerById(Qe))),ve={pFlags:{only_new_subscribers:E()||void 0,winners_are_visible:O()||void 0},boost_peer:Ee[0],random_id:xu(),until_date:r(),additional_peers:Ee.length>1?Ee.slice(1):void 0,countries_iso2:C()?.length?C():void 0,prize_description:R()&&N()||void 0};return h()?{...m(),...ve,_:"inputStorePaymentStarsGiveaway",users:f().users}:{..._(),...ve,_:"inputStorePaymentPremiumGiveaway"}},Je=async()=>{const{amount:Ee,currency:ve}=_(),Qe=await Promise.all(d().map(A=>this.managers.appUsersManager.getUserInput(A.toUserId())));return{_:"inputStorePaymentPremiumGiftCode",amount:Ee,currency:ve,boost_peer:await this.managers.appPeersManager.getInputPeerById(this.peerId),users:Qe}},tt=async Ee=>(await Rt({titleLangKey:"BoostingStartGiveawayConfirmTitle",descriptionLangKey:"BoostingStartGiveawayConfirmText",button:{langKey:"Start"}}),this.managers.appPaymentsManager.launchPrepaidGiveaway(this.peerId,this.prepaidGiveaway.id,Ee)),ht=async Ee=>{const ve=Ee._==="inputStorePaymentStarsGiveaway"?{_:"inputInvoiceStars",purpose:Ee}:{_:"inputInvoicePremiumGiftCode",purpose:Ee,option:_()},Qe=await Ln.create({inputInvoice:ve});await new Promise((A,F)=>{Qe.addEventListener("finish",Q=>{Q==="cancelled"||Q==="failed"?F():A()})})};return J(this.btnConfirm,async()=>{const Ee=os(this.btnConfirm,!0);try{const ve=await(y()?Je:Ze)();let Qe;H()?Qe=tt(ve):Qe=ht(ve),await Qe,this.onCreated?.(),this.hide()}catch(ve){console.error("boosts via gifts error",ve),Ee()}},{listenerSetter:this.listenerSetter}),Ye}async construct(){const[e,t,s]=await Promise.all([this.managers.appPaymentsManager.getPremiumGiftCodeOptions(this.peerId),this.managers.apiManager.getAppConfig(),this.managers.appPaymentsManager.getStarsGiveawayOptions()]);this.premiumGiftCodeOptions=e,this.appConfig=t,this.starsOptions=s,this.subscribersLimit=this.channelsLimit=t.giveaway_add_peers_max??10,this.countriesLimit=t.giveaway_countries_max??10,this.appendSolid(()=>this._construct()),this.show()}}Fs(["input"]);function Bb(a,e,t=!0){const s=()=>{clearTimeout(n)},i=a;t||(a=as);let n;return function r(){a(),n=dm.setTimeout(r,Math.max(0,e()))}(),a=i,s}function j1(a,e){return Bb(a,()=>1e3-new Date().getMilliseconds(),e)}const yl=class yl{constructor(e){this.rows={},this.duration=e?.duration??yl.DEFAULT_DURATION,this.container=document.createElement("div"),this.container.className=yl.BASE_CLASS}getRow(e,t=!1){if(this.rows[e])return this.rows[e].element;const s=document.createElement("div"),i=!Object.keys(this.rows).length&&!t;return s.className=yl.BASE_CLASS+"-row"+(i?"":" is-hiding hide"),this.rows[e]={element:s,middleware:s.middlewareHelper=Ht(),new:!0},this.container.append(s),s}clearRow(e){this.rows[e]&&(this.rows[e].element.remove(),this.rows[e].middleware.destroy(),delete this.rows[e])}clearRows(e){this.clearTimeout&&clearTimeout(this.clearTimeout),this.clearTimeout=window.setTimeout(()=>{for(const t in this.rows)+t!==e&&this.clearRow(+t)},this.duration)}setNewRow(e,t=!1){const s=this.rows[e];s.new&&(t?(s.element.classList.remove("hide"),s.element.offsetLeft):s.element.classList.remove("is-hiding","hide"),delete s.new),this.clearRows(e)}animate(e,t,s=e>t,i=!1){if(e===t)return this.setNewRow(e);const n=this.rows[e],r=this.rows[t];if(!r&&!i)return this.setNewRow(e);const o=["from-top","from-bottom"];s||o.reverse(),n.element.classList.add(o[0]),n.element.classList.remove(o[1]),r&&(r.element.classList.add(o[1]),r.element.classList.remove(o[0])),n.new&&this.setNewRow(e,!0),n.element.classList.toggle("is-hiding",!1),r&&r.element.classList.toggle("is-hiding",!0),this.clearRows(e)}destroy(){for(const e in this.rows)this.clearRow(+e)}};yl.BASE_CLASS="animated-super",yl.DEFAULT_DURATION=200;let nd=yl;const Ca=class Ca{constructor(e){if(this.decimals=[],this.previousNumber=0,this.reverse=e.reverse,this.duration=e.duration??nd.DEFAULT_DURATION,this.container=document.createElement("div"),this.container.className=Ca.BASE_CLASS,this.calculateWidth=e.calculateWidth,this.calculateWidth&&this.container.classList.add("animated-counter-dynamic-width"),e.prefix){const t=document.createElement("div");t.className=Ca.BASE_CLASS+"-decimal-prefix",t.innerText=this.prefix=e.prefix,this.container.append(t),this.prefixContainer=t}}getDecimal(e){if(this.decimals[e])return this.decimals[e];const t=document.createElement("div");t.className=Ca.BASE_CLASS+"-decimal";const s=document.createElement("div");s.className=Ca.BASE_CLASS+"-decimal-placeholder";const i=new nd({duration:this.duration});return i.container.className=Ca.BASE_CLASS+"-decimal-wrapper",t.append(s,i.container),this.container.append(t),this.decimals[e]={container:t,placeholder:s,animatedSuper:i}}clear(e){this.clearTimeout&&clearTimeout(this.clearTimeout);const t=(""+e).length;t>=this.decimals.length||(this.clearTimeout=window.setTimeout(()=>{this.decimals.splice(t,this.decimals.length-t).forEach(i=>{i.container.remove()})},this.duration))}hideLeft(e){const t=(""+e).length;this.decimals.slice(t).forEach(i=>{const n=+i.placeholder.innerText||0;i.animatedSuper.getRow(Ca.EMPTY_INDEX,!0),i.animatedSuper.animate(Ca.EMPTY_INDEX,n,this.reverse?e<this.previousNumber:e>this.previousNumber,!0)}),this.clear(e)}setCount(e,t){const s=[],i=[],n=Array.from(""+this.previousNumber).map(c=>+c);Array.from(""+e).map(c=>+c).forEach((c,d)=>{const u=this.getDecimal(d),h=u.animatedSuper.getRow(c,!0),p=n[d]??Ca.EMPTY_INDEX,m=""+c;h.innerText=u.placeholder.innerText=m,s.push(m),i.push(h),u.animatedSuper.animate(c,p,this.reverse?e<this.previousNumber:e>this.previousNumber,!0)});const o=()=>{let c;if(typeof l=="boolean")c=i.reduce((d,u)=>d+u.clientWidth,0),this.prefixContainer&&(c+=this.prefixContainer.clientWidth);else{const d=(this.prefix||"")+s.join("");c=l(d)}this.container.style.setProperty("--width",c+"px")},{calculateWidth:l}=this;l&&(t?o():$s(o)),this.hideLeft(e),this.previousNumber=e}destroy(){this.decimals.forEach(e=>{e.animatedSuper.destroy()})}};Ca.EMPTY_INDEX=-1,Ca.BASE_CLASS="animated-counter";let ad=Ca;const i3=Y('<span class=tooltip-undo><span class=tooltip-undo-timer><svg class=tooltip-undo-timer-svg width=24px height=24px><circle cx=12 cy=12 r=10 class=tooltip-undo-timer-circle transform="rotate(-90, 12, 12)"></circle></svg><span class=tooltip-undo-timer-number>'),n3={titleKey:"PaidReaction.Sent",subtitleKey:"StarsSentText"},a3={titleKey:"PaidMessages.MessagesSent",subtitleKey:"PaidMessages.YouPaidForMessages"};function q1(a){Ft(e=>{const[t,s]=K(),[i,n]=K(),r=new Ne.IntlElement({key:a.titleKey}),o=new Ne.IntlElement({key:a.subtitleKey});r.element.classList.add("text-bold"),le(()=>{r.compareAndUpdate({args:[a.titleCount()]}),o.compareAndUpdate({args:[a.subtitleCount()]})}),le(()=>{if(!a.sendTime())e(),u();else{const h=j1(()=>{s((a.sendTime()-Date.now())/1e3|0)});No(()=>{const m=(a.sendTime()-Date.now())/Oh;return n(m*c),!p});let p=!1;ze(()=>{p=!0,h()})}});const c=10*2*Math.PI,d=new ad({reverse:!1});le(()=>d.setCount(t()));const{close:u}=Ra({element:Ce.chat.bubbles.container,container:Ce.chat.bubbles.container,mountOn:Ce.chat.bubbles.container,relative:!0,vertical:"top",class:Ge("paid-reaction-tooltip",a.wider&&"paid-reaction-tooltip--a-little-wider"),textElement:r.element,subtitleElement:o.element,rightElement:(()=>{const h=i3(),p=h.firstChild,m=p.firstChild,g=m.firstChild,f=m.nextSibling;return h.$$click=()=>void a.onUndo(),k(h,()=>P("Undo"),p),k(f,()=>d.container),Me(()=>Es(g,"stroke-dasharray",`${i()} ${c}`)),h})(),icon:"star"})})}Fs(["click"]);const r3=()=>Ft(a=>{const[e,t]=K(0),[s,i]=K(0),[n,r]=K(0);let o=new AbortController;return{timeoutId:0,messageCount:e,setMessageCount:t,sendTime:s,setSendTime:i,reserved:n,setReserved:r,abort(){o.abort()},get signal(){return o.signal},softReset(){self.clearTimeout(this.timeoutId),this.timeoutId=0,o=new AbortController},resetGlobalReserved(){eu(l=>l-n())},reset(){this.softReset(),i(0),t(0),r(0)},dispose:a}}),Fn=Symbol("Payment rejected"),Fr=class Fr{constructor(e,t){this.chat=e,this.managers=t,this.pendingUndoableMessage=r3()}dispose(){this.pendingUndoableMessage.dispose()}static get starsBalance(){return+this.rawStars()}async prepareStarsForPayment(e){const{peerId:t,starsAmount:s}=this.chat;if(!s)return;const i=e*s;if(Fr.starsBalance<i)return this.pendingUndoableMessage.abort(),ue.createPopup(ba),Fn;const n=await Fr.checkIfUserReallyWantsToPay({peerId:t,messageCount:e,starsAmount:s,withDontShowAgain:!0});if(n===2)return Fn;const r=Fr.canUndoMessageSending({userConfirmation:n,messageCount:e,starsAmount:s})||!!this.pendingUndoableMessage.messageCount();return r&&(eu(o=>o+i),this.pendingUndoableMessage.setReserved(o=>o+i),this.triggerUndoableMessages({peerId:t,messageCount:e,starsAmount:s})),{starsAmount:s,canUndo:r}}static canUndoMessageSending(e){const{messageCount:t,starsAmount:s,userConfirmation:i}=e;return i!==0?!1:s>=this.MIN_UNDO_SENDING_PARAMS.starsAmount||t>=this.MIN_UNDO_SENDING_PARAMS.messageCount}static async prepareStarsForPayment(e){const{peerId:t,messageCount:s}=e,i=await I.managers.appPeersManager.getStarsAmount(t);if(!i)return;const n=s*i;return Fr.starsBalance<n?(ue.createPopup(ba),Fn):await Fr.checkIfUserReallyWantsToPay({peerId:t,messageCount:s,starsAmount:i,withDontShowAgain:!1})===2?Fn:{starsAmount:i,canUndo:!1}}static async checkIfUserReallyWantsToPay({peerId:e,messageCount:t,starsAmount:s,withDontShowAgain:i}){const n=s*t;let r=as;if(i){const{dontShowPaidMessageWarningFor:o=[]}=await I.managers.appStateManager.getState();if(!!o.includes(e))return 0;r=()=>{I.managers.appStateManager.setByKey("dontShowPaidMessageWarningFor",[...o,e])}}try{const o=await Rt({titleLangKey:"ConfirmPayment",descriptionLangKey:t>1?"PaidMessages.UserChargesForMultipleMessageWarning":"PaidMessages.UserChargesForOneMessageWarning",descriptionLangArgs:[await qe({peerId:e,onlyFirstName:!0}),P("Stars",[s]),P("Stars",[n]),...t>1?[t]:[]],checkbox:i?{text:"DontAskAgain"}:void 0,button:{langKey:"PaidMessages.PayForMessages",langArgs:[t]}});i&&o&&r()}catch{return 2}return 1}triggerUndoableMessages({peerId:e,messageCount:t,starsAmount:s}){this.pendingUndoableMessage.setMessageCount(i=>i+t),this.pendingUndoableMessage.setSendTime(Date.now()+Oh),this.pendingUndoableMessage.timeoutId||q1({sendTime:this.pendingUndoableMessage.sendTime,titleCount:this.pendingUndoableMessage.messageCount,subtitleCount:()=>this.pendingUndoableMessage.messageCount()*s,onUndo:()=>void this.pendingUndoableMessage.abort(),...a3}),this.pendingUndoableMessage.softReset(),this.pendingUndoableMessage.signal.addEventListener("abort",()=>{this.managers.appMessagesManager.cancelQueuedPaidMessages(e),this.pendingUndoableMessage.resetGlobalReserved(),this.pendingUndoableMessage.reset()}),this.pendingUndoableMessage.timeoutId=self.setTimeout(()=>{this.managers.appMessagesManager.sendQueuedPaidMessages(e),this.pendingUndoableMessage.reset()},Oh)}};Fr.rawStars=Jl(),Fr.MIN_UNDO_SENDING_PARAMS={starsAmount:100,messageCount:3};let _r=Fr;Di.PaidMessagesInterceptor=_r;const o3=Object.freeze(Object.defineProperty({__proto__:null,PAYMENT_REJECTED:Fn,default:_r},Symbol.toStringTag,{value:"Module"})),l3=Y("<div class=popup-gift-link-wrapper><div class=popup-gift-link-header><img class=popup-gift-link-image><div class=popup-gift-link-title></div><div class=popup-gift-link-subtitle>"),c3=Y("<div class=popup-gift-link-share>");class Ir extends ue{constructor(e,t,s){super("popup-boosts popup-gift-link",{closable:!0,overlayClosable:!0,body:!0,withConfirm:!0,scrollable:!0,floatingHeader:!0,footer:!0,title:!0}),this.slug=e,this.stack=t,this.checkedGiftCode=s,this.isInChat=!!s,this.construct()}_construct(e){const t=this,s=!!this.checkedGiftCode.used_date,i=s?"BoostingUsedGiftLink":"BoostingGiftLink";this.title.replaceChildren(P(i));const n=this.isInChat&&!s?"":"https://t.me/giftcode/"+this.slug,r=new Uu({button:!1,listenerSetter:this.listenerSetter,url:n,noRightButton:!n,onClick:!n&&(()=>{$e({langPackKey:"BoostingOnlyRecipientCode"})})});e&&(e.classList.add("invite-link-dots"),r.container.appendChild(e));const o=y=>{const w=this;return T(Pm,{peerId:y,onClick:()=>{w.hideWithCallback(()=>{Ce.setInnerPeer({peerId:y})})}})},l=this.checkedGiftCode.pFlags.via_giveaway,c=it(this.checkedGiftCode.from_id),d=this.checkedGiftCode.to_id&&it(this.checkedGiftCode.to_id),u=this.checkedGiftCode.giveaway_msg_id||l?document.createElement("a"):void 0;u&&(u.href="#",u.append(P("BoostingIncompleteGiveaway")),J(u,()=>{this.hideWithCallback(()=>{Ce.setInnerPeer({peerId:c,lastMsgId:this.checkedGiftCode.giveaway_msg_id})})},{listenerSetter:this.listenerSetter}));const h=d?d===I.myId?P("BoostingYouWereSelected"):P("BoostingUserWasSelected",[new Xt({peerId:d}).element]):u;let p=[["BoostingFrom",o(c)],["BoostingTo",d?o(d):P("BoostingNoRecipient")],["BoostingGift",P("BoostingTelegramPremiumFor",[Zr(this.checkedGiftCode.months)])],!this.isInChat&&["BoostingReason",h],["BoostingDate",gs(this.checkedGiftCode.date,void 0,!0)]];p=p.filter(Boolean);const m=xi(y=>{_e(y),this.hideWithCallback(()=>{Ir.shareGiftLink(n,!0)})});let g;const f=(()=>{const y=l3(),w=y.firstChild,b=w.firstChild,S=b.nextSibling,_=S.nextSibling,M=g;return typeof M=="function"?Ue(M,b):g=b,k(S,()=>P(i)),k(_,()=>s?P("BoostingLinkUsed"):P(d===I.myId?"BoostingLinkAllows":d?"BoostingLinkAllowsToUser":"BoostingLinkAllowsAnyone",d?[new Xt({peerId:d}).element]:void 0)),k(y,()=>r.container,null),k(y,T(Rb,{boldKey:!0,content:p}),null),k(y,(()=>{const C=V(()=>!t.isInChat||!s);return()=>C()&&(()=>{const L=c3();return k(L,()=>s?P("BoostingUsedLinkDate",[gs(t.checkedGiftCode.used_date,void 0,!0)]):t.isInChat&&!t.checkedGiftCode.slug?P("BoostingLinkNotActivated"):P(d?"Giveaway.SendLinkToFriend":"Giveaway.SendLinkToAnyone",[m])),L})()})(),null),y})();Ka(g,`assets/img/premium-star${window.devicePixelRatio>1?"@2x":""}.png`);const v=!this.isInChat&&!s;return this.btnConfirm.append(P(v?"BoostingUseLink":"OK")),this.btnConfirm.classList.add("popup-boosts-button"),this.footer.append(this.btnConfirm),this.body.after(this.footer),this.footer.classList.add("abitlarger"),J(this.btnConfirm,()=>{if(!v){this.hide();return}Ir.applyGiftCode(this.slug,this.btnConfirm,this)},{listenerSetter:this.listenerSetter}),f}async construct(){if(this.checkedGiftCode??(this.checkedGiftCode=await this.managers.appPaymentsManager.checkGiftCode(this.slug)),fm(this.checkedGiftCode)){this.destroy(),rs.show({gift:this.checkedGiftCode,stack:this.stack});return}let e;if(this.isInChat&&!this.checkedGiftCode.used_date){const{canvas:i,readyResult:n}=Fu.create({width:320,height:32,middleware:this.middlewareHelper.get(),animationGroup:"STICKERS-POPUP",config:{particlesCount:1e3,color:Ls.isNight()?16777215:0}});await n,e=i}const t=document.createElement("div");this.scrollable.append(t,this.btnConfirm);const s=wi(()=>this._construct(e),t);this.addEventListener("closeAfterTimeout",s),this.show()}static shareGiftLink(e,t){Rs.createSharingPicker({onSelect:async s=>{const i=await _r.prepareStarsForPayment({messageCount:1,peerId:s});if(i===Fn)throw new Error;I.managers.appMessagesManager.sendText({peerId:s,text:e,confirmedPaymentResult:i}),t?Ce.setInnerPeer({peerId:s}):$e({langPackKey:I.myId===s?"BoostingGiftLinkForwardedToSavedMsg":"BoostingGiftLinkForwardedTo",langPackArguments:[await qe({peerId:s})]})}})}static async applyGiftCode(e,t,s){const i=os(t,!0);try{await ue.MANAGERS.appPaymentsManager.applyGiftCode(e),s.hide(),$e({langPackKey:"GiftLink.UseSuccess"})}catch(n){if(n.type.includes("PREMIUM_SUB_ACTIVE_UNTIL_")){s.hide();const r=+n.type.split("_").pop();let o;Rt({titleLangKey:"GiftPremiumActivateErrorTitle",descriptionLangKey:"GiftCode.Activation.After",descriptionLangArgs:[gs(r),xi(()=>{Xs(o.element),s.hide(),this.shareGiftLink("https://t.me/giftcode/"+e)})],button:o={langKey:"OK",isCancel:!0}})}console.error("giftcode error",n),i()}}}const d3=Y("<div><div class=menu-horizontal-div-item-span><i>"),jp=Y("<div>"),h3=Y('<div class="menu-horizontal-div-item boosts-users-tab"><div class=menu-horizontal-div-item-span><i>'),u3=Y('<div class="menu-horizontal-div boosts-users-tabs">'),p3=Y("<div class=boosts-users-contents>"),Y1=a=>a===12?"red":a===3?"green":"blue",GS=(a,e)=>{const t=(e-a)/86400;return Math.round(t/30)},Q1=a=>{const{quantity:e}=a.giveaway,t=a.giveaway.stars,s=a.giveaway.months,i=t?a.giveaway.boosts:(a.appConfig.giveaway_boosts_per_premium||1)*e,n=new Fe({titleLangKey:t?"Stars":"BoostingGiveawayMsgInfoPlural1",titleLangArgs:[t||e],subtitleLangKey:t?"Giveaway.Prepaid.For":"Giveaway.Prepaid.Subtitle",subtitleLangArgs:[e,P("Giveaway.Prepaid.Period",[s])],clickable:a.clickable,listenerSetter:a.listenerSetter,rightContent:W1({boosts:i})});n.title.classList.add("text-bold");const r=n.createMedia("abitbigger"),o=jn({size:42});return t?o.set({icon:"star",color:"stars"}):o.set({icon:"gift_premium",color:Y1(s)}),r.append(o.node),n.container};function m3(a){const e=a.class,t=c=>(()=>{const d=d3(),u=d.firstChild,h=u.firstChild;return k(u,()=>c.children,h),Me(()=>be(d,Ge("menu-horizontal-div-item",`${e}-tab`))),d})(),s=c=>(()=>{const d=jp();return k(d,()=>c.children),Me(()=>be(d,Ge(`${e}-content`,c.hide&&"hide"))),d})();let i,n;const r=[(()=>{const c=jp(),d=i;return typeof d=="function"?Ue(d,c):i=c,k(c,T(Cs,{get each(){return a.menu},children:u=>T(t,{children:u})})),Me(()=>be(c,Ge("menu-horizontal-div",`${e}-tabs`))),c})(),(()=>{const c=jp(),d=n;return typeof d=="function"?Ue(d,c):n=c,k(c,T(Cs,{get each(){return a.content},children:(u,h)=>T(s,{get hide(){return h()!==a.tab()},children:u})})),Me(()=>be(c,Ge(`${e}-contents`))),c})()],o=new $t;return ze(()=>{o.removeAll()}),vd(i,n,c=>{a.onChange(c)},void 0,void 0,void 0,o)(a.tab()),r}class g3 extends Bs{constructor(){super(...arguments);ro(this,"renderBoost",async t=>{const s=1*(t.multiplier||1),i=GS(t.date,t.expires);let n=t.user_id?.toPeerId(!1);n===I.myId&&t.pFlags.unclaimed&&(n=void 0);let r;s>1&&(r=document.createElement("span"),r.classList.add("boosts-user-boosts","boosts-user-badge"),r.append(Be("boost"),` ${s}`));let o;n?(o=await qe({peerId:n}),o.classList.add("boosts-user-name")):t.stars?o=P("Stars",[t.stars]):o=P(t.pFlags.unclaimed?"BoostingUnclaimed":"BoostingToBeDistributed");let l;n||t.stars?l=P("BoostsExpiration",[s,gs(t.expires,void 0,!0)]):(l=document.createElement("span"),l.append(...Kl([P("BoostingShortMonths",[i]),gs(t.expires,void 0,!0)]," • ")));let c;(t.pFlags.giveaway||t.pFlags.gift)&&(c=document.createElement("span"),c.classList.add("boosts-user-badge-right","boosts-user-badge"),c.append(Be(t.pFlags.giveaway?"gift_premium":"gift"),P(t.pFlags.giveaway?"BoostingGiveaway":"BoostingGift")),c.classList.toggle("is-gift",!t.pFlags.giveaway&&!!t.pFlags.gift));const d=new Fe({title:!0,subtitle:l,clickable:!0,noWrap:!0,rightContent:c});n&&(d.container.dataset.peerId=""+n),d.title.classList.add("boosts-user-title"),d.title.append(...[o,r].filter(Boolean));const u=d.createMedia("abitbigger"),h=vs({peerId:n,size:42,middleware:this.middlewareHelper.get()});return u.append(h.node),n?await h.readyThumbPromise:t.stars?h.set({icon:"star",color:"stars"}):h.set({icon:t.pFlags.unclaimed?"deleteuser":"noncontacts",color:Y1(i)}),this.targets.set(d.container,t),d.container})}_construct(t,s,i,n){const r=this,o=new xg({progress:!0,hint:{icon:"boost",noStartEnd:!0}}),c=t.next_level_boosts===void 0?1:(t.boosts-t.current_level_boosts)/(t.next_level_boosts-t.current_level_boosts);o.setProgress(c,""+t.boosts,{from1:P("BoostsLevel",[t.level]),to1:P("BoostsLevel",[t.level+1]),from2:P("BoostsLevel",[t.level]),to2:P("BoostsLevel",[t.level+1])}),o._setHintActive();const d=t.boost_url,u=new Uu({listenerSetter:this.listenerSetter,url:d}),h=ot("btn-primary btn-transparent primary",{icon:"gift_premium",text:"BoostingGetBoostsViaGifts"});J(h,()=>{ue.createPopup(HS,this.peerId)},{listenerSetter:this.listenerSetter});const p=P("NoBoostersHint");p.classList.add("boosts-no-boosters");let m,g;const f=E=>(()=>{const x=h3(),R=x.firstChild,B=R.firstChild;return k(R,()=>P(E.key,[E.count]),B),x})(),v=E=>{const x=this;return(()=>{const R=jp();return k(R,(()=>{const B=V(()=>!!E.list.count);return()=>B()?[V(()=>E.list.rendered),V((()=>{const N=V(()=>!!E.list.loadMore);return()=>N()&&Mm(E.list.count-E.list.rendered.length,G=>{const O=os(G,!0);E.list.loadMore().finally(()=>O())},x.listenerSetter,E.moreKey)})())]:p})()),Me(()=>be(R,Ge("boosts-users-content",!E.list.count&&"is-empty",E.hide&&"hide"))),R})()},[y,w]=K(0),[b,S]=K(t.prepaid_giveaways?.slice()||[],{equals:!1}),_=V(()=>t.gift_boosts===t.boosts),M=V(()=>!_()&&!!n().count),C=[T(Ms,{get children(){return[V(()=>o.container),T(G1,{get items(){return[{title:"BoostsLevel2",value:Oa(t.level),includeZeroValue:!0},{title:"PremiumSubscribers",value:t.premium_audience,includeZeroValue:!0,describePercentage:!0},{title:"BoostsExisting",value:Oa(t.boosts),includeZeroValue:!0},{title:"BoostsToLevel",value:Oa(t.next_level_boosts-t.boosts)}]}})]}}),V((()=>{const E=V(()=>!!(r.canCreateGiveaway&&b().length));return()=>E()&&T(Ms,{name:"Giveaway.Prepaid",nameArgs:[1],caption:"BoostingSelectPaidGiveaway",get children(){return T(Cs,{get each(){return b()},children:x=>T(Q1,{giveaway:x,appConfig:s,clickable:()=>{ue.createPopup(HS,r.peerId,x,()=>{S(R=>(Vs(R,x),R))})},get listenerSetter(){return r.listenerSetter}})})}})})()),T(Ms,{class:"boosts-users-container",get children(){return[(()=>{const E=u3(),x=m;return typeof x=="function"?Ue(x,E):m=E,k(E,T(f,{key:"BoostingBoostsCount",get count(){return i().count}}),null),k(E,(()=>{const R=V(()=>!!M());return()=>R()&&T(f,{key:"BoostingGiftsCount",get count(){return n().count}})})(),null),E})(),(()=>{const E=p3();E.$$click=async R=>{const B=ne(R.target,"row"),N=r.targets.get(B);if(!N)return;if(N.stars){Ln.create({noPaymentForm:!0,transaction:{_:"starsTransaction",date:N.date,id:"",peer:{_:"starsTransactionPeer",peer:{_:"peerChannel",channel_id:r.peerId.toChatId()}},pFlags:{},stars:hr(N.stars),giveaway_post_id:N.giveaway_msg_id},boost:N});return}const G=N.used_gift_slug,O=N.user_id?.toPeerId(!1);O&&!N.pFlags.gift&&!N.pFlags.unclaimed&&!N.pFlags.giveaway?Ce.setInnerPeer({peerId:N.user_id.toPeerId(!1)}):O&&O!==I.myId?ue.createPopup(Ir,G,void 0,{_:"payments.checkedGiftCode",chats:[],date:N.date,months:GS(N.date,N.expires),pFlags:{via_giveaway:N.pFlags.giveaway||void 0},users:[],from_id:await r.managers.appPeersManager.getOutputPeer(r.peerId),giveaway_msg_id:N.giveaway_msg_id,slug:G,to_id:O.toUserId(),used_date:G?1:void 0}):G?ue.createPopup(Ir,G):$e({langPackKey:"BoostingRecipientWillBeSelected"})};const x=g;return typeof x=="function"?Ue(x,E):g=E,k(E,T(v,{get list(){return i()},get hide(){return y()!==0},moreKey:"BoostingShowMoreBoosts"}),null),k(E,(()=>{const R=V(()=>!!M());return()=>R()&&T(v,{get list(){return n()},get hide(){return y()!==1},moreKey:"BoostingShowMoreGifts"})})(),null),E})()]}}),T(Ms,{name:"LinkForBoosting",caption:"BoostingShareThisLink",get children(){return u.container}}),V((()=>{const E=V(()=>!!r.canCreateGiveaway);return()=>E()&&T(Ms,{caption:"BoostingGetMoreBoosts",children:h})})())];return vd(m,g,E=>{w(E)},void 0,void 0,void 0,this.listenerSetter)(y()),C}async init(t){this.container.classList.add("boosts-container"),this.peerId=t,this.targets=new Map,this.setTitle("Boosts");const s=p=>{const m=this.middlewareHelper.get();let g="",f=!0;const v=async()=>{const b=f?20:100;f=!1;const S=await this.managers.appBoostsManager.getBoostsList({peerId:t,offset:g,limit:b,gifts:p});if(!m())return;const _=S.boosts.map(this.renderBoost),M=await Promise.all(_);w(C=>(C.count=S.count,g=S.next_offset,g||(C.loadMore=void 0),C.rendered.push(...M),C))},[y,w]=id({loadMore:v});return y},[i,n]=Ft(p=>(this.middlewareHelper.get().onDestroy(p),[s(!1),s(!0)])),[r,o,l,c,d]=await Promise.all([this.managers.appBoostsManager.getBoostsStatus(t),this.managers.apiManager.getAppConfig(),i().loadMore(),n().loadMore(),this.managers.appChatsManager.hasRights(t.toChatId(),"create_giveaway")]);this.canCreateGiveaway=d;const u=document.createElement("div");this.scrollable.append(u);const h=wi(()=>this._construct(r,o,i,n),u);this.eventListener.addEventListener("destroy",h)}}Fs(["click"]);function Vv(a){const{mediaSpoiler:e,reveal:t,destroyAfter:s}=a;Dt({element:e,forwards:t,className:"is-revealing",duration:250,onTransitionEnd:()=>{t&&s&&(e.remove(),e.middlewareHelper.destroy())}})}function f3(a){const{mediaSpoiler:e,event:t}=a,s=e.querySelector("canvas.media-spoiler-thumbnail"),i=e.querySelector("canvas.canvas-dots"),n=Fu.getImageSpoilerByElement(i);if(!n||!s)return!1;const r=n.revealWithAnimation(t,s);return r?r.then(()=>{e?.remove?.(),e?.middlewareHelper?.destroy?.()}):!1}function X1(a){const{mediaSpoiler:e,event:t}=a;if(_e(t),e.classList.contains("is-revealing")||e.dataset.isRevealing)return;const s=e.parentElement.querySelector("video");if(s&&!e.parentElement.querySelector(".video-play")&&(s.autoplay=!0,Sn(s)),f3({mediaSpoiler:e,event:t})){e.dataset.isRevealing="true";return}Vv({mediaSpoiler:e,reveal:!0,destroyAfter:!0})}function v3(a){const{middleware:e,image:t}=a;if(!e())return;t.classList.add("media-spoiler-thumbnail");const s=document.createElement("div");s.classList.add("media-spoiler-container"),s.middlewareHelper=e.create();const{canvas:i,readyResult:n}=Fu.create({...a,middleware:s.middlewareHelper.get()});return s.append(t,i),{container:s,readyResult:n}}async function ju(a){const{media:e}=a,s=(e.sizes||e.thumbs).find(l=>l._==="photoStrippedSize");if(!s)return;const{image:i,loadPromise:n}=gv(e,s,!0);await n;const{container:r,readyResult:o}=v3({...a,image:i});return o instanceof Promise&&await o,r}const y3=a=>a._==="chatInvitePeek"?a.chat.pFlags.broadcast?"JoinByPeekChannelTitle":"JoinByPeekGroupTitle":a.pFlags.request_needed?"RequestJoin.Button":a.pFlags.broadcast?"JoinByPeekChannelTitle":"JoinByPeekGroupTitle";async function Z1(a,e){const t=document.createElement("div");t.classList.add("peer-title","chat-title");const s=await Tv({peerId:Wt,noVerifiedIcon:!1,noFakeIcon:!1,noPremiumIcon:!1,peer:{_:"channel",pFlags:{verified:a.pFlags.verified,scam:a.pFlags.scam,fake:a.pFlags.fake},date:0,id:0,photo:void 0,title:""},wrapOptions:{middleware:e}}),i=je(a.title);if(s.length){t.classList.add("with-icons");const n=document.createElement("span");n.classList.add("peer-title-inner"),n.append(i),t.append(n,...s)}else Qt(t,i);return t}async function J1(a,e,t){const s=vs({middleware:e,size:t,isDialog:!1,isSubscribed:!!a.subscription_pricing||void 0});return a.photo?._==="photo"?(await U_(s,a.photo),a.subscription_pricing&&s.setIsSubscribed(!0)):(s.render({peerTitle:a.title}),await s.readyThumbPromise),s}class Lm extends mi{constructor(e,t){super("popup-join-chat-invite",{closable:!0,overlayClosable:!0,body:!0,buttons:Go([{langKey:y3(t),callback:()=>{Lm.import(e)}}]),description:!0}),this.hash=e,this.chatInvite=t,this.construct()}static openChat(e){const t=e.toPeerId(!0);Ce.setInnerPeer({peerId:t})}static import(e){I.managers.appChatInvitesManager.importChatInvite(e).then(t=>{this.openChat(t)},t=>{t.type==="INVITE_REQUEST_SENT"&&$e({langPackKey:"RequestToJoinSent"})})}static async open(e,t){t._==="chatInviteAlready"?(await I.managers.appChatInvitesManager.checkChatInvite(e),this.openChat(t.chat.id)):t._==="chatInvitePeek"?this.openChat(t.chat.id):ue.createPopup(Lm,e,t)}async construct(){this.header.remove();const{chatInvite:e}=this,t=await J1(e,this.middlewareHelper.get(),100),s=await Z1(e,this.middlewareHelper.get());e.about?this.description.replaceChildren(je(e.about)):(this.description.remove(),this.description=void 0);const i=e.pFlags.broadcast,n=P(i?"Subscribers":"Members",[ln(e.participants_count)]);if(n.classList.add("chat-participants-count"),this.body.append(...[t.node,s,n,this.description].filter(Boolean)),e.pFlags.request_needed){const r=document.createElement("div");ks(r,i?"RequestToJoinChannelDescription":"RequestToJoinGroupDescription"),r.classList.add("chat-participants-count","request-caption"),this.body.append(r)}this.show()}}const b3=Y('<svg width=26 height=25 viewBox="0 0 26 25"fill=none xmlns=http://www.w3.org/2000/svg><path fill-rule=evenodd clip-rule=evenodd d="M12.413 20.3615L7.4621 23.3945C6.9473 23.7098 6.27431 23.5482 5.95894 23.0333C5.80491 22.7819 5.75899 22.4789 5.8316 22.1931L6.598 19.1766C6.87465 18.0876 7.61981 17.1774 8.63265 16.6911L14.0338 14.0979C14.2857 13.977 14.3918 13.6749 14.2709 13.4231C14.173 13.2191 13.9516 13.105 13.7287 13.1436L7.71644 14.1845C6.49429 14.3961 5.24099 14.0586 4.29035 13.2619L2.39103 11.6702C1.92831 11.2825 1.86756 10.593 2.25533 10.1303C2.44393 9.90522 2.71514 9.7655 3.00787 9.74259L8.81084 9.28846C9.2208 9.25637 9.57808 8.99693 9.73546 8.61702L11.9741 3.21299C12.2052 2.65524 12.8447 2.39039 13.4024 2.62145C13.6702 2.7324 13.883 2.94518 13.9939 3.21299L16.2326 8.61702C16.39 8.99693 16.7473 9.25637 17.1572 9.28846L22.9921 9.74509C23.594 9.79219 24.0437 10.3183 23.9966 10.9202C23.974 11.2097 23.837 11.4783 23.616 11.6668L19.166 15.4605C18.8527 15.7275 18.7161 16.148 18.8124 16.5482L20.1805 22.2314C20.3218 22.8184 19.9605 23.4087 19.3735 23.55C19.0915 23.6179 18.794 23.5709 18.5467 23.4194L13.5551 20.3615C13.2046 20.1468 12.7634 20.1468 12.413 20.3615Z"fill=url(#paint0_linear_4300_30119) stroke=url(#paint1_linear_4300_30119) stroke-width=1.22222></path><path fill-rule=evenodd clip-rule=evenodd d="M12.413 20.3615L7.4621 23.3945C6.9473 23.7098 6.27431 23.5482 5.95894 23.0334C5.80491 22.7819 5.75899 22.4789 5.8316 22.1931L6.598 19.1766C6.87465 18.0876 7.61981 17.1774 8.63265 16.6911L14.0338 14.0979C14.2857 13.977 14.3918 13.6749 14.2709 13.4231C14.173 13.2191 13.9516 13.105 13.7287 13.1436L7.71644 14.1845C6.49429 14.3961 5.24099 14.0586 4.29035 13.2619L2.39103 11.6702C1.92831 11.2825 1.86756 10.593 2.25533 10.1303C2.44393 9.90522 2.71514 9.7655 3.00787 9.74259L8.81084 9.28846C9.2208 9.25637 9.57808 8.99693 9.73546 8.61702L11.9741 3.21299C12.2052 2.65524 12.8447 2.39039 13.4024 2.62145C13.6702 2.7324 13.883 2.94518 13.9939 3.21299L16.2326 8.61702C16.39 8.99693 16.7473 9.25637 17.1572 9.28846L22.9921 9.74509C23.594 9.79219 24.0437 10.3183 23.9966 10.9202C23.974 11.2097 23.837 11.4783 23.616 11.6668L19.166 15.4605C18.8527 15.7275 18.7161 16.148 18.8124 16.5482L20.1805 22.2314C20.3218 22.8184 19.9605 23.4087 19.3735 23.55C19.0915 23.6179 18.794 23.5709 18.5467 23.4194L13.5551 20.3615C13.2046 20.1468 12.7634 20.1468 12.413 20.3615Z"stroke=url(#paint2_linear_4300_30119) stroke-width=2.44444 style=mix-blend-mode:soft-light></path><defs><linearGradient id=paint0_linear_4300_30119 x1=0.0870915 y1=28.1529 x2=41.4 y2=-18.3997 gradientUnits=userSpaceOnUse><stop stop-color=#FDEB32></stop><stop offset=0.439058 stop-color=#FEBD04></stop><stop offset=1 stop-color=#D75902></stop></linearGradient><linearGradient id=paint1_linear_4300_30119 x1=27.0556 y1=3.61111 x2=9.33333 y2=15.8333 gradientUnits=userSpaceOnUse><stop stop-color=#DB5A00></stop><stop offset=1 stop-color=#FF9145></stop></linearGradient><linearGradient id=paint2_linear_4300_30119 x1=29.5 y1=3.00001 x2=13 y2=13.0592 gradientUnits=userSpaceOnUse><stop stop-color=var(--star-background-color) stop-opacity=0></stop><stop offset=0.395833 stop-color=var(--star-background-color) stop-opacity=0.85></stop><stop offset=0.520833 stop-color=var(--star-background-color)></stop><stop offset=0.645833 stop-color=var(--star-background-color) stop-opacity=0.85></stop><stop offset=1 stop-color=var(--star-background-color) stop-opacity=0>'),w3=Y('<svg><path d="M1.55275 9.54149L2.08783 9.9899L1.55275 9.54149C0.839803 10.3922 0.951509 11.6599 1.80225 12.3728L3.70157 13.9645C4.85897 14.9344 6.38486 15.3453 7.87281 15.0877L10.9718 14.5512L8.2359 15.8647C6.9783 16.4685 6.05307 17.5988 5.70955 18.9509L4.94315 21.9674C4.80966 22.4929 4.89409 23.0499 5.17728 23.5122C5.75711 24.4587 6.99445 24.7559 7.94094 24.1761L12.8919 21.1432C12.9484 21.1085 13.0197 21.1085 13.0762 21.1432L18.0678 24.201C18.5226 24.4796 19.0695 24.5661 19.5881 24.4412C20.6672 24.1815 21.3315 23.096 21.0717 22.0169L19.7036 16.3336C19.6881 16.269 19.7101 16.2012 19.7607 16.1581L24.2107 12.3643L23.616 11.6668L24.2107 12.3643C24.617 12.0179 24.8688 11.524 24.9105 10.9917C24.9971 9.8851 24.1702 8.91782 23.0636 8.83122L17.2288 8.37458C17.1626 8.3694 17.1049 8.32752 17.0795 8.26619L16.2326 8.61702L17.0795 8.26619L14.8408 2.86217C14.6368 2.36977 14.2456 1.97856 13.7532 1.77457C12.7278 1.34976 11.5521 1.83669 11.1273 2.86216L8.88858 8.26619C8.86318 8.32752 8.8055 8.3694 8.73932 8.37458L2.93635 8.82872C2.39814 8.87084 1.8995 9.12772 1.55275 9.54149Z"stroke=var(--star-background-color) stroke-width=1.83333></svg>',!1,!0),S3=Y("<div class=stars-stacked>"),C3=Y("<div class=stars-balance><div class=stars-balance-title></div><div class=stars-balance-subtitle>"),Em=Y("<div>"),_3=Y("<span class=popup-stars-pay-amount-status>"),I3=Y("<b>"),P3=Y('<span class="popup-stars-cancelled danger">'),M3=Y("<div class=popup-stars-title>"),L3=Y("<div class=popup-stars-subtitle>"),E3=Y("<div class=popup-stars-options>"),k3=Y("<div class=popup-stars-option><div class=popup-stars-option-title></div><div class=popup-stars-option-subtitle>");function VS(a){return(()=>{const e=b3(),t=e.firstChild;return k(e,(()=>{const s=V(()=>!!a.stroke);return()=>s()&&w3()})(),t),Me(s=>{const i=Ge("stars-star-icon",a.stroke&&"stars-star-icon-stroke"),n=a.style;return i!==s._v$&&Es(e,"class",s._v$=i),s._v$2=Ii(e,n,s._v$2),s},{_v$:void 0,_v$2:void 0}),e})()}function eI(a){let e=1;a.stars>=2500?e=6:a.stars>=1e3?e=5:a.stars>=500?e=4:a.stars>=250?e=3:a.stars>=50&&(e=2);let t;const s=a.size+(a.size===18?4:6);if(e>1){t=[];for(let i=0;i<e;++i)t.push(T(VS,{stroke:i!==e-1,get style(){return{"margin-right":Math.min(i,1)*-s+"px"}}}))}else t=T(VS,{});return t=(()=>{const i=S3();return k(i,t),Me(n=>{const r=`${a.size+(e-1)*6}px`,o=a.size+"px";return r!==n._v$3&&((n._v$3=r)!=null?i.style.setProperty("width",r):i.style.removeProperty("width")),o!==n._v$4&&((n._v$4=o)!=null?i.style.setProperty("--size",o):i.style.removeProperty("--size")),n},{_v$3:void 0,_v$4:void 0}),i})(),t}function ya(){return ob()}function Vg(){const a=Jl();return(()=>{const e=C3(),t=e.firstChild,s=t.nextSibling;return k(t,()=>P("StarsBalance")),k(s,T(ya,{}),null),k(s,()=>""+(a()??0),null),e})()}function zg(a){return(()=>{const e=Em();return k(e,T(ya,{}),null),k(e,()=>a.stars,null),Me(()=>be(e,Ge("popup-stars-pay-amount","popup-stars-pay-amount-plain"))),e})()}function zv(a){return(()=>{const e=Em();return k(e,()=>`${+a.stars>0&&!a.noSign?"+":""}${a.stars}`,null),k(e,T(ya,{}),null),k(e,(()=>{const t=V(()=>!!a.isRefund);return()=>t()&&(()=>{const s=_3();return k(s,()=>P("StarsRefunded")),s})()})(),null),Me(()=>be(e,Ge("popup-stars-pay-amount",+a.stars>0?"green":"danger",a.reverse&&"reverse",a.inline&&"inline"))),e})()}function T3(a){if(a.subscription_period)return P("Stars.Subscription.Title");if(a.pFlags.gift)return P("StarsGiftReceived");const t={starsTransactionPeerFragment:"Stars.Via.Fragment",starsTransactionPeerPremiumBot:"Stars.Via.Bot",starsTransactionPeerAppStore:"Stars.Via.App",starsTransactionPeerPlayMarket:"Stars.Via.App"}[a.peer._]??"Stars.Via.Unsupported";return P(t)}function tI(a){let e=!1;const t=I.managers.appAttachMenuBotsManager.getPopularAppBots(),s=xi(async()=>{if(e)return;e=!0;const{userIds:i}=await t;e=!1,ue.createPopup(Rs,{onSelect:n=>{a(()=>{Ce.setInnerPeer({peerId:n})})},peerType:["custom"],getMoreCustom:async()=>({result:i.map(n=>n.toPeerId(!1)),isEnd:!0}),headerLangPackKey:"SearchAppsExamples"})});return s.append(P("GiftStarsSubtitleLinkName")),s}async function sI({transaction:a,middleware:e,size:t,paidMedia:s,paidMediaPeerId:i,chatInvite:n,subscription:r,photo:o}){const[l,c]=await Promise.all([r?qe({peerId:it(r.peer)}):n?Z1(n,e):s||a?.extended_media?qe({peerId:i||it(a.peer.peer)}):!a||a.peer._==="starsTransactionPeer"?qe({peerId:a?it(a.peer.peer):i}):T3(a),(async()=>{const d=async(p,m)=>{const g=[];Bi({container:p,photo:m,boxWidth:t,boxHeight:t,middleware:e,loadPromises:g,withoutPreloader:!0,size:m._==="webDocument"?{_:"photoSizeEmpty",type:""}:void 0}),await Promise.all(g)};if(o){const p=document.createElement("div");return p.classList.add("popup-stars-pay-item"),await d(p,o),p}if(n)return(await J1(n,e,90)).node;if(s||a?.extended_media){const p=s?.extended_media||a.extended_media;let m;if(s){const v=s.extended_media[0];m=Cb(v)}else{const v=a.extended_media[0];m=v.photo||v.document}const g=document.createElement("div");if(g.classList.add("popup-stars-transaction-media","is-paid-media"),s){const v=await ju({media:m,animationGroup:"chat",middleware:e,width:t,height:t});g.append(v)}else await d(g,m);const f=p.length;if(f>1){const v=document.createElement("span");v.classList.add("popup-stars-transaction-media-counter"),v.textContent=""+f,g.append(v)}return g}if(a?.photo){const p=document.createElement("div");return p.classList.add("popup-stars-transaction-media","is-paid-media"),await d(p,a?.photo),p}let u;if(r?u=it(r.peer):a&&a.peer._==="starsTransactionPeer"?u=it(a.peer.peer):i&&(u=i),u){const p=vs({peerId:u,size:t,middleware:e});return await p.readyThumbPromise,p.node}const h=document.createElement("div");return h.classList.add("popup-stars-transaction-media"),h.append(Be("star")),h})()]);return{title:l,media:c}}class ba extends ue{constructor(t={}){super("popup-stars",{closable:!0,overlayClosable:!0,floatingHeader:!0,body:!0,title:"TelegramStars",scrollable:!0});ro(this,"renderTransaction",async t=>{const s=this.middlewareHelper.get(),{title:i,media:n}=await sI({transaction:t,middleware:s,size:42});return Ft(r=>{s.onDestroy(r);const o=t.extended_media?P("StarMediaPurchase"):i;let l;t.extended_media?l=i:t.description?l=je(t.description):t.pFlags.reaction?l=P("StarsReactionTitle"):t.giveaway_post_id?l=P("StarsGiveawayPrizeReceived"):t.paid_messages?l=P("PaidMessages.FeeForMessages",[t.paid_messages]):hr(t.stars)>0?l=t.pFlags.gift?P("StarsGiftReceived"):P("Stars.TopUp"):t.subscription_period&&(l=P("Stars.Subscription.Title"));const c=gs(t.date);let d;t.pFlags.refund?d=P("StarsRefunded"):t.pFlags.failed?d=P("StarsFailed"):t.pFlags.pending&&(d=P("StarsPending"));let u;return T(En,{ref(h){const p=u;typeof p=="function"?p(h):u=h},get title(){return(()=>{const h=I3();return k(h,o),h})()},midtitle:l,subtitle:d?[c," — ",d]:c,media:n,mediaSize:"abitbigger",clickable:()=>{Ln.create({transaction:t})},get rightContent(){return T(zv,{get stars(){return hr(t.stars)}})}}),u})});ro(this,"renderSubscription",async t=>{const s=this.middlewareHelper.get(),i=it(t.peer),n=await qe({peerId:i});n.classList.add("text-bold");const r=Ot(()=>vs({peerId:i,size:42,middleware:s}));await r.readyThumbPromise;const o=!!t.pFlags.canceled,l=Qs(!0)>t.until_date;return Ft(c=>{const d=this;s.onDestroy(c);let u;return T(En,{ref(h){const p=u;typeof p=="function"?p(h):u=h},title:n,get titleRight(){return!o&&T(zg,{get stars(){return t.pricing.amount}})},get subtitle(){return P(l?"Stars.Subscriptions.Expired":o?"Stars.Subscriptions.Expires":"Stars.Subscriptions.Renews",[gs(t.until_date,void 0,!0)])},get subtitleRight(){return!o&&P("Stars.Subscriptions.PerMonth")},get rightContent(){return o&&(()=>{const h=P3();return k(h,()=>P("Stars.Subscriptions.Cancelled")),h})()},get media(){return r.node},mediaSize:"abitbigger",clickable:async()=>{(await Ln.create({subscription:t,noPaymentForm:!0})).addEventListener("finish",p=>{p==="paid"&&d.hide()})}}),u})});Nt(this,t),this.construct()}_construct(t,s,i){const n=this,r=this,o=this,l=this,c=this;this.header.append(Vg());const d=Jl(),u=V(()=>this.itemPrice?this.itemPrice-+d():0),h=V(()=>{if(this.itemPrice){const $=this.options.filter(H=>+H.stars>=u());return $.length?$:[this.options[this.options.length-1]]}return this.options}),p=h().length>3?h().filter($=>!$.pFlags.extended):h(),[m,g]=K(h().length<=3),f=V(()=>Math.ceil((m()?h().length:p.length)/2));let v=!1,y;this.giftPeerId&&!this.itemPrice?y=P("GiftStarsTitle"):this.itemPrice?y=P("StarsNeededTitle",[u()]):y=P("TelegramStars");let w;if(this.giftPeerId&&!this.purpose)w=[V(()=>P("GiftStarsSubtitle",[s]))," ",V(()=>tI(n.hideWithCallback))];else if(this.purpose){let $;if(this.purpose==="reaction")$="Stars.TopUp.Reaction";else{const H="Stars.TopUp.Label_";Ne.strings.get(H+this.purpose)?$=H+this.purpose:$=H+"default"}w=P($,[s])}else this.itemPrice?w=P(this.paymentForm?"StarsNeededText":"Stars.Subscribe.Need",[s]):w=P("TelegramStarsInfo");const b=T(Ms,{caption:"Stars.TOS",get children(){return[t,i,(()=>{const $=M3();return k($,y),$})(),(()=>{const $=L3();return k($,w),$})(),(()=>{const $=E3();return k($,T(Cs,{get each(){return h()},children:(H,D)=>{const U=V(()=>m()||H.pFlags.extended?D():p.indexOf(H)),j=V(()=>U()%2?"calc(100% + .5rem)":"0"),q=V(()=>Math.floor(U()/2)*79+Math.floor(U()/2)*8+"px"),W=V(()=>(m()?h():p).length%2?m()||H.pFlags.extended?U()===h().length-1:U()===p.length-1:!1),ee=eI({stars:+H.stars,size:26});return(()=>{const z=k3(),Z=z.firstChild,de=Z.nextSibling;return z.$$click=async()=>{if(v)return;v=!0;const oe={_:"inputInvoiceStars",purpose:r.giftPeerId?{_:"inputStorePaymentStarsGift",amount:H.amount,currency:H.currency,stars:H.stars,user_id:await r.managers.appUsersManager.getUserInput(r.giftPeerId.toUserId())}:{_:"inputStorePaymentStarsTopup",amount:H.amount,currency:H.currency,stars:H.stars}};try{const ae=await r.managers.appPaymentsManager.getPaymentForm(oe);(await Ln.create({inputInvoice:oe,paymentForm:ae})).addEventListener("finish",re=>{re==="paid"&&(r.toppedUp=!0,r.onTopup&&(r.hide(),r.onTopup(+H.amount)))})}catch(ae){console.error("stars error",ae)}v=!1},k(Z,()=>`+${H.stars}`,null),k(Z,ee,null),k(de,()=>qi(H.amount,H.currency)),Me(ie=>{const oe=!!(H.pFlags.extended&&!m()),ae=!!W(),ke=`translate(${j()}, ${q()})`;return oe!==ie._v$5&&z.classList.toggle("invisible",ie._v$5=oe),ae!==ie._v$6&&z.classList.toggle("full",ie._v$6=ae),ke!==ie._v$7&&((ie._v$7=ke)!=null?z.style.setProperty("transform",ke):z.style.removeProperty("transform")),ie},{_v$5:void 0,_v$6:void 0,_v$7:void 0}),z})()}})),Me(()=>f()*79+(f()-1)*8+"px"!=null?$.style.setProperty("height",f()*79+(f()-1)*8+"px"):$.style.removeProperty("height")),$})(),T(Za,{get class(){return Ge("btn-primary btn-transparent primary popup-stars-more",!m()&&"is-visible")},icon:"down",text:"ShowMoreOptions",onClick:()=>g($=>!$)})]}}),S=$=>{const H=this.middlewareHelper.get();let D="",U=!1;const j=async()=>{if(U)return;U=!0;const ee=await this.managers.appPaymentsManager.getStarsTransactions(D,$);if(!H())return;const z=(ee.history||[]).map(this.renderTransaction),Z=await Promise.all(z);H()&&(W(de=>(D=ee.next_offset,D||(de.loadMore=void 0),de.rendered.push(...Z),de)),U=!1)},[q,W]=id({loadMore:j});return q},_=[void 0,!0,!1].map($=>{const H=S($);return H().loadMore(),H}),[M,C]=K(0);this.scrollable.onScrolledBottom=()=>{const $=_[M()];$().loadMore?.()};const L=this.middlewareHelper.get();let E;const x=async()=>{const $=await this.managers.appPaymentsManager.getStarsSubscriptions(E);if(!L())return;const H=($.subscriptions||[]).map(this.renderSubscription),D=await Promise.all(H);L()&&B(U=>(U.count+=D.length,E=$.subscriptions_next_offset,E||(U.loadMore=void 0),U.rendered.push(...D),U))},[R,B]=id({loadMore:x});R().loadMore();const N=T(Ms,{class:"popup-stars-subscriptions-section",name:"Stars.Subscriptions",get children(){return[(()=>{const $=Em();return k($,()=>R().rendered),$})(),V(()=>V(()=>!!R().loadMore)()&&Mm(R().count-R().rendered.length,$=>{const H=os($,!0);R().loadMore().finally(()=>H())},o.listenerSetter))]}}),G=T(Ms,{class:"popup-stars-transactions-section",get children(){return T(m3,{tab:M,onChange:C,class:"popup-stars-transactions",get menu(){return[P("StarsTransactionsAll"),P("StarsTransactionsIncoming"),P("StarsTransactionsOutgoing")]},get content(){return _.map($=>(()=>{const H=Em();return k(H,()=>$().rendered),H})())}})}}),O=[V((()=>{const $=V(()=>!!l.appConfig.stars_gifts_enabled);return()=>$()&&T(Ms,{get children(){return T(Za,{class:"btn-primary btn-transparent primary",text:"TelegramStarsGift",onClick:async()=>{l.hide();const H=await Rs.createContactPicker();ue.createPopup(ba,{giftPeerId:H,onTopup:async D=>{$e({langPackKey:"StarsGiftSentPopupInfo",langPackArguments:[D,await qe({peerId:H})]})}})}})}})})()),V(()=>!!R().count&&N),G];return[b,V(()=>!u()&&!c.giftPeerId&&O)]}async construct(){const[t,s,i,n,r,o]=await Promise.all([(async()=>{const l=document.createElement("img");return l.classList.add("popup-stars-image"),await Vn(l,`assets/img/${Tb(this.giftPeerId?"stars_pay":"stars")}.png`),l})(),this.peerId||this.paymentForm?.bot_id||this.giftPeerId?qe({peerId:this.peerId||this.giftPeerId||this.paymentForm.bot_id.toPeerId(!1)}):void 0,this.giftPeerId?this.managers.appPaymentsManager.getStarsGiftOptions(this.giftPeerId.toUserId()):this.managers.appPaymentsManager.getStarsTopupOptions(),this.giftPeerId&&(async()=>{const l=vs({peerId:this.giftPeerId,size:100,middleware:this.middlewareHelper.get()});return await l.readyThumbPromise,l.node.classList.add("popup-stars-gift-avatar"),l.node})(),this.managers.apiManager.getAppConfig(),this.itemPrice&&$1(this.middlewareHelper.get())]);this.options=i,this.appConfig=r,this.appendSolid(()=>this._construct(t,s,n)),this.addEventListener("close",()=>{!this.toppedUp&&this.onCancel&&this.onCancel()}),this.show()}}Fs(["click"]);const go="reaction",x3=go+"-element";var la=(a=>(a.Inline="inline",a.Block="block",a.Tag="tag",a))(la||{});const Wv={inline:14,block:22,tag:22},Kv={inline:2,block:4},A3=a=>a;class Ff{constructor(e){this.transformation=e,this.keyframes=this.transformation.k,this.keyframeIndex=0,this.nextKeyframe=this.keyframes[this.keyframeIndex]}withProgress(e){let s=(e-this.keyframe.t)/(this.nextKeyframe.t-this.keyframe.t);const i=Array.isArray(this.beziers);return i||(s=this.beziers(s)),this.keyframe.s.map((n,r)=>n+(this.nextKeyframe.s[r]-n)*(i?this.beziers[r](s):s))}computeAtPoint(e){if(this.nextKeyframe)return e>=this.nextKeyframe.t?(this.keyframe=this.nextKeyframe,this.nextKeyframe=this.keyframes[++this.keyframeIndex],this.keyframe.o&&this.keyframe.i?Array.isArray(this.keyframe.o.x)?new Set(this.keyframe.o.x).size===1?this.beziers=lh(this.keyframe.o.x[0],this.keyframe.o.y[0],this.keyframe.i.x[0],this.keyframe.i.y[0]):this.beziers=this.keyframe.o.x.map((t,s)=>lh(this.keyframe.o.x[s],this.keyframe.o.y[s],this.keyframe.i.x[s],this.keyframe.i.y[s])):this.beziers=lh(this.keyframe.o.x,this.keyframe.o.y,this.keyframe.i.x,this.keyframe.i.y):this.beziers=A3,!this.nextKeyframe||e===this.nextKeyframe.t?this.keyframe.s:this.withProgress(e)):this.keyframe?this.withProgress(e):this.nextKeyframe.s}}function R3(a){const e=a.ks,t=e.a,s=a.op,i=new Array(s-1),n=e.o&&new Ff(e.o),r=e.p&&new Ff(e.p),o=e.s&&new Ff(e.s);for(let l=0;l<s;++l){if(l<a.ip)continue;const c=i[l-1]||{},d={},u=r.computeAtPoint(l);u?(d.translation=u,t&&(d.anchor=t.k)):(d.translation=c.translation,d.anchor=c.anchor);const h=o.computeAtPoint(l);h?d.scale=h:d.scale=c.scale;const p=n.computeAtPoint(l);p?d.opacity=p:d.opacity=c.opacity,(u||h||p)&&(i[l]=d)}return i}let Bf;function F3(){if(Bf)return Bf;const a=Ns.makeAssetUrl("ReactionGeneric");return Bf=Ns.loadAnimationDataFromURL(a,"json").then(t=>{const s=t.layers.filter(n=>n.nm.startsWith("placeholder_")),i=[];for(const n of s)i.push(R3(n));return{layersPositions:i,op:t.op}})}class Qo extends HTMLElement{constructor(){super(),this.classList.add(go),this.managers=I.managers}get reactionCount(){return this._reactionCount}set reactionCount(e){this._reactionCount=e}get count(){return this.reactionCount.count}init(e,t){this.type=e,this.classList.add(go+"-"+e),this.classList.toggle(go+"-like-block",e==="block"||e==="tag"),this.middleware=t,e==="tag"&&this.insertAdjacentHTML("beforeend",`
- <div class="reaction-tag-background"></div>
- <svg class="reaction-tag-svg" width="43" height="30" viewBox="0 0 43 30" xmlns="http://www.w3.org/2000/svg">
- <path class="reaction-tag-svg-path" d="M40.8317 12.0432L34.9967 4.08636C33.1129 1.51761 30.1181 0 26.9326 0H7C3.13401 0 0 3.13401 0 7V23C0 26.866 3.13401 30 7 30H26.9326C30.1181 30 33.1129 28.4824 34.9967 25.9136L40.8317 17.9568C42.1223 16.1969 42.1223 13.8031 40.8317 12.0432Z" />
- </svg>
- <div class="reaction-tag-dot"></div>
- `)}setCanRenderAvatars(e){this.canRenderAvatars=e}render(e){const t=!!this.stickerContainer;if(!t)this.stickerContainer=document.createElement("div"),this.stickerContainer.classList.add(go+"-sticker"),this.append(this.stickerContainer);else return this.customEmojiElement;const s=this.reactionCount;if(e||t)return;const i=s.reaction;if(i._==="reactionEmoji"){const n=Ae.getReaction(i.emoticon);return en(n,r=>{r.center_icon?this.stickerContainer.classList.add("is-regular"):this.stickerContainer.classList.add("is-static"),r.pFlags.inactive&&this.classList.add("is-inactive");const o=r.center_icon??r.static_icon;this.renderDoc(o)})}else if(i._==="reactionCustomEmoji"){if(this.stickerContainer.classList.add("is-custom"),!this.customEmojiElement){this.customEmojiElement=Wy.create();const n=this.wrapStickerPromise=this.customEmojiElement.readyPromise=Mt();this.wrapStickerPromise.finally(()=>{this.wrapStickerPromise===n&&(this.wrapStickerPromise=void 0)}),this.stickerContainer.append(this.customEmojiElement)}return this.customEmojiElement.docId=i.document_id,this.customEmojiElement}else i._==="reactionPaid"&&(this.classList.add("is-paid"),Gi||this.append(Rl({mode:"button",isDiv:!0})),this.stickerContainer.append(ya()))}setPaidReactionCounter(e){this.paidReactionCounter?this.paidReactionCounter.setCount(e):(this.paidReactionCounter=new ad({reverse:!1,prefix:"+",calculateWidth:!0}),this.paidReactionCounter.container.classList.add("reaction-paid-counter"),this.append(this.paidReactionCounter.container),this.paidReactionCounter.setCount(e,!0))}destroyPaidReactionCounter(){if(this.paidReactionCounter){const{container:e}=this.paidReactionCounter;this.paidReactionCounter=void 0,setTimeout(()=>{e.remove()},300)}}renderDoc(e){const t=Wv[this.type],s=this.wrapStickerPromise=ai({div:this.stickerContainer,doc:e,width:t,height:t,static:!0,managers:this.managers,middleware:this.middleware,needFadeIn:!1}).then(({render:i})=>i).finally(()=>{this.wrapStickerPromise===s&&(this.wrapStickerPromise=void 0)})}findTitle(){let e;return this.type==="tag"&&(e=su.find(s=>Wn(s.reaction,this.reactionCount.reaction))?.title),e}renderCounter(e,t=this.findTitle()){const s=Kv[this.type];if(s===void 0&&!e&&!t&&!this.hasTitle)return;const i=this.reactionCount;let n=!1;if(e||t||i.count>=s||this.type==="block"&&!this.canRenderAvatars){this.counter||(this.counter=document.createElement(this.type==="inline"?"i":"span"),this.counter.classList.add(go+"-counter"));const r=un(i.count);if(t){const o=document.createElement("span");o.classList.add(go+"-counter-title"),o.append(typeof t=="string"?je(t):t),this.counter.replaceChildren(o),n=!0,e&&this.counter.append(" ",r)}else this.counter.textContent!==r&&(this.counter.textContent=r);this.counter.parentElement||this.append(this.counter)}else this.counter?.parentElement&&(this.counter.remove(),this.counter=void 0);this.hasTitle=n}renderAvatars(e){if(this.type==="block"){if(this.reactionCount.count>=Kv[this.type]||!this.canRenderAvatars){this.stackedAvatars&&(this.stackedAvatars.container.remove(),this.stackedAvatars=void 0);return}this.stackedAvatars||(this.stackedAvatars=new Zl({avatarSize:24,middleware:this.middleware}),this.append(this.stackedAvatars.container)),this.stackedAvatars.render(e.map(t=>it(t.peer_id)))}}setIsChosen(e=this.reactionCount.chosen_order!==void 0){if(this.type==="inline")return;(this.classList.contains("is-chosen")&&!this.classList.contains("backwards"))!==e&&Dt({element:this,className:"is-chosen",forwards:e,duration:this.isConnected?300:0})}fireAroundAnimation(e){let t=0;return this.type==="inline"?t=14:(this.type==="block"||this.type==="tag")&&(t=18),Qo?.fireAroundAnimation({waitPromise:e,cache:this,middleware:this.middleware,reaction:this.reactionCount?.reaction,stickerContainer:this.stickerContainer,managers:this.managers,sizes:{genericEffect:26,genericEffectSize:100,size:Wv[this.type]+t,effectSize:80},scrollable:Ce.chat.bubbles.scrollable})}static fireAroundAnimation(e){if(e.cache.hasAroundAnimation||!wt.isAvailable("effects_reactions"))return;e.managers??(e.managers=I.managers);const t=e.reaction;if(t._==="reactionEmpty")return;const s=({availableReaction:r,genericEffect:o,sticker:l,onlyAround:c,assetName:d})=>{const u=o?e.sizes.genericEffect:e.sizes.size,h=o?void 0:document.createElement("div");h&&h.classList.add(go+"-sticker-activate");const p=e.sizes.genericEffectSize,m=o&&l.sticker!==2,g=e.textColor||"primary-text-color",f={doc:o||r?.around_animation,size:o?p:e.sizes.effectSize,target:e.stickerContainer,side:"center",skipRatio:1,play:!1,managers:e.managers,middleware:e.middleware,scrollable:e.scrollable},v=d?Ns.loadAnimationAsAsset({width:e.sizes.effectSize,height:e.sizes.effectSize,skipRatio:1,autoplay:!1,middleware:e.middleware,container:h,noCache:!0},d):Dh(f).stickerPromise,y=o&&Dh({...f,doc:m?f.doc:l,size:p,stickerSize:u,loopEffect:!0,textColor:g}),w=(!o||m)&&!c&&ai({div:h||document.createElement("div"),doc:l||r.center_icon,width:u,height:u,withThumb:!1,needUpscale:!0,play:!1,skipRatio:1,group:"none",needFadeIn:!1,managers:e.managers,middleware:e.middleware,textColor:g,loop:m}).then(({render:b})=>b);return Promise.all([o?y.stickerPromise:w,v,w,o&&F3(),e.waitPromise]).then(([b,S,_,M,C])=>{c&&(b=S);const L=Mt(),E=()=>{L.resolve(),b?.remove(),h?.remove(),e.stickerContainer.classList.remove("has-animation")};if(o){const R=b.canvas[0];R.classList.add("hide");const B=b.contexts[0],N=R.dpr,G=p*N,O=R.width;y.animationDiv.append(R),y.animationDiv.style.transform="scaleX(-1)";const $=_?.[0],H=$ instanceof HTMLVideoElement;b.addEventListener("firstFrame",()=>{b.setSize(G,G),R.classList.remove("hide"),H&&Sn($)},{once:!0});let D=0;const U=G/512,{layersPositions:j,op:q}=M;b.overrideRender=W=>{m&&(W=$);const ee=W instanceof ImageData;B.clearRect(0,0,G,G);for(let z=0;z<j.length;++z){const de=j[z][D];if(!de)continue;let ie=!1,oe=!1,ae=!1,ke=O,re=O;if(de.scale){const[Ve,fe]=de.scale;ke*=Ve*4/100,re*=fe*4/100,oe=Ve<0,ae=fe<0}let[ce,Ie]=de.translation;ce=(ce+de.anchor[0])*U-Math.abs(ke)/2,Ie=(Ie+de.anchor[1])*U-Math.abs(re)/2,(oe||ae)&&(ie=!0,B.save(),B.scale(oe?-1:1,ae?-1:1),oe&&(ce=-ce),ae&&(Ie=-Ie)),de.opacity&&(ie||(ie=!0,B.save()),B.globalAlpha=de.opacity[0]/100),ee?B.putImageData(W,ce,Ie):B.drawImage(W,ce,Ie,ke,re),ie&&B.restore()}D++,D>=q&&x()}}if(!b||!S)return E(),L;const x=()=>{$s(E)};return e.middleware.onDestroy(x),!o&&b.addEventListener("enterFrame",R=>{R===b.maxFrame&&(e.cache.wrapStickerPromise?e.cache.wrapStickerPromise.then(()=>{setTimeout(x,1e3)}):x())}),b.addEventListener("firstFrame",()=>{h&&e.stickerContainer.append(h),e.stickerContainer.classList.add("has-animation"),b.play(),S.play()},{once:!0}),L})},i=(r,o=r.stickerEmojiRaw)=>Ky([Ae.getReaction(o),r?e.managers.appReactionsManager.getRandomGenericAnimation():void 0],([l,c])=>s(l?{availableReaction:l,onlyAround:!!r}:{genericEffect:c,sticker:r}));let n;t._==="reactionEmoji"?n=i(void 0,t.emoticon):t._==="reactionPaid"?(n=Promise.resolve(),s({onlyAround:!0,assetName:`StarReactionEffect${fg(1,3)}`})):n=en(e.managers.appEmojiManager.getCustomEmojiDocument(t.document_id),r=>i(r)),e.middleware.onDestroy(()=>{e.cache.hasAroundAnimation=void 0}),e.cache.hasAroundAnimation=n,n.finally(()=>{e.cache.hasAroundAnimation===n&&(e.cache.hasAroundAnimation=void 0)})}}customElements.define(x3,Qo);const nl="reactions",B3=nl+"-element",wc=new Map,vh=new Map,zS=Symbol("Reaction was sent");function iI(a){return a.peerId+"_"+a.mid}const su=[];I.addEventListener("saved_tags",({savedPeerId:a,tags:e})=>{a||(su.splice(0,su.length,...e),wc.forEach(t=>{t.forEach(s=>{s.getContext().peerId===I.myId&&s.getType()===la.Tag&&s.render()})}))});class Wg extends HTMLElement{constructor(){super(),this.classList.add(nl),this.sorted=[],this.middlewareHelpers=new Map,this.managers=I.managers}connectedCallback(){let e=wc.get(this.key);e||wc.set(this.key,e=new Set),e.add(this),this.onConnectCallback&&this.isConnected&&(this.onConnectCallback(),this.onConnectCallback=void 0)}disconnectedCallback(){const e=wc.get(this.key);e.delete(this),e.size||wc.delete(this.key)}getType(){return this.type}getReactionCount(e){return this.sorted[this.sorted.indexOf(e)].reactionCount}getContext(){return this.context}getSorted(){return this.sorted}shouldUseTagsForContext(e){if(e.peerId!==I.myId)return!1;const t=e.reactions;return!t||t.pFlags.reactions_as_tags?!0:!t.results.length}init({context:e,type:t,middleware:s,isPlaceholder:i=this.isPlaceholder,animationGroup:n,lazyLoadQueue:r,forceCounter:o}){this.key!==void 0&&this.disconnectedCallback(),this.middleware!==s&&s.onDestroy(()=>{this.middlewareHelpers.clear()}),this.context=e,this.key=this.context.peerId+"_"+this.context.mid,this.middleware=s,this.isPlaceholder=i,this.animationGroup=n,this.lazyLoadQueue=r,this.forceCounter=o,this.setType(t),this.connectedCallback()}setType(e){if(e===la.Block&&this.shouldUseTagsForContext(this.context)&&(e=la.Tag),this.type!==e){this.type=e;for(const t in la)this.classList.remove(nl+"-"+t);this.classList.add(nl+"-"+e),this.classList.toggle(nl+"-like-block",e===la.Block||e===la.Tag)}}changeContext(e){return this.init({context:e,type:this.type,middleware:this.middleware})}update(e,t,s){this.context=e,this.render(t,s)}render(e,t){const s=this.context.reactions,i=!!(s&&s.results.length);if(this.classList.toggle("has-no-reactions",!i),!i&&!this.sorted.length)return;const n=i?s.results:[];hn(this.sorted,(h,p,m)=>{const g=h.reactionCount.reaction;n.some(v=>Wn(v.reaction,g))||(this.middlewareHelpers.get(h).destroy(),this.middlewareHelpers.delete(h),m.splice(p,1),h.remove())});let r=!1;const o=n.reduce((h,p)=>h+p.count,0),l=s&&(!!s.pFlags.can_see_list||this.context.peerId.isUser())&&o<Kv[this.type],c=new Array(n.length);let d,u;if(this.sorted=n.map((h,p,m)=>{let g=this.sorted.find(_=>Wn(_.reactionCount.reaction,h.reaction));if(!g){const _=this.middleware.create();g=new Qo,g.init(this.type,_.get()),this.middlewareHelpers.set(g,_)}g.classList.toggle("is-last",p===m.length-1);const f=h.reaction._==="reactionPaid",v=f&&vh.get(iI(this.context));v&&(d=g,u=v);const y=s.recent_reactions?s.recent_reactions.filter(_=>Wn(_.reaction,h.reaction)):[],w=g.isUnread,b=y.some(_=>_.pFlags.unread);g.reactionCount={...h,count:h.count+(v?.count?.()??0)},g.setCanRenderAvatars(l);const S=g.render(this.isPlaceholder);return g.renderCounter(this.forceCounter),g.renderAvatars(y),g.isUnread=b,g.setIsChosen(f?!!v||s.top_reactors.some(_=>_.pFlags.my&&_.count):void 0),w&&!b&&!e?.includes(h)&&((e??(e=[])).push(h),r=!0),c[p]=S,g}),this.sorted.forEach((h,p)=>{di(h,this,p)}),u){const{width:h}=d.getBoundingClientRect();d.style.setProperty("--width",h+"px"),d.setPaidReactionCounter(u.count()),d.classList.contains("effect-active")||(d.classList.add("effect-active"),u.abortController.signal.addEventListener("abort",()=>{d.classList.remove("effect-active"),d.querySelectorAll(".reaction-sticker-activate").forEach(p=>p.remove()),d.destroyPaidReactionCounter()}))}Ky(c,h=>{const p=new Map;if(h.forEach(m=>{m&&p.set(m.docId,new Set([m]))}),!p.size){this.customEmojiRenderer&&(this.customEmojiRendererMiddlewareHelper.destroy(),this.customEmojiRenderer.remove(),this.customEmojiRenderer=this.customEmojiRendererMiddlewareHelper=void 0);return}if(!this.customEmojiRenderer){const m=Wv[this.type];this.customEmojiRendererMiddlewareHelper=this.middleware.create(),this.customEmojiRenderer=jy.create({animationGroup:this.animationGroup,customEmojiSize:ii(m,m),middleware:this.customEmojiRendererMiddlewareHelper.get(),lazyLoadQueue:this.lazyLoadQueue,observeResizeElement:this}),this.customEmojiRenderer.classList.add(nl+"-renderer"),this.customEmojiRenderer.canvas.classList.add(nl+"-renderer-canvas"),this.prepend(this.customEmojiRenderer)}this.customEmojiRenderer.add({addCustomEmojis:p,lazyLoadQueue:this.lazyLoadQueue})}),!this.isPlaceholder&&e?.length&&(this.isConnected?this.handleChangedResults(e,t,r):this.onConnectCallback=()=>{this.handleChangedResults(e,t,r)})}async handleChangedResults(e,t,s){await vi(),this.context.peerId===Ce.chat.peerId&&(s&&(t=(t||Promise.resolve()).then(()=>ns(150))),e.forEach(i=>{this.sorted.find(r=>Wn(r.reactionCount.reaction,i.reaction))?.fireAroundAnimation(t)}))}}customElements.define(B3,Wg);class D3{constructor(e){this.observing=new Map,this.observingQueue=new Map,this.intersecting=new Set,this.freezedObservingNew=!1,this.observer=new IntersectionObserver(t=>{const s=this.observing;for(let i=0,n=t.length;i<n;++i){const r=t[i],o=s.get(r.target);if(!o){console.error("intersection process no callbacks:",r);debugger;continue}r.isIntersecting?this.intersecting.add(r.target):this.intersecting.delete(r.target);for(const l of o)try{l(r)}catch(c){console.error("intersection process callback error:",c)}}},e)}getIntersecting(){return this.intersecting}disconnect(){this.observing.clear(),this.observingQueue.clear(),this.intersecting.clear(),this.observer.disconnect()}toggleObservingNew(e){if(this.freezedObservingNew===e)return;this.freezedObservingNew=e;const t=this.observingQueue;if(!e&&t.size){for(const[s,i]of t)for(const n of i)this.observe(s,n);t.clear()}}has(e,t,s=this.observing){const i=s.get(e);return!!(i&&i.has(t))}observe(e,t){if(this.freezedObservingNew&&this.has(e,t))return;const s=this.freezedObservingNew?this.observingQueue:this.observing;let i=s.get(e);i&&i.has(t)||(i||(i=new Set,s.set(e,i),s===this.observing&&this.observer.observe(e)),i.add(t))}unobserve(e,t){const s=this.freezedObservingNew&&!this.has(e,t)?this.observingQueue:this.observing,i=s.get(e);i&&(i.delete(t),i.size||(s.delete(e),this.observer.unobserve(e),this.intersecting.delete(e)))}}function $3(a){si(a.textContent)}function Db(a,e,t){if(t)return jt(a.description||"",{...e,entities:a.entities});e??(e={}),e.whitelistedDomains??(e.whitelistedDomains=Ot(()=>EL.appConfig?.whitelisted_domains));const s=Ya(a.description||"",150,180);return jt(s,e)}function nI(a){let e=a.title||a.author||"";return e=Ya(e,80,100),jt(e,{noLinks:!0,noLinebreaks:!0})}function WS(a){if(!a)return!1;const e=a.media?.document;return!!(a.pFlags.media_unread&&a.pFlags.mentioned&&(!e||!["voice","round"].includes(e.type)))}function aI(a){let e=0,t;for(const s of a)if(s.message){if(++e>1)break;t=s}return e>1&&(t=void 0),t}const ut={None:0,Top:1,Right:2,Bottom:4,Left:8};class km{constructor(e,t,s,i,n=t){this.sizes=e,this.maxWidth=t,this.minWidth=s,this.spacing=i,this.maxHeight=n,this.count=e.length,this.ratios=km.countRatios(e),this.proportions=km.countProportions(this.ratios),this.averageRatio=Uo(this.ratios,1)/this.count,this.maxSizeRatio=t/this.maxHeight}layout(){if(this.count){if(this.count===1)return this.layoutOne()}else return[];return this.count>=5||this.ratios.find(e=>e>2)?new $b(this.ratios,this.averageRatio,this.maxWidth,this.minWidth,this.spacing).layout():this.count===2?this.layoutTwo():this.count===3?this.layoutThree():this.layoutFour()}layoutTwo(){return this.proportions==="ww"&&this.averageRatio>1.4*this.maxSizeRatio&&this.ratios[1]-this.ratios[0]<.2?this.layoutTwoTopBottom():this.proportions==="ww"||this.proportions==="qq"?this.layoutTwoLeftRightEqual():this.layoutTwoLeftRight()}layoutThree(){return this.proportions[0]==="n"?this.layoutThreeLeftAndOther():this.layoutThreeTopAndOther()}layoutFour(){return this.proportions[0]==="w"?this.layoutFourTopAndOther():this.layoutFourLeftAndOther()}layoutOne(){const e=this.maxWidth,t=this.sizes[0].h*e/this.sizes[0].w;return[{geometry:{x:0,y:0,width:e,height:t},sides:ut.Left|ut.Top|ut.Right|ut.Bottom}]}layoutTwoTopBottom(){const e=this.maxWidth,t=Math.round(Math.min(e/this.ratios[0],Math.min(e/this.ratios[1],(this.maxHeight-this.spacing)/2)));return[{geometry:{x:0,y:0,width:e,height:t},sides:ut.Left|ut.Top|ut.Right},{geometry:{x:0,y:t+this.spacing,width:e,height:t},sides:ut.Left|ut.Bottom|ut.Right}]}layoutTwoLeftRightEqual(){const e=(this.maxWidth-this.spacing)/2,t=Math.round(Math.min(e/this.ratios[0],Math.min(e/this.ratios[1],this.maxHeight*1)));return[{geometry:{x:0,y:0,width:e,height:t},sides:ut.Top|ut.Left|ut.Bottom},{geometry:{x:e+this.spacing,y:0,width:e,height:t},sides:ut.Top|ut.Right|ut.Bottom}]}layoutTwoLeftRight(){const e=Math.round(this.minWidth*1.5),t=Math.min(Math.round(Math.max(.4*(this.maxWidth-this.spacing),(this.maxWidth-this.spacing)/this.ratios[0]/(1/this.ratios[0]+1/this.ratios[1]))),this.maxWidth-this.spacing-e),s=this.maxWidth-t-this.spacing,i=Math.min(this.maxHeight,Math.round(Math.min(s/this.ratios[0],t/this.ratios[1])));return[{geometry:{x:0,y:0,width:s,height:i},sides:ut.Top|ut.Left|ut.Bottom},{geometry:{x:s+this.spacing,y:0,width:t,height:i},sides:ut.Top|ut.Right|ut.Bottom}]}layoutThreeLeftAndOther(){const e=this.maxHeight,t=Math.round(Math.min((this.maxHeight-this.spacing)/2,this.ratios[1]*(this.maxWidth-this.spacing)/(this.ratios[2]+this.ratios[1]))),s=e-t-this.spacing,i=Math.max(this.minWidth,Math.round(Math.min((this.maxWidth-this.spacing)/2,Math.min(t*this.ratios[2],s*this.ratios[1])))),n=Math.min(Math.round(e*this.ratios[0]),this.maxWidth-this.spacing-i);return[{geometry:{x:0,y:0,width:n,height:e},sides:ut.Top|ut.Left|ut.Bottom},{geometry:{x:n+this.spacing,y:0,width:i,height:s},sides:ut.Top|ut.Right},{geometry:{x:n+this.spacing,y:s+this.spacing,width:i,height:t},sides:ut.Bottom|ut.Right}]}layoutThreeTopAndOther(){const e=this.maxWidth,t=Math.round(Math.min(e/this.ratios[0],(this.maxHeight-this.spacing)*.66)),s=(this.maxWidth-this.spacing)/2,i=Math.min(this.maxHeight-t-this.spacing,Math.round(Math.min(s/this.ratios[1],s/this.ratios[2]))),n=e-s-this.spacing;return[{geometry:{x:0,y:0,width:e,height:t},sides:ut.Left|ut.Top|ut.Right},{geometry:{x:0,y:t+this.spacing,width:s,height:i},sides:ut.Bottom|ut.Left},{geometry:{x:s+this.spacing,y:t+this.spacing,width:n,height:i},sides:ut.Bottom|ut.Right}]}layoutFourTopAndOther(){const e=this.maxWidth,t=Math.round(Math.min(e/this.ratios[0],(this.maxHeight-this.spacing)*.66)),s=Math.round((this.maxWidth-2*this.spacing)/(this.ratios[1]+this.ratios[2]+this.ratios[3])),i=Math.max(this.minWidth,Math.round(Math.min((this.maxWidth-2*this.spacing)*.4,s*this.ratios[1]))),n=Math.round(Math.max(Math.max(this.minWidth*1,(this.maxWidth-2*this.spacing)*.33),s*this.ratios[3])),r=e-i-n-2*this.spacing,o=Math.min(this.maxHeight-t-this.spacing,s);return[{geometry:{x:0,y:0,width:e,height:t},sides:ut.Left|ut.Top|ut.Right},{geometry:{x:0,y:t+this.spacing,width:i,height:o},sides:ut.Bottom|ut.Left},{geometry:{x:i+this.spacing,y:t+this.spacing,width:r,height:o},sides:ut.Bottom},{geometry:{x:i+this.spacing+r+this.spacing,y:t+this.spacing,width:n,height:o},sides:ut.Right|ut.Bottom}]}layoutFourLeftAndOther(){const e=this.maxHeight,t=Math.round(Math.min(e*this.ratios[0],(this.maxWidth-this.spacing)*.6)),s=Math.round((this.maxHeight-2*this.spacing)/(1/this.ratios[1]+1/this.ratios[2]+1/this.ratios[3])),i=Math.round(s/this.ratios[1]),n=Math.round(s/this.ratios[2]),r=e-i-n-2*this.spacing,o=Math.max(this.minWidth,Math.min(this.maxWidth-t-this.spacing,s));return[{geometry:{x:0,y:0,width:t,height:e},sides:ut.Top|ut.Left|ut.Bottom},{geometry:{x:t+this.spacing,y:0,width:o,height:i},sides:ut.Top|ut.Right},{geometry:{x:t+this.spacing,y:i+this.spacing,width:o,height:n},sides:ut.Right},{geometry:{x:t+this.spacing,y:i+n+2*this.spacing,width:o,height:r},sides:ut.Bottom|ut.Right}]}static countRatios(e){return e.map(t=>t.w/t.h)}static countProportions(e){return e.map(t=>t>1.2?"w":t<.8?"n":"q").join("")}}class $b{constructor(e,t,s,i,n,r=s*4/3){this.averageRatio=t,this.maxWidth=s,this.minWidth=i,this.spacing=n,this.maxHeight=r,this.ratios=$b.cropRatios(e,t),this.count=e.length}static cropRatios(e,t){return e.map(n=>t>1.1?zt(n,1,2.75):zt(n,.6667,1))}layout(){const e=new Array(this.count),t=[],s=(h,p)=>{const m=this.ratios.slice(h,h+p),g=Uo(m,0);return(this.maxWidth-(p-1)*this.spacing)/g},i=h=>{const p=[];let m=0;for(const g of h)p.push(s(m,g)),m+=g;t.push({lineCounts:h,heights:p})};for(let h=1;h!==this.count;++h){const p=this.count-h;h>3||p>3||i([h,p])}for(let h=1;h!==this.count-1;++h)for(let p=1;p!==this.count-h;++p){const m=this.count-h-p;h>3||p>(this.averageRatio<.85?4:3)||m>3||i([h,p,m])}for(let h=1;h!==this.count-1;++h)for(let p=1;p!==this.count-h;++p)for(let m=1;m!==this.count-h-p;++m){const g=this.count-h-p-m;h>3||p>3||m>3||g>3||i([h,p,m,g])}let n=null,r=0;for(const h of t){const{heights:p,lineCounts:m}=h,g=m.length,f=Uo(p,0)+this.spacing*(g-1),v=Math.min(...p);Math.max(...p);const y=v<this.minWidth?1.5:1,w=(()=>{for(let S=1;S!==g;++S)if(m[S-1]>m[S])return 1.5;return 1})(),b=Math.abs(f-this.maxHeight)*y*w;(!n||b<r)&&(n=h,r=b)}const o=n.lineCounts,l=n.heights,c=o.length;let d=0,u=0;for(let h=0;h!==c;++h){const p=o[h],m=l[h],g=Math.round(m);let f=0;for(let v=0;v!==p;++v){const y=ut.None|(h===0?ut.Top:ut.None)|(h===c-1?ut.Bottom:ut.None)|(v===0?ut.Left:ut.None)|(v===p-1?ut.Right:ut.None),w=this.ratios[d],b=v===p-1?this.maxWidth-f:Math.round(w*m);e[d]={geometry:{x:f,y:u,width:b,height:g},sides:y},f+=b+this.spacing,++d}u+=g+this.spacing}return e}}function rI(a){const t=new km(a.items,a.maxWidth,a.minWidth,a.spacing,a.maxHeight).layout(),s=t.find(c=>c.sides&ut.Right),i=s.geometry.width+s.geometry.x,n=t.find(c=>c.sides&ut.Bottom),r=n.geometry.height+n.geometry.y,o=a.container;o.style.width=i+"px",o.style.height=r+"px";const l=o.children;t.forEach(({geometry:c,sides:d},u)=>{let h;if(h=l[u],h||(h=document.createElement("div"),o.append(h)),h.classList.add("album-item"),a.noGroupedItem||h.classList.add("grouped-item"),h.style.width=c.width/i*100+"%",h.style.height=c.height/r*100+"%",h.style.top=c.y/r*100+"%",h.style.left=c.x/i*100+"%",d&ut.Left&&d&ut.Top&&(h.style.borderStartStartRadius=`calc(var(--border-start-start-radius) - ${a.spacing}px)`),d&ut.Left&&d&ut.Bottom&&(h.style.borderEndStartRadius=`calc(var(--border-end-start-radius) - ${a.spacing}px)`),d&ut.Right&&d&ut.Top&&(h.style.borderStartEndRadius=`calc(var(--border-start-end-radius) - ${a.spacing}px)`),d&ut.Right&&d&ut.Bottom&&(h.style.borderEndEndRadius=`calc(var(--border-end-end-radius) - ${a.spacing}px)`),a.forMedia){const p=document.createElement("div");p.classList.add("album-item-media"),h.append(p)}})}function Df({messages:a,media:e,attachmentDiv:t,middleware:s,uploading:i,lazyLoadQueue:n,isOut:r,chat:o,loadPromises:l,autoDownload:c,managers:d=I.managers,animationGroup:u,spoilered:h,videoTimes:p,uploadingFileName:m}){const g=[];for(const b of e||a){const S=!!a,_=S?Vi(b,!0):b,M=_._==="photo"?ha(_,480,480):{w:_.w,h:_.h};g.push({size:M,media:_,message:S?b:void 0})}rI({container:t,items:g.map(b=>({w:b.size.w,h:b.size.h})),maxWidth:st.active.album.width,minWidth:100,spacing:1,forMedia:!0,noGroupedItem:!a});const{width:f,height:v}=t.style,y=parseInt(f),w=parseInt(v);g.forEach((b,S)=>{const{size:_,media:M,message:C}=b,L=C?.media,E=h||!!L?.pFlags?.spoiler,x=t.children[S];C?(x.dataset.mid=""+C.mid,x.dataset.peerId=""+C.peerId):x.dataset.index=""+S;const R=x.firstElementChild,B=M._==="photo";let N;if(B?N=Bi({photo:M,message:C,container:R,boxWidth:0,boxHeight:0,isOut:r,lazyLoadQueue:n,middleware:s,size:_,loadPromises:l,autoDownloadSize:c.photo,managers:d,uploadingFileName:m?.[S]}):N=Xa({doc:M,container:R,message:C,boxWidth:0,boxHeight:0,withTail:!1,isOut:r,lazyLoadQueue:n,middleware:s,loadPromises:l,autoDownload:c,managers:d,noAutoplayAttribute:!0,uploadingFileName:m?.[S]}),N&&l?.push(N),E){const O=(N||Promise.resolve()).then(async()=>{if(!s())return;const{width:$,height:H}=x.style,D=+$.slice(0,-1)/100*y,U=+H.slice(0,-1)/100*w,j=await ju({media:M,animationGroup:u,middleware:s,width:D,height:U});s()&&R.append(j)});l?.push(O)}const G=p?.[S];G&&R.append(G)})}const N3={Á:"A",Ă:"A",Ắ:"A",Ặ:"A",Ằ:"A",Ẳ:"A",Ẵ:"A",Ǎ:"A",Â:"A",Ấ:"A",Ậ:"A",Ầ:"A",Ẩ:"A",Ẫ:"A",Ä:"A",Ǟ:"A",Ȧ:"A",Ǡ:"A",Ạ:"A",Ȁ:"A",À:"A",Ả:"A",Ȃ:"A",Ā:"A",Ą:"A",Å:"A",Ǻ:"A",Ḁ:"A","Ⱥ":"A",Ã:"A","Ꜳ":"AA",Æ:"AE",Ǽ:"AE",Ǣ:"AE","Ꜵ":"AO","Ꜷ":"AU","Ꜹ":"AV","Ꜻ":"AV","Ꜽ":"AY",Ḃ:"B",Ḅ:"B",Ɓ:"B",Ḇ:"B","Ƀ":"B",Ƃ:"B",Ć:"C",Č:"C",Ç:"C",Ḉ:"C",Ĉ:"C",Ċ:"C",Ƈ:"C","Ȼ":"C",Ď:"D",Ḑ:"D",Ḓ:"D",Ḋ:"D",Ḍ:"D",Ɗ:"D",Ḏ:"D",Dz:"D",Dž:"D",Đ:"D",Ƌ:"D",DZ:"DZ",DŽ:"DZ",É:"E",Ĕ:"E",Ě:"E",Ȩ:"E",Ḝ:"E",Ê:"E",Ế:"E",Ệ:"E",Ề:"E",Ể:"E",Ễ:"E",Ḙ:"E",Ë:"E",Ė:"E",Ẹ:"E",Ȅ:"E",È:"E",Ẻ:"E",Ȇ:"E",Ē:"E",Ḗ:"E",Ḕ:"E",Ę:"E","Ɇ":"E",Ẽ:"E",Ḛ:"E","Ꝫ":"ET",Ḟ:"F",Ƒ:"F",Ǵ:"G",Ğ:"G",Ǧ:"G",Ģ:"G",Ĝ:"G",Ġ:"G",Ɠ:"G",Ḡ:"G",Ǥ:"G",Ḫ:"H",Ȟ:"H",Ḩ:"H",Ĥ:"H","Ⱨ":"H",Ḧ:"H",Ḣ:"H",Ḥ:"H",Ħ:"H",Í:"I",Ĭ:"I",Ǐ:"I",Î:"I",Ï:"I",Ḯ:"I",İ:"I",Ị:"I",Ȉ:"I",Ì:"I",Ỉ:"I",Ȋ:"I",Ī:"I",Į:"I",Ɨ:"I",Ĩ:"I",Ḭ:"I","Ꝺ":"D","Ꝼ":"F","Ᵹ":"G","Ꞃ":"R","Ꞅ":"S","Ꞇ":"T","Ꝭ":"IS",Ĵ:"J","Ɉ":"J",Ḱ:"K",Ǩ:"K",Ķ:"K","Ⱪ":"K","Ꝃ":"K",Ḳ:"K",Ƙ:"K",Ḵ:"K","Ꝁ":"K","Ꝅ":"K",Ĺ:"L","Ƚ":"L",Ľ:"L",Ļ:"L",Ḽ:"L",Ḷ:"L",Ḹ:"L","Ⱡ":"L","Ꝉ":"L",Ḻ:"L",Ŀ:"L","Ɫ":"L",Lj:"L",Ł:"L",LJ:"LJ",Ḿ:"M",Ṁ:"M",Ṃ:"M","Ɱ":"M",Ń:"N",Ň:"N",Ņ:"N",Ṋ:"N",Ṅ:"N",Ṇ:"N",Ǹ:"N",Ɲ:"N",Ṉ:"N","Ƞ":"N",Nj:"N",Ñ:"N",NJ:"NJ",Ó:"O",Ŏ:"O",Ǒ:"O",Ô:"O",Ố:"O",Ộ:"O",Ồ:"O",Ổ:"O",Ỗ:"O",Ö:"O",Ȫ:"O",Ȯ:"O",Ȱ:"O",Ọ:"O",Ő:"O",Ȍ:"O",Ò:"O",Ỏ:"O",Ơ:"O",Ớ:"O",Ợ:"O",Ờ:"O",Ở:"O",Ỡ:"O",Ȏ:"O","Ꝋ":"O","Ꝍ":"O",Ō:"O",Ṓ:"O",Ṑ:"O",Ɵ:"O",Ǫ:"O",Ǭ:"O",Ø:"O",Ǿ:"O",Õ:"O",Ṍ:"O",Ṏ:"O",Ȭ:"O",Ƣ:"OI","Ꝏ":"OO",Ɛ:"E",Ɔ:"O",Ȣ:"OU",Ṕ:"P",Ṗ:"P","Ꝓ":"P",Ƥ:"P","Ꝕ":"P","Ᵽ":"P","Ꝑ":"P","Ꝙ":"Q","Ꝗ":"Q",Ŕ:"R",Ř:"R",Ŗ:"R",Ṙ:"R",Ṛ:"R",Ṝ:"R",Ȑ:"R",Ȓ:"R",Ṟ:"R","Ɍ":"R","Ɽ":"R","Ꜿ":"C",Ǝ:"E",Ś:"S",Ṥ:"S",Š:"S",Ṧ:"S",Ş:"S",Ŝ:"S",Ș:"S",Ṡ:"S",Ṣ:"S",Ṩ:"S","ẞ":"SS",Ť:"T",Ţ:"T",Ṱ:"T",Ț:"T","Ⱦ":"T",Ṫ:"T",Ṭ:"T",Ƭ:"T",Ṯ:"T",Ʈ:"T",Ŧ:"T","Ɐ":"A","Ꞁ":"L",Ɯ:"M","Ʌ":"V","Ꜩ":"TZ",Ú:"U",Ŭ:"U",Ǔ:"U",Û:"U",Ṷ:"U",Ü:"U",Ǘ:"U",Ǚ:"U",Ǜ:"U",Ǖ:"U",Ṳ:"U",Ụ:"U",Ű:"U",Ȕ:"U",Ù:"U",Ủ:"U",Ư:"U",Ứ:"U",Ự:"U",Ừ:"U",Ử:"U",Ữ:"U",Ȗ:"U",Ū:"U",Ṻ:"U",Ų:"U",Ů:"U",Ũ:"U",Ṹ:"U",Ṵ:"U","Ꝟ":"V",Ṿ:"V",Ʋ:"V",Ṽ:"V","Ꝡ":"VY",Ẃ:"W",Ŵ:"W",Ẅ:"W",Ẇ:"W",Ẉ:"W",Ẁ:"W","Ⱳ":"W",Ẍ:"X",Ẋ:"X",Ý:"Y",Ŷ:"Y",Ÿ:"Y",Ẏ:"Y",Ỵ:"Y",Ỳ:"Y",Ƴ:"Y",Ỷ:"Y","Ỿ":"Y",Ȳ:"Y","Ɏ":"Y",Ỹ:"Y",Ź:"Z",Ž:"Z",Ẑ:"Z","Ⱬ":"Z",Ż:"Z",Ẓ:"Z",Ȥ:"Z",Ẕ:"Z",Ƶ:"Z",IJ:"IJ",Œ:"OE","ᴀ":"A","ᴁ":"AE",ʙ:"B","ᴃ":"B","ᴄ":"C","ᴅ":"D","ᴇ":"E","ꜰ":"F",ɢ:"G",ʛ:"G",ʜ:"H",ɪ:"I",ʁ:"R","ᴊ":"J","ᴋ":"K",ʟ:"L","ᴌ":"L","ᴍ":"M",ɴ:"N","ᴏ":"O",ɶ:"OE","ᴐ":"O","ᴕ":"OU","ᴘ":"P",ʀ:"R","ᴎ":"N","ᴙ":"R","ꜱ":"S","ᴛ":"T","ⱻ":"E","ᴚ":"R","ᴜ":"U","ᴠ":"V","ᴡ":"W",ʏ:"Y","ᴢ":"Z",á:"a",ă:"a",ắ:"a",ặ:"a",ằ:"a",ẳ:"a",ẵ:"a",ǎ:"a",â:"a",ấ:"a",ậ:"a",ầ:"a",ẩ:"a",ẫ:"a",ä:"a",ǟ:"a",ȧ:"a",ǡ:"a",ạ:"a",ȁ:"a",à:"a",ả:"a",ȃ:"a",ā:"a",ą:"a","ᶏ":"a",ẚ:"a",å:"a",ǻ:"a",ḁ:"a","ⱥ":"a",ã:"a","ꜳ":"aa",æ:"ae",ǽ:"ae",ǣ:"ae","ꜵ":"ao","ꜷ":"au","ꜹ":"av","ꜻ":"av","ꜽ":"ay",ḃ:"b",ḅ:"b",ɓ:"b",ḇ:"b","ᵬ":"b","ᶀ":"b",ƀ:"b",ƃ:"b",ɵ:"o",ć:"c",č:"c",ç:"c",ḉ:"c",ĉ:"c",ɕ:"c",ċ:"c",ƈ:"c","ȼ":"c",ď:"d",ḑ:"d",ḓ:"d","ȡ":"d",ḋ:"d",ḍ:"d",ɗ:"d","ᶑ":"d",ḏ:"d","ᵭ":"d","ᶁ":"d",đ:"d",ɖ:"d",ƌ:"d",ı:"i","ȷ":"j",ɟ:"j",ʄ:"j",dz:"dz",dž:"dz",é:"e",ĕ:"e",ě:"e",ȩ:"e",ḝ:"e",ê:"e",ế:"e",ệ:"e",ề:"e",ể:"e",ễ:"e",ḙ:"e",ë:"e",ė:"e",ẹ:"e",ȅ:"e",è:"e",ẻ:"e",ȇ:"e",ē:"e",ḗ:"e",ḕ:"e","ⱸ":"e",ę:"e","ᶒ":"e","ɇ":"e",ẽ:"e",ḛ:"e","ꝫ":"et",ḟ:"f",ƒ:"f","ᵮ":"f","ᶂ":"f",ǵ:"g",ğ:"g",ǧ:"g",ģ:"g",ĝ:"g",ġ:"g",ɠ:"g",ḡ:"g","ᶃ":"g",ǥ:"g",ḫ:"h",ȟ:"h",ḩ:"h",ĥ:"h","ⱨ":"h",ḧ:"h",ḣ:"h",ḥ:"h",ɦ:"h",ẖ:"h",ħ:"h",ƕ:"hv",í:"i",ĭ:"i",ǐ:"i",î:"i",ï:"i",ḯ:"i",ị:"i",ȉ:"i",ì:"i",ỉ:"i",ȋ:"i",ī:"i",į:"i","ᶖ":"i",ɨ:"i",ĩ:"i",ḭ:"i","ꝺ":"d","ꝼ":"f","ᵹ":"g","ꞃ":"r","ꞅ":"s","ꞇ":"t","ꝭ":"is",ǰ:"j",ĵ:"j",ʝ:"j","ɉ":"j",ḱ:"k",ǩ:"k",ķ:"k","ⱪ":"k","ꝃ":"k",ḳ:"k",ƙ:"k",ḵ:"k","ᶄ":"k","ꝁ":"k","ꝅ":"k",ĺ:"l",ƚ:"l",ɬ:"l",ľ:"l",ļ:"l",ḽ:"l","ȴ":"l",ḷ:"l",ḹ:"l","ⱡ":"l","ꝉ":"l",ḻ:"l",ŀ:"l",ɫ:"l","ᶅ":"l",ɭ:"l",ł:"l",lj:"lj",ſ:"s","ẜ":"s",ẛ:"s","ẝ":"s",ḿ:"m",ṁ:"m",ṃ:"m",ɱ:"m","ᵯ":"m","ᶆ":"m",ń:"n",ň:"n",ņ:"n",ṋ:"n","ȵ":"n",ṅ:"n",ṇ:"n",ǹ:"n",ɲ:"n",ṉ:"n",ƞ:"n","ᵰ":"n","ᶇ":"n",ɳ:"n",ñ:"n",nj:"nj",ó:"o",ŏ:"o",ǒ:"o",ô:"o",ố:"o",ộ:"o",ồ:"o",ổ:"o",ỗ:"o",ö:"o",ȫ:"o",ȯ:"o",ȱ:"o",ọ:"o",ő:"o",ȍ:"o",ò:"o",ỏ:"o",ơ:"o",ớ:"o",ợ:"o",ờ:"o",ở:"o",ỡ:"o",ȏ:"o","ꝋ":"o","ꝍ":"o","ⱺ":"o",ō:"o",ṓ:"o",ṑ:"o",ǫ:"o",ǭ:"o",ø:"o",ǿ:"o",õ:"o",ṍ:"o",ṏ:"o",ȭ:"o",ƣ:"oi","ꝏ":"oo",ɛ:"e","ᶓ":"e",ɔ:"o","ᶗ":"o",ȣ:"ou",ṕ:"p",ṗ:"p","ꝓ":"p",ƥ:"p","ᵱ":"p","ᶈ":"p","ꝕ":"p","ᵽ":"p","ꝑ":"p","ꝙ":"q",ʠ:"q","ɋ":"q","ꝗ":"q",ŕ:"r",ř:"r",ŗ:"r",ṙ:"r",ṛ:"r",ṝ:"r",ȑ:"r",ɾ:"r","ᵳ":"r",ȓ:"r",ṟ:"r",ɼ:"r","ᵲ":"r","ᶉ":"r","ɍ":"r",ɽ:"r","ↄ":"c","ꜿ":"c",ɘ:"e",ɿ:"r",ś:"s",ṥ:"s",š:"s",ṧ:"s",ş:"s",ŝ:"s",ș:"s",ṡ:"s",ṣ:"s",ṩ:"s",ʂ:"s","ᵴ":"s","ᶊ":"s","ȿ":"s",ɡ:"g",ß:"ss","ᴑ":"o","ᴓ":"o","ᴝ":"u",ť:"t",ţ:"t",ṱ:"t",ț:"t","ȶ":"t",ẗ:"t","ⱦ":"t",ṫ:"t",ṭ:"t",ƭ:"t",ṯ:"t","ᵵ":"t",ƫ:"t",ʈ:"t",ŧ:"t","ᵺ":"th",ɐ:"a","ᴂ":"ae",ǝ:"e","ᵷ":"g",ɥ:"h","ʮ":"h","ʯ":"h","ᴉ":"i",ʞ:"k","ꞁ":"l",ɯ:"m",ɰ:"m","ᴔ":"oe",ɹ:"r",ɻ:"r",ɺ:"r","ⱹ":"r",ʇ:"t",ʌ:"v",ʍ:"w",ʎ:"y","ꜩ":"tz",ú:"u",ŭ:"u",ǔ:"u",û:"u",ṷ:"u",ü:"u",ǘ:"u",ǚ:"u",ǜ:"u",ǖ:"u",ṳ:"u",ụ:"u",ű:"u",ȕ:"u",ù:"u",ủ:"u",ư:"u",ứ:"u",ự:"u",ừ:"u",ử:"u",ữ:"u",ȗ:"u",ū:"u",ṻ:"u",ų:"u","ᶙ":"u",ů:"u",ũ:"u",ṹ:"u",ṵ:"u","ᵫ":"ue","ꝸ":"um","ⱴ":"v","ꝟ":"v",ṿ:"v",ʋ:"v","ᶌ":"v","ⱱ":"v",ṽ:"v","ꝡ":"vy",ẃ:"w",ŵ:"w",ẅ:"w",ẇ:"w",ẉ:"w",ẁ:"w","ⱳ":"w",ẘ:"w",ẍ:"x",ẋ:"x","ᶍ":"x",ý:"y",ŷ:"y",ÿ:"y",ẏ:"y",ỵ:"y",ỳ:"y",ƴ:"y",ỷ:"y","ỿ":"y",ȳ:"y",ẙ:"y","ɏ":"y",ỹ:"y",ź:"z",ž:"z",ẑ:"z",ʑ:"z","ⱬ":"z",ż:"z",ẓ:"z",ȥ:"z",ẕ:"z","ᵶ":"z","ᶎ":"z",ʐ:"z",ƶ:"z","ɀ":"z",ff:"ff",ffi:"ffi",ffl:"ffl",fi:"fi",fl:"fl",ij:"ij",œ:"oe",st:"st","ₐ":"a","ₑ":"e","ᵢ":"i","ⱼ":"j","ₒ":"o","ᵣ":"r","ᵤ":"u","ᵥ":"v","ₓ":"x",Ё:"YO",Й:"I",Ц:"TS",У:"U",К:"K",Е:"E",Н:"N",Г:"G",Ш:"SH",Щ:"SCH",З:"Z",Х:"H",Ъ:"",ё:"yo",й:"i",ц:"ts",у:"u",к:"k",е:"e",н:"n",г:"g",ш:"sh",щ:"sch",з:"z",х:"h",ъ:"",Ф:"F",Ы:"I",В:"V",А:"A",П:"P",Р:"R",О:"O",Л:"L",Д:"D",Ж:"ZH",Э:"E",ф:"f",ы:"i",в:"v",а:"a",п:"p",р:"r",о:"o",л:"l",д:"d",ж:"zh",э:"e",Я:"Ya",Ч:"CH",С:"S",М:"M",И:"I",Т:"T",Ь:"",Б:"B",Ю:"YU",я:"ya",ч:"ch",с:"s",м:"m",и:"i",т:"t",ь:"",б:"b",ю:"yu"},O3=/[`~!@#$%^&*()\-_=+\[\]\\|{}'";:\/?.>,<]+/g,U3=/^\s+|\s$/g,H3={й:"q",ц:"w",у:"e",к:"r",е:"t",н:"y",г:"u",ш:"i",щ:"o",з:"p",х:"[",ъ:"]",ф:"a",ы:"s",в:"d",а:"f",п:"g",р:"h",о:"j",л:"k",д:"l",ж:";",э:"'",я:"z",ч:"x",с:"c",м:"v",и:"b",т:"n",ь:"m",б:",",ю:".",".":"/"};function oI(a){return a.replace(O3,"").replace(U3,"")}function G3(a){return a.toLowerCase().replace(/[\wа-я]/g,e=>H3[e]??e)}function V3(a){return a.replace(/[^A-Za-z0-9]/g,e=>N3[e]??e)}function z3(a="",e={}){const t=e.includeTag&&a.charAt(0)==="%",s=a;return e.clearBadChars&&(a=oI(a)),e.latinize&&(a=V3(a)),e.ignoreCase&&(a=a.toLowerCase()),t&&(a="%"+a),e.latinize&&(a+=""+G3(s)),a}I.addEventListener("document_downloading",a=>{Array.from(document.querySelectorAll(`.document[data-doc-id="${a}"]`)).forEach(t=>{t.querySelector(".preloader-container.manual")&&Xs(t)})});async function rd({message:a,withTime:e,fontWeight:t,voiceAsMusic:s,showSender:i,searchContext:n,loadPromises:r,autoDownloadSize:o,lazyLoadQueue:l,sizeType:c,managers:d=I.managers,cacheContext:u,fontSize:h,getSize:p,canTranscribeVoice:m,isOut:g,uploadingFileName:f,shouldWrapAsVoice:v,customAudioToTextButton:y,globalMedia:w}){t??(t=500),c??(c=""),h??(h=16);const b=o===0,S=a.media.document||a.media.webpage.document;if(f??(f=a?.uploadingFileName?.[0]),S.type==="audio"||S.type==="voice"||S.type==="round"){const ae=new Pb;return ae.withTime=e,ae.message=a,ae.noAutoDownload=b,ae.lazyLoadQueue=l,ae.loadPromises=r,ae.uploadingFileName=f,ae.shouldWrapAsVoice=v,ae.customAudioToTextButton=y,ae.audio=w,w&&(ae.dataset.toBeSkipped="1"),m&&S.type==="voice"&&(ae.transcriptionState=0),ae.getSize=p,s&&(ae.voiceAsMusic=s),n&&(ae.searchContext=n),i&&(ae.showSender=i),ae.dataset.fontWeight=""+t,ae.dataset.fontSize=""+h,ae.dataset.sizeType=c,g&&ae.classList.add("is-out"),await ae.render(),ae}const _=S.file_name?S.file_name.split("."):"";let M="";M=_.length>1&&Array.isArray(_)?oI(_.pop().split(" ",1)[0].toLowerCase()):"file";const C=document.createElement("div");C.classList.add("document",`ext-${M}`),C.dataset.docId=""+S.id,C.doc=S;const L=document.createElement("div");L.classList.add("document-ico");let E;const x=!!u;u=x?u:Ae.getCacheContext(S);let B=!1;if(S.thumbs?.length||a.pFlags.is_outgoing&&u.url&&S.type==="photo"){C.classList.add("document-with-thumb"),B=!0;const ae=[];if(a.pFlags.is_outgoing&&["photo","video"].includes(S.type)&&u.url)L.innerHTML=`<img src="${u.url}">`,ae.push(L.firstElementChild);else{performance.now();const ke=await Bi({photo:S,message:null,container:L,boxWidth:54,boxHeight:54,loadPromises:r,withoutPreloader:!0,lazyLoadQueue:l,size:ha(S,54,54,!0),managers:d});L.style.width=L.style.height="",ke.images.thumb&&ae.push(ke.images.thumb),ke.images.full&&ae.push(ke.images.full)}ae.forEach(ke=>ke.classList.add("document-thumb"))}else E=document.createElement("span"),E.classList.add("document-ico-text"),E.innerText=M,L.append(E);const N=S.file_name?Oo(S.file_name):"Unknown.file";document.createElement("div").classList.add("document-description");const O=document.createElement("span"),$=ur(S.size),H=" / ",D=[$];if(e&&D.push(gs(a.date)),i&&D.push(await Sm(a)),!e&&!i){const ae=document.createElement("span"),ke=ur(S.size);ae.append(H,ke),ae.style.visibility="hidden",D.push(ae)}C.innerHTML=`
- ${u.downloaded&&!f||!a.mid||!B?"":'<div class="document-download"></div>'}
- <div class="document-name"></div>
- <div class="document-size"></div>
- `;const U=C.querySelector(".document-name"),j=new _b;j.dataset.fontWeight=""+t,j.dataset.fontSize=""+h,j.dataset.sizeType=c,j.getSize=p,j.textContent=N,a.mid||C.classList.add("downloaded"),U.append(j),i&&U.append(Ib(a));const q=C.querySelector(".document-size");if(O.append(...Kl(D," · ")),q.append(O),C.prepend(L),!f&&a.pFlags.is_outgoing&&!a.mid)return C;const W=S.size<=yv;let ee,z=null;const Z=()=>{if(C.classList.remove("downloading"),S.size>yv&&!f){z.setManual(),z.attach(ee),z.preloader.classList.add("manual"),z.setDownloadFunction(ie);return}if(W&&C.classList.add("downloaded"),ee){if(ee!==L){const ae=ee;setTimeout(()=>{ae.remove()},200)}ee=null}z&&(z=null)},de=ae=>{C.classList.add("downloading");const ke=document.createElement("span"),re=ur(S.size);ke.style.position="absolute",ke.style.left="0",ae.then(Z,as).finally(()=>{O.style.visibility="",ke.remove()});const ce=Ve=>ur(Ve);let Ie=ce(0);O.style.visibility="hidden",ke.append(Ie,H,re),O.parentElement.append(ke),ae.addNotifyListener(Ve=>{const fe=ce(Ve.done);Ie.replaceWith(fe),Ie=fe})},ie=ae=>{const ke=!ae||ae.isTrusted,re=C.doc;let ce;const Ie=Ce.chat.bubbles?Ce.chat.bubbles.lazyLoadQueue.queueId:void 0;ke?(re.type,Wr.has(re.mime_type)&&re.thumbs?.length&&W?ce=fs.downloadMediaURL({media:re,queueId:Ie}):(ce=fs.downloadToDisc({media:re,queueId:Ie}),re.mime_type==="image/svg+xml"&&Rt({descriptionLangKey:"Chat.File.QuickLook.Svg",button:{langKey:"OK",isCancel:!0}}))):ce=fs.downloadToDisc({media:re,queueId:Ie},!0),ce.catch(()=>{C.classList.remove("downloading")}),ee&&(z.attach(ee,!0,ce),de(ce))},{fileName:oe}=kL({media:S,downloadId:"1"});if(await d.apiFileManager.isDownloading(oe)){ee=C.querySelector(".document-download")||L;const ae=fs.downloadToDisc({media:S},!0);z=new Kn,z.attach(ee,!1,ae),z.setDownloadFunction(ie),de(ae)}else if(!u.downloaded||f)if(ee=C.querySelector(".document-download")||L,z=new Kn({isUpload:!!f}),!f)z.construct(),z.setManual(),z.attach(ee),z.setDownloadFunction(ie),o!==void 0&&o>=S.size&&Xs(z.preloader);else{const ae=fs.getUpload(f);z.attachPromise(ae),z.attach(ee),de(ae)}return J(C,ae=>{ne(ae.target,"time")||(z?z.onClick(ae):ie(ae))}),C}function yh(a){if(!a)return;const e=a.media?.document;return["voice","audio","video"].includes(e?.type)&&e.duration||void 0}async function W3({albumMustBeRenderedFull:a,message:e,bubble:t,messageDiv:s,chat:i,loadPromises:n,autoDownloadSize:r,lazyLoadQueue:o,searchContext:l,useSearch:c,sizeType:d,managers:u,fontWeight:h,fontSize:p,richTextFragment:m,richTextOptions:g,canTranscribeVoice:f,translatableParams:v,factCheckBox:y,isOut:w}){let b;const{peerId:S}=e,_=a?await i.getMidsByMid(e.peerId,e.mid):[e.mid],M=_.map(async(L,E,x)=>{const R=i.getMessageByPeer(S,L),B=await rd({message:R,loadPromises:n,autoDownloadSize:r,lazyLoadQueue:o,searchContext:l,sizeType:d,managers:u,fontWeight:h,fontSize:p,canTranscribeVoice:f,isOut:w}),N=document.createElement("div");N.classList.add("document-container"),N.dataset.mid=""+L,N.dataset.peerId=""+R.peerId;const G=document.createElement("div");G.classList.add("document-wrapper");const O=E===0,$=E===x.length-1;O&&N.classList.add("is-first"),$&&N.classList.add("is-last");let H;if((R.message||$&&y)&&(H=document.createElement("div"),H.classList.add("document-message")),R.message){let D=m;D||(v?D=Nu({...v,message:R,richTextOptions:{...v.richTextOptions,maxMediaTimestamp:yh(R)}}):D=jt(R.message,{...g,entities:R.totalEntities,maxMediaTimestamp:yh(R)})),Qt(H,D)}if(y&&H&&$&&H.append(y),_.length>1){const D=document.createElement("div");D.classList.add("document-selection"),N.append(D),N.classList.add("grouped-item"),E===0&&(b=G)}return G.append(...[B,H].filter(Boolean)),N.append(G),N}),C=await Promise.all(M);return s.append(...C),_.length>1&&t.classList.add("is-multiple-documents","is-grouped"),b}function K3({message:a,managers:e=I.managers,middleware:t,translatableParams:s,richTextOptions:i}){const n=new $l;return n.message=a,n.managers=e,n.translatableParams=s,n.richTextOptions=i,n.setAttribute("peer-id",""+a.peerId),n.setAttribute("poll-id",""+a.media.poll.id),n.setAttribute("message-id",""+a.mid),n.middlewareHelper=t.create(),n.render(),n}const j3="֑-߿יִ-﷽ﹰ-ﻼ",lI=new RegExp("["+j3+"]");function q3(a,e){return lI.test(a)}function Y3(a){return lI.test(a?.slice(-1))}async function cI(a){const{peerId:e,threadId:t,lastMsgId:s}=a;let i=Promise.resolve(),n;if(a.noLink){n=document.createElement("span"),n.dataset.savedFrom=`${a.peerId}_${a.lastMsgId}`,n.classList.add("has-avatar");const r=vs({peerId:a.peerId,isDialog:!0,middleware:a.wrapOptions.middleware,size:30});r.node.classList.add("topic-name-button-avatar"),n.append(r.node,Be("next","topic-name-button-arrow")),i=r.readyThumbPromise,a.withIcons=!1}else n=YC("t.me/c/"+e.toChatId()+(t?"/"+An(t):"")+(s?"/"+An(s):""));return n.classList.add("topic-name","topic-name-button"),n.append(await qe(a)),{cached:!0,element:n,loadPromise:i}}const Q3=new Set(["showMaskedAlert","execBotCommand"]);function ei(a){window[(a.protocol?a.protocol+"_":"")+a.name]=(e,t)=>{!a.noCancelEvent&&_e(null);let s=e.href;if(!s)return;let i,n;const r=new URL(s),o=r.host.match(/(.+?)\.t(?:elegram)?\.me/);o&&!TL.has(o[1])&&(r.pathname=o[1]+(r.pathname==="/"?"":r.pathname),s=r.toString()),a.noPathnameParams||(i=new URL(s).pathname.split("/").slice(1)),a.noUriParams||(n=QC(s));const l=e.href!==Bo(e.textContent).url&&e.getAttribute("safe")===null,c=a.callback({pathnameParams:i,uriParams:n},e,l);if(!t?.isTrusted)return c}}function xo(a,e,t){const s=document.createElement(a);return s.className=`badge badge-${e} badge-${t} is-badge-empty`,s}const X3=Y("<div class=popup-boost-avatars-avatar-container>"),Z3=Y("<div><div class=popup-boost-avatars-left></div><div class=popup-boost-avatars-right>"),J3=Y("<div class=popup-boost-title>"),eR=Y("<span>"),Hd="popup-boost";class tR extends mi{constructor(e,t,s){super("popup-forward popup-chatlist-invite "+Hd,{closable:!0,overlayClosable:!0,body:!0,description:!0,footer:!0,withConfirm:!0}),this.peerId=e,this.myBoosts=t,this.appConfig=s,this.btnClose.remove(),this.header.remove(),Ft(i=>{this.middlewareHelper.get().onDestroy(i),this.construct()})}async construct(){const[e,t]=K([]),[s,i]=K(0),n=new Map,r=()=>{const h=y=>{const w=Ot(()=>jn({peerId:y.peerId,size:60}));return w.node.classList.add(`${Hd}-avatars-avatar`),w.node.append(),w},p=h({peerId:this.peerId,right:!0}),m=V(y=>{const w=new Map;y?.forEach((S,_)=>{w.set(S,_)});const b=eo(e().map(S=>it(S.peer)).reverse());return b.sort((S,_)=>(w.get(S)??0)-(w.get(_)??0)),b}),g=26,f=T(Cs,{get each(){return m()},children:(y,w)=>{const{element:b}=h({peerId:y}),S=V(()=>m().length-w()-1);return(()=>{const _=X3();return k(_,b,null),k(_,T(hs,{icon:"boostcircle",get class(){return Ge(`${Hd}-avatars-avatar-icon`,!S()&&"is-visible")}}),null),Me(M=>Ii(_,`--offset: ${S()*-g}px`,M)),_})()}}),v=Lb(yd(()=>f).toArray,{exitMethod:"keep-index",onChange:({added:y,removed:w,finishRemoved:b})=>{const S={duration:wt.isAvailable("animations")?200:0,easing:"ease-in-out"},_=[{transform:"translateX(var(--offset)) scale(0)"},{transform:"translateX(var(--offset)) scale(1)"}];queueMicrotask(()=>{for(const L of y)L.animate(_,S);const M=_.slice().reverse(),C=[];for(const L of w){const E=L.animate(M,S);C.push(E.finished)}Promise.all(C).then(()=>b(w))})}});return(()=>{const y=Z3(),w=y.firstChild,b=w.nextSibling;return k(w,v),k(y,T(hs,{icon:"next",class:`${Hd}-avatars-arrow`}),b),k(b,()=>p.element),Me(S=>{const _=Ge(`${Hd}-avatars`,m().length&&"has-left"),M=`transform: translateX(${Math.max(0,m().length-1)*(g/2)}px)`;return _!==S._v$&&be(y,S._v$=_),S._v$2=Ii(y,M,S._v$2),S},{_v$:void 0,_v$2:void 0}),y})()};this.description.before(r(),(()=>{const h=J3();return k(h,()=>P("Boost.Replace")),h})());const o=new Map;this.selector=new wn({middleware:this.middlewareHelper.get(),appendTo:this.body,onChange:h=>{t(this.selector.getSelected().map(p=>n.get(p))),i(h)},onFirstRender:()=>{this.show()},multiSelect:!0,noSearch:!0,sectionNameLangPackKey:"BoostingRemoveBoostFrom",avatarSize:"abitbigger",managers:this.managers,peerType:[],getSubtitleForElement:h=>{const p=n.get(h);return Ft(m=>{this.middlewareHelper.get().onDestroy(()=>{m(),clearInterval(w)});const g=P("BoostsExpiration",[1,gs(p.expires,void 0,!0)]),[f,v]=K(Qs(!0)),y=V(b=>{const S=Math.max(0,(p.cooldown_until_date||0)-f());return!S&&b!==void 0&&clearInterval(w),S});o.set(h,y);const w=y()?window.setInterval(()=>{v(Qs(!0))},1e3):void 0;return(()=>{const b=eR();return k(b,(()=>{const S=V(()=>!!y());return()=>S()?P("BoostingAvailableIn",[w_(y())]):g})()),b})()})},getPeerIdFromKey:h=>h.split("_")[1].toPeerId(),processElementAfter:(h,p)=>{const m=o.get(h);Ft(g=>{this.middlewareHelper.get().onDestroy(g),le(()=>{p.container.classList.toggle("is-unavailable",!!m())})})}});const l=this.selector.add.bind(this.selector);this.selector.add=(...h)=>this.selector.getElementByPeerId(h[0].key).classList.contains("is-unavailable")?($e({langPackKey:"Boost.Reassign.Wait",langPackArguments:[P("MoreBoosts",[this.appConfig.boosts_per_sent_gift??1]),xi(()=>{no(),this.hideWithCallback(()=>{Ce.initGifting()})})]}),!1):l(...h);const c=this.myBoosts.my_boosts.map(h=>{const p=it(h.peer);if(p===this.peerId)return;const m="S"+h.slot+"_"+p;return n.set(m,h),m}).filter(Boolean);this.scrollable=this.selector.scrollable,this.attachScrollableListeners(),this.selector.renderResultsFunc(c);let d=!1;const u=async h=>{_e(h),d=!0;const p=os(this.btnConfirm,!0);try{const m=e().map(f=>f.slot),g=eo(e().map(f=>it(f.peer)));await this.managers.appBoostsManager.applyBoost(this.peerId,m),this.hide(),$e({langPackKey:"BoostingReassignedFromPlural",langPackArguments:[m.length,P("BoostingFromOtherChannel",[g.length])]})}catch(m){console.error("error replacing boosts",m),p()}d=!1};J(this.btnConfirm,u,{listenerSetter:this.listenerSetter}),K1({button:this.btnConfirm,langKey:()=>"Boost.Reassign",langArgs:()=>[s()||1],boosts:s}),le(()=>{d||os(this.btnConfirm,!s())}),this.description.append(P("Boost.Reassign.Description",[await qe({peerId:this.peerId}),P("Boost.GiftPremium",[xi(()=>{this.hideWithCallback(()=>{Ce.initGifting()})})]),P("Boost.Additional",[this.appConfig.boosts_per_sent_gift??1])])),this.footer.append(this.btnConfirm),this.body.after(this.footer)}}const Ip="popup-boost";class sR extends mi{constructor(e){super(Ip,{closable:!0,overlayClosable:!0,description:!0}),this.peerId=e,this.btnClose.remove(),this.header.remove(),this.construct()}async construct(){let[e,t,s,i]=await Promise.all([this.managers.appBoostsManager.getBoostsStatus(this.peerId),this.managers.appBoostsManager.getMyBoosts(),this.managers.apiManager.getAppConfig(),Ae.isPremiumPurchaseBlocked()]);const n=wn.renderEntity({key:this.peerId,middleware:this.middlewareHelper.get(),avatarSize:30});n.element.classList.add(`${Ip}-entity`,"selector-user-alone","hover-primary");const r=xo("span",20,"premium");r.classList.add(`${Ip}-entity-badge`),n.element.append(r),J(n.element,()=>{this.hideWithCallback(()=>{Ce.setInnerPeer({peerId:this.peerId})})},{listenerSetter:this.listenerSetter});const o=document.createElement("div");o.classList.add(`${Ip}-title`);const l=await qe({peerId:this.peerId});await n.avatar.readyThumbPromise;let c,d,u,h,p=!1;const m=C=>{e=C,c=e.level>0||e.next_level_boosts===e.boosts,d=e.next_level_boosts-e.boosts,u=e.next_level_boosts===void 0,h=!!e.pFlags.my_boost},g=()=>{h?o.replaceChildren(P("YouBoostedChannel")):u?o.replaceChildren(P("BoostsMaxLevelReached")):c?o.replaceChildren(P("HelpUpgradeChannel")):o.replaceChildren(P("Boost.EnableStoriesFor"))},f=()=>{p&&e.level===0&&c?this.description.replaceChildren(P("Boost.DescriptionJustReachedLevel1")):u||p&&e.level>0?this.description.replaceChildren(P("Boost.DescriptionJustReachedLevel",[e.level,P("Boost.StoriesCount",[e.level+1])])):c?this.description.replaceChildren(P("ChannelNeedBoostsDescriptionForNewFeatures",[l,P("MoreBoosts",[d])])):this.description.replaceChildren(P("ChannelNeedBoostsDescriptionLevel1",[P("MoreBoosts",[d])]))},v=new xg({progress:!0,hint:{icon:"boost",noStartEnd:!0}});this.description.before(v.container,o,n.element);const y=()=>t.my_boosts.filter(C=>it(C.peer)===this.peerId),w=()=>{const C=u?1:(e.boosts-e.current_level_boosts)/(e.next_level_boosts-e.current_level_boosts);v.setProgress(C,""+e.boosts,{from1:P("BoostsLevel",[e.level]),to1:P("BoostsLevel",[e.level+1]),from2:P("BoostsLevel",[e.level]),to2:P("BoostsLevel",[e.level+1])}),g(),f(),b(),r.textContent=`x${y().length}`,r.classList.toggle("is-badge-empty",!h)},b=()=>{this.setButtons(Go([u||y().length===t.my_boosts.length&&i?{langKey:"OK",isCancel:!0}:{langKey:"BoostChannel",iconLeft:"boost",callback:M}]))},S=C=>{if(C==="PREMIUM_ACCOUNT_REQUIRED")_();else if(C.includes("FLOOD_WAIT")){const L=+C.split("_")[2];Rt({titleLangKey:"CantBoostTooOften",descriptionLangKey:"CantBoostTooOftenDescription",descriptionLangArgs:[wd(Yl(L,2),!1)],button:{langKey:"OK",isCancel:!0}})}else C==="PREMIUM_GIFTED_NOT_ALLOWED"&&Rt({titleLangKey:"CantBoostWithGiftedPremium",descriptionLangKey:"CantBoostWithGiftedPremiumDescription",button:{langKey:"OK",isCancel:!0}})},_=()=>{Rt({titleLangKey:"PremiumNeeded",descriptionLangKey:"PremiumNeededForBoosting",button:{langKey:"Yes"}}).then(()=>{rs.show()})},M=async C=>{_e(C);try{const L=y(),E=t.my_boosts.find(R=>!R.peer);let x;if(!I.premium)x="PREMIUM_ACCOUNT_REQUIRED";else if(L.length===t.my_boosts.length){await Rt({titleLangKey:"BoostingMoreBoostsNeeded",descriptionLangKey:"Boost.GetMoreBoosts",descriptionLangArgs:[await qe({peerId:this.peerId}),s.boosts_per_sent_gift??1],button:{langKey:"GiftPremium"}}),this.hideWithCallback(()=>{Ce.initGifting()});return}else if(!E){this.hide(),ue.createPopup(tR,this.peerId,t,s);return}if(x)throw{type:x};await this.managers.appBoostsManager.applyBoost(this.peerId,[E.slot]),[t,e]=await Promise.all([this.managers.appBoostsManager.getMyBoosts(),this.managers.appBoostsManager.getBoostsStatus(this.peerId)]),p=!0,m(e),w()}catch(L){S(L.type)}return!1};m(e),w(),v._setHintActive(),this.show()}}var dI={exports:{}};(function(a){var e=function(t){var s=1e7,i=7,n=9007199254740992,r=m(n),o="0123456789abcdefghijklmnopqrstuvwxyz",l=typeof BigInt=="function";function c(A,F,Q,X){return typeof A>"u"?c[0]:typeof F<"u"?+F==10&&!Q?ve(A):Xe(A,F,Q,X):ve(A)}function d(A,F){this.value=A,this.sign=F,this.isSmall=!1}d.prototype=Object.create(c.prototype);function u(A){this.value=A,this.sign=A<0,this.isSmall=!0}u.prototype=Object.create(c.prototype);function h(A){this.value=A}h.prototype=Object.create(c.prototype);function p(A){return-n<A&&A<n}function m(A){return A<1e7?[A]:A<1e14?[A%1e7,Math.floor(A/1e7)]:[A%1e7,Math.floor(A/1e7)%1e7,Math.floor(A/1e14)]}function g(A){f(A);var F=A.length;if(F<4&&U(A,r)<0)switch(F){case 0:return 0;case 1:return A[0];case 2:return A[0]+A[1]*s;default:return A[0]+(A[1]+A[2]*s)*s}return A}function f(A){for(var F=A.length;A[--F]===0;);A.length=F+1}function v(A){for(var F=new Array(A),Q=-1;++Q<A;)F[Q]=0;return F}function y(A){return A>0?Math.floor(A):Math.ceil(A)}function w(A,F){var Q=A.length,X=F.length,ge=new Array(Q),he=0,Le=s,Se,xe;for(xe=0;xe<X;xe++)Se=A[xe]+F[xe]+he,he=Se>=Le?1:0,ge[xe]=Se-he*Le;for(;xe<Q;)Se=A[xe]+he,he=Se===Le?1:0,ge[xe++]=Se-he*Le;return he>0&&ge.push(he),ge}function b(A,F){return A.length>=F.length?w(A,F):w(F,A)}function S(A,F){var Q=A.length,X=new Array(Q),ge=s,he,Le;for(Le=0;Le<Q;Le++)he=A[Le]-ge+F,F=Math.floor(he/ge),X[Le]=he-F*ge,F+=1;for(;F>0;)X[Le++]=F%ge,F=Math.floor(F/ge);return X}d.prototype.add=function(A){var F=ve(A);if(this.sign!==F.sign)return this.subtract(F.negate());var Q=this.value,X=F.value;return F.isSmall?new d(S(Q,Math.abs(X)),this.sign):new d(b(Q,X),this.sign)},d.prototype.plus=d.prototype.add,u.prototype.add=function(A){var F=ve(A),Q=this.value;if(Q<0!==F.sign)return this.subtract(F.negate());var X=F.value;if(F.isSmall){if(p(Q+X))return new u(Q+X);X=m(Math.abs(X))}return new d(S(X,Math.abs(Q)),Q<0)},u.prototype.plus=u.prototype.add,h.prototype.add=function(A){return new h(this.value+ve(A).value)},h.prototype.plus=h.prototype.add;function _(A,F){var Q=A.length,X=F.length,ge=new Array(Q),he=0,Le=s,Se,xe;for(Se=0;Se<X;Se++)xe=A[Se]-he-F[Se],xe<0?(xe+=Le,he=1):he=0,ge[Se]=xe;for(Se=X;Se<Q;Se++){if(xe=A[Se]-he,xe<0)xe+=Le;else{ge[Se++]=xe;break}ge[Se]=xe}for(;Se<Q;Se++)ge[Se]=A[Se];return f(ge),ge}function M(A,F,Q){var X;return U(A,F)>=0?X=_(A,F):(X=_(F,A),Q=!Q),X=g(X),typeof X=="number"?(Q&&(X=-X),new u(X)):new d(X,Q)}function C(A,F,Q){var X=A.length,ge=new Array(X),he=-F,Le=s,Se,xe;for(Se=0;Se<X;Se++)xe=A[Se]+he,he=Math.floor(xe/Le),xe%=Le,ge[Se]=xe<0?xe+Le:xe;return ge=g(ge),typeof ge=="number"?(Q&&(ge=-ge),new u(ge)):new d(ge,Q)}d.prototype.subtract=function(A){var F=ve(A);if(this.sign!==F.sign)return this.add(F.negate());var Q=this.value,X=F.value;return F.isSmall?C(Q,Math.abs(X),this.sign):M(Q,X,this.sign)},d.prototype.minus=d.prototype.subtract,u.prototype.subtract=function(A){var F=ve(A),Q=this.value;if(Q<0!==F.sign)return this.add(F.negate());var X=F.value;return F.isSmall?new u(Q-X):C(X,Math.abs(Q),Q>=0)},u.prototype.minus=u.prototype.subtract,h.prototype.subtract=function(A){return new h(this.value-ve(A).value)},h.prototype.minus=h.prototype.subtract,d.prototype.negate=function(){return new d(this.value,!this.sign)},u.prototype.negate=function(){var A=this.sign,F=new u(-this.value);return F.sign=!A,F},h.prototype.negate=function(){return new h(-this.value)},d.prototype.abs=function(){return new d(this.value,!1)},u.prototype.abs=function(){return new u(Math.abs(this.value))},h.prototype.abs=function(){return new h(this.value>=0?this.value:-this.value)};function L(A,F){var Q=A.length,X=F.length,ge=Q+X,he=v(ge),Le=s,Se,xe,lt,mt,at;for(lt=0;lt<Q;++lt){mt=A[lt];for(var kt=0;kt<X;++kt)at=F[kt],Se=mt*at+he[lt+kt],xe=Math.floor(Se/Le),he[lt+kt]=Se-xe*Le,he[lt+kt+1]+=xe}return f(he),he}function E(A,F){var Q=A.length,X=new Array(Q),ge=s,he=0,Le,Se;for(Se=0;Se<Q;Se++)Le=A[Se]*F+he,he=Math.floor(Le/ge),X[Se]=Le-he*ge;for(;he>0;)X[Se++]=he%ge,he=Math.floor(he/ge);return X}function x(A,F){for(var Q=[];F-- >0;)Q.push(0);return Q.concat(A)}function R(A,F){var Q=Math.max(A.length,F.length);if(Q<=30)return L(A,F);Q=Math.ceil(Q/2);var X=A.slice(Q),ge=A.slice(0,Q),he=F.slice(Q),Le=F.slice(0,Q),Se=R(ge,Le),xe=R(X,he),lt=R(b(ge,X),b(Le,he)),mt=b(b(Se,x(_(_(lt,Se),xe),Q)),x(xe,2*Q));return f(mt),mt}function B(A,F){return-.012*A-.012*F+15e-6*A*F>0}d.prototype.multiply=function(A){var F=ve(A),Q=this.value,X=F.value,ge=this.sign!==F.sign,he;if(F.isSmall){if(X===0)return c[0];if(X===1)return this;if(X===-1)return this.negate();if(he=Math.abs(X),he<s)return new d(E(Q,he),ge);X=m(he)}return B(Q.length,X.length)?new d(R(Q,X),ge):new d(L(Q,X),ge)},d.prototype.times=d.prototype.multiply;function N(A,F,Q){return A<s?new d(E(F,A),Q):new d(L(F,m(A)),Q)}u.prototype._multiplyBySmall=function(A){return p(A.value*this.value)?new u(A.value*this.value):N(Math.abs(A.value),m(Math.abs(this.value)),this.sign!==A.sign)},d.prototype._multiplyBySmall=function(A){return A.value===0?c[0]:A.value===1?this:A.value===-1?this.negate():N(Math.abs(A.value),this.value,this.sign!==A.sign)},u.prototype.multiply=function(A){return ve(A)._multiplyBySmall(this)},u.prototype.times=u.prototype.multiply,h.prototype.multiply=function(A){return new h(this.value*ve(A).value)},h.prototype.times=h.prototype.multiply;function G(A){var F=A.length,Q=v(F+F),X=s,ge,he,Le,Se,xe;for(Le=0;Le<F;Le++){Se=A[Le],he=0-Se*Se;for(var lt=Le;lt<F;lt++)xe=A[lt],ge=2*(Se*xe)+Q[Le+lt]+he,he=Math.floor(ge/X),Q[Le+lt]=ge-he*X;Q[Le+F]=he}return f(Q),Q}d.prototype.square=function(){return new d(G(this.value),!1)},u.prototype.square=function(){var A=this.value*this.value;return p(A)?new u(A):new d(G(m(Math.abs(this.value))),!1)},h.prototype.square=function(A){return new h(this.value*this.value)};function O(A,F){var Q=A.length,X=F.length,ge=s,he=v(F.length),Le=F[X-1],Se=Math.ceil(ge/(2*Le)),xe=E(A,Se),lt=E(F,Se),mt,at,kt,Us,Ts,zs,et;for(xe.length<=Q&&xe.push(0),lt.push(0),Le=lt[X-1],at=Q-X;at>=0;at--){for(mt=ge-1,xe[at+X]!==Le&&(mt=Math.floor((xe[at+X]*ge+xe[at+X-1])/Le)),kt=0,Us=0,zs=lt.length,Ts=0;Ts<zs;Ts++)kt+=mt*lt[Ts],et=Math.floor(kt/ge),Us+=xe[at+Ts]-(kt-et*ge),kt=et,Us<0?(xe[at+Ts]=Us+ge,Us=-1):(xe[at+Ts]=Us,Us=0);for(;Us!==0;){for(mt-=1,kt=0,Ts=0;Ts<zs;Ts++)kt+=xe[at+Ts]-ge+lt[Ts],kt<0?(xe[at+Ts]=kt+ge,kt=0):(xe[at+Ts]=kt,kt=1);Us+=kt}he[at]=mt}return xe=H(xe,Se)[0],[g(he),g(xe)]}function $(A,F){for(var Q=A.length,X=F.length,ge=[],he=[],Le=s,Se,xe,lt,mt,at;Q;){if(he.unshift(A[--Q]),f(he),U(he,F)<0){ge.push(0);continue}xe=he.length,lt=he[xe-1]*Le+he[xe-2],mt=F[X-1]*Le+F[X-2],xe>X&&(lt=(lt+1)*Le),Se=Math.ceil(lt/mt);do{if(at=E(F,Se),U(at,he)<=0)break;Se--}while(Se);ge.push(Se),he=_(he,at)}return ge.reverse(),[g(ge),g(he)]}function H(A,F){var Q=A.length,X=v(Q),ge=s,he,Le,Se,xe;for(Se=0,he=Q-1;he>=0;--he)xe=Se*ge+A[he],Le=y(xe/F),Se=xe-Le*F,X[he]=Le|0;return[X,Se|0]}function D(A,F){var Q,X=ve(F);if(l)return[new h(A.value/X.value),new h(A.value%X.value)];var ge=A.value,he=X.value,Le;if(he===0)throw new Error("Cannot divide by zero");if(A.isSmall)return X.isSmall?[new u(y(ge/he)),new u(ge%he)]:[c[0],A];if(X.isSmall){if(he===1)return[A,c[0]];if(he==-1)return[A.negate(),c[0]];var Se=Math.abs(he);if(Se<s){Q=H(ge,Se),Le=g(Q[0]);var xe=Q[1];return A.sign&&(xe=-xe),typeof Le=="number"?(A.sign!==X.sign&&(Le=-Le),[new u(Le),new u(xe)]):[new d(Le,A.sign!==X.sign),new u(xe)]}he=m(Se)}var lt=U(ge,he);if(lt===-1)return[c[0],A];if(lt===0)return[c[A.sign===X.sign?1:-1],c[0]];ge.length+he.length<=200?Q=O(ge,he):Q=$(ge,he),Le=Q[0];var mt=A.sign!==X.sign,at=Q[1],kt=A.sign;return typeof Le=="number"?(mt&&(Le=-Le),Le=new u(Le)):Le=new d(Le,mt),typeof at=="number"?(kt&&(at=-at),at=new u(at)):at=new d(at,kt),[Le,at]}d.prototype.divmod=function(A){var F=D(this,A);return{quotient:F[0],remainder:F[1]}},h.prototype.divmod=u.prototype.divmod=d.prototype.divmod,d.prototype.divide=function(A){return D(this,A)[0]},h.prototype.over=h.prototype.divide=function(A){return new h(this.value/ve(A).value)},u.prototype.over=u.prototype.divide=d.prototype.over=d.prototype.divide,d.prototype.mod=function(A){return D(this,A)[1]},h.prototype.mod=h.prototype.remainder=function(A){return new h(this.value%ve(A).value)},u.prototype.remainder=u.prototype.mod=d.prototype.remainder=d.prototype.mod,d.prototype.pow=function(A){var F=ve(A),Q=this.value,X=F.value,ge,he,Le;if(X===0)return c[1];if(Q===0)return c[0];if(Q===1)return c[1];if(Q===-1)return F.isEven()?c[1]:c[-1];if(F.sign)return c[0];if(!F.isSmall)throw new Error("The exponent "+F.toString()+" is too large.");if(this.isSmall&&p(ge=Math.pow(Q,X)))return new u(y(ge));for(he=this,Le=c[1];X&!0&&(Le=Le.times(he),--X),X!==0;)X/=2,he=he.square();return Le},u.prototype.pow=d.prototype.pow,h.prototype.pow=function(A){var F=ve(A),Q=this.value,X=F.value,ge=BigInt(0),he=BigInt(1),Le=BigInt(2);if(X===ge)return c[1];if(Q===ge)return c[0];if(Q===he)return c[1];if(Q===BigInt(-1))return F.isEven()?c[1]:c[-1];if(F.isNegative())return new h(ge);for(var Se=this,xe=c[1];(X&he)===he&&(xe=xe.times(Se),--X),X!==ge;)X/=Le,Se=Se.square();return xe},d.prototype.modPow=function(A,F){if(A=ve(A),F=ve(F),F.isZero())throw new Error("Cannot take modPow with modulus 0");var Q=c[1],X=this.mod(F);for(A.isNegative()&&(A=A.multiply(c[-1]),X=X.modInv(F));A.isPositive();){if(X.isZero())return c[0];A.isOdd()&&(Q=Q.multiply(X).mod(F)),A=A.divide(2),X=X.square().mod(F)}return Q},h.prototype.modPow=u.prototype.modPow=d.prototype.modPow;function U(A,F){if(A.length!==F.length)return A.length>F.length?1:-1;for(var Q=A.length-1;Q>=0;Q--)if(A[Q]!==F[Q])return A[Q]>F[Q]?1:-1;return 0}d.prototype.compareAbs=function(A){var F=ve(A),Q=this.value,X=F.value;return F.isSmall?1:U(Q,X)},u.prototype.compareAbs=function(A){var F=ve(A),Q=Math.abs(this.value),X=F.value;return F.isSmall?(X=Math.abs(X),Q===X?0:Q>X?1:-1):-1},h.prototype.compareAbs=function(A){var F=this.value,Q=ve(A).value;return F=F>=0?F:-F,Q=Q>=0?Q:-Q,F===Q?0:F>Q?1:-1},d.prototype.compare=function(A){if(A===1/0)return-1;if(A===-1/0)return 1;var F=ve(A),Q=this.value,X=F.value;return this.sign!==F.sign?F.sign?1:-1:F.isSmall?this.sign?-1:1:U(Q,X)*(this.sign?-1:1)},d.prototype.compareTo=d.prototype.compare,u.prototype.compare=function(A){if(A===1/0)return-1;if(A===-1/0)return 1;var F=ve(A),Q=this.value,X=F.value;return F.isSmall?Q==X?0:Q>X?1:-1:Q<0!==F.sign?Q<0?-1:1:Q<0?1:-1},u.prototype.compareTo=u.prototype.compare,h.prototype.compare=function(A){if(A===1/0)return-1;if(A===-1/0)return 1;var F=this.value,Q=ve(A).value;return F===Q?0:F>Q?1:-1},h.prototype.compareTo=h.prototype.compare,d.prototype.equals=function(A){return this.compare(A)===0},h.prototype.eq=h.prototype.equals=u.prototype.eq=u.prototype.equals=d.prototype.eq=d.prototype.equals,d.prototype.notEquals=function(A){return this.compare(A)!==0},h.prototype.neq=h.prototype.notEquals=u.prototype.neq=u.prototype.notEquals=d.prototype.neq=d.prototype.notEquals,d.prototype.greater=function(A){return this.compare(A)>0},h.prototype.gt=h.prototype.greater=u.prototype.gt=u.prototype.greater=d.prototype.gt=d.prototype.greater,d.prototype.lesser=function(A){return this.compare(A)<0},h.prototype.lt=h.prototype.lesser=u.prototype.lt=u.prototype.lesser=d.prototype.lt=d.prototype.lesser,d.prototype.greaterOrEquals=function(A){return this.compare(A)>=0},h.prototype.geq=h.prototype.greaterOrEquals=u.prototype.geq=u.prototype.greaterOrEquals=d.prototype.geq=d.prototype.greaterOrEquals,d.prototype.lesserOrEquals=function(A){return this.compare(A)<=0},h.prototype.leq=h.prototype.lesserOrEquals=u.prototype.leq=u.prototype.lesserOrEquals=d.prototype.leq=d.prototype.lesserOrEquals,d.prototype.isEven=function(){return(this.value[0]&1)===0},u.prototype.isEven=function(){return(this.value&1)===0},h.prototype.isEven=function(){return(this.value&BigInt(1))===BigInt(0)},d.prototype.isOdd=function(){return(this.value[0]&1)===1},u.prototype.isOdd=function(){return(this.value&1)===1},h.prototype.isOdd=function(){return(this.value&BigInt(1))===BigInt(1)},d.prototype.isPositive=function(){return!this.sign},u.prototype.isPositive=function(){return this.value>0},h.prototype.isPositive=u.prototype.isPositive,d.prototype.isNegative=function(){return this.sign},u.prototype.isNegative=function(){return this.value<0},h.prototype.isNegative=u.prototype.isNegative,d.prototype.isUnit=function(){return!1},u.prototype.isUnit=function(){return Math.abs(this.value)===1},h.prototype.isUnit=function(){return this.abs().value===BigInt(1)},d.prototype.isZero=function(){return!1},u.prototype.isZero=function(){return this.value===0},h.prototype.isZero=function(){return this.value===BigInt(0)},d.prototype.isDivisibleBy=function(A){var F=ve(A);return F.isZero()?!1:F.isUnit()?!0:F.compareAbs(2)===0?this.isEven():this.mod(F).isZero()},h.prototype.isDivisibleBy=u.prototype.isDivisibleBy=d.prototype.isDivisibleBy;function j(A){var F=A.abs();if(F.isUnit())return!1;if(F.equals(2)||F.equals(3)||F.equals(5))return!0;if(F.isEven()||F.isDivisibleBy(3)||F.isDivisibleBy(5))return!1;if(F.lesser(49))return!0}function q(A,F){for(var Q=A.prev(),X=Q,ge=0,he,Le,Se;X.isEven();)X=X.divide(2),ge++;e:for(Le=0;Le<F.length;Le++)if(!A.lesser(F[Le])&&(Se=e(F[Le]).modPow(X,A),!(Se.isUnit()||Se.equals(Q)))){for(he=ge-1;he!=0;he--){if(Se=Se.square().mod(A),Se.isUnit())return!1;if(Se.equals(Q))continue e}return!1}return!0}d.prototype.isPrime=function(A){var F=j(this);if(F!==t)return F;var Q=this.abs(),X=Q.bitLength();if(X<=64)return q(Q,[2,3,5,7,11,13,17,19,23,29,31,37]);for(var ge=Math.log(2)*X.toJSNumber(),he=Math.ceil(A===!0?2*Math.pow(ge,2):ge),Le=[],Se=0;Se<he;Se++)Le.push(e(Se+2));return q(Q,Le)},h.prototype.isPrime=u.prototype.isPrime=d.prototype.isPrime,d.prototype.isProbablePrime=function(A,F){var Q=j(this);if(Q!==t)return Q;for(var X=this.abs(),ge=A===t?5:A,he=[],Le=0;Le<ge;Le++)he.push(e.randBetween(2,X.minus(2),F));return q(X,he)},h.prototype.isProbablePrime=u.prototype.isProbablePrime=d.prototype.isProbablePrime,d.prototype.modInv=function(A){for(var F=e.zero,Q=e.one,X=ve(A),ge=this.abs(),he,Le,Se;!ge.isZero();)he=X.divide(ge),Le=F,Se=X,F=Q,X=ge,Q=Le.subtract(he.multiply(Q)),ge=Se.subtract(he.multiply(ge));if(!X.isUnit())throw new Error(this.toString()+" and "+A.toString()+" are not co-prime");return F.compare(0)===-1&&(F=F.add(A)),this.isNegative()?F.negate():F},h.prototype.modInv=u.prototype.modInv=d.prototype.modInv,d.prototype.next=function(){var A=this.value;return this.sign?C(A,1,this.sign):new d(S(A,1),this.sign)},u.prototype.next=function(){var A=this.value;return A+1<n?new u(A+1):new d(r,!1)},h.prototype.next=function(){return new h(this.value+BigInt(1))},d.prototype.prev=function(){var A=this.value;return this.sign?new d(S(A,1),!0):C(A,1,this.sign)},u.prototype.prev=function(){var A=this.value;return A-1>-n?new u(A-1):new d(r,!0)},h.prototype.prev=function(){return new h(this.value-BigInt(1))};for(var W=[1];2*W[W.length-1]<=s;)W.push(2*W[W.length-1]);var ee=W.length,z=W[ee-1];function Z(A){return Math.abs(A)<=s}d.prototype.shiftLeft=function(A){var F=ve(A).toJSNumber();if(!Z(F))throw new Error(String(F)+" is too large for shifting.");if(F<0)return this.shiftRight(-F);var Q=this;if(Q.isZero())return Q;for(;F>=ee;)Q=Q.multiply(z),F-=ee-1;return Q.multiply(W[F])},h.prototype.shiftLeft=u.prototype.shiftLeft=d.prototype.shiftLeft,d.prototype.shiftRight=function(A){var F,Q=ve(A).toJSNumber();if(!Z(Q))throw new Error(String(Q)+" is too large for shifting.");if(Q<0)return this.shiftLeft(-Q);for(var X=this;Q>=ee;){if(X.isZero()||X.isNegative()&&X.isUnit())return X;F=D(X,z),X=F[1].isNegative()?F[0].prev():F[0],Q-=ee-1}return F=D(X,W[Q]),F[1].isNegative()?F[0].prev():F[0]},h.prototype.shiftRight=u.prototype.shiftRight=d.prototype.shiftRight;function de(A,F,Q){F=ve(F);for(var X=A.isNegative(),ge=F.isNegative(),he=X?A.not():A,Le=ge?F.not():F,Se=0,xe=0,lt=null,mt=null,at=[];!he.isZero()||!Le.isZero();)lt=D(he,z),Se=lt[1].toJSNumber(),X&&(Se=z-1-Se),mt=D(Le,z),xe=mt[1].toJSNumber(),ge&&(xe=z-1-xe),he=lt[0],Le=mt[0],at.push(Q(Se,xe));for(var kt=Q(X?1:0,ge?1:0)!==0?e(-1):e(0),Us=at.length-1;Us>=0;Us-=1)kt=kt.multiply(z).add(e(at[Us]));return kt}d.prototype.not=function(){return this.negate().prev()},h.prototype.not=u.prototype.not=d.prototype.not,d.prototype.and=function(A){return de(this,A,function(F,Q){return F&Q})},h.prototype.and=u.prototype.and=d.prototype.and,d.prototype.or=function(A){return de(this,A,function(F,Q){return F|Q})},h.prototype.or=u.prototype.or=d.prototype.or,d.prototype.xor=function(A){return de(this,A,function(F,Q){return F^Q})},h.prototype.xor=u.prototype.xor=d.prototype.xor;var ie=1<<30,oe=(s&-s)*(s&-s)|ie;function ae(A){var F=A.value,Q=typeof F=="number"?F|ie:typeof F=="bigint"?F|BigInt(ie):F[0]+F[1]*s|oe;return Q&-Q}function ke(A,F){if(F.compareTo(A)<=0){var Q=ke(A,F.square(F)),X=Q.p,ge=Q.e,he=X.multiply(F);return he.compareTo(A)<=0?{p:he,e:ge*2+1}:{p:X,e:ge*2}}return{p:e(1),e:0}}d.prototype.bitLength=function(){var A=this;return A.compareTo(e(0))<0&&(A=A.negate().subtract(e(1))),A.compareTo(e(0))===0?e(0):e(ke(A,e(2)).e).add(e(1))},h.prototype.bitLength=u.prototype.bitLength=d.prototype.bitLength;function re(A,F){return A=ve(A),F=ve(F),A.greater(F)?A:F}function ce(A,F){return A=ve(A),F=ve(F),A.lesser(F)?A:F}function Ie(A,F){if(A=ve(A).abs(),F=ve(F).abs(),A.equals(F))return A;if(A.isZero())return F;if(F.isZero())return A;for(var Q=c[1],X,ge;A.isEven()&&F.isEven();)X=ce(ae(A),ae(F)),A=A.divide(X),F=F.divide(X),Q=Q.multiply(X);for(;A.isEven();)A=A.divide(ae(A));do{for(;F.isEven();)F=F.divide(ae(F));A.greater(F)&&(ge=F,F=A,A=ge),F=F.subtract(A)}while(!F.isZero());return Q.isUnit()?A:A.multiply(Q)}function Ve(A,F){return A=ve(A).abs(),F=ve(F).abs(),A.divide(Ie(A,F)).multiply(F)}function fe(A,F,Q){A=ve(A),F=ve(F);var X=Q||Math.random,ge=ce(A,F),he=re(A,F),Le=he.subtract(ge).add(1);if(Le.isSmall)return ge.add(Math.floor(X()*Le));for(var Se=Je(Le,s).value,xe=[],lt=!0,mt=0;mt<Se.length;mt++){var at=lt?Se[mt]+(mt+1<Se.length?Se[mt+1]/s:0):s,kt=y(X()*at);xe.push(kt),kt<Se[mt]&&(lt=!1)}return ge.add(c.fromArray(xe,s,!1))}var Xe=function(A,F,Q,X){Q=Q||o,A=String(A),X||(A=A.toLowerCase(),Q=Q.toLowerCase());var ge=A.length,he,Le=Math.abs(F),Se={};for(he=0;he<Q.length;he++)Se[Q[he]]=he;for(he=0;he<ge;he++){var xe=A[he];if(xe!=="-"&&xe in Se&&Se[xe]>=Le){if(xe==="1"&&Le===1)continue;throw new Error(xe+" is not a valid digit in base "+F+".")}}F=ve(F);var lt=[],mt=A[0]==="-";for(he=mt?1:0;he<A.length;he++){var xe=A[he];if(xe in Se)lt.push(ve(Se[xe]));else if(xe==="<"){var at=he;do he++;while(A[he]!==">"&&he<A.length);lt.push(ve(A.slice(at+1,he)))}else throw new Error(xe+" is not a valid character")}return Ye(lt,F,mt)};function Ye(A,F,Q){var X=c[0],ge=c[1],he;for(he=A.length-1;he>=0;he--)X=X.add(A[he].times(ge)),ge=ge.times(F);return Q?X.negate():X}function Ze(A,F){return F=F||o,A<F.length?F[A]:"<"+A+">"}function Je(A,F){if(F=e(F),F.isZero()){if(A.isZero())return{value:[0],isNegative:!1};throw new Error("Cannot convert nonzero numbers to base 0.")}if(F.equals(-1)){if(A.isZero())return{value:[0],isNegative:!1};if(A.isNegative())return{value:[].concat.apply([],Array.apply(null,Array(-A.toJSNumber())).map(Array.prototype.valueOf,[1,0])),isNegative:!1};var Q=Array.apply(null,Array(A.toJSNumber()-1)).map(Array.prototype.valueOf,[0,1]);return Q.unshift([1]),{value:[].concat.apply([],Q),isNegative:!1}}var X=!1;if(A.isNegative()&&F.isPositive()&&(X=!0,A=A.abs()),F.isUnit())return A.isZero()?{value:[0],isNegative:!1}:{value:Array.apply(null,Array(A.toJSNumber())).map(Number.prototype.valueOf,1),isNegative:X};for(var ge=[],he=A,Le;he.isNegative()||he.compareAbs(F)>=0;){Le=he.divmod(F),he=Le.quotient;var Se=Le.remainder;Se.isNegative()&&(Se=F.minus(Se).abs(),he=he.next()),ge.push(Se.toJSNumber())}return ge.push(he.toJSNumber()),{value:ge.reverse(),isNegative:X}}function tt(A,F,Q){var X=Je(A,F);return(X.isNegative?"-":"")+X.value.map(function(ge){return Ze(ge,Q)}).join("")}d.prototype.toArray=function(A){return Je(this,A)},u.prototype.toArray=function(A){return Je(this,A)},h.prototype.toArray=function(A){return Je(this,A)},d.prototype.toString=function(A,F){if(A===t&&(A=10),A!==10||F)return tt(this,A,F);for(var Q=this.value,X=Q.length,ge=String(Q[--X]),he="0000000",Le;--X>=0;)Le=String(Q[X]),ge+=he.slice(Le.length)+Le;var Se=this.sign?"-":"";return Se+ge},u.prototype.toString=function(A,F){return A===t&&(A=10),A!=10||F?tt(this,A,F):String(this.value)},h.prototype.toString=u.prototype.toString,h.prototype.toJSON=d.prototype.toJSON=u.prototype.toJSON=function(){return this.toString()},d.prototype.valueOf=function(){return parseInt(this.toString(),10)},d.prototype.toJSNumber=d.prototype.valueOf,u.prototype.valueOf=function(){return this.value},u.prototype.toJSNumber=u.prototype.valueOf,h.prototype.valueOf=h.prototype.toJSNumber=function(){return parseInt(this.toString(),10)};function ht(A){if(p(+A)){var F=+A;if(F===y(F))return l?new h(BigInt(F)):new u(F);throw new Error("Invalid integer: "+A)}var Q=A[0]==="-";Q&&(A=A.slice(1));var X=A.split(/e/i);if(X.length>2)throw new Error("Invalid integer: "+X.join("e"));if(X.length===2){var ge=X[1];if(ge[0]==="+"&&(ge=ge.slice(1)),ge=+ge,ge!==y(ge)||!p(ge))throw new Error("Invalid integer: "+ge+" is not a valid exponent.");var he=X[0],Le=he.indexOf(".");if(Le>=0&&(ge-=he.length-Le-1,he=he.slice(0,Le)+he.slice(Le+1)),ge<0)throw new Error("Cannot include negative exponent part for integers");he+=new Array(ge+1).join("0"),A=he}var Se=/^([0-9][0-9]*)$/.test(A);if(!Se)throw new Error("Invalid integer: "+A);if(l)return new h(BigInt(Q?"-"+A:A));for(var xe=[],lt=A.length,mt=i,at=lt-mt;lt>0;)xe.push(+A.slice(at,lt)),at-=mt,at<0&&(at=0),lt-=mt;return f(xe),new d(xe,Q)}function Ee(A){if(l)return new h(BigInt(A));if(p(A)){if(A!==y(A))throw new Error(A+" is not an integer.");return new u(A)}return ht(A.toString())}function ve(A){return typeof A=="number"?Ee(A):typeof A=="string"?ht(A):typeof A=="bigint"?new h(A):A}for(var Qe=0;Qe<1e3;Qe++)c[Qe]=ve(Qe),Qe>0&&(c[-Qe]=ve(-Qe));return c.one=c[1],c.zero=c[0],c.minusOne=c[-1],c.max=re,c.min=ce,c.gcd=Ie,c.lcm=Ve,c.isInstance=function(A){return A instanceof d||A instanceof u||A instanceof h},c.randBetween=fe,c.fromArray=function(A,F,Q){return Ye(A.map(ve),ve(F||10),Q)},c}();a.hasOwnProperty("exports")&&(a.exports=e)})(dI);var iR=dI.exports;const hI=ek(iR),nR=Y("<div>"),uI=a=>{const e=ni({size:100},a);let t;const s=(()=>{const i=nR();return i.$$click=()=>{e.restartOnClick&&t?.then(n=>{n.playOrRestart()})},Me(n=>{const r={[e.class]:!!e.class},o=e.size+"px";return n._v$=er(i,r,n._v$),o!==n._v$2&&((n._v$2=o)!=null?i.style.setProperty("--size",o):i.style.removeProperty("--size")),n},{_v$:void 0,_v$2:void 0}),i})();return Me(()=>{t=e.lottieLoader.loadAnimationAsAsset({container:s,loop:!1,autoplay:!0,width:e.size,height:e.size,...e.rlottieOptions},e.name),ze(()=>{t?.then(i=>{i.remove()})})}),e.onPromise?.(t),s};Fs(["click"]);function aR(a){return a.map(e=>hI(e)).sort((e,t)=>e.compare(t)).map(e=>e.toString(10))}class rR extends XC{constructor(e,t,s){super(e),this.onVisibilityChange=t,this.elementsMap=new Map,this.intersector=new vg(i=>{const{target:n,visible:r}=i,o=this.elementsMap.get(n);o.visible=r,r?(o.wasSeen=!0,this.queue.includes(o)||this.queue.push(o)):Vs(this.queue,o),this.onVisibilityChange?.(i),this.setProcessQueueTimeout()},s)}clear(){super.clear(),this.elementsMap.clear()}observe(e){this.elementsMap.set(e.div,e),super.observe(e)}unobserve(e){this.elementsMap.delete(e.div),super.unobserve(e)}}class Id{constructor(e){this.animated=new Set,this.checkAnimationContainer=(t,s)=>{Ut.getAnimations(t).forEach(n=>{s?Ut.checkAnimation(n,!1):Ut.removeAnimation(n)})},this.processVisible=async t=>{const s=t.dataset.docId,i=await this.managers.appDocsManager.getDoc(s),n=st.active.esgSticker.width;t.middlewareHelper??(t.middlewareHelper=Ht()),t.middlewareHelper.clean();const r=ai({doc:i,div:t,width:n,height:n,lazyLoadQueue:null,group:this.group,onlyThumb:!1,play:!0,loop:!0,withLock:this.withLock,middleware:t.middlewareHelper.get(),...this.visibleRenderOptions||{}}).then(({render:o})=>o);return r.then(()=>{this.checkAnimationContainer(t,this.lazyLoadQueue.intersector.isVisible(t))},as),r},this.processInvisible=async t=>{const s=t.dataset.docId,i=await this.managers.appDocsManager.getDoc(s);this.checkAnimationContainer(t,!1),t.middlewareHelper?.clean(),t.replaceChildren(),this.renderSticker(i,t)},e.withLock??(e.withLock=!0),Nt(this,e),this.lazyLoadQueue=new rR(void 0,({target:t,visible:s})=>{s||this.processInvisible(t)},this.intersectionObserverInit)}clear(){this.lazyLoadQueue.clear(),this.animated.forEach(e=>{e.middlewareHelper?.destroy()}),this.animated.clear()}destroy(){this.clear()}renderSticker(e,t,s,i){return t||(t=document.createElement("div"),t.classList.add("grid-item","super-sticker"),t.dataset.docId=""+e.id,e.animated&&this.observeAnimated(t)),t.middlewareHelper??(t.middlewareHelper=i?i.create():Ht()),ai({doc:e,div:t,lazyLoadQueue:this.regularLazyLoadQueue,group:this.group,onlyThumb:e.animated,loadPromises:s,middleware:t.middlewareHelper.get(),...e.animated?{}:this.visibleRenderOptions||{}}),t}observeAnimated(e){this.animated.add(e),this.lazyLoadQueue.observe({div:e,load:this.processVisible})}unobserveAnimated(e){e.middlewareHelper?.destroy(),this.animated.delete(e),this.lazyLoadQueue.delete({div:e})}deleteSticker(e){return this.unobserveAnimated(e)}}const oR="_grid_1shbt_6",lR="_viewProfile_1shbt_15",cR="_gridItem_1shbt_20",dR="_itemPrice_1shbt_41",hR="_viewList_1shbt_62",uR="_itemFrom_1shbt_74",pR="_itemFromAnonymous_1shbt_82",mR="_itemBackdrop_1shbt_97",gR="_badgeSoldout_1shbt_104",fR="_badgeUnique_1shbt_108",vR="_itemSticker_1shbt_112",yR="_itemPin_1shbt_125",bR="_itemUnsaved_1shbt_134",sa={grid:oR,viewProfile:lR,gridItem:cR,itemPrice:dR,viewList:hR,itemFrom:uR,itemFromAnonymous:pR,itemBackdrop:mR,badgeSoldout:gR,badgeUnique:fR,itemSticker:vR,itemPin:yR,itemUnsaved:bR},wR="_badge_19hq8_1",SR="_text_19hq8_12",KS={badge:wR,text:SR},CR=Y("<div><div>");function bh(a){return(()=>{const e=CR(),t=e.firstChild;return k(t,()=>a.children),Me(s=>{const i=Ge(KS.badge,a.class),n=a.backdropAttr?Mc(a.backdropAttr.edge_color,.8):void 0,r=Ge(KS.text,a.textClass);return i!==s._v$&&be(e,s._v$=i),n!==s._v$2&&((s._v$2=n)!=null?e.style.setProperty("background",n):e.style.removeProperty("background")),r!==s._v$3&&be(t,s._v$3=r),s},{_v$:void 0,_v$2:void 0,_v$3:void 0}),e})()}const _R="_wrap_1a9iw_16",IR="_halo_1a9iw_24",PR="_haloSmall_1a9iw_37",MR="_canvas_1a9iw_42",Pp={wrap:_R,halo:IR,haloSmall:PR,canvas:MR},LR=Y("<div><div>"),jS=.1,ac=.2,an=.3,ER=266,kR=184,TR=120,xR=120,AR=[[55,47,18,an],[23,26,18,ac],[0,64,18,ac],[0,165,18,jS],[17,125,18,ac],[58,141,22,an],[81,13,24,an],[38,82,26,an],[187,46,18,an],[219,26,18,ac],[119,5,18,an],[242,64,18,ac],[245,165,18,jS],[225,125,18,ac],[118,151,22,an],[180,141,22,an],[155,13,24,an],[196,82,26,an]],RR=[[49,1,20,an],[93,12,20,an],[99,42,20,an],[89,86,20,an],[49,97,20,an],[9,86,20,an],[-5,42,20,an],[5,12,20,an]];function qu(a){const e=Ht(),[t,s]=K();function i(){const n=e.get(),r=a.patternEmoji;kb({docId:a.patternEmoji,middleware:n,canvasWidth:a.small?TR:ER,canvasHeight:a.small?xR:kR,emojiSize:24,positions:a.small?RR:AR,color:Mc(a.backdrop.pattern_color)}).then(o=>{n()&&r===a.patternEmoji&&(o.classList.add(Pp.canvas,a.canvasClass),s(o))})}return le(Vt(()=>[a.patternEmoji,a.backdrop],()=>{i()})),(()=>{const n=LR(),r=n.firstChild;return k(n,T(Du,{get children(){return t()}}),r),Me(o=>{const l=Ge(Pp.wrap,a.class),c=Mc(a.backdrop.edge_color),d=Mc(a.backdrop.center_color),u=Ge(Pp.halo,a.small&&Pp.haloSmall);return l!==o._v$&&be(n,o._v$=l),c!==o._v$2&&((o._v$2=c)!=null?n.style.setProperty("--stargift-backdrop-edge-color",c):n.style.removeProperty("--stargift-backdrop-edge-color")),d!==o._v$3&&((o._v$3=d)!=null?n.style.setProperty("--stargift-backdrop-center-color",d):n.style.removeProperty("--stargift-backdrop-center-color")),u!==o._v$4&&be(r,o._v$4=u),o},{_v$:void 0,_v$2:void 0,_v$3:void 0,_v$4:void 0}),n})()}async function pI(a){if(!I.premium)return ue.createPopup(rs),!1;const e=Mt();I.managers.appUsersManager.updateEmojiStatus({_:"inputEmojiStatusCollectible",collectible_id:a}).then(()=>{$e({langPackKey:"SetAsEmojiStatusInfo"}),e.resolve(!0)}).catch(()=>{$e({langPackKey:"Error.AnError"}),e.resolve(!1)})}function mI(a){const{saved:e,input:t}=a,s=Mt();return Rs.createPicker2({filterPeerTypeBy:["isRegularUser"],placeholder:"StarGiftTransferTo",exceptSelf:!0}).then(async i=>{const n=await I.managers.appUsersManager.getUserInputPeer(i);Number(e.transfer_stars)!==0?(await Ln.create({inputInvoice:{_:"inputInvoiceStarGiftTransfer",stargift:t,to_id:n}})).addEventListener("finish",o=>{o==="paid"?s.resolve(!0):s.resolve(!1)}):(await I.managers.appGiftsManager.transferStarGift(t,i),s.resolve(!0))}),s}const FR=Y("<div><div>"),BR=Y("<div><span>"),gI=Y("<div>"),DR=Y("<div><img src=/assets/img/anon_paid_reaction.png alt=Anonymous>");function $R(a){let e,t;Jt(()=>{if(a.renderer.renderSticker(a.item.sticker,t),a.renderer.observeAnimated(t),a.view==="profile"){const{raw:i,saved:n,input:r,isIncoming:o}=a.item,l=i._==="starGiftUnique"&&it(i.owner_id)===I.myId&&n!==void 0;Dn({listenTo:e,buttons:[{icon:"forward",text:"ShareFile",verify:()=>i._==="starGiftUnique",onClick:()=>{Rs.createSharingPicker2().then(c=>{I.managers.appMessagesManager.sendText({peerId:c,text:"https://t.me/nft/"+i.slug}),Ce.setInnerPeer({peerId:c})})}},{icon:n?.pFlags.pinned_to_top?"unpin":"pin",text:n?.pFlags.pinned_to_top?"StarGiftUnpin":"StarGiftPin",verify:()=>l,onClick:()=>{I.managers.appGiftsManager.togglePinnedGift(r)}},{icon:"link",text:"CopyLink",verify:()=>i._==="starGiftUnique",onClick:()=>{si("https://t.me/nft/"+i.slug),$e({langPackKey:"LinkCopied"})}},{icon:"gem_transfer",text:"StarGiftTransferFull",verify:()=>l,onClick:()=>{mI(a.item)}},{icon:"crown",text:"StarGiftWearFull",verify:()=>l,onClick:()=>{pI(i.id)}},{icon:n.pFlags.unsaved?"eye":"eyecross_outline",text:n.pFlags.unsaved?"Show":"Hide",verify:()=>l||o,onClick:()=>{I.managers.appGiftsManager.toggleGiftHidden(r,!n.pFlags.unsaved)}}]})}});const s=()=>a.item.saved?.pFlags.pinned_to_top;return(()=>{const i=FR(),n=i.firstChild,r=e;typeof r=="function"?Ue(r,i):e=i,Lr(i,"click",a.onClick,!0),be(i,Ge(sa.gridItem,a.view==="profile"?sa.viewProfile:sa.viewList)),k(i,(()=>{const l=V(()=>!!a.item.collectibleAttributes);return()=>l()&&T(qu,{class:sa.itemBackdrop,small:!0,get backdrop(){return a.item.collectibleAttributes.backdrop},get patternEmoji(){return a.item.collectibleAttributes.pattern.document}})})(),n),k(i,(()=>{const l=V(()=>!!s());return()=>l()&&T(hs,{icon:"pin2",class:sa.itemPin})})(),n),k(i,(()=>{const l=V(()=>!!(a.view==="profile"&&a.item.saved?.pFlags.unsaved));return()=>l()&&T(hs,{icon:"hide",class:sa.itemUnsaved})})(),n);const o=t;return typeof o=="function"?Ue(o,n):t=n,be(n,sa.itemSticker),k(i,(()=>{const l=V(()=>a.view==="list"&&a.item.raw._==="starGift");return()=>l()&&(()=>{const c=BR(),d=c.firstChild;return be(c,sa.itemPrice),k(c,T(ya,{}),d),k(d,()=>a.item.raw.stars),c})()})(),null),k(i,(()=>{const l=V(()=>a.view==="profile"&&a.item.raw._==="starGift");return()=>l()&&(()=>{const c=gI();return be(c,sa.itemFrom),k(c,(()=>{const d=V(()=>!!a.item.saved.from_id);return()=>d()?T(Eg,{get peerId(){return it(a.item.saved.from_id)},size:20}):(()=>{const u=DR();return be(u,sa.itemFromAnonymous),u})()})()),c})()})(),null),k(i,()=>{const l=a.item.raw;if(l._!=="starGift")return T(bh,{class:sa.badgeUnique,get backdropAttr(){return a.item.collectibleAttributes.backdrop},get children(){return V(()=>!!s())()?`#${l.num}`:P("StarGiftLimitedBadgeNum",[un(l.availability_total,1)])}});if(a.view==="list"&&l.availability_remains===0)return T(bh,{class:sa.badgeSoldout,get children(){return P("StarGiftSoldOutBadge")}});if(a.item.raw.availability_total)return T(bh,{get children(){return V(()=>a.view==="list")()?P("StarGiftLimitedBadge"):P("StarGiftLimitedBadgeNum",[un(l.availability_total,1)])}})},null),i})()}function fI(a){const e=new sr,t=new Id({regularLazyLoadQueue:e,group:"none",managers:I.managers,intersectionObserverInit:{root:a.scrollParent},visibleRenderOptions:{loop:!1,width:120,height:120},withLock:!1});return ze(()=>{t.destroy(),e.clear()}),(()=>{const s=gI();return k(s,T(Cs,{get each(){return a.items},children:i=>T($R,{item:i,get view(){return a.view},onClick:()=>a.onClick?.(i),renderer:t})})),Me(()=>be(s,Ge(sa.grid,a.class))),s})()}Fs(["click"]);const NR="_root_o287b_1",OR="_content_o287b_10",qS={root:NR,content:OR},UR=Y("<div><div>");function HR(a){let e;return(()=>{const t=UR(),s=t.firstChild,i=e;return typeof i=="function"?Ue(i,t):e=t,k(t,T(zE,{get managers(){return I.managers},themeController:Ls,get peerId(){return a.peerId},onHighlightColor:n=>Ls.applyHighlightingColor({hsla:n,element:e})}),s),be(s,qS.content),k(s,()=>a.children),Me(()=>be(t,Ge(qS.root,a.class))),t})()}const GR="_wrap_bee5c_1",VR="_text_bee5c_10",zR="_addon_bee5c_25",Tm={wrap:GR,text:VR,addon:zR},WR=Y("<div><div>");function KR(a){const[e,{refetch:t}]=ma(()=>gm({message:a.message}));return le(Vt(()=>a.message,t)),(()=>{const s=WR(),i=s.firstChild;return be(i,Tm.text),k(i,e),k(s,()=>a.children,null),Me(()=>be(s,Ge(Tm.wrap,a.class))),s})()}const jR="_bubble_6dqj0_1",qR="_bubbleIsUnique_6dqj0_12",YR="_sticker_6dqj0_22",QR="_from_6dqj0_29",XR="_fromUser_6dqj0_49",ZR="_message_6dqj0_58",JR="_badge_6dqj0_69",eF="_upgradeButton_6dqj0_77",tF="_backdrop_6dqj0_85",sF="_uniqueGiftInfo_6dqj0_92",iF="_uniqueGiftTitle_6dqj0_98",nF="_uniqueGiftProps_6dqj0_103",aF="_uniqueGiftPropName_6dqj0_111",rF="_uniqueGiftPropValue_6dqj0_117",oF="_webPageBox_6dqj0_123",lF="_webPageBackdrop_6dqj0_129",cF="_webPageBackdropCanvas_6dqj0_134",dF="_webPageSticker_6dqj0_138",Ai={bubble:jR,bubbleIsUnique:qR,sticker:YR,from:QR,fromUser:XR,message:ZR,badge:JR,upgradeButton:eF,backdrop:tF,uniqueGiftInfo:sF,uniqueGiftTitle:iF,uniqueGiftProps:nF,uniqueGiftPropName:aF,uniqueGiftPropValue:rF,webPageBox:oF,webPageBackdrop:lF,webPageBackdropCanvas:cF,webPageSticker:dF};function vI(a,e){le(Vt(e,(t,s)=>{s&&a.classList.remove(...s.split(" ")),t&&a.classList.add(...t.split(" "))}))}function oi(a){const e=yd(()=>a.args,i=>i instanceof Node||typeof i=="string"),t=()=>e.toArray(),s=new Ne.IntlElement({key:a.key,args:t()});return vI(s.element,()=>a.class),le(Vt(()=>[a.key,t()],([i,n],r)=>{s.update({key:i,args:n})},{defer:!0})),s.element}const hF=Y("<div><div> #</div><div><div></div><div></div><div>"),uF=Y("<span>"),pF=Y("<div><div>"),yI=Y("<div>");function bI(a){const e=V(()=>a.gift.raw._==="starGiftUnique"?(()=>{const t=hF(),s=t.firstChild,i=s.firstChild,n=s.nextSibling,r=n.firstChild,o=r.nextSibling,l=o.nextSibling;return be(t,Ai.uniqueGiftInfo),be(s,Ai.uniqueGiftTitle),k(s,()=>a.gift.raw.title,i),k(s,()=>ln(a.gift.raw.num,","),null),be(n,Ai.uniqueGiftProps),k(n,T(oi,{class:Ai.uniqueGiftPropName,key:"StarGiftModel"}),r),be(r,Ai.uniqueGiftPropValue),k(r,()=>a.gift.collectibleAttributes.model.name),k(n,T(oi,{class:Ai.uniqueGiftPropName,key:"StarGiftBackdrop"}),o),be(o,Ai.uniqueGiftPropValue),k(o,()=>a.gift.collectibleAttributes.backdrop.name),k(n,T(oi,{class:Ai.uniqueGiftPropName,key:"StarGiftPattern"}),l),be(l,Ai.uniqueGiftPropValue),k(l,()=>a.gift.collectibleAttributes.pattern.name),t})():a.message?jt(a.message.text,{entities:a.message.entities}):a.asUpgrade&&a.ownerId?T(oi,{key:"StarGiftDefaultMessageUpgradeOut",get args(){return T(Cl,{get peerId(){return a.ownerId}})}}):a.asUpgrade?T(oi,{key:"StarGiftDefaultMessageUpgrade"}):a.gift.raw.convert_stars!==void 0&&!a.gift.isUpgraded?a.gift.isIncoming?T(oi,{key:"StarGiftDefaultMessageConvertable",get args(){return(()=>{const t=uF();return k(t,()=>a.gift.raw.convert_stars),t})()}}):T(oi,{key:"StarGiftDefaultMessageConvertableOut",get args(){return[T(Cl,{get peerId(){return a.ownerId}}),`${a.gift.raw.convert_stars}`]}}):a.gift.isIncoming?T(oi,{key:"StarGiftDefaultMessage"}):T(oi,{key:"StarGiftDefaultMessageOut",get args(){return T(Cl,{get peerId(){return a.ownerId}})}}));return(()=>{const t=pF(),s=t.firstChild;return be(t,Ge(Ai.bubble,a.gift.raw._==="starGiftUnique"&&Ai.bubbleIsUnique,Tm.addon)),k(t,(()=>{const i=V(()=>!!a.gift.raw.availability_total);return()=>i()&&T(bh,{class:Ai.badge,get backdropAttr(){return a.gift.collectibleAttributes?.backdrop},get children(){return T(oi,{key:"StarGiftLimitedBadgeNum",get args(){return[un(a.gift.raw.availability_total)]}})}})})(),s),k(t,(()=>{const i=V(()=>!!a.gift.collectibleAttributes);return()=>i()&&T(qu,{class:Ai.backdrop,get backdrop(){return a.gift.collectibleAttributes.backdrop},get patternEmoji(){return a.gift.collectibleAttributes.pattern.document}})})(),s),k(t,T(qy,{class:Ai.sticker,get sticker(){return a.gift.sticker},width:120,height:120,get extraOptions(){return a.wrapStickerOptions}}),s),k(t,T(oi,{key:"StarGiftFrom",class:Ai.from,get args(){return(()=>{const i=yI();return be(i,Ai.fromUser),k(i,T(Eg,{get peerId(){return a.fromId},size:16}),null),k(i,T(Cl,{get peerId(){return a.fromId}}),null),i})()}}),s),be(s,Ai.message),k(s,e),k(t,(()=>{const i=V(()=>!!a.asUpgrade);return()=>i()?T(Za,{class:Ge("bubble-service-button",Ai.upgradeButton),get onClick(){return a.onViewClick},iconAfter:"unpack",get children(){return[T(Rl,{mode:"button",isDiv:!0}),T(oi,{key:"ActionGiftPremiumUnpack"})]}}):T(Za,{class:"bubble-service-button",get onClick(){return a.onViewClick},get children(){return[T(Rl,{mode:"button",isDiv:!0}),T(oi,{key:"ActionGiftPremiumView"})]}})})(),null),t})()}function mF(a){return(()=>{const e=yI();return e.$$click=t=>Xs(t.target.closest(".webpage-quote")),be(e,Ai.webPageBox),k(e,T(qu,{class:Ai.webPageBackdrop,canvasClass:Ai.webPageBackdropCanvas,get backdrop(){return a.gift.collectibleAttributes.backdrop},get patternEmoji(){return a.gift.collectibleAttributes.pattern.document}}),null),k(e,T(qy,{class:Ai.webPageSticker,width:120,height:120,get extraOptions(){return a.wrapStickerOptions},get sticker(){return a.gift.collectibleAttributes.model.document}}),null),e})()}Fs(["click"]);function xc(a){const[e,t]=a.signal??K(a.checked),s=new _t({text:a.text,toggle:a.toggle});let i=!0;return le(()=>{s.setValueSilently(e()),!i&&a.onChange&&Ot(()=>a.onChange(e())),i=!1}),Ta(s.input)("change",()=>{t(s.input.checked)}),s.label}const gF="_bubble_a8i6f_1",fF="_sticker_a8i6f_11",vF="_subtitle_a8i6f_19",$f={bubble:gF,sticker:fF,subtitle:vF},yF=Y("<div><span class=text-bold></span><span>");function qp(a){return(()=>{const e=yF(),t=e.firstChild,s=t.nextSibling;return be(e,Ge($f.bubble,Tm.addon)),k(e,T(uI,{class:$f.sticker,size:160,get name(){return a.assetName},lottieLoader:Ns,get rlottieOptions(){return{autoplay:wt.isAvailable("stickers_chat"),...a.rlottieOptions}}}),t),k(t,()=>a.title),be(s,$f.subtitle),k(s,()=>a.subtitle),k(e,(()=>{const i=V(()=>!!a.buttonText);return()=>i()&&T(Za,{class:"bubble-service-button",get onClick(){return a.buttonCallback},get children(){return a.buttonText}})})(),null),e})()}const bF=Y("<button>"),Pi=a=>{const[,e]=wa(a,["icon","noRipple"]),t=(()=>{const s=bF();return so(s,ni(e,{get class(){return Ge("btn-icon",a.class)},tabIndex:-1}),!1,!0),k(s,(()=>{const i=V(()=>!!a.icon);return()=>i()&&Be(a.icon)})(),null),k(s,()=>a.children,null),s})();return a.noRipple||Ei(t),t},YS=Y("<div>");function wF(a){const[,e]=wa(a,["children","currentPage","class","tabClass"]);let t;return Jt(()=>{const s=Sr({...e,content:t});le(Vt(()=>a.currentPage,i=>s(i)))}),(()=>{const s=YS(),i=t;return typeof i=="function"?Ue(i,s):t=s,k(s,T(Cs,{get each(){return a.children},children:n=>(()=>{const r=YS();return k(r,n),Me(()=>be(r,Ge("tabs-tab",a.tabClass))),r})()})),Me(()=>be(s,Ge("tabs-container",a.class))),s})()}const SF=Y("<div>"),CF=Y("<div class=scrollable-thumb-container><div class=scrollable-thumb>"),_F=24,th=!xL;let jv,qv;th?(jv=a=>requestAnimationFrame(a),qv=a=>cancelAnimationFrame(a)):(jv=a=>window.setTimeout(a,_F),qv=a=>window.clearTimeout(a));function od(a){const e=a.axis??"y",t=e==="x"?"scrollLeft":"scrollTop",s=e==="x"?"scrollWidth":"scrollHeight",i=e==="x"?"clientWidth":"clientHeight",n=e==="x"?"offsetWidth":"offsetHeight",r=e==="x"?"clientX":"clientY",o=()=>j[t],l=()=>j[s],c=()=>j[i],d=()=>j[n],u=()=>l()-Math.round(o()+d()),h=V(()=>a.onScrollOffset??300);let p=0,m=0,g,f,v=!1,y=!1;const[w,b]=K(!0),[S,_]=K(!0);let M=0;const C=yg(()=>{v=!0,M&&(E(),y=!0)},()=>{v=!1,y&&(L(),y=!1)});ze(C);const L=()=>{if(v){E(),y=!0;return}!a.onScrolledTop&&!a.onScrolledBottom&&!N().length&&!th||M||(M=jv(()=>{M=0;const W=o();p=m===W?0:m<W?1:-1,m=W,B(W),N().forEach(ee=>ee()),x()}))},E=()=>{M&&(qv(M),M=0)},x=()=>{if(!a.onScrolledTop&&!a.onScrolledBottom)return;const W=l();if(!W)return;const ee=o(),z=d(),Z=h(),de=W-z;a.onScrolledTop&&ee<=Z&&p<=0&&a.onScrolledTop(),a.onScrolledBottom&&de-ee<=Z&&p>=0&&a.onScrolledBottom()},R=()=>{b(!o()),_(u()<=1)},B=(W=o())=>{if(!th||!q)return;const ee=l(),z=c(),Z=ee/z/.75,de=Math.max(20,z/Z),ie=W/(ee-z)*z,oe=W/(ee-z),ae=z-de;z<ee?(q.style.height=de+"px",q.style.transform=`translateY(${Math.min(ae,ie-de*oe)}px)`):q.style.height="0px"},N=V(()=>[a.onScroll,a.withBorders&&R].filter(Boolean)),G=W=>{_e(W);const ee=l(),z=c(),Z=q.offsetHeight,de=ee-z,ie=z-Z,ae=(W[r]-g)/ie*de,ke=f+ae;j[t]=ke},O=W=>{_e(W),g=W[r],f=o(),W.target.classList.add("is-focused"),window.addEventListener("mousemove",G),window.addEventListener("mouseup",$,{once:!0})},$=W=>{window.removeEventListener("mousemove",G),q.classList.remove("is-focused")},H=W=>{W.stopPropagation();const ee=W.target;!W.deltaX&&ee.scrollWidth>ee.clientWidth&&(ee.scrollLeft+=W.deltaY/4,_e(W))},D=()=>{th&&q&&L()},U=yd(()=>a.children);le(Vt(U,D));let j,q;return(()=>{const W=SF();return Lr(W,"wheel",e==="x"&&!pt&&H||void 0),W.addEventListener("scroll",L),Ue(ee=>(j=ee,a.ref?.(ee)),W),k(W,th&&e==="y"&&(()=>{const ee=CF(),z=ee.firstChild;z.$$mousedown=O;const Z=q;return typeof Z=="function"?Ue(Z,z):q=z,ee})(),null),k(W,U,null),Me(()=>be(W,Ge("scrollable",`scrollable-${e}`,a.class,dn&&!wr&&"no-scrollbar",...a.withBorders?[w()&&"scrolled-start",S()&&"scrolled-end",e==="y"&&"scrollable-y-bordered",(a.withBorders==="top"||a.withBorders==="both")&&"scrollable-y-bordered-top",(a.withBorders==="bottom"||a.withBorders==="both")&&"scrollable-y-bordered-bottom"]:[]))),W})()}Fs(["mousedown"]);function IF(a,e,t=.001){return Math.abs(a-e)<t}function PF(a){return a[fg(0,a.length-1)]}function Nf(a,e){const t=a.indexOf(e);if(t===-1)return PF(a);let s=fg(0,a.length-1);return s===t&&(s=t+(Math.random()<.5?-1:1),s<0?s=a.length-1:s>=a.length&&(s=0)),a[s]}const MF=Y("<div class=popup-star-gift-upgrade-container><div class=popup-star-gift-upgrade-header><div class=popup-star-gift-upgrade-sticker></div><div class=popup-star-gift-upgrade-title></div><div class=popup-star-gift-upgrade-subtitle></div></div><div class=popup-star-gift-upgrade-body><div class=popup-star-gift-upgrade-feature><div class=popup-star-gift-upgrade-feature-body></div></div><div class=popup-star-gift-upgrade-feature><div class=popup-star-gift-upgrade-feature-body></div></div><div class=popup-star-gift-upgrade-feature><div class=popup-star-gift-upgrade-feature-body>"),LF=Y("<div class=popup-star-gift-upgrade-footer>");class Kg extends ue{constructor(e,t){super("popup-star-gift-upgrade",{closable:!0,overlayClosable:!0,body:!0,footer:!0,withConfirm:"OK",withFooterConfirm:!0}),this.gift=e,this.descriptionForPeerId=t}_construct(e,t){const s=this;this.header.remove(),this.footer.classList.add("abitlarger");const i=this.gift.isUpgradedBySender||this.gift.saved?.upgrade_stars!==void 0;this.descriptionForPeerId?this.btnConfirm.replaceChildren(P("OK")):this.btnConfirm.replaceChildren(i?P("StarGiftUpgradeFree"):P("StarGiftUpgrade",[qi(this.gift.raw.upgrade_stars,Mo)]));const n=K(!0);J(this.btnConfirm,()=>{if(this.descriptionForPeerId)this.hide();else if(i){const m=os(this.btnConfirm,!0);this.managers.appGiftsManager.upgradeStarGift(this.gift.input,n[0]()).then(()=>this.hide(),m)}else{const m=os(this.btnConfirm,!0);Ln.create({inputInvoice:{_:"inputInvoiceStarGiftUpgrade",stargift:this.gift.input,pFlags:{keep_original_details:n[0]()?!0:void 0}},noShowIfStars:!0}).then(g=>{g.addEventListener("finish",f=>{f==="paid"?this.hide():m()})})}});const[r,o]=K(),[l,c]=K(),[d,u]=K(),h=()=>{o(m=>Nf(e.models,m)),c(m=>Nf(e.backdrops,m)),u(m=>Nf(e.patterns,m))};h(),le(()=>{const m=r();ai({doc:m.document,div:p,width:120,height:120,play:!0,loop:!1,middleware:this.middlewareHelper.get()}).then(({render:g})=>g).then(g=>{const f=g;f.playOrRestart(),f.addEventListener("enterFrame",v=>{v===f.maxFrame&&(f.stop(!1),h())})})});let p;return(()=>{const m=MF(),g=m.firstChild,f=g.firstChild,v=f.nextSibling,y=v.nextSibling,w=g.nextSibling,b=w.firstChild,S=b.firstChild,_=b.nextSibling,M=_.firstChild,C=_.nextSibling,L=C.firstChild;k(g,T(qu,{class:"popup-star-gift-upgrade-backdrop",get backdrop(){return l()},get patternEmoji(){return d().document}}),f),k(g,T(Pi,{class:"popup-star-gift-upgrade-close",icon:"close",onClick:()=>s.hide()}),f);const E=p;return typeof E=="function"?Ue(E,f):p=f,k(v,()=>P(s.descriptionForPeerId?"StarGiftUpgradeTitleFor":"StarGiftUpgradeTitle")),k(y,()=>P(s.descriptionForPeerId?"StarGiftUpgradeSubtitleFor":"StarGiftUpgradeSubtitle",[t])),k(b,T(hs,{class:"popup-star-gift-upgrade-feature-icon",icon:"gem"}),S),k(S,T(oi,{class:"popup-star-gift-upgrade-feature-title",key:"StarGiftUpgradeUniqueTitle"}),null),k(S,T(oi,{class:"popup-star-gift-upgrade-feature-text",key:"StarGiftUpgradeUniqueText"}),null),k(_,T(hs,{class:"popup-star-gift-upgrade-feature-icon",icon:"gem_exchange"}),M),k(M,T(oi,{class:"popup-star-gift-upgrade-feature-title",key:"StarGiftUpgradeTransferableTitle"}),null),k(M,T(oi,{class:"popup-star-gift-upgrade-feature-text",key:"StarGiftUpgradeTransferableText"}),null),k(C,T(hs,{class:"popup-star-gift-upgrade-feature-icon",icon:"trade"}),L),k(L,T(oi,{class:"popup-star-gift-upgrade-feature-title",key:"StarGiftUpgradeTradableTitle"}),null),k(L,T(oi,{class:"popup-star-gift-upgrade-feature-text",key:"StarGiftUpgradeTradableText"}),null),k(m,(()=>{const x=V(()=>!s.descriptionForPeerId);return()=>x()&&(()=>{const R=LF();return k(R,T(En,{get checkboxField(){return T(xc,{text:"StarGiftUpgradeKeepInfo",signal:n})}})),R})()})(),null),m})()}static async create(e,t){const s=new Kg(e,t),i=await s.managers.appGiftsManager.getUpgradePreview(e.raw.id),n=t?await qe({peerId:t}):void 0;s.appendSolid(()=>s._construct(i,n)),s.show()}}const EF=Y("<div class=popup-send-gift-title>"),kF=Y("<div class=popup-send-gift-subtitle>"),TF=Y("<div class=popup-send-gift-premium-options>"),xF=Y("<div class=popup-send-gift-premium-option><div class=popup-send-gift-premium-option-title></div><div class=popup-send-gift-premium-option-subtitle></div><div class=popup-send-gift-premium-option-price>"),AF=Y("<div class=popup-send-gift-premium-option-price-stars><div class=popup-send-gift-premium-option-price-stars-inner>"),RF=Y("<div>"),FF=Y("<div class=popup-send-gift-main><div class=popup-send-gift-main-header><div class=popup-title></div></div><div class=popup-send-gift-avatar><img class=popup-send-gift-image></div><div class=popup-send-gift-title></div><div class=popup-send-gift-subtitle></div><div class=popup-send-gift-categories></div><div class=popup-send-gift-gifts>"),BF=Y("<div class=popup-send-gift-limited-progress-wrap><div class=popup-send-gift-limited-progress-bar><div class=popup-send-gift-limited-progress></div><div class=popup-send-gift-limited-progress-text>"),QS=Y("<div class=popup-send-gift-form-sheet>"),XS=Y("<div class=popup-send-gift-form-hint>"),DF=Y("<div class=popup-send-gift-form><div class=popup-send-gift-form-header><div class=popup-title></div></div><div class=popup-send-gift-form-body>"),$F=Y("<div class=popup-send-gift-balance><a class=popup-send-gift-balance-get-more>"),NF=Y("<b>"),ZS={All:"StarGiftCategoryAll",Limited:"StarGiftCategoryLimited",InStock:"StarGiftCategoryInStock"};function OF(a){const e=new Set;for(const h of a.giftOptions)e.add(String(h.raw.stars));const t=aR([...e.values()]),[s,i]=K("All");let n,r,o;const l=a.peer._==="user"&&[(()=>{const h=EF();return k(h,()=>P("GiftPremium")),h})(),(()=>{const h=kF();return k(h,T(oi,{key:"GiftTelegramPremiumDescription",get args(){return T(Rv,{get peerId(){return a.peerId},get onlyFirstName(){return a.peer._==="user"}})}})),h})(),(()=>{const h=TF();return k(h,T(Cs,{get each(){return a.premiumOptions},children:p=>(()=>{const m=xF(),g=m.firstChild,f=g.nextSibling,v=f.nextSibling;return m.$$click=()=>a.onGiftChosen(p),k(m,T(uI,{lottieLoader:Ns,class:"popup-send-gift-premium-option-sticker",get name(){return`Gift${p.months}`},size:84}),g),k(g,()=>Zr(p.months,!1)),k(f,()=>P("PremiumStickersShort")),k(v,()=>qi(p.price,p.currency)),k(m,(()=>{const y=V(()=>!!p.discountPercent);return()=>y()&&T(bh,{class:"popup-send-gift-premium-option-badge",textClass:"popup-send-gift-premium-option-badge-text",get children(){return["-",V(()=>Math.round(p.discountPercent)),"%"]}})})(),null),k(m,(()=>{const y=V(()=>!!p.priceStars);return()=>y()&&(()=>{const w=AF(),b=w.firstChild;return k(w,()=>P("PremiumOr"),b),k(b,T(ya,{}),null),k(b,()=>p.priceStars,null),w})()})(),null),m})()})),h})()],c=h=>(()=>{const p=RF();return p.$$click=m=>{const g=n.classList.contains("is-pinned");i(h);const f=m.target.closest(".popup-send-gift-category");$s(()=>{n.classList.contains("is-pinned")||o.scrollTo({top:n.offsetTop-56,behavior:g?"instant":"smooth"});const v=f.getBoundingClientRect(),y=Ko(f,r,!1,v);(!y||y.overflow.horizontal)&&Bu({element:f,container:r,position:"center",axis:"x"})})},k(p,(()=>{const m=V(()=>h in ZS);return()=>m()?P(ZS[h]):[T(ya,{}),h]})()),Me(()=>be(p,Ge("popup-send-gift-category",s()===h&&"active"))),p})(),d=V(()=>{const h=s();return h==="All"?a.giftOptions:h==="Limited"?a.giftOptions.filter(p=>p.raw.availability_total):h==="InStock"?a.giftOptions.filter(p=>p.raw.availability_remains>0):a.giftOptions.filter(p=>p.raw.stars.toString()===h)}),u=h=>{if(h.raw.availability_remains===0){ue.createPopup(iu,h);return}a.onGiftChosen(h)};return Jt(()=>{$s(()=>{o.style.setProperty("--height",`${o.offsetHeight}px`)})}),T(od,{ref(h){const p=o;typeof p=="function"?p(h):o=h},onScroll:()=>{o.classList.toggle("is-scrolled",o.scrollTop>0);const h=o.getBoundingClientRect(),p=n.getBoundingClientRect(),m=IF(p.top-h.top,56,.1);n.classList.toggle("is-pinned",m),o.classList.toggle("has-pinned-categories",m)},get children(){const h=FF(),p=h.firstChild,m=p.firstChild,g=p.nextSibling,f=g.firstChild,v=g.nextSibling,y=v.nextSibling,w=y.nextSibling,b=w.nextSibling;k(p,T(Pi,{icon:"close",get onClick(){return a.onClose}}),m),k(m,()=>P("Chat.Menu.SendGift")),k(g,T(Eg,{get peerId(){return a.peerId},size:100}),null),k(h,l,v),k(v,()=>P("Chat.Menu.SendGift")),k(y,T(oi,{key:"SendStarGiftSubtitle",get args(){return T(Rv,{get peerId(){return a.peerId},get onlyFirstName(){return a.peer._==="user"}})}}));const S=n;return typeof S=="function"?Ue(S,w):n=w,k(w,T(od,{axis:"x",ref(_){const M=r;typeof M=="function"?M(_):r=_},get children(){return[V(()=>c("All")),V(()=>c("Limited")),V(()=>c("InStock")),T(Cs,{each:t,children:c})]}})),k(b,T(fI,{class:"popup-send-gift-gifts-grid",get items(){return d()},view:"list",scrollParent:o,onClick:u})),Me(()=>Es(f,"src",`assets/img/${Tb("stars_pay")}.png`)),h}})}function UF(a){const e=P("StarGiftLimitedLeft",[a.gift.availability_remains]);e.classList.add("popup-send-gift-limited-progress-left");const t=100*a.gift.availability_remains/a.gift.availability_total;return(()=>{const s=BF(),i=s.firstChild,n=i.firstChild,r=n.nextSibling;return`linear-gradient(90deg, #fff ${t}%, var(--secondary-text-color) ${t}%)`!=null?r.style.setProperty("background-image",`linear-gradient(90deg, #fff ${t}%, var(--secondary-text-color) ${t}%)`):r.style.removeProperty("background-image"),k(r,e,null),k(r,()=>P("StarGiftLimitedSold",[a.gift.availability_total-a.gift.availability_remains]),null),Me(()=>`${100*a.gift.availability_remains/a.gift.availability_total}%`!=null?n.style.setProperty("width",`${100*a.gift.availability_remains/a.gift.availability_total}%`):n.style.removeProperty("width")),s})()}function HF(a){const[e,t]=K(),[s,i]=K(!1),[n,r]=K(!1),[o,l]=K(!1),[c,d]=K(!1),u=V(()=>({_:"messageService",pFlags:{out:!0},id:0,peer_id:{_:"peerUser",user_id:a.peerId.toUserId()},date:0,action:a.chosenGift.type==="stargift"?{_:"messageActionStarGift",gift:a.chosenGift.raw,pFlags:{}}:{_:"messageActionGiftPremium",currency:n()?Mo:a.chosenGift.currency,amount:n()?a.chosenGift.priceStars:a.chosenGift.price,months:a.chosenGift.months}}));async function h(){d(!0);let p;if(a.chosenGift.type==="stargift"){const g=a.peerId.isUser()?await I.managers.appUsersManager.getUserInputPeer(a.peerId.toUserId()):await I.managers.appChatsManager.getChannelInputPeer(a.peerId.toChatId());p={_:"inputInvoiceStarGift",pFlags:{hide_name:s()?!0:void 0,include_upgrade:o()?!0:void 0},message:e(),peer:g,gift_id:a.chosenGift.raw.id}}else{const g=n(),f=await I.managers.appUsersManager.getUserInput(a.peerId.toUserId());g?p={_:"inputInvoicePremiumGiftStars",user_id:f,months:a.chosenGift.months,message:e()}:p={_:"inputInvoicePremiumGiftCode",purpose:{_:"inputStorePaymentPremiumGiftCode",users:[f],currency:a.chosenGift.currency,amount:a.chosenGift.price,message:e()},option:a.chosenGift.raw}}(await Ln.create({inputInvoice:p,noShowIfStars:!0,purpose:"stargift"})).addEventListener("finish",g=>{g==="paid"||g==="pending"?a.onClose():d(!1)})}return(()=>{const p=DF(),m=p.firstChild,g=m.firstChild,f=m.nextSibling;return k(m,T(Pi,{icon:"back",get onClick(){return a.onBack}}),g),k(g,()=>P("Chat.Menu.SendGift")),k(m,Vg,null),k(f,T(od,{get children(){return[T(HR,{get peerId(){return a.peerId},class:"popup-send-gift-bubbles",get children(){return T(KR,{get message(){return u()},get children(){return V(()=>a.chosenGift.type==="stargift")()?T(bI,{get gift(){return a.chosenGift},get fromId(){return I.myId},get asUpgrade(){return o()},get ownerId(){return a.peerId},get message(){return e()},wrapStickerOptions:{play:!0,loop:!1}}):T(qp,{get title(){return P("ActionGiftPremiumTitle2",[Zr(a.chosenGift.months,!1)])},get subtitle(){return V(()=>!!e())()?jt(e().text,{entities:e().entities}):P("ActionGiftPremiumSubtitle2")},get buttonText(){return P("ActionGiftPremiumView")},get assetName(){return`Gift${a.chosenGift.months}`}})}})}}),(()=>{const v=QS();return k(v,(()=>{const y=V(()=>!!(a.chosenGift.type==="stargift"&&a.chosenGift.raw.availability_total));return()=>y()&&T(UF,{get gift(){return a.chosenGift.raw}})})(),null),k(v,T(Yy,{class:"popup-send-gift-form-input",placeholder:"StarGiftMessagePlaceholder",instanceRef:y=>{y.input.addEventListener("input",()=>{const w=xn(y.input,!0);t(w.value?{_:"textWithEntities",text:w.value,entities:w.entities}:void 0)})},get maxLength(){return bg()[0].appConfig.stargifts_message_length_max}}),null),k(v,(()=>{const y=V(()=>a.chosenGift.type==="stargift");return()=>y()&&T(En,{get title(){return P("StarGiftHideMyName")},get checkboxFieldToggle(){return T(xc,{get checked(){return s()},toggle:!0,onChange:i})}})})(),null),k(v,(()=>{const y=V(()=>!!("months"in a.chosenGift&&a.chosenGift.priceStars));return()=>y()&&T(En,{get title(){return T(oi,{key:"PayWithStars",get args(){return[T(ya,{}),Jr(a.chosenGift.priceStars)]}})},get checkboxFieldToggle(){return T(xc,{get checked(){return n()},toggle:!0,onChange:r})}})})(),null),v})(),(()=>{const v=XS();return k(v,(()=>{const y=V(()=>a.chosenGift.type==="stargift");return()=>y()?P("StarGiftHideMyNameHint",[jt(a.peerName),jt(a.peerName)]):""})()),v})(),V(()=>V(()=>!!(a.chosenGift.type==="stargift"&&a.chosenGift.raw.upgrade_stars))()&&[(()=>{const v=QS();return k(v,T(En,{get title(){return T(oi,{key:"StarGiftMakeUnique",get args(){return[T(ya,{}),Jr(a.chosenGift.raw.upgrade_stars)]}})},get checkboxFieldToggle(){return T(xc,{get checked(){return o()},toggle:!0,onChange:l})}})),v})(),(()=>{const v=XS();return k(v,T(oi,{key:"StarGiftMakeUniqueHint",get args(){return[jt(a.peerName),(()=>{const y=xi(()=>Kg.create(a.chosenGift,a.peerId));return y.append(P("StarGiftMakeUniqueLink")),y})()]}})),v})()])]}})),k(p,T(Za,{class:"popup-send-gift-form-send btn-primary btn-color-primary",onClick:h,get disabled(){return c()},get children(){return T(oi,{key:"StarGiftSend",get args(){return[(()=>{if(a.chosenGift.type==="stargift"){const v=a.chosenGift.raw;let y=v.stars;return o()&&(y=hI(y).add(v.upgrade_stars).toString()),qi(y,Mo)}return n()?qi(a.chosenGift.priceStars,Mo):qi(a.chosenGift.price,a.chosenGift.currency)})()]}})}}),null),p})()}function GF(){const a=Jl();return(()=>{const e=$F(),t=e.firstChild;return k(e,T(oi,{key:"StarsBalanceLong",get args(){return[T(ya,{}),(()=>{const s=NF();return k(s,a),s})()]}}),t),t.$$click=()=>ue.createPopup(ba),k(t,()=>P("GetMoreStars")),e})()}class wI extends ue{constructor(e){super("popup-send-gift",{title:"Chat.Menu.SendGift",closable:!0,overlayClosable:!0,body:!0,onBackClick:()=>{this.chosenGift()&&this.setChosenGift(void 0)}}),this.peerId=e,this.construct()}async construct(){const[e,t,s]=await Promise.all([this.peerId.isUser()?this.managers.appGiftsManager.getPremiumGiftOptions():[],this.managers.appGiftsManager.getStarGiftOptions(),this.managers.appPeersManager.getPeer(this.peerId)]),[i,n]=K();this.chosenGift=i,this.setChosenGift=n;const[r,o]=K(0);this.container.replaceChildren();const l=wi(()=>{const c=this;return[T(wF,{type:"navigation",transitionTime:150,animateFirst:!1,onTransitionStart:d=>{c.container.classList.toggle("is-chosen-gift",d===1)},onTransitionEnd:d=>{d===0&&c.setChosenGift(void 0)},get currentPage(){return r()},get children(){return[T(OF,{peer:s,get peerId(){return c.peerId},premiumOptions:e,giftOptions:t,onGiftChosen:d=>{n(d),o(1)},onClose:()=>c.hide()}),T(Js,{get when(){return i()!==void 0},get children(){return T(HF,{get peerId(){return c.peerId},get peerName(){return s._==="user"?s.first_name:s.title},get chosenGift(){return i()},onBack:()=>o(0),onClose:()=>c.hide()})}})]}}),T(GF,{})]},this.container);this.addEventListener("closeAfterTimeout",l),this.show()}}Fs(["click"]);const VF=a=>{const[,e]=wa(a,["class"]),t=ki(e);return vI(t,()=>a.class),t},Of=Y("<span>"),zF=Y("<div><div class=popup-star-gift-info-header><div class=popup-star-gift-info-title></div></div><div class=popup-star-gift-info-table>"),WF=Y("<div class=popup-star-gift-info-subtitle-unavailable>"),KF=Y("<div class=popup-star-gift-info-price>"),jF=Y("<div class=popup-star-gift-info-subtitle> <a href=https://telegram.org/blog/telegram-stars target=_blank>"),qF=Y("<div class=popup-star-gift-info-subtitle>"),YF=Y("<div class=popup-star-gift-info-actions>"),QF=Y("<div class=popup-star-gift-info-hint>"),XF=Y("<a href=#>");function Uf(a){return T(Kp,{onClick:e=>{Ra({element:e.target,vertical:"top",container:document.body,class:"popup-star-gift-info-tooltip",textElement:P("StarGiftAttributeTooltip",[`${a.permille/10}%`])})},get children(){return[V(()=>a.permille/10),"%"]}})}class iu extends ue{constructor(e){super("popup-star-gift-info",{closable:!0,overlayClosable:!0,body:!0,footer:!0,withConfirm:"OK",withFooterConfirm:!0}),this.gift=e,this.construct()}_construct(){const e=this,{saved:t,raw:s,sticker:i,isIncoming:n,isConverted:r,collectibleAttributes:o,input:l}=this.gift,c=!t&&s.availability_remains===0,d=t?it(t.from_id):Wt,u=t?new Date(t.date*1e3):null,h=s.first_sale_date?new Date(s.first_sale_date*1e3):null,p=s.last_sale_date?new Date(s.last_sale_date*1e3):null,m=s.stars,g=s._==="starGiftUnique"&&it(s.owner_id)===I.myId&&t!==void 0,f=s._==="starGift"&&n&&!r||g;if(f){this.btnConfirm.replaceChildren(P(t.pFlags.unsaved?"StarGiftDisplayOnMyPage":"StarGiftHideFromMyPage"));let b=!1;J(this.btnConfirm,()=>{b||(b=!0,this.managers.appGiftsManager.toggleGiftHidden(l,!t.pFlags.unsaved).then(()=>{this.hide()}))})}else J(this.btnConfirm,()=>this.hide());const v=V(()=>{const b=this,S=this,_=this,M=this,C=[];if(s._==="starGiftUnique")return s.owner_id&&C.push(["StarGiftOwner",T(Pm,{get peerId(){return it(s.owner_id)},onClick:()=>{Ce.setInnerPeer({peerId:it(s.owner_id)}),b.hide()}})]),C.push(["StarGiftModel",[V(()=>o.model.name),T(Uf,{get permille(){return o.model.rarity_permille}})]]),C.push(["StarGiftBackdrop",[V(()=>o.backdrop.name),T(Uf,{get permille(){return o.backdrop.rarity_permille}})]]),C.push(["StarGiftPattern",[V(()=>o.pattern.name),T(Uf,{get permille(){return o.pattern.rarity_permille}})]]),C.push(["StarGiftAvailability",P("StarGiftAvailabilityIssued",[ln(s.availability_issued),ln(s.availability_total)])]),C;d!==Wt&&C.push(["StarGiftFromShort",[T(Pm,{peerId:d}),T(Kp,{text:"StarGiftSendInline",onClick:()=>{S.hide(),ue.createPopup(wI,d)}})]]),u&&C.push(["StarGiftDate",(()=>{const E=Of();return k(E,()=>gs(u.getTime()/1e3|0)),E})()]),c&&(h&&C.push(["StarGiftUnavailableFirstSale",(()=>{const E=Of();return k(E,()=>gs(h.getTime()/1e3|0)),E})()]),p&&C.push(["StarGiftUnavailableLastSale",(()=>{const E=Of();return k(E,()=>gs(p.getTime()/1e3|0)),E})()]));const L=t?.convert_stars&&n&&!r&&Qs(!0)-(u.getTime()/1e3|0)<bg()[0].appConfig.stargifts_convert_period_max;return C.push(["StarGiftValue",[T(ya,{}),m,L&&T(Kp,{text:"StarGiftConvertButton",get textArgs(){return[t.convert_stars]},onClick:()=>{I.managers.appGiftsManager.convertGift(l).then(()=>{_.hide()}).catch(()=>{$e({langPackKey:"Error.AnError"})})}})]]),s.availability_total>0&&C.push(["StarGiftAvailability",P("StarGiftAvailabilityValue",[ln(s.availability_remains??0),ln(s.availability_total)])]),s._==="starGift"&&t?.pFlags.can_upgrade&&C.push(["StarGiftStatus",[V(()=>P("StarGiftStatusNonUnique")),n&&T(Kp,{text:"StarGiftStatusUpgrade",onClick:()=>Kg.create(M.gift).then(()=>M.hide())})]]),C}),y=()=>{if(o?.original){const b=M=>{const C=this,L=it(M);return T(Cl,{peerId:L,onlyFirstName:!0,onClick:()=>{Ce.setInnerPeer({peerId:L}),C.hide()}})};let S;const _=[];if(o.original.sender_id?(S=o.original.message?"StarGiftOriginalDetailsSenderComment":"StarGiftOriginalDetailsSender",_.push(b(o.original.sender_id))):S=o.original.message?"StarGiftOriginalDetailsComment":"StarGiftOriginalDetailsBasic",_.push(b(o.original.recipient_id)),_.push(Dy(new Date(o.original.date*1e3))),o.original.message){const M=document.createElement("span");M.append(jt(o.original.message.text,{entities:o.original.message.entities})),_.push(M)}return T(oi,{class:"popup-star-gift-info-original",key:S,args:_})}if(t?.message)return jt(t.message.text,{entities:t.message.entities})},w=()=>{Rs.createSharingPicker2().then(b=>{I.managers.appMessagesManager.sendText({peerId:b,text:"https://t.me/nft/"+s.slug}),Ce.setInnerPeer({peerId:b}),this.hide()})};return(()=>{const b=zF(),S=b.firstChild,_=S.firstChild,M=S.nextSibling;return k(S,(()=>{const C=V(()=>s._==="starGiftUnique");return()=>C()&&T(qu,{class:"popup-star-gift-info-backdrop",get backdrop(){return o.backdrop},get patternEmoji(){return o.pattern.document}})})(),_),k(S,T(Pi,{class:"popup-star-gift-info-close",icon:"close",onClick:()=>e.hide()}),_),k(S,T(VF,{class:"popup-star-gift-info-menu-toggle",icon:"more",direction:"bottom-left",get buttons(){return[{icon:t?.pFlags.pinned_to_top?"unpin":"pin",text:t?.pFlags.pinned_to_top?"StarGiftUnpin":"StarGiftPin",verify:()=>g,onClick:()=>{e.managers.appGiftsManager.togglePinnedGift(l).then(()=>{e.hide()})}},{icon:"forward",text:"ShareFile",onClick:w},{icon:"link",text:"CopyLink",onClick:()=>{si("https://t.me/nft/"+s.slug),$e({langPackKey:"LinkCopied"})}}]}}),_),k(S,T(qy,{class:"popup-star-gift-info-sticker",sticker:i,width:120,height:120,extraOptions:{play:!0,loop:!1}}),_),k(_,(()=>{const C=V(()=>s._==="starGift");return()=>C()?P(c?"StarGiftUnavailableTitle":n?"StarGiftReceivedTitle":"StarGiftTitle"):s.title})()),k(S,T(Js,{get when(){return s._==="starGift"},get children(){return[V(()=>c?(()=>{const C=WF();return k(C,()=>P("StarGiftUnavailableSubtitle")),C})():(()=>{const C=KF();return k(C,T(ya,{}),null),k(C,m,null),C})()),V(()=>n&&!r&&(()=>{const C=jF(),L=C.firstChild,E=L.nextSibling;return k(C,()=>P("StarGiftReceivedSubtitle",[t.convert_stars]),L),k(E,()=>P("StarGiftReceivedSubtitleLink")),C})())]}}),null),k(S,(()=>{const C=V(()=>s._==="starGiftUnique");return()=>C()&&(()=>{const L=qF();return k(L,()=>P("StarGiftCollectibleNum",[ln(s.num,",")])),L})()})(),null),k(S,g&&(()=>{const C=YF();return k(C,T(Za,{class:"popup-star-gift-info-action",icon:"gem_transfer",text:"StarGiftTransfer",onClick:()=>mI(e.gift).then(L=>{L&&e.hide()})}),null),k(C,T(Za,{class:"popup-star-gift-info-action",icon:"crown",text:"StarGiftWear",onClick:()=>{pI(s.id).then(L=>{L&&e.hide()})}}),null),k(C,T(Za,{class:"popup-star-gift-info-action",icon:"forward_filled",text:"StarGiftShare",onClick:w}),null),C})(),null),k(M,T(Rb,{get content(){return v()},get footer(){return y()},cellClass:"popup-star-gift-info-table-cell",get footerClass(){return s._==="starGiftUnique"?"popup-star-gift-info-footer-unique":void 0}})),k(b,f&&(()=>{const C=QF();return k(C,(()=>{const L=V(()=>!!t.pFlags.unsaved);return()=>L()?P("StarGiftHiddenHint"):[V(()=>P("StarGiftVisibleHint"))," ",(()=>{const E=XF();return k(E,()=>P("StarGiftVisibleHintLink")),E})()]})()),C})(),null),Me(()=>be(b,`popup-star-gift-info-container ${s._==="starGiftUnique"?"is-collectible":""}`)),b})()}async construct(){this.header.remove(),this.appendSolid(()=>this._construct()),this.show()}}class ZF{constructor(){this.processMessageLink=e=>{const t=e.post?+e.post:void 0,s=e.comment?+e.comment:void 0,i=e.thread?+e.thread:void 0;return Ce.openUsername({userName:e.domain,lastMsgId:t,commentId:s,startParam:e.start,stack:e.stack,threadId:i,mediaTimestamp:e.t&&+e.t,text:e.text})},this.processPrivatePostLink=async e=>{const t=e.channel.toChatId(),s=await this.managers.appChatsManager.getChat(t);if(!s)try{await this.managers.appChatsManager.resolveChannel(t)}catch(r){throw $e({langPackKey:"LinkNotFound"}),r}const i=+e.post,n=e.thread?+e.thread:void 0;return Ce.op({peer:s,lastMsgId:i,threadId:n,stack:e.stack,mediaTimestamp:e.t&&+e.t})},this.processStickerSetLink=e=>{const t=ue.createPopup(ga,{id:e.set},e._===Ct.EMOJI_SET);return t.show(),t},this.processJoinChatLink=e=>this.managers.appChatInvitesManager.checkChatInvite(e.invite).then(async t=>{if(t._==="chatInviteAlready"||t._==="chatInvitePeek"){Ce.setInnerPeer({peerId:t.chat.id.toPeerId(!0)});return}if(t.subscription_pricing&&!t.pFlags.can_refulfill_subscription){const s={_:"inputInvoiceChatInviteSubscription",hash:e.invite},i=await Ln.create({inputInvoice:s,chatInvite:t,noPaymentForm:!0});return i.addEventListener("finish",n=>{n==="paid"&&this.processJoinChatLink(e)}),i}return ue.createPopup(Lm,e.invite,t)},t=>{t.type==="INVITE_HASH_EXPIRED"&&Wi(P("InviteExpired"))}),this.processVoiceChatLink=async e=>{const t=s=>{if(Ce.chat.peerId!==s)return Ce.setInnerPeer({peerId:s})};if(e.livestream!==void 0){const i=(await this.managers.appUsersManager.resolveUsername(e.domain)).id.toPeerId(!0);return await t(i),Ce.joinLiveStream(i)}if(Uh&&e.id){const s=e.chat_id.toPeerId(!0);return await t(s),Ce.joinGroupCall(s,e.id)}},this.processUserPhoneNumberLink=e=>this.managers.appUsersManager.resolvePhone(e.phone).then(t=>Ce.setInnerPeer({peerId:t.id.toPeerId(!1),text:e.text})).catch(t=>{t.type==="PHONE_NOT_OCCUPIED"&&$e({langPackKey:"Alert.UserDoesntExists"})}),this.processInvoiceLink=e=>this.managers.appPaymentsManager.getInputInvoiceBySlug(e.slug).then(t=>this.managers.appPaymentsManager.getPaymentForm(t).then(s=>Ln.create({inputInvoice:t,paymentForm:s}),s=>{throw s.type==="SLUG_INVALID"&&$e({langPackKey:"PaymentInvoiceLinkInvalid"}),s})),this.processAttachMenuBotLink=async e=>{const t=e.attach||e.domain||e.nestedLink.domain,s=await this.managers.appUsersManager.resolveUserByUsername(t).catch(()=>{});let i;e.attach!==void 0&&(i=this.processInternalLink(e.nestedLink));let n;if(s?s.pFlags.bot_attach_menu||(n="BotCantAddToAttachMenu"):n="Alert.UserDoesntExists",n){$e({langPackKey:n});return}i&&await i;const r=await Ce.toggleBotInAttachMenu(s.id,!0);if(e.choose){const o=e.choose.split("+"),l={bots:"attachMenuPeerTypeBotPM",users:"attachMenuPeerTypePM",groups:"attachMenuPeerTypeChat",channels:"attachMenuPeerTypeBroadcast"},c=o.filter(u=>{const h=l[u];return r.peer_types.some(p=>p._===h)}),d=await Rs.createPicker(c);await Ce.setInnerPeer({peerId:d})}Ce.chat.openWebApp({attachMenuBot:r,startParam:e.startattach})},this.processWebAppLink=async e=>{const t=await this.managers.appUsersManager.resolveUserByUsername(e.domain).catch(()=>{});if(!t){$e({langPackKey:"Alert.UserDoesntExists"});return}const s=t.id,i={compact:e.mode==="compact",startParam:e.startapp,botId:s};if(!e.appname){if(!t.pFlags.bot_has_main_app){$e({langPackKey:"Alert.BotAppDoesntExist"});return}e.masked&&await Ce.confirmBotWebViewInner({botId:s}),Ce.chat.openWebApp({...i,main:!0});return}let n;try{n=await this.managers.appAttachMenuBotsManager.getBotApp(s,e.appname)}catch(l){if(l.type==="BOT_APP_INVALID"){$e({langPackKey:"Alert.BotAppDoesntExist"});return}else throw l}const r=t.pFlags.bot_attach_menu&&await Ce.toggleBotInAttachMenu(s,!0);let o;r||(e.masked||n.pFlags.inactive)&&(o=await Ce.confirmBotWebViewInner({botId:s,requestWriteAccess:n.pFlags.request_write_access,showDisclaimer:t.pFlags.bot_attach_menu&&n.pFlags.inactive})),Ce.chat.openWebApp({...i,attachMenuBot:r,writeAllowed:o,app:n.app,noConfirmation:!r,hasSettings:n.pFlags.has_settings})},this.processListLink=async e=>{let t;try{t=await this.managers.filtersStorage.checkChatlistInvite(e.slug)}catch(s){if(s.type==="INVITE_SLUG_EXPIRED"){$e({langPackKey:"SharedFolder.Link.Expired"});return}throw s}ue.createPopup(Sb,{chatlistInvite:t,slug:e.slug})},this.processStoryLink=async e=>{const t=window.event,s=ne(t.target,"bubble");if(s&&s.classList.contains("story")){Xs(s.querySelector(".media-container").querySelector("img, video"));return}let i;try{i=await this.managers.appUsersManager.resolveUsername(e.domain)}catch(o){o.type==="USERNAME_NOT_OCCUPIED"?$e({langPackKey:"NoUsernameFound"}):console.error(o);return}const n=i.id.toPeerId(i._!=="user");if(!await this.managers.appStoriesManager.getStoryById(n,+e.story)){$e({langPackKey:"NoStoryFound"});return}Fo({peerId:n,id:+e.story})},this.processBoostLink=async e=>{let t=e.channel?e.channel.toPeerId(!0):void 0;t===void 0&&(t=(await this.managers.appUsersManager.resolveUsername(e.domain)).id.toPeerId(!0)),ue.createPopup(sR,t)},this.processPremiumFeaturesLink=async e=>{if(I.premium){$e({langPackKey:"Premium.Offset.AlreadyHave"});return}rs.show()},this.processGiftCodeLink=e=>{ue.createPopup(Ir,e.slug,e.stack)},this.processBusinessChatLink=async e=>{const t=await this.managers.appBusinessManager.resolveBusinessChatLink(e.slug);Ce.setInnerPeer({peerId:t.peerId,text:t.message,entities:t.entities})},this.processStarsTopupLink=async e=>{const t=Ht(),s=+await $1(t.get());t.destroy();const i=e.purpose||"topup",n=+e.balance;if(s>=n){$e({langPackKey:"Stars.TopUp.Enough",langPackArguments:[xi(()=>{no();const o=ue.createPopup(ba,{onTopup:()=>{o.hide()},purpose:i})})]});return}const r=ue.createPopup(ba,{itemPrice:n,onTopup:()=>{r.hide()},purpose:i})},this.processShareLink=async e=>{const t=await Rs.createSharingPicker2();Ce.setInnerPeer({peerId:t,text:[e.url,e.text].filter(Boolean).join(`
- `)})},this.processUniqueStarGiftLink=async e=>{const t=await this.managers.appGiftsManager.getGiftBySlug(e.slug).catch(as);if(!t){$e({langPackKey:"Error.AnError"});return}ue.createPopup(iu,t)}}construct(e){this.managers=e,ei({name:"showMaskedAlert",callback:(t,s)=>{const i=s.href,n=s.cloneNode(!0);n.className="anchor-url",n.innerText=i,n.removeAttribute("onclick");const r=ue.createPopup(mi,"popup-masked-url",{titleLangKey:"OpenUrlTitle",descriptionLangKey:"OpenUrlAlert2",descriptionLangArgs:[n],buttons:[{langKey:"Open",callback:()=>{n.click()}}]});return r.show(),r}}),ei({name:"execBotCommand",callback:({uriParams:t})=>{const{command:s,bot:i}=t;return this.managers.appMessagesManager.sendText({peerId:Ce.chat.peerId,text:"/"+s+(i?"@"+i:"")})}}),ei({name:"searchByHashtag",callback:({uriParams:t})=>{const{hashtag:s}=t;if(s)return Ce.chat.initSearch({query:"#"+s+" "})}}),ei({name:"setMediaTimestamp",callback:(t,s)=>{const i=+s.dataset.timestamp;if(ne(s,"bubble")){Ce.chat.bubbles.playMediaWithTimestamp(s,i);return}if(ne(s,"media-viewer-caption"))return window.appMediaViewer.setMediaTimestamp(i)}}),[["addstickers",Ct.STICKER_SET],["addemoji",Ct.EMOJI_SET]].forEach(([t,s])=>{ei({name:t,callback:({pathnameParams:i})=>{if(!i[1])return;const n={_:s,set:i[1]};return this.processInternalLink(n)}}),ei({name:t,protocol:"tg",callback:({uriParams:i})=>{const n=this.makeLink(s,i);return this.processInternalLink(n)}})}),ei({name:"invoice",callback:({pathnameParams:t})=>{const s={_:Ct.INVOICE,slug:t.length>1?t[1]:t[0].slice(1)};return this.processInternalLink(s)}}),ei({name:"addlist",callback:({pathnameParams:t})=>{const s={_:Ct.ADD_LIST,slug:t[1]};return this.processInternalLink(s)}}),ei({name:"joinchat",callback:({pathnameParams:t})=>{const s={_:Ct.JOIN_CHAT,invite:t[1]||decodeURIComponent(t[0]).slice(1)};return this.processInternalLink(s)}}),Uh&&ei({name:"voicechat",protocol:"tg",callback:({uriParams:t})=>{const s=this.makeLink(Ct.VOICE_CHAT,t);return this.processInternalLink(s)}}),ei({name:"im",callback:async({pathnameParams:t,uriParams:s},i,n)=>{let r;if("voicechat"in s||"videochat"in s||"livestream"in s)r={_:Ct.VOICE_CHAT,domain:t[0],...s};else if("boost"in s||t?.[0]==="boost"){const o=t?.[0]==="c"?t[1]:s.c;r={_:Ct.BOOST,domain:o?void 0:"boost"in s?t[0]:t[1],channel:o}}else if(t?.[1]==="s")r={_:Ct.STORY,domain:t[0],story:t[2]};else if(AL.test(t[0]))r={_:Ct.USER_PHONE_NUMBER,phone:t[0],text:s.text};else if(t[0]==="c"){t.shift();const o="thread"in s?s.thread:t[2]&&t[1];r={_:Ct.PRIVATE_POST,channel:t[0],post:t[2]||t[1],thread:o,comment:s.comment,stack:Ce.getStackFromElement(i),t:s.t}}else if(t[1]?tT(t[1]):s.startapp!==void 0)r={_:Ct.WEB_APP,domain:t[0],appname:t[1],startapp:s.startapp,masked:n,mode:s.mode};else{const o="thread"in s?s.thread:t[2]&&t[1];r={_:Ct.MESSAGE,domain:t[0],post:t[2]||t[1],thread:o,comment:s.comment,start:"start"in s?s.start:void 0,stack:Ce.getStackFromElement(i),t:s.t,text:s.text}}return("startattach"in s||"attach"in s)&&(r={_:Ct.ATTACH_MENU_BOT,nestedLink:r,...s}),this.processInternalLink(r)}}),ei({name:"resolve",protocol:"tg",callback:({uriParams:t},s,i)=>{let n;if(t.voicechat!==void 0||t.videochat!==void 0||t.livestream!==void 0?n=this.makeLink(Ct.VOICE_CHAT,t):t.story?n=this.makeLink(Ct.STORY,t):t.phone?n=this.makeLink(Ct.USER_PHONE_NUMBER,t):t.domain==="telegrampassport"||((t.appname||t.startapp)!==void 0?n=this.makeLink(Ct.WEB_APP,{masked:i,...t}):n=this.makeLink(Ct.MESSAGE,{...t,stack:Ce.getStackFromElement(s)})),t.attach!==void 0||t.startattach!==void 0){const r=n;n=this.makeLink(Ct.ATTACH_MENU_BOT,t),n.nestedLink=r}return this.processInternalLink(n)}}),ei({name:"privatepost",protocol:"tg",callback:({uriParams:t})=>{const s=this.makeLink(Ct.PRIVATE_POST,t);return this.processInternalLink(s)}}),ei({name:"invoice",protocol:"tg",callback:({uriParams:t})=>{const s=this.makeLink(Ct.INVOICE,t);return this.processInternalLink(s)}}),ei({name:"addlist",protocol:"tg",callback:({uriParams:t})=>{const s=this.makeLink(Ct.ADD_LIST,t);return this.processInternalLink(s)}}),["joinchat","join"].forEach(t=>{ei({name:t,protocol:"tg",callback:({uriParams:s})=>{const i=this.makeLink(Ct.JOIN_CHAT,s);return this.processInternalLink(i)}})}),ei({name:"boost",protocol:"tg",callback:({uriParams:t})=>{const s=this.makeLink(Ct.BOOST,t);return this.processInternalLink(s)}}),ei({name:"boost",callback:({pathnameParams:t})=>{const s={_:Ct.BOOST,domain:t[1]};return this.processInternalLink(s)}}),ei({name:"premium_offer",protocol:"tg",callback:({uriParams:t})=>{const s=this.makeLink(Ct.PREMIUM_FEATURES,t);return this.processInternalLink(s)}}),ei({name:"giftcode",callback:({pathnameParams:t},s)=>{const i={_:Ct.GIFT_CODE,slug:t[1],stack:Ce.getStackFromElement(s)};return this.processInternalLink(i)}}),ei({name:"giftcode",protocol:"tg",callback:({uriParams:t},s)=>{const i=this.makeLink(Ct.GIFT_CODE,t);return i.stack=Ce.getStackFromElement(s),this.processInternalLink(i)}}),ei({name:"m",callback:({pathnameParams:t})=>{const s={_:Ct.BUSINESS_CHAT,slug:t[1]};return this.processInternalLink(s)}}),ei({name:"message",protocol:"tg",callback:({uriParams:t})=>{const s=this.makeLink(Ct.BUSINESS_CHAT,t);return this.processInternalLink(s)}}),ei({name:"stars_topup",protocol:"tg",callback:({uriParams:t})=>{const s=this.makeLink(Ct.STARS_TOPUP,t);return this.processInternalLink(s)}}),ei({name:"share",callback:({pathnameParams:t,uriParams:s})=>{const i={_:Ct.SHARE,url:s.url,text:s.text};return this.processInternalLink(i)}}),ei({name:"msg_url",protocol:"tg",callback:({uriParams:t})=>{const s={_:Ct.SHARE,url:t.url,text:t.text};return this.processInternalLink(s)}}),ei({name:"nft",callback:({pathnameParams:t})=>{const s={_:Ct.UNIQUE_STAR_GIFT,slug:t.slice(1).join("/")};return this.processInternalLink(s)}}),ei({name:"nft",protocol:"tg",callback:({uriParams:t})=>{const s=this.makeLink(Ct.UNIQUE_STAR_GIFT,t);return this.processInternalLink(s)}})}makeLink(e,t){return{_:e,...t}}processInternalLink(e){const s={[Ct.MESSAGE]:this.processMessageLink,[Ct.PRIVATE_POST]:this.processPrivatePostLink,[Ct.EMOJI_SET]:this.processStickerSetLink,[Ct.STICKER_SET]:this.processStickerSetLink,[Ct.JOIN_CHAT]:this.processJoinChatLink,[Ct.VOICE_CHAT]:this.processVoiceChatLink,[Ct.USER_PHONE_NUMBER]:this.processUserPhoneNumberLink,[Ct.INVOICE]:this.processInvoiceLink,[Ct.ATTACH_MENU_BOT]:this.processAttachMenuBotLink,[Ct.WEB_APP]:this.processWebAppLink,[Ct.ADD_LIST]:this.processListLink,[Ct.STORY]:this.processStoryLink,[Ct.BOOST]:this.processBoostLink,[Ct.PREMIUM_FEATURES]:this.processPremiumFeaturesLink,[Ct.GIFT_CODE]:this.processGiftCodeLink,[Ct.BUSINESS_CHAT]:this.processBusinessChatLink,[Ct.STARS_TOPUP]:this.processStarsTopupLink,[Ct.SHARE]:this.processShareLink,[Ct.UNIQUE_STAR_GIFT]:this.processUniqueStarGiftLink}[e._];if(!s){console.warn("Not supported internal link:",e);return}return s(e)}}const Yu=new ZF;Di&&(Di.internalLinkProcessor=Yu);function SI(){return window.getSelection?window.getSelection().toString():document.selection?document.selection.createRange().text:""}const JF=Y("<span class=delimiter-with-text><span class=delimiter-with-text-stripe></span><span class=delimiter-with-text-stripe>"),eB=Y("<a class=bubble-giveaway-link>"),tB=Y("<b>"),sB=Y("<br>"),JS=Y("<div class=bubble-giveaway-channels>"),iB=Y("<div class=bubble-giveaway-countries>"),nB=Y("<div class=bubble-giveaway-and-more>"),aB=Y("<div><div class=bubble-giveaway-sticker><div></div></div><div class=bubble-giveaway-row><div class=bubble-giveaway-row-title></div></div><div class=bubble-giveaway-row><div class=bubble-giveaway-row-title></div></div><div class=bubble-giveaway-row><div class=bubble-giveaway-row-title>");function Yv(a){return{3:"Gift3",6:"Gift6",12:"Gift12"}[zt(a??0,3,12)]}function CI(a){return(()=>{const e=JF(),t=e.firstChild,s=t.nextSibling;return k(e,()=>P(a.langKey),s),e})()}async function rB(a){const e=a.media,t=await I.managers.appPaymentsManager.getGiveawayInfo(a.peerId,a.mid),s=document.createDocumentFragment(),i=Zr(e.months,!0),n=a.fwdFromId||a.peerId,r=e._==="messageMediaGiveawayResults",o=t._==="payments.giveawayInfoResults",l=o&&t.pFlags.refunded,c=!l&&o&&t.pFlags.winner,d=!o&&t.pFlags.participating,u=!!e.stars,h=e.pFlags.only_new_subscribers,p=r?e.winners_count+e.unclaimed_count:e.quantity,m=r?e.additional_peers_count||0:e.channels.length-1,g=L=>gs(L,void 0,!0);let f="Giveaway.Info";const v=[g(o?t.finish_date:e.until_date),P("Giveaway.Info.Users",[p]),await qe({peerId:n})];m&&(f+=".Several",v.push(P("Giveaway.Info.OtherChannels",[m]))),h&&(f+=".Date",v.push(g(t.start_date))),o&&(f+=".End");let y,w,b;l?y="BoostingGiveawayCanceledByPayment":c?(y="Giveaway.Won",w=[je("🏆")],b=!0):o?(y="BoostingGiveawayYouNotWon",b=!0):t.joined_too_early_date?(y="BoostingGiveawayNotEligible",w=[g(t.joined_too_early_date)]):t.disallowed_country?y="BoostingGiveawayNotEligibleCountry":t.admin_disallowed_chat_id?(y="BoostingGiveawayNotEligibleAdmin",w=[await qe({peerId:t.admin_disallowed_chat_id.toPeerId(!0)})]):(y=d?"Giveaway.Participation":"Giveaway.TakePart",w=[await qe({peerId:n})],m&&(y+=".Multi",w.push(P("Giveaway.Info.OtherChannels",[m]))),!d&&t.start_date&&w.push(g(e.until_date)));let S;u?S=o?"BoostingStarsGiveawayHowItWorksTextEnd":"BoostingStarsGiveawayHowItWorksText":S=o?"BoostingGiveawayHowItWorksTextEnd":"BoostingGiveawayHowItWorksText";const _=P(S,[e.stars||p,await qe({peerId:n}),p,i]),M=P(f,v),C=P(y,w);(b||l)&&C.classList.add("popup-description-framed"),l&&C.classList.add("popup-description-danger"),s.append(...[...b?[C,document.createElement("br")]:[],_,document.createElement("br"),document.createElement("br"),...e.prize_description?[P("Giveaway.AlsoPrizes",[await qe({peerId:n}),p,je(e.prize_description),P("Giveaway.AlsoPrizes2",[p])]),document.createElement("br"),document.createElement("br")]:[],M,...o&&t.activated_count?[" ",P("BoostingGiveawayUsedLinksPlural",[t.activated_count])]:[],...b?[]:[document.createElement("br"),document.createElement("br"),C]].filter(Boolean)),await Rt({titleLangKey:o?"BoostingGiveawayEnd":"BoostingGiveAwayAbout",description:s,button:c?{langKey:"BoostingGiveawayViewPrize"}:{langKey:"OK",isCancel:!0}}),c&&ue.createPopup(Ir,t.gift_code_slug)}function oB(a){const e=ui().get(),t=a.giveaway,s=t._==="messageMediaGiveawayResults",i=s?t.stars??t.winners_count:t.stars??t.quantity,n=!s&&t.countries_iso2?.map(f=>{const v=document.createElement("span");v.classList.add("bubble-giveaway-country");const y=Ne.countriesList.find(w=>w.iso2===f);return v.append(je(vv(f)+" "+(y.name||y.default_name))),v}),r=Zr(t.months,!0);let o;if(s){let f;(()=>{const v=eB(),y=f;return typeof y=="function"?Ue(y,v):f=v,Me(()=>Es(v,"data-saved-from",`${t.channel_id.toPeerId(!0)}_${t.launch_msg_id}`)),v})(),o=V(()=>P("Giveaway.Results.Subtitle",[t.winners_count,f]))}else o=t.prize_description?[(()=>{const f=tB();return k(f,`${i} `),f})(),V(()=>je(t.prize_description)),T(CI,{langKey:"Giveaway.With"}),V((()=>{const f=V(()=>!!t.stars);return()=>f()?P("Giveaway.WithStars",[t.quantity,P("Giveaway.WithStars.Stars",[+t.stars])]):P(+i>1?"Giveaway.WithSubscriptionsPlural":"Giveaway.WithSubscriptionsSingle",[r])})())]:[V(()=>P(t.stars?"BoostingStarsGiveawayMsgInfoPlural1":"BoostingGiveawayMsgInfoPlural1",[i])),sB(),V(()=>P(t.stars?"BoostingStarsGiveawayMsgInfoPlural2":"BoostingGiveawayMsgInfoPlural2",[t.stars?t.quantity:r]))];const l=f=>{const v=wn.renderEntity({key:f,middleware:e,avatarSize:30,meAsSaved:!1});return Ce.setPeerColorToElement({peerId:f,element:v.element}),v.element.classList.add("bubble-giveaway-channel","hover-primary"),v.element},c=!s&&(()=>{const f=JS();return k(f,T(Cs,{get each(){return t.channels},children:v=>l(v.toPeerId(!0))})),f})(),d=n&&(()=>{const f=iB();return k(f,()=>P("BoostingGiveAwayFromCountries",[Yi(n)])),f})();let u;s?u=[(()=>{const f=JS();return k(f,T(Cs,{get each(){return t.winners},children:v=>l(v.toPeerId(!1))})),f})(),V((()=>{const f=V(()=>t.winners_count>t.winners.length);return()=>f()&&(()=>{const v=nB();return k(v,()=>P("Giveaway.Results.AndMore",[t.winners_count-t.winners.length])),v})()})())]:u=[V(()=>P(t.pFlags.only_new_subscribers?"BoostingGiveawayMsgNewSubsPlural":"BoostingGiveawayMsgAllSubsPlural",[t.channels.length])),c,d];let h;const p=(()=>{const f=aB(),v=f.firstChild,y=v.firstChild,w=v.nextSibling,b=w.firstChild,S=w.nextSibling,_=S.firstChild,M=S.nextSibling,C=M.firstChild,L=h;return typeof L=="function"?Ue(L,v):h=v,k(y,(()=>{const E=V(()=>!!t.stars);return()=>E()&&T(hs,{icon:"star"})})(),null),k(y,()=>t.stars?` ${i}`:`X${i}`,null),k(b,()=>P(s?"Giveaway.Results.Title":"BoostingGiveawayPrizes",[s?t.winners_count:i])),k(w,o,null),k(_,()=>P(s?"BoostingGiveawayResultsMsgWinners":"BoostingGiveawayMsgParticipants",[s?t.winners_count:i])),k(S,u,null),k(C,(()=>{const E=V(()=>!!(s&&t.stars));return()=>E()?P((t.winners_count>1,"Giveaway.Results.Stars.Winners.Single"),[P("Giveaway.Results.Stars.Winners.Stars",[i])]):P(s?"Giveaway.Results.Footer":"BoostingWinnersDate",[i,t.stars])})()),k(M,()=>!s&&gs(t.until_date),null),Me(E=>{const x=Ge("bubble-giveaway","no-select","disable-hover",s&&"bubble-giveaway-results"),R=Ge("bubble-giveaway-sticker-counter",t.stars&&"bubble-giveaway-sticker-counter-stars");return x!==E._v$&&be(f,E._v$=x),R!==E._v$2&&be(y,E._v$2=R),E},{_v$:void 0,_v$2:void 0}),f})(),m=s?80:160,g=Dg({width:m,height:m,assetName:s?"Congratulations":Yv(t.months),middleware:e,loop:!1,autoplay:wt.isAvailable("stickers_chat")}).then(({container:f,promise:v})=>(h.style.position="relative",h.style.width=h.style.height=m+"px",h.append(f),v));return a.loadPromises.push(g),p}function lB(a,e){const t=[];for(;a.parentElement&&a.parentElement!==document.body&&(a=a.parentElement,t.push(a),!(e&&a.matches(e))););return t}const cB=Y("<span class=similar-channels-channel-badge>"),dB=Y("<div>"),hB=Y("<div class=similar-channels-channel-avatar-stack><div class=similar-channels-channel-avatar-stack-middle></div><div class=similar-channels-channel-avatar-stack-last>"),uB=Y("<div class=similar-channels-list>"),e0=Y("<div class=similar-channels-list-margin>"),pB=Y('<div class=similar-channels-container><svg class=similar-channels-notch width=19 height=7 viewBox="0 0 19 7"fill=none xmlns=http://www.w3.org/2000/svg><path class=similar-channels-notch-path fill-rule=evenodd clip-rule=evenodd d="M19 7C16.8992 7 13.59 3.88897 11.5003 1.67424C10.7648 0.894688 10.397 0.50491 10.0434 0.385149C9.70568 0.270811 9.4225 0.270474 9.08456 0.38401C8.73059 0.50293 8.36133 0.892443 7.62279 1.67147C5.52303 3.88637 2.18302 7 0 7L19 7Z"></path></svg><div class=similar-channels-header>');let co,t0;function _I(a){co||(co=document.createElement("canvas"),co.width=20,co.height=20,t0=co.getContext("2d",{alpha:!1,willReadFrequently:!0}));const[e,t]=K(),[s,i]=K(),n=p=>{p.naturalWidth<100||(t0.drawImage(p,0,0,co.width,co.height),i(RL(co)))},r=Ot(()=>jn({peerId:a.peerId,size:a.avatarSize,processImageOnLoad:n}));r.node.classList.add("similar-channels-channel-avatar");const o=[];o.push(r.readyThumbPromise),a.isLast&&r.node.classList.add("similar-channels-channel-avatar-stack-first"),r.readyThumbPromise.then(()=>{t(r.color())});let l;if(a.isLast)l=P("MoreSimilar");else{const p=new Xt;o.push(p.update({peerId:Ot(()=>a.peerId)})),l=p.element}l.classList.add("similar-channels-channel-name");const c=T(hs,{get icon(){return a.isLast?"premium_lock":"newprivate_filled"},class:"similar-channels-channel-badge-icon"});a.promises&&a.promises.push(...o);const d=Qy(a.peerId),u=(()=>{const p=cB();return k(p,(()=>{const m=V(()=>!!a.isLast);return()=>m()?[V(()=>`+${a.count-a.defaultLimit}`),V(()=>!Ot(()=>a.premium)&&c)]:[c,V(()=>un(d.bot_active_users||d.participants_count||1,1))]})()),Me(m=>Ii(p,s()?{"background-image":`url(${s()})`}:{"background-color":`var(--peer-avatar-${e()}-bottom)`},m)),p})(),h=V(()=>d._!=="user"||d.bot_active_users!==void 0);return(()=>{const p=dB(),m=a.ref;return typeof m=="function"?Ue(m,p):a.ref=p,k(p,(()=>{const g=V(()=>!!a.isLast);return()=>g()?(()=>{const f=hB(),v=f.firstChild;return k(f,()=>r.element,v),f})():r.element})(),null),k(p,()=>h()&&u,null),k(p,l,null),Me(()=>be(p,Ge("similar-channels-channel",a.isLast&&"is-last",!h()&&"no-badge"))),p})()}function mB(a){const[e,t]=K(I.premium),[s,i]=K(),[n,r]=K();let{onAcked:o,onReady:l,onEmpty:c}=a;const d=document.createElement("canvas");d.width=20,d.height=20,d.getContext("2d",{alpha:!1,willReadFrequently:!0}),I.addEventListener("premium_toggle",t);const u=async()=>{const h=Ae.isPremiumFeaturesHidden(),p=await Promise.all([I.managers.acknowledged.appChatsManager.getChannelRecommendations(a.chatId),I.managers.acknowledged.apiManager.getLimit("recommendedChannels",!1),I.managers.acknowledged.apiManager.getLimit("recommendedChannels",!0),{cached:!(h instanceof Promise),result:Promise.resolve(h)}]);return{cached:p.every(m=>m.cached),results:Promise.all(p.map(m=>m.result))}};return le(async()=>{e();const h=ui().get(),{cached:p,results:m}=await u();if(o?.(p),o=void 0,!h())return;const g=await m;if(h()){if(!g[0].chats.length){a.onEmpty?.();return}i(g)}}),le(async()=>{const h=s();if(!h)return;const[p,m,g,f]=h,v=p.count??p.chats.length,y=v>m&&!f,w=new Map,b=ui().get(),S=[];let _;const M=(()=>{const L=uB(),E=_;return typeof E=="function"?Ue(E,L):_=L,k(L,T(Cs,{get each(){return p.chats.slice(0,m)},children:(x,R)=>{const B=y&&R()===m-1;return T(_I,{get peerId(){return x.id.toPeerId(!0)},promises:S,isLast:B,ref:N=>w.set(N,B?void 0:x),count:v,defaultLimit:m,get premium(){return Ot(e)},avatarSize:60})}})),L})(),C=J(_,L=>{const E=ne(L.target,"similar-channels-channel");if(!E)return;_e(L);const x=w.get(E);if(x){Ce.setInnerPeer({peerId:x.id.toPeerId(!0)});return}if(e()){ue.createPopup(Rs,{onSelect:N=>{Ce.setInnerPeer({peerId:N})},peerType:["custom"],getMoreCustom:async()=>({result:p.chats.map(N=>N.id.toPeerId(!0)),isEnd:!0}),headerLangPackKey:"SimilarChannels"});return}const R=xi(()=>{B(),rs.show()});R.classList.add("primary");const{close:B}=Ra({element:E.querySelector(".similar-channels-channel-avatar-stack, .similar-channels-channel-avatar"),container:E.parentElement,vertical:"top",textElement:P("SimilarChannels.Unlock",[R,g]),icon:"star"})});ze(C),await Promise.all(S),b()&&(r(M),l?.(),l=void 0)}),(()=>{const h=pB(),p=h.firstChild,m=p.nextSibling;return k(m,()=>P("SimilarChannels"),null),k(m,T(Pi,{icon:"close",get onClick(){return a.onClose}}),null),k(h,T(cu,{get children(){return[e0(),V(()=>n()),e0()]}}),null),h})()}function Yr(a){return a?._==="forumTopic"}function pr(a){return a?._==="savedDialog"}function Po(a){return a?._==="dialog"}function II(a){const e=a.fwd_from;if(!e)return!1;const t=Aa(e),s=it(e.from_id);return!!(t&&(s||e.from_name&&e.saved_from_name&&e.from_name!==e.saved_from_name))||!!e.saved_from_id}function xm(a){return a[0]}function PI(a){if(a.type==="click"){_e(a);return}document.body.addEventListener("click",_e,{once:!0,capture:!0})}function Hf(a){const t=a?.reactions?.recent_reactions;if(!t)return;const s=t.filter(i=>i.pFlags.unread);if(s.length)return s}const gB=Y("<div class=popup-about-ad-icon>"),fB=Y("<div class=popup-about-ad-title>"),vB=Y("<div class=popup-about-ad-subtitle>"),yB=Y("<div class=popup-about-ad-caption><div class=popup-about-ad-caption-title></div><div class=popup-about-ad-caption-subtitle>");class MI extends ue{constructor(){super("popup-about-ad",{overlayClosable:!0,body:!0,scrollable:!0,withConfirm:"RevenueSharingAdsAlertButton",footer:!0}),this.header.remove(),this.footer.append(this.btnConfirm),J(this.btnConfirm,()=>{this.hide()}),this.construct()}_construct(){return[(()=>{const e=gB();return k(e,T(hs,{icon:"ads"})),e})(),(()=>{const e=fB();return k(e,()=>P("AboutRevenueSharingAds")),e})(),(()=>{const e=vB();return k(e,()=>P("RevenueSharingAdsAlertSubtitle")),e})(),T(En,{icon:"lock",get title(){return P("RevenueSharingAdsInfo1Title")},get subtitle(){return P("RevenueSharingAdsInfo1Subtitle")}}),T(En,{icon:"revenue",get title(){return P("RevenueSharingAdsInfo2Title")},get subtitle(){return P("RevenueSharingAdsInfo2Subtitle")}}),T(En,{icon:"nochannel",get title(){return P("RevenueSharingAdsInfo3Title")},get subtitle(){return P("RevenueSharingAdsInfo3Subtitle")}}),(()=>{const e=yB(),t=e.firstChild,s=t.nextSibling;return k(t,()=>P("RevenueSharingAdsInfo4Title")),k(s,()=>P("RevenueSharingAdsInfo4Subtitle2",[P("RevenueSharingAdsInfo4SubtitleLearnMore1")])),e})()]}async construct(){const e=document.createElement("div");this.scrollable.append(e);const t=wi(()=>this._construct(),e);this.addEventListener("closeAfterTimeout",t),this.show()}}function LI(a,e,t,s){return{_:"inputWebFileGeoPointLocation",access_hash:a.access_hash,geo_point:{_:"inputGeoPoint",lat:a.lat,long:a.long},w:e,h:t,scale:window.devicePixelRatio,zoom:s}}function Nb(a){return"https://maps.google.com/maps?q="+a.lat+","+a.long}function bB({messageMedia:a,attachmentDiv:e,bubble:t,timeSpan:s,wrapOptions:i,message:n,middleware:r,loadPromises:o,messageDiv:l,updateLocationOnEdit:c}){t.classList.add("photo");const d=document.createElement("a");d.classList.add("geo-container","shimmer-bright");const u=a._==="messageMediaVenue",h=a._==="messageMediaGeoLive",{geo:p}=a,m=277,g=195;d.innerHTML=`
- <svg class="geo-svg" width="${m}px" height="${g}px" viewBox="0 0 277 195" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
- <g id="Artboard" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
- <path class="geo-svg-path" d="M274.275109,103.333333 C275.780025,103.333333 277,104.567636 277,106.090226 L277,195 L201.724891,195 C200.219975,195 199,193.765697 199,192.243108 L199,109.536341 C199,106.110514 201.744944,103.333333 205.131004,103.333333 L274.275109,103.333333 Z M71.8689956,103.333333 C75.2550558,103.333333 78,106.110514 78,109.536341 L78,192.243108 C78,193.765697 76.7800248,195 75.2751092,195 L3.05533376e-13,195 L3.05533376e-13,106.090226 C3.05533376e-13,104.567636 1.21997518,103.333333 2.72489083,103.333333 L71.8689956,103.333333 Z M179.467331,145 C185.100269,145 190,149.937497 190,155.617021 L190,192.257683 C190,193.772223 188.448961,195 186.946844,195 L90.0531561,195 C88.5510395,195 87,193.772223 87,192.257683 L87,155.617021 C87,149.937497 91.8997314,145 97.5326689,145 L179.467331,145 Z M141.438333,165.734879 L136.933333,167.553888 L136.933333,166.559118 C136.933333,166.237002 136.805833,166.000152 136.550833,165.848568 C136.295833,165.696983 136.026667,165.678035 135.743333,165.791724 L130.02,168.236016 C129.698889,168.368652 129.448611,168.581817 129.269167,168.875512 C129.089722,169.169206 129,169.486585 129,169.827649 L129,180.628013 C129,181.101713 129.165278,181.504358 129.495833,181.835948 C129.826389,182.167538 130.227778,182.333333 130.7,182.333333 L149.966667,182.333333 C150.438889,182.333333 150.840278,182.167538 151.170833,181.835948 C151.501389,181.504358 151.666667,181.101713 151.666667,180.628013 L151.666667,168.690769 L142.6,168.690769 L142.6,166.530696 C142.6,166.227528 142.477222,165.990678 142.231667,165.820146 C141.986111,165.649613 141.721667,165.621191 141.438333,165.734879 Z M140.5,173.333333 C140.740741,173.333333 140.939815,173.410069 141.097222,173.563542 C141.25463,173.717014 141.333333,173.911111 141.333333,174.145833 L141.333333,176.854167 C141.333333,177.088889 141.25463,177.282986 141.097222,177.436458 C140.939815,177.589931 140.740741,177.666667 140.5,177.666667 C140.259259,177.666667 140.060185,177.589931 139.902778,177.436458 C139.74537,177.282986 139.666667,177.088889 139.666667,176.854167 L139.666667,174.145833 C139.666667,173.911111 139.74537,173.717014 139.902778,173.563542 C140.060185,173.410069 140.259259,173.333333 140.5,173.333333 Z M135.833333,173.333333 C136.074074,173.333333 136.273148,173.410069 136.430556,173.563542 C136.587963,173.717014 136.666667,173.911111 136.666667,174.145833 L136.666667,176.854167 C136.666667,177.088889 136.587963,177.282986 136.430556,177.436458 C136.273148,177.589931 136.074074,177.666667 135.833333,177.666667 C135.592593,177.666667 135.393519,177.589931 135.236111,177.436458 C135.078704,177.282986 135,177.088889 135,176.854167 L135,174.145833 C135,173.911111 135.078704,173.717014 135.236111,173.563542 C135.393519,173.410069 135.592593,173.333333 135.833333,173.333333 Z M144.833333,173.333333 C145.074074,173.333333 145.273148,173.410069 145.430556,173.563542 C145.587963,173.717014 145.666667,173.911111 145.666667,174.145833 L145.666667,176.854167 C145.666667,177.088889 145.587963,177.282986 145.430556,177.436458 C145.273148,177.589931 145.074074,177.666667 144.833333,177.666667 C144.592593,177.666667 144.393519,177.589931 144.236111,177.436458 C144.078704,177.282986 144,177.088889 144,176.854167 L144,174.145833 C144,173.911111 144.078704,173.717014 144.236111,173.563542 C144.393519,173.410069 144.592593,173.333333 144.833333,173.333333 Z M149.658824,159.666667 L148.341176,159.666667 C148.139869,159.666667 147.966013,159.735119 147.819608,159.872024 C147.673203,160.008929 147.581699,160.177778 147.545098,160.378571 L146.666667,167.333333 L151.333333,167.333333 L150.454902,160.378571 C150.418301,160.177778 150.326797,160.008929 150.180392,159.872024 C150.033987,159.735119 149.860131,159.666667 149.658824,159.666667 Z M249.919094,140.666667 L238.414239,140.666667 C237.928803,140.666667 237.516181,140.839506 237.176375,141.185185 C236.83657,141.530864 236.666667,141.950617 236.666667,142.444444 L236.666667,144.518519 L242.812298,148.903704 C243.02589,149.061728 243.200647,149.298765 243.33657,149.614815 C243.472492,149.930864 243.540453,150.237037 243.540453,150.533333 L243.540453,162 L249.919094,162 C250.404531,162 250.817152,161.82716 251.156958,161.481481 C251.496764,161.135802 251.666667,160.716049 251.666667,160.222222 L251.666667,142.444444 C251.666667,141.950617 251.496764,141.530864 251.156958,141.185185 C250.817152,140.839506 250.404531,140.666667 249.919094,140.666667 Z M233.681454,145 C233.306839,145 232.961799,145.109357 232.646334,145.32807 L226.406038,149.831579 C226.169439,149.990643 225.987061,150.204386 225.858903,150.472807 C225.730746,150.741228 225.666667,151.01462 225.666667,151.292982 L225.666667,161.105263 C225.666667,161.363743 225.750462,161.577485 225.918053,161.746491 C226.085644,161.915497 226.297597,162 226.553913,162 L231.315465,162 L231.315465,155.408772 L236.047443,155.408772 L236.047443,162 L240.779421,162 C241.035736,162 241.247689,161.915497 241.41528,161.746491 C241.582871,161.577485 241.666667,161.363743 241.666667,161.105263 L241.666667,151.292982 C241.666667,151.01462 241.602588,150.741228 241.47443,150.472807 C241.346272,150.204386 241.163894,149.990643 240.927295,149.831579 L234.716574,145.32807 C234.401109,145.109357 234.056069,145 233.681454,145 Z M28.1107355,151 C26.7011204,151.535116 25.6080384,152.177255 24.8314897,152.926418 C24.054941,153.67558 23.6666667,154.507839 23.6666667,155.423195 C23.6666667,156.313825 24.0383266,157.128954 24.7816465,157.868583 C25.5249664,158.608212 26.5730748,159.243985 27.9259717,159.775903 L28.3614887,159.946655 C29.6189312,160.436878 31.0759356,160.969375 32.7325021,161.229902 C34.5839587,161.521079 36.6177601,161.666667 38.8339062,161.666667 C41.0575639,161.666667 43.0932432,161.521079 44.940944,161.229902 C46.7886449,160.938725 48.3905989,160.30782 49.746806,159.775903 C51.1030131,159.243985 52.1509305,158.608212 52.8905583,157.868583 C53.6301861,157.128954 54,156.313825 54,155.423195 C54,154.74612 53.7747506,154.109424 53.3242518,153.513108 C52.8737529,152.916792 52.232252,152.376601 51.399749,151.892537 C51.0481091,152.042615 50.6745076,152.157696 50.2789446,152.237779 C49.8833815,152.317862 49.4585364,152.366145 49.0044091,152.382629 C48.0792219,153.944799 46.7901408,155.168707 45.137166,156.054355 C43.4841911,156.940003 41.5781488,157.382827 39.4190391,157.382827 L38.373477,157.382827 C36.7571047,157.382827 35.2762577,157.12145 33.9309359,156.598697 C32.5856141,156.075944 31.4161441,155.337853 30.4225259,154.384424 C29.4289077,153.430995 28.6583108,152.302854 28.1107355,151 Z M246.666667,155.666667 L246.666667,157.333333 L245,157.333333 L245,155.666667 L246.666667,155.666667 Z M38.9247583,138.333333 C36.8805223,138.333333 35.0878837,138.524784 33.5468423,138.907687 C32.005801,139.290589 30.807178,139.825485 29.9509735,140.512377 C29.0947689,141.199268 28.6666667,142.000558 28.6666667,142.916248 L28.6666667,145.217011 C28.6666667,146.65308 28.8977785,147.968639 29.3600021,149.163689 C29.8222257,150.358738 30.4832473,151.391681 31.343067,152.262516 C32.2028866,153.133352 33.2290636,153.807308 34.421598,154.284385 C35.6141324,154.761462 36.9411543,155 38.4026637,155 L39.4443793,155 C41.3903102,155 43.0928254,154.597401 44.5519248,153.792202 C46.0110242,152.987003 47.1473979,151.850115 47.961046,150.381537 C48.0380117,150.24262 48.1113372,150.101439 48.1810225,149.957994 L48.8310449,149.957752 C50.1301926,149.957752 51.1498054,149.643464 51.8898832,149.014889 C52.6299611,148.386314 53,147.516781 53,146.406291 C53,145.303865 52.6297708,144.436566 51.8893124,143.804392 C51.2166514,143.230102 50.3137723,142.916665 49.1810488,142.863979 C49.1649624,141.970034 48.735209,141.186167 47.8917885,140.512377 C47.0319689,139.825485 45.8315067,139.290589 44.2904019,138.907687 C42.7492971,138.524784 40.9607493,138.333333 38.9247583,138.333333 Z M246.666667,150.333333 L246.666667,152 L245,152 L245,150.333333 L246.666667,150.333333 Z M49.3462947,144.666667 C49.9216674,144.707967 50.3794206,144.850985 50.719554,145.095721 C51.1287402,145.390142 51.3333333,145.798671 51.3333333,146.321307 C51.3333333,146.844067 51.1285423,147.254623 50.7189604,147.552974 C50.312817,147.848821 49.7398788,147.997986 49,148 C49.2305654,147.116215 49.3458481,146.164212 49.3458481,145.143993 L49.3462947,144.666667 Z M246.666667,145.333333 L246.666667,147 L245,147 L245,145.333333 L246.666667,145.333333 Z M39.0006663,140.333333 C40.5947307,140.333333 42.0207584,140.451406 43.2787493,140.687551 C44.5367403,140.923696 45.527002,141.243793 46.2495345,141.647842 C46.9720671,142.051891 47.3333333,142.502395 47.3333333,142.999356 C47.3333333,143.49558 46.9718767,143.9459 46.2489634,144.350317 C45.5260501,144.754734 44.5357884,145.07523 43.2781782,145.311805 C42.020568,145.548379 40.5947307,145.666667 39.0006663,145.666667 C37.406475,145.666667 35.9822242,145.548379 34.7279138,145.311805 C33.4736034,145.07523 32.4831513,144.754734 31.7565574,144.350317 C31.0299636,143.9459 30.6666667,143.49558 30.6666667,142.999356 C30.6666667,142.502395 31.0297732,142.051891 31.7559863,141.647842 C32.4821994,141.243793 33.4724611,140.923696 34.7267715,140.687551 C35.9810819,140.451406 37.4057135,140.333333 39.0006663,140.333333 Z M176.83043,52 C183.919688,52 190,58.1245592 190,65.2683983 L190,122.398268 C190,129.542107 183.919688,135 176.83043,135 L100.16957,135 C93.0803124,135 87,129.542107 87,122.398268 L87,65.2683983 C87,58.1245592 93.0803124,52 100.16957,52 L176.83043,52 Z M138.333333,80.3333333 C135.511111,80.3333333 133.027778,81.3372814 130.883333,83.3451777 C128.738889,85.3530739 127.666667,88.0490694 127.666667,91.4331641 C127.666667,93.6215454 128.488889,95.9791314 130.133333,98.5059222 C131.777778,101.032713 134.255556,103.77383 137.566667,106.729272 C137.677778,106.819515 137.8,106.887197 137.933333,106.932318 C138.066667,106.977439 138.211111,107 138.366667,107 C138.5,107 138.627778,106.977439 138.75,106.932318 C138.872222,106.887197 138.988889,106.819515 139.1,106.729272 C142.411111,103.77383 144.888889,101.032713 146.533333,98.5059222 C148.177778,95.9791314 149,93.6215454 149,91.4331641 C149,88.0490694 147.927778,85.3530739 145.783333,83.3451777 C143.638889,81.3372814 141.155556,80.3333333 138.333333,80.3333333 Z M138,88 C138.920635,88 139.706349,88.3253968 140.357143,88.9761905 C141.007937,89.6269841 141.333333,90.4126984 141.333333,91.3333333 C141.333333,92.2539683 141.007937,93.0396825 140.357143,93.6904762 C139.706349,94.3412698 138.920635,94.6666667 138,94.6666667 C137.079365,94.6666667 136.293651,94.3412698 135.642857,93.6904762 C134.992063,93.0396825 134.666667,92.2539683 134.666667,91.3333333 C134.666667,90.4126984 134.992063,89.6269841 135.642857,88.9761905 C136.293651,88.3253968 137.079365,88 138,88 Z M277,0 L277,91.2454212 C277,92.7667331 275.781665,94 274.278772,94 L205.227621,94 C201.846113,94 199.104859,91.2251494 199.104859,87.8021978 L199.104859,66.7985348 C199.104859,54.8182041 189.51047,41.6630037 177.675192,41.6630037 L149.102302,41.6630037 C146.284378,41.6630037 144,39.3506282 144,36.4981685 L144,2.75457875 C144,1.23326692 145.218335,0 146.721228,0 L277,0 Z M129.945299,0 C131.448269,0 132.666667,1.23326692 132.666667,2.75457875 L132.666667,36.4981685 C132.666667,39.3506282 130.382171,41.6630037 127.564103,41.6630037 L99.3299145,41.6630037 C87.4940275,41.6630037 77.8991453,54.8182041 77.8991453,66.7985348 L77.8991453,87.8021978 C77.8991453,91.2251494 75.1577504,94 71.7760684,94 L2.72136752,94 C1.21839774,94 0,92.7667331 0,91.2454212 L0,0 L129.945299,0 Z M237.333333,28.6666667 C235.486111,28.6666667 233.875868,29.2909326 232.502604,30.5394645 C231.12934,31.7879963 230.333333,33.3393899 230.114583,35.1936451 C228.753472,35.7622834 227.671875,36.6708685 226.869792,37.9194003 C226.067708,39.1679322 225.666667,40.5339002 225.666667,42.0173044 C225.666667,44.0693469 226.377604,45.8185276 227.799479,47.2648467 C229.221354,48.7111658 230.940972,49.4343254 232.958333,49.4343254 L236.239583,49.4343254 L236.239583,55.0331916 L232.958333,55.0331916 C232.642361,55.0331916 232.381076,55.1382661 232.174479,55.348415 C231.967882,55.5585639 231.864583,56.5660426 231.864583,56.8874469 C231.864583,57.2088511 231.967882,57.4746277 232.174479,57.6847766 C232.381076,57.8949255 232.642361,58 232.958333,58 L241.34375,58 C241.659722,58 241.921007,57.8949255 242.127604,57.6847766 C242.334201,57.4746277 242.4375,57.2088511 242.4375,56.8874469 C242.4375,56.5660426 242.334201,55.5585639 242.127604,55.348415 C241.921007,55.1382661 241.659722,55.0331916 241.34375,55.0331916 L238.427083,55.0331916 L238.427083,49.4343254 L241.708333,49.4343254 C243.725694,49.4343254 245.445312,48.7111658 246.867188,47.2648467 C248.289062,45.8185276 249,44.0693469 249,42.0173044 C249,40.5339002 248.598958,39.1679322 247.796875,37.9194003 C246.994792,36.6708685 245.913194,35.7622834 244.552083,35.1936451 C244.333333,33.3393899 243.537326,31.7879963 242.164062,30.5394645 C240.790799,29.2909326 239.180556,28.6666667 237.333333,28.6666667 Z M39.3280935,33 C39.2243891,33 39.1258699,33.0154494 39.0325359,33.0463483 C38.9392019,33.0772472 38.8510531,33.1235955 38.7680896,33.1853933 L31.8613745,38.3405982 L31.8613745,37.6966292 L31.8583795,37.640264 C31.8289402,37.347262 31.5754523,36.7755434 30.7901174,36.7755434 L30.6207017,36.7767977 L30.4578933,36.7810704 C29.9778294,36.7994331 29.824306,36.8638758 29.6931536,36.9792263 L29.6369144,37.0323034 C29.4606169,37.207397 29.3724681,37.428839 29.3724681,37.6966292 L29.3724681,40.2921348 L26.3857805,42.5477528 C26.1783716,42.7125468 26.0539263,42.9185393 26.0124445,43.1657303 C25.9709628,43.4129213 26.0331854,43.6395131 26.1991125,43.8455056 C26.3650396,44.0514981 26.5724485,44.1750936 26.8213391,44.2162921 C27.0702297,44.2574906 27.2983795,44.1956929 27.5057883,44.0308989 L29.3724681,42.6095506 L29.3724681,54.0730337 C29.3724681,54.340824 29.4606169,54.5622659 29.6369144,54.7373596 C29.8132119,54.9124532 30.0361765,55 30.305808,55 L36.866591,55 C37.3669257,55 37.7725271,54.5921805 37.7725271,54.0891096 L37.7725271,49.1292135 C37.7725271,48.8614232 37.8606758,48.6399813 38.0369734,48.4648876 C38.2132709,48.289794 39.058462,47.9008773 39.3280935,47.9008773 C39.5977251,47.9008773 40.4429162,48.289794 40.6192137,48.4648876 C40.7955112,48.6399813 40.88366,48.8614232 40.88366,49.1292135 L40.88366,54.0891096 C40.88366,54.5921805 41.2892614,55 41.7895961,55 L48.3503791,55 C48.6200106,55 48.8429751,54.9124532 49.0192726,54.7373596 C49.1955702,54.5622659 49.283719,54.340824 49.283719,54.0730337 L49.283719,42.6095506 L51.2441994,44.0774017 C51.4336674,44.2081039 51.6357355,44.2595506 51.8504036,44.2317416 C52.0889238,44.2008427 52.2911475,44.082397 52.4570746,43.8764045 C52.6230016,43.670412 52.6904095,43.4438202 52.6592982,43.1966292 C52.6281869,42.9494382 52.5089268,42.7434457 52.3015179,42.5786517 L39.8880975,33.1853933 C39.8051339,33.1235955 39.7169851,33.0772472 39.6236512,33.0463483 C39.5303172,33.0154494 39.431798,33 39.3280935,33 Z" id="Shape" fill="#FFFFFF"></path>
- </g>
- </svg>`,jl(d);const f=d.firstElementChild;e.append(d);const v=16,y=B=>{d.href=Nb(B)},w=st.isMobile?m:420;let b=0;const S=(B,N)=>{const G=B.geo,O=++b,$=d.querySelector(".geo-image-container");$&&(wt.isAvailable("animations")?$.classList.add("fade-out"):$.remove()),d.classList.add("shimmer"),d.prepend(f);const H={...i,...O!==0?{lazyLoadQueue:void 0}:{}},D=document.createElement("div");if(D.classList.add("geo-image-container"),h){const U=document.createElement("div");U.classList.add("geo-live-pin");const j=document.createElement("div");j.classList.add("geo-live-pin-heading"),U.append(j),U.insertAdjacentHTML("beforeend",`
- <svg version="1.1" class="geo-live-pin-svg" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 64 64" style="enable-background:new 0 0 64 64;" xml:space="preserve">
- <g>
- <circle cx="32" cy="32" r="24.5"/>
- <path d="M32,8c13.23,0,24,10.77,24,24S45.23,56,32,56S8,45.23,8,32S18.77,8,32,8 M32,7C18.19,7,7,18.19,7,32s11.19,25,25,25 s25-11.19,25-25S45.81,7,32,7L32,7z"/>
- </g>
- <g>
- <polygon points="29.38,57.67 27.4,56.08 30.42,54.42 32,51.54 33.58,54.42 36.6,56.08 34.69,57.61 32,60.73"></polygon>
- <path d="M32,52.58l1.07,1.95l0.14,0.26l0.26,0.14l2.24,1.22l-1.33,1.06l-0.07,0.06l-0.06,0.07L32,59.96l-2.24-2.61l-0.06-0.07 l-0.07-0.06l-1.33-1.06l2.24-1.22l0.26-0.14l0.14-0.26L32,52.58 M32,50.5l-1.94,3.56L26.5,56l2.5,2l3,3.5l3-3.5l2.5-2l-3.56-1.94 L32,50.5L32,50.5z"/>
- </g>
- </svg>
- `);const q=vs({middleware:r,size:54,peerId:n.fromId,isDialog:!1,wrapOptions:H});q.node.classList.add("geo-live-pin-avatar"),N?.push(q.readyThumbPromise),U.append(q.node),D.append(U)}else D.innerHTML=`
- <svg class="geo-pin" xmlns="http://www.w3.org/2000/svg" width="21.333" height="37.218" viewBox="0 0 20 34.892">
- <g transform="translate(-965.773 -331.784) scale(1.18559)">
- <path d="M817.112 282.971c-1.258 1.343-2.046 3.299-2.015 5.139.064 3.845 1.797 5.3 4.568 10.592.999 2.328 2.04 4.792 3.031 8.873.138.602.272 1.16.335 1.21.062.048.196-.513.334-1.115.99-4.081 2.033-6.543 3.031-8.871 2.771-5.292 4.504-6.748 4.568-10.592.031-1.84-.759-3.798-2.017-5.14-1.437-1.535-3.605-2.67-5.916-2.717-2.312-.048-4.481 1.087-5.919 2.621z" style="fill:#ea4336;stroke:#ea4336;stroke-width:1;"/>
- <circle r="3.035" cy="288.253" cx="823.031" style="fill:#970a0a;stroke-width:0"/>
- </g>
- </svg>
- `;Bi({photo:LI(G,w,w/(m/g),v),container:D,fadeInElement:D,onRender:()=>{O===b&&d.append(D)},onRenderFinish:()=>{O===b&&(d.classList.remove("shimmer"),f.remove(),$?.remove())},loadPromises:N,...H})};function _(B,N){return 156543.03392*Math.cos(B*(Math.PI/180))/2**N}y(p),S(a,o);let M=h?(n.date+a.period)*1e3:void 0;const C=h&&Date.now()>=M;let L,E,x,R;if(u||h&&!C?(t.classList.remove("is-message-empty"),L=document.createElement("div"),L.classList.add("geo-footer"),E=document.createElement("div"),E.classList.add("geo-footer-title"),x=document.createElement("div"),x.classList.add("geo-footer-address"),L.append(E,x),l.append(L)):R=!1,h&&(d.classList.add("is-live"),d.classList.toggle("is-expired",C)),u)E.append(je(a.title)),x.append(je(a.address));else if(h&&!C){s.classList.add("hide"),E.classList.add("disable-hover"),x.classList.add("disable-hover"),L.classList.add("is-live");const B=new Ne.IntlElement;E.append(P("AttachLiveLocation")),x.append(B.element);const N=document.createElement("div");N.classList.add("geo-footer-timer");const G=13,O=(G+2)*2,$=G*2*Math.PI,H=new Ne.IntlElement;N.append(H.element),N.insertAdjacentHTML("beforeend",`
- <svg class="geo-footer-timer-svg" width="${O}px" height="${O}px">
- <circle cx="${O/2}" cy="${O/2}" r="${G}" class="geo-footer-timer-circle" transform="rotate(-90, ${O/2}, ${O/2})" stroke-dasharray="${$} ${$}"></circle>
- </svg>
- `);const D=N.lastElementChild.firstElementChild,U=D.cloneNode(!0);U.classList.add("geo-footer-timer-circle-shadow"),N.lastElementChild.append(U),L.append(N);let j=n,q=!1;const W=(Z=j,de)=>{if(q)return;const ie=Z.media,{period:oe}=ie,ae=ie.geo;if(M=de?0:(Z.date+oe)*1e3,j!==Z&&(j&&(p.lat!==ae.lat||p.long!==ae.long)&&(y(ae),S(ie)),j=Z),Date.now()>=M){t.classList.add("is-message-empty"),d.classList.add("is-expired"),s.classList.remove("hide"),L.replaceWith(s),z();return}if(d.style.setProperty("--heading",`${ie.heading}deg`),ae.accuracy_radius!==void 0){const Ve=ae.accuracy_radius/_(ae.lat,v);d.style.setProperty("--accuracy-size",`${Ve*2}px`)}let ke,re;Qs(!0)-(Z.edit_date??Z.date)<60?ke="LocationUpdatedJustNow":(ke="UpdatedMinutes",re=[Math.floor((Qs(!0)-Z.edit_date)/60)]);const ce=(M-Date.now())/1e3,Ie=(1-ce/oe)*$;D.setAttribute("stroke-dashoffset",`-${Ie}`),B.compareAndUpdate({key:ke,args:re}),H.compareAndUpdate({key:ce<3600?"JustArgument":"MessageTimer.ShortHours",args:[Math.round(ce<3600?ce/60:ce/3600)]})},ee=setInterval(W,1e3);W();const z=()=>{q=!0,c.delete(t),clearInterval(ee)};c.set(t,W),r.onClean(z)}return x&&x.append(s),R}function EI({button:a,chat:e,message:t,noTextInject:s,replyMarkup:i}){let n=jt(a.text,{noLinks:!0,noLinebreaks:!0}),r,o,l;const{peerId:c}=e,d=t?.media,u=i?.mid||t?.mid,h=i?.fromId||t?.viaBotId||t?.fromId;switch(a._){case"keyboardButtonUrl":{const p=jt(" ",{entities:[{_:"messageEntityTextUrl",length:1,offset:0,url:a.url}]});r=$u(p).firstElementChild,r.classList.add("is-link"),o=Be("arrow_next");break}case"keyboardButtonSwitchInline":{r=document.createElement("button"),r.classList.add("is-switch-inline"),o=Be("forward_filled"),l=p=>{_e(p);let m;a.pFlags.same_peer?m=Promise.resolve(c):m=I.managers.appInlineBotsManager.checkSwitchReturn(h).then(g=>{if(g)return g;let f;if(a.peer_types){const v={inlineQueryPeerTypePM:"users",inlineQueryPeerTypeBotPM:"bots",inlineQueryPeerTypeBroadcast:"channels",inlineQueryPeerTypeChat:"groups",inlineQueryPeerTypeMegagroup:"groups"};f=a.peer_types.map(y=>v[y._])}return Rs.createPicker(f,["send_inline"])}),m.then(async g=>{const f=c===g?e.threadId:void 0;await e.appImManager.setInnerPeer({peerId:g,threadId:f}),I.managers.appInlineBotsManager.switchInlineQuery(g,f,h,a.query)})};break}case"keyboardButtonBuy":{const p=d._==="messageMediaInvoice"?d:void 0;if(p?.extended_media)break;r=document.createElement("button"),r.classList.add("is-buy"),o=Be("card"),p?.receipt_msg_id&&(n=P("Message.ReplyActionButtonShowReceipt"));break}case"keyboardButtonUrlAuth":{r=document.createElement("button"),r.classList.add("is-url-auth");const{url:p,button_id:m}=a;l=()=>{const g=os([r],!0);e.appImManager.handleUrlAuth({peerId:c,mid:u,url:p,buttonId:m}).then(()=>{g()})};break}case"keyboardButtonSimpleWebView":case"keyboardButtonWebView":{r=document.createElement("button"),r.classList.add("is-web-view"),o=Be("webview"),l=()=>{const p=os([r],!0);e.openWebApp({botId:h,url:a.url,isSimpleWebView:a._==="keyboardButtonSimpleWebView",buttonText:a.text}).finally(()=>{p()})};break}case"keyboardButtonRequestPhone":{r=document.createElement("button"),r.classList.add("is-request-phone"),l=()=>{e.appImManager.requestPhone(c)};break}case"keyboardButtonCallback":{r=document.createElement("button"),l=()=>{I.managers.appInlineBotsManager.callbackButtonClick(c,u,a).then(p=>{typeof p.message=="string"&&p.message.length&&Wi(jt(p.message,{noLinks:!0,noLinebreaks:!0}))})};break}case"keyboardButtonRequestPeer":{r=document.createElement("button"),l=async()=>{let p;const m=a.peer_type,g=m._==="requestPeerTypeUser",f=m._==="requestPeerTypeBroadcast",v=m._==="requestPeerTypeChat",y=["dialogs"];if(g)p=b=>!(b._!=="user"||m.bot!==void 0&&m.bot!==!!b.pFlags.bot||m.premium!==void 0&&m.premium!==!!b.pFlags.premium),y.push("contacts");else{let b;v&&(b=(await I.managers.appUsersManager.getCommonChats(c,100)).chats.map(_=>_.id)),p=S=>{if(S._!=="channel"&&(f||S._!=="chat")||!!S.pFlags.broadcast!==f||m.pFlags.creator&&!S.pFlags.creator||m.has_username!==void 0&&!!ji(S)[0]!=!!m.has_username||m.forum!==void 0&&m.forum!==!!S.pFlags.forum)return!1;if(m.user_admin_rights){for(const _ in m.user_admin_rights.pFlags)if(!Cr(S,_))return!1}return!(m.pFlags.bot_participant&&!b.includes(S.id)&&!Cr(S,"invite_users"))}}const w=await Rs.createPicker2({peerType:y,filterPeerTypeBy:p,multiSelect:!0,limit:a.max_quantity,limitCallback:()=>{$e({langPackKey:"RequestPeer.MultipleLimit",langPackArguments:[P(g?"RequestPeer.MultipleLimit.Users":f?"RequestPeer.MultipleLimit.Channels":"RequestPeer.MultipleLimit.Groups",[a.max_quantity])]})},titleLangKey:g?"RequestPeer.Title.Users":f?"RequestPeer.Title.Channels":"RequestPeer.Title.Groups"});if(!g){const b=await Promise.all(w.map(L=>qe({peerId:L}))),S=Yi(b,!1);let _;S.length===1?_=S[0]:(_=document.createElement("span"),_.append(...S));const M=[_,await qe({peerId:c})];await Rt({descriptionLangKey:"Chat.Service.PeerRequest.Confirm.Plain",descriptionLangArgs:M,button:{langKey:"Chat.Service.PeerRequest.Confirm.Ok"}})}I.managers.appMessagesManager.sendBotRequestedPeer(c,u,a.button_id,w).catch(b=>{b.type==="CHAT_ADMIN_INVITE_REQUIRED"&&$e({langPackKey:f?"Error.RequestPeer.NoRights.Channel":"Error.RequestPeer.NoRights.Group"})})};break}case"keyboardButtonCopy":{r=document.createElement("button"),o=Be("copy"),l=()=>{si(a.copy_text),$e({langPackKey:"TextCopied"})};break}default:{r=document.createElement("button"),t||(l=()=>{I.managers.appMessagesManager.sendText({peerId:c,text:a.text})});break}}return o&&o.classList.add("reply-markup-button-icon"),s||r?.append(n),{text:n,buttonEl:r,buttonIcon:o,onClick:l}}const Am=Y("<div>"),wB=Y("<div class=webpage-name><strong>"),SB=Y("<span class=webpage-name-tip>"),CB=Y("<div class=webpage-title><strong>"),_B=Y("<div class=webpage-text>"),IB=Y("<div class=webpage-preview-resizer>"),Ac="webpage";function PB(a){return a?.content&&(()=>{const e=Am(),t=a.ref;return typeof t=="function"?Ue(t,e):a.ref=e,k(e,()=>a.content,null),k(e,(()=>{const s=V(()=>!!a.link);return()=>s()&&T(hs,{icon:"arrow_next",class:`${Ac}-footer-icon`})})(),null),Me(s=>{const i=wg(),n=Ge(`${Ac}-footer`,a.link&&"is-link",a.text&&"is-text",!a.text&&"is-button");return i!==s._v$&&Es(e,"dir",s._v$=i),n!==s._v$2&&be(e,s._v$2=n),s},{_v$:void 0,_v$2:void 0}),e})()}function MB(a){return a?.content&&(()=>{const e=wB(),t=e.firstChild;return k(t,()=>a.content),k(e,(()=>{const s=V(()=>!!a.tip);return()=>s()&&(()=>{const i=SB();return Lr(i,"click",a.tip.onClick,!0),k(i,()=>a.tip.content),i})()})(),null),Me(()=>Es(e,"dir",wg())),e})()}function LB(a){return a&&(()=>{const e=CB(),t=e.firstChild;return k(t,a),Me(()=>Es(e,"dir",wg())),e})()}function EB(a){return(()=>{const e=_B();return k(e,()=>a.children),Me(()=>Es(e,"dir",wg())),e})()}function kB(a){if(!a)return;const e=`${Ac}-preview`,t=a.hasDocument&&`${e}-with-document`;return a.content&&a.content.classList.add(...[e,t].filter(Boolean)),(()=>{const s=IB();return k(s,()=>a.content||(()=>{const i=Am(),n=a.ref;return typeof n=="function"?Ue(n,i):a.ref=i,Me(()=>be(i,Ge(e,t))),i})()),s})()}function s0(a){const e=PB(a.footer),t=MB(a.name),s=LB(a.title),i=kB(a.media),n=(()=>{const l=Am();return k(l,()=>a.media?.position==="top"&&i,null),k(l,t,null),k(l,s,null),k(l,(()=>{const c=V(()=>!!a.text);return()=>c()&&T(EB,{get children(){return a.text}})})(),null),k(l,()=>a.media?.position==="bottom"&&i,null),k(l,e,null),Me(()=>be(l,Ge(`${Ac}-content`,a.media?.hasDocument&&"has-document",a.minContent&&"min-content"))),l})(),r=(()=>{const l=Am();return k(l,n),Me(()=>be(l,Ge(`${Ac}-quote`,"quote-like-border"))),l})(),o=T(Ru,{get component(){return a.clickable?"a":"div"},ref(l){const c=a.ref;typeof c=="function"?c(l):a.ref=l},get class(){return Ge(Ac,"quote-like",a.clickable&&"quote-like-hoverable",a.media?.photoSize&&`has-${a.media.photoSize}-photo`)},children:r});return a.clickable?T(Ku,{children:o}):o}Fs(["click"]);function i0(){const a=document.createElement("span");return a.classList.add("clearfix"),a}const n0=180;function TB({bubble:a,message:e,globalMediaDeferred:t,searchContext:s}){const i=a.querySelector(".bubble-content"),n=!!a.querySelector(".bubble-beside-button"),r=document.createElement("div");r.classList.add("bubble-beside-button","bubble-beside-button--transcribe","with-hover"),n&&r.classList.add("bubble-beside-button--lifted"),r.append(Be("transcribe")),i.append(r),a.classList.add("with-beside-button");const o=a.querySelector(".attachment.media-container"),l=document.createElement("div");l.append(gr('<span class="clearfix"></span>')),l.classList.add("message"),l.style.display="none",i.append(l);const c=i.querySelector(".time"),d=c.cloneNode(!0);d.classList.remove("is-floating");const u=["round","just-media"],h=["can-have-tail","voice-message"],p=[".topic-name-button-container",".reply",".bubble-name-forwarded"],m=()=>a.closest(".bubbles");let g=!1,f=!1,v;async function y(){if(!v)return;const _=o.querySelector(".media-video"),M=o.querySelector(".video-round-canvas"),C=v.getContext("2d"),L=await t;v&&(rt.getPlayingMedia()===L?C.drawImage(M,0,0,v.width,v.height):C.drawImage(_,0,0,v.width,v.height))}function w(){const _=m().getBoundingClientRect();return{x:M=>M-_.left,y:M=>M-_.top}}async function b(){const _=w(),M=l.querySelector(".audio-thumb")?.getBoundingClientRect(),C=_.x(M.left+M.width/2),L=_.y(M.top+M.height/2),E=M.width,x=window.getComputedStyle(i),R=[x.borderStartStartRadius,x.borderStartEndRadius,x.borderEndEndRadius,x.borderEndStartRadius];y(),v.style.left=C+"px",v.style.top=L+"px",v.style.width=E+"px",v.style.height=E+"px",v.style.borderRadius="50%",m().append(v),r.style.removeProperty("display");const B=i.clientHeight,N=i.clientWidth;i.style.height=B+"px",i.style.width=N+"px",i.style.overflow="hidden",i.style.setProperty("background",x.background,"important"),l.style.width=l.clientWidth+"px",l.style.height=l.clientHeight+"px",o.style.opacity="0",o.style.position="absolute",o.style.display="block",u.forEach($=>a.classList.add($)),h.forEach($=>a.classList.remove($)),p.forEach($=>{a.querySelector($)?.style.removeProperty("display")}),await hi();const G=o.clientHeight,O=o.clientWidth;zi(0,1,n0,$=>{const H=w(),D=i?.getBoundingClientRect(),U=H.x(D.left+D.width/2),j=H.y(D.top+D.height/2),q=D.width;v.style.left=js(C,U,$)+"px",v.style.top=js(L,j,$)+"px",v.style.width=js(E,q,$)+"px",v.style.height=js(E,q,$)+"px",i.style.height=js(B,G,$)+"px",i.style.width=js(N,O,$)+"px";const W=R.map(ee=>js(parseInt(ee),q,$*Math.sqrt($))+"px").join(" ");i.style.setProperty("border-radius",W),l.style.opacity=js(.5,0,Math.min(1,$*2))+"",y()},{easing:Ww,onEnd:()=>{v.remove(),v=void 0,l.style.display="none",o.style.removeProperty("opacity"),o.style.removeProperty("position"),o.style.display="block",i.style.removeProperty("overflow"),i.style.removeProperty("background"),i.style.removeProperty("width"),i.style.removeProperty("height"),i.style.removeProperty("max-width"),i.style.removeProperty("border-radius"),l.style.removeProperty("width"),l.style.removeProperty("height"),l.style.removeProperty("opacity"),c.style.removeProperty("display")}})}async function S(){if(!I.getPremium()){$e({langPackKey:"RoundVideoTranscription.PremiumAlert",langPackArguments:[xi(()=>{no(),rs.show({feature:"voice_to_text"})})]});return}if(f)return;if(f=!0,!g){g=!0;const ee=xB();r.append(ee);const z=document.createElement("div");z.classList.add("video-transcribed-text");try{const Z=await I.managers.appMessagesManager.transcribeAudio(e,!0);if(!Z.text)throw"";z.innerText=Z.text}catch{z.append(P("Chat.Voice.Transribe.Error"))}l.append(z),z.append(d),z.append(gr('<span class="clearfix"></span>')),ee.remove()}const _=i.getBoundingClientRect(),M=_.width,C=w();v=document.createElement("canvas"),v.width=M,v.height=M,y(),v.style.position="absolute",v.style.zIndex="1000",v.style.transform="translate(-50%, -50%)";const L=C.x(_.left+_.width/2),E=C.y(_.top+_.height/2);v.style.left=L+"px",v.style.top=E+"px",v.style.width=M+"px",v.style.height=M+"px",v.style.borderRadius="50%",m().append(v);const x=i.clientHeight,R=i.clientWidth,B=Math.max(x,i.clientWidth);u.forEach(ee=>a.classList.remove(ee)),h.forEach(ee=>a.classList.add(ee));const N=window.getComputedStyle(i),G=[N.borderStartStartRadius,N.borderStartEndRadius,N.borderEndEndRadius,N.borderEndStartRadius];i.style.height=x+"px",i.style.width=R+"px",i.style.setProperty("border-radius",B+"px"),o.style.display="none",r.style.display="none",c.style.display="none",i.style.overflow="hidden";const O=a.querySelector(".bubble-content-wrapper");O.style.position="relative",l.style.display="block";const $=gr(`
- <div style="position: absolute;width:min-content;opacity:0;"></div>
- `);$.append(l),O.append($),await hi();const H=$.clientWidth,D=$.clientHeight,U=window.getComputedStyle(l);l.style.width=H-(+parseFloat(U.marginLeft)+parseFloat(U.marginRight))+"px";const j=a.querySelector(".bubble-tail");p.forEach(ee=>{const z=a.querySelector(ee);z&&z.style.setProperty("display","none","important")}),$.remove(),i.append(l),await hi(),O.style.removeProperty("position"),await hi();const W=window.getComputedStyle(j).transform;j.style.transform=`${W!=="none"?W:""} translateX(calc(100% * var(--reflect)))`,j.style.transition=".2s",zi(0,1,n0,ee=>{const z=w(),Z=l.querySelector(".audio-thumb")?.getBoundingClientRect(),de=z.x(Z.left+Z.width/2),ie=z.y(Z.top+Z.height/2),oe=Z.width;v.style.left=js(L,de,ee)+"px",v.style.top=js(E,ie,ee)+"px",v.style.width=js(M,oe,ee)+"px",v.style.height=js(M,oe,ee)+"px",i.style.height=js(x,D,ee)+"px",i.style.width=js(R,H,ee)+"px";const ae=G.map(ke=>js(B,parseInt(ke),Math.min(1,ee*1))+"px").join(" ");i.style.setProperty("border-radius",ae),y()},{easing:Ww,onEnd:async()=>{f=!1,v.style.opacity="1",v.style.transition=".2s",i.style.removeProperty("overflow"),j?.style.removeProperty("transform"),await hi(),v.style.opacity="0",await ns(200),v.remove(),i.style.removeProperty("width"),i.style.removeProperty("height"),i.style.removeProperty("border-radius"),l.style.removeProperty("width"),l.style.removeProperty("height"),v.style.removeProperty("transition"),v.style.removeProperty("opacity"),j?.style.removeProperty("transition")}})}r.addEventListener("click",()=>{S()}),(async()=>{const _=document.createElement("div");_.classList.add("audio-to-text-button"),_.append(Be("up")),_.addEventListener("click",()=>{b()});const M=await t,C=await rd({message:e,customAudioToTextButton:_,shouldWrapAsVoice:!0,globalMedia:M,searchContext:s});l.append(C)})()}function xB(){return gr(`<svg class="transcribe-button-spinner-svg" viewBox="0 0 24 24" width="100" height="100">
- <circle
- cx="12"
- cy="12"
- r="10.5"
- fill="none"
- stroke="white"
- stroke-width="1"
- stroke-linecap="round"
- stroke-dashoffset="0"
- ></circle>
- </svg>`)}function Rm(a,e,t,s,i){return(a-e)/(t-e)*(i-s)+s}function a0(a,e,t,s,i,n,r,o,l,c){const d=e.width,u=e.height,h=Math.floor(t/d)*d,p=Math.floor(s/u)*u,m=(Math.floor((t+i)/d)+1)*d,g=(Math.floor((s+n)/u)+1)*u;for(let f=h;f<m;f+=d)for(let v=p;v<g;v+=u){const y=Math.max(t,f),w=Math.max(s,v),b=y%d,S=w%u,_=Math.min(d-b,t+i-y),M=Math.min(u-S,s+n-w);a.drawImage(e,b,S,_,M,Rm(y,t,t+i,r,r+l),Rm(w,s,s+n,o,o+c),_/i*l,M/n*c)}}const AB=lh(.45,.37,.29,1),RB=2,FB=100,BB=5,r0=.1;function DB(a,e){return{left:Math.floor(e.left-a.left),top:Math.floor(e.top-a.top),width:Math.ceil(e.width+.99),height:Math.ceil(e.height+.99)}}function kI(a,e){return{left:a.left+e.left,top:a.top+e.top,width:e.width,height:e.height}}function $B(a,e,t){const s=t.map(i=>kI(e,i));return Math.max(...s.map(i=>Math.max(Math.hypot(a.clientX-i.left,a.clientY-i.top),Math.hypot(a.clientX-i.left,a.clientY-(i.top+i.height)),Math.hypot(a.clientX-(i.left+i.width),a.clientY-i.top),Math.hypot(a.clientX-(i.left+i.width),a.clientY-(i.top+i.height)))))}function NB(a){return Math.max(600,Math.sqrt(a/160)*350)}function OB(a){const e=[];for(let t=0;t<a.length;t++)e.push(a.item(t));return e}function o0(a,e,t){const s=e.getBoundingClientRect();for(const i of t){const n=kI(s,i);if(n.left<=a.clientX&&a.clientX<=n.left+n.width&&n.top<=a.clientY&&a.clientY<=n.top+n.height)return!0}return!1}function l0(){return Ls.isNight()?"white":"#101010"}const UB=Ni("resize-paint");async function HB(a){const e=Mt();let t=0,s=-1;const i=a.contentRect;return No(()=>{if(s=(s+1)%BB,s)return!0;const n=a.target.getBoundingClientRect();if(Math.abs(n.width-i.width)<r0&&Math.abs(n.height-i.height)<r0){e.resolve(),UB("Resize was painted after attempts :>> ",t);return}return t++<FB||e.reject()}),e}function GB(a){const e=a.match(/rgba?\((\d+), (\d+), (\d+),?\s?(\d?.?\d+)?\)/);return e?{r:parseInt(e[1],10),g:parseInt(e[2],10),b:parseInt(e[3],10),a:parseFloat(e[4]??"1")}:{r:0,g:0,b:0,a:0}}function VB(a,e){const t=e.a+a.a*(1-e.a),s=Math.round((e.a*e.r+a.a*a.r*(1-e.a))/t),i=Math.round((e.a*e.g+a.a*a.g*(1-e.a))/t),n=Math.round((e.a*e.b+a.a*a.b*(1-e.a))/t);return{r:s,g:i,b:n,a:t}}function zB(a){let e={r:0,g:0,b:0,a:0},t=10;for(;a&&e.a<1&&t--;){const s=window.getComputedStyle(a).backgroundColor;if(s!=="rgba(0, 0, 0, 0)"&&s!=="transparent"){const i=GB(s);e=VB(i,e)}a=a.parentElement}return e.a===1?`rgb(${e.r}, ${e.g}, ${e.b})`:void 0}function WB(a,e){const t=zB(a),i=OB(a.getClientRects()).map(r=>DB(e,r)).map(r=>({...r,color:t}));let n;if(n=a.closest("blockquote")){const r=n.getBoundingClientRect();return i.filter(o=>o.top+e.top+o.height<r.bottom)}return i}function KB(a){a=[...a].sort((e,t)=>e.top-t.top);for(let e=0;e<a.length-1;e++){const t=a[e];let s=e;for(;++s<a.length;){const i=a[s],n=i.top-(t.top+t.height);if(n<=RB){if(n<0)continue;const r=Math.floor(n/2),o=n-r;a[s]={...i,top:i.top-r,height:i.height+r},a[e]={...t,height:t.height+o}}else break}}return a}const jB=Y("<canvas class=message-spoiler-overlay__canvas>"),qB=Y("<canvas>"),YB=1e4,QB=Ni("spoiler-overlay");function XB(a){const{rootScope:e}=Xy(),[t,s]=K([]),[i,n]=K("transparent"),[r,o]=K(l0()),[l,c]=K(0),[d,u]=K(),[h,p]=K(),[m,g]=K(),f=V(()=>m()?.dpr||window.devicePixelRatio),v={update(){x()}};a.controlsRef(v);let y,w;Jt(()=>{x();const ie=new $t,oe=Gy(a.parentElement,$i(R,100));ie.add(a.messageElement)("click",D,!0),ie.add(a.messageElement)("mousemove",U),ie.add(a.messageElement)("mouseout",j),ie.add(e)("chat_background_set",W),ie.add(e)("theme_changed",()=>{setTimeout(()=>{x()},200)}),E(),ze(()=>{w?.(),window.clearTimeout(y),ie.removeAll(),oe(),QB("cleaning-up",a.mid)})});const b=V(()=>m()&&t().length);le(()=>{b()&&setTimeout(()=>{a.parentElement.closest(".spoilers-container")?.classList.add("can-show-spoiler-text")},400)}),le(()=>{!t().length&&l()===0&&a.parentElement.closest(".spoilers-container")?.classList.remove("can-show-spoiler-text")});let S;le(()=>{t().length||S||(S=window.setTimeout(()=>{S=void 0,!t().length&&x()},3e3))});const _=(()=>{const ie=jB();return Me(()=>ie.classList.toggle("message-spoiler-overlay__canvas--hidden",l()===1||!b())),ie})(),M=_.getContext("2d"),C=qB(),L=C.getContext("2d");async function E(){const ie=ui();ze(()=>{ie.destroy()});const oe=Fu.attachTextSpoilerTarget({animationGroup:a.animationGroup,canvas:_,draw:ee,middleware:ie.get()});await oe.readyResult,g(oe)}function x(){pi(()=>{N(),G(),O()})}async function R(ie){ie&&(B(),await HB(ie),x(),ee())}function B(){M.clearRect(0,0,_.width,_.height),s([])}le(()=>{N()});function N(){const ie=a.parentElement.getBoundingClientRect();C.width=_.width=ie.width*f(),C.height=_.height=ie.height*f()}function G(){const ie=a.parentElement.getBoundingClientRect(),ae=Array.from(a.messageElement.querySelectorAll(".spoiler-text")).map(re=>WB(re,ie)).flat(),ke=KB(ae);s(ke)}function O(){pi(()=>{$(),H()})}function $(){let ie="transparent";const oe=a.messageElement.parentElement;oe&&(ie=window.getComputedStyle(oe).backgroundColor),n(ie)}function H(){o(l0())}function D(ie){if(!o0(ie,a.parentElement,t())||l())return;ie.stopImmediatePropagation(),ie.stopPropagation(),ie.preventDefault();const oe=a.parentElement.getBoundingClientRect();u([ie.clientX-oe.left,ie.clientY-oe.top]),p($B(ie,oe,t()||[])+20),a.messageElement.classList.remove("is-hovering-spoiler"),w=zi(0,1,NB(h()),c,{easing:AB,onEnd:()=>{y=window.setTimeout(()=>{q()},YB)}})}function U(ie){l()||a.messageElement.classList.toggle("is-hovering-spoiler",o0(ie,a.parentElement,t()))}function j(){a.messageElement.classList.remove("is-hovering-spoiler")}function q(){w?.(),window.clearTimeout(y),l()!==1?w=zi(l(),0,200,c,{onEnd:()=>{pi(()=>{u(),p()})}}):(pi(()=>{c(0),u(),p()}),m()?.animation.paused&&No(()=>{ee()}))}function W(){B(),setTimeout(()=>{x(),ee()},200)}function ee(){M.clearRect(0,0,_.width,_.height),Z(),de()}function z(...ie){return ie.map(oe=>oe*f())}function Z(){const ie=i(),oe=t(),ae=l(),ke=d();if(!oe)return;const{sourceCanvas:re}=m()||{};for(const ce of oe){const Ie=ce.left,Ve=Math.max(0,ce.top),fe=ce.width,Xe=ce.height;if(M.fillStyle=ce.color||ie,M.fillRect(...z(Ie,Ve,fe,Xe)),!!re){if(L.clearRect(...z(Ie,Ve,fe,Xe)),!ke)a0(L,re,...z(Ie,Ve,fe,Xe,Ie,Ve,fe,Xe));else{const Ye=ae**2*.4;a0(L,re,...z(Ie+(ke[0]-Ie)*Ye,Ve+(ke[1]-Ve)*Ye,fe*(1-Ye),Xe*(1-Ye),Ie,Ve,fe,Xe))}L.globalCompositeOperation="source-atop",L.fillStyle=r(),L.fillRect(...z(Ie,Ve,fe,Xe)),L.globalCompositeOperation="source-over",M.drawImage(C,...z(Ie,Ve,fe,Xe,Ie,Ve,fe,Xe))}}}function de(){const ie=d(),oe=h();if(!ie||!oe)return;const ae=l();M.save(),M.globalCompositeOperation="destination-out",M.fillStyle="white",M.shadowBlur=oe/3.5*f()*ae,M.shadowColor="white",M.beginPath(),M.arc(...z(ie[0],ie[1],oe*ae),0,2*Math.PI),M.fill(),M.globalCompositeOperation="source-over",M.restore()}return _}function ZB(a,e){const t=document.createElement("div");t.classList.add("message-spoiler-overlay");let s;const i=wi(()=>T(e,{get children(){return T(XB,ni({parentElement:t,controlsRef:n=>{s=n}},a))}}),t);return{element:t,get controls(){return s},dispose:i}}async function JB({isAnyGroup:a,bubble:e,message:t,our:s,peerId:i,groupedMessages:n}){const r=Number(t.paid_message_stars);if(r&&!a){e.classList.add("has-fake-service","is-forced-rounded"),e.dataset.isPaid="1";const o=document.createElement("div");o.classList.add("service-msg");const l=n?.length||1,c=r*l;o.append(s?P("PaidMessages.YouPaidToSendMessages",[l,P("Stars",[c])]):P("PaidMessages.YouReceivedStarsFrom",[P("Stars",[c]),await qe({peerId:i,onlyFirstName:!0})])),e.prepend(o)}}function Fm(a){return new Promise(async e=>{const t=document.createElement("canvas"),s=a.size??a.mediaSize.aspectFitted(a.boxSize),i=window.devicePixelRatio&&1;t.width=s.width*i,t.height=s.height*i;const n=t.getContext("2d");let r;Kw?r=await createImageBitmap(a.media,{resizeWidth:s.width,resizeHeight:s.height}):r=a.media,n.drawImage(r,0,0,t.width,t.height),Kw&&r?.close();const o=a.mimeType??"image/jpeg",l=a.quality??1;if(a.toDataURL){const c=t.toDataURL(o,l);e({url:c,size:s})}else t.toBlob(c=>{e({blob:c,size:s})},o,l)})}function TI(a){let e,t;return a instanceof HTMLVideoElement?(e=a.videoWidth,t=a.videoHeight):(e=a.naturalWidth,t=a.naturalHeight),Fm({media:a,mediaSize:ii(e,t),boxSize:ii(320,240),quality:.9})}function c0(a){return new Promise((e,t)=>{a.onseeked=()=>{a.onseeked=()=>{TI(a).then(e),a.onseeked=void 0},on(a,0)},a.onerror=t,on(a,Math.min(a.duration,1))})}function eD(a){const e=a.src;return fetch(e).then(t=>t.arrayBuffer()).then(t=>{const s=new Uint8Array(t);let i=0;for(let n=0,r=s.length;n<r;++n)if(s[n]==33&&s[n+1]==249&&s[n+2]==4&&s[n+7]==0){const o=s[n+5]<<8|s[n+4]&255;i+=o<2?10:o}return i/1e3})}function tD(a,e){const t={writable:!0,configurable:!0},s={};e.forEach(i=>{a.hasOwnProperty(i)||(s[i]=t)}),Object.defineProperties(a,s)}const Mp=new Set(["audio/mpeg","audio/aac","audio/wav"]);function xI(a,e){const t=Lc(a.message),s=a.entities||[],i=El(s,t);return ug(a.message,{...e,entities:i})}const sD=Y("<div class=btn-send-effect>"),iD=Y("<div>");function AI(a){const[e,t]=K(),s=V(n=>e()||n),[i]=ma(async()=>I.managers.appReactionsManager.getAvailableEffects());return le(async()=>{const n=a.effect();if(!n||!i()){t();return}const r=i().find(h=>h.id===n);let o;const l=(()=>{const h=sD(),p=o;return typeof p=="function"?Ue(p,h):o=h,h})(),d=ui().get(),u=[];ai({doc:await I.managers.appDocsManager.getDoc(r.static_icon_id),div:o,middleware:d,loadPromises:u,width:20,height:20}),await Promise.all(u),d()&&t(l),S1({isOut:!0,effectId:n,element:o,middleware:d})}),(()=>{const n=iD();return k(n,T(Yo,{type:"cross-fade",get children(){return s()}})),Me(()=>be(n,Ge("btn-send-effect-container",e()&&"is-visible"))),n})()}function RI(a){const e=new Yt({inputMode:"numeric",label:a.label,placeholder:a.placeholder,plainText:!0,withLinebreaks:!1});e.container.classList.add("popup-make-paid-input");const t=ob();t.classList.add("popup-make-paid-star"),e.container.append(t);const s=()=>{let n=(""+ +e.value).replace(/[^0-9]/g,"");+n>a.max&&(n=""+a.max),e.setValueSilently(n),a.onValue?.(+n)};return e.input.addEventListener("input",s),a.middleware.onDestroy(()=>{e.input.removeEventListener("input",s)}),e}class d0 extends ue{constructor(e,t){if(super("popup-make-paid",{closable:!0,overlayClosable:!0,body:!0,title:"PaidMedia.Title",withConfirm:"PaidMedia.Button",footer:!0,withFooterConfirm:!0}),this.editingFrom=t,this.footer.classList.add("abitlarger"),J(this.btnConfirm,()=>{const s=parseInt(this.inputField.value||"0");s>0?(e(s),this.hide()):to(this.inputField.container)},{listenerSetter:this.listenerSetter}),t){const s=ot("btn-primary btn-primary-transparent primary",{text:"PaidMedia.KeepFree"});J(s,()=>{e(0),this.hide()},{listenerSetter:this.listenerSetter}),this.btnConfirm.after(s)}this.d()}async d(){const e=await this.managers.apiManager.getAppConfig();this.appendSolid(()=>{const t=this.inputField=RI({middleware:this.middlewareHelper.get(),label:"PaidMedia.Enter",max:e.stars_paid_post_amount_max});return this.editingFrom&&(t.value=""+this.editingFrom),setTimeout(()=>{this.show(),Ki(t.input)},0),T(Ms,{caption:"PaidMedia.Caption",get captionArgs(){return[xi(()=>{ue.createPopup(ba)})]},noShadow:!0,noDelimiter:!0,get children(){return t.container}})})}}const nD=()=>[{key:"enhance",signal:K(0),uniform:"uEnhance",label:()=>P("MediaEditor.Adjustments.Enhance"),to100:!0},{key:"brightness",signal:K(0),uniform:"uBrightness",label:()=>P("MediaEditor.Adjustments.Brightness"),to100:!1},{key:"contrast",signal:K(0),uniform:"uContrast",label:()=>P("MediaEditor.Adjustments.Contrast"),to100:!1},{key:"saturation",signal:K(0),uniform:"uSaturation",label:()=>P("MediaEditor.Adjustments.Saturation"),to100:!1},{key:"warmth",signal:K(0),uniform:"uWarmth",label:()=>P("MediaEditor.Adjustments.Warmth"),to100:!1},{key:"fade",signal:K(0),uniform:"uFade",label:()=>P("MediaEditor.Adjustments.Fade"),to100:!0},{key:"highlights",signal:K(0),uniform:"uHighlights",label:()=>P("MediaEditor.Adjustments.Highlights"),to100:!1},{key:"shadows",signal:K(0),uniform:"uShadows",label:()=>P("MediaEditor.Adjustments.Shadows"),to100:!1},{key:"vignette",signal:K(0),uniform:"uVignette",label:()=>P("MediaEditor.Adjustments.Vignette"),to100:!0},{key:"grain",signal:K(0),uniform:"uGrain",label:()=>P("MediaEditor.Adjustments.Grain"),to100:!0},{key:"sharpen",signal:K(0),uniform:"uSharpen",label:()=>P("MediaEditor.Adjustments.Sharpen"),to100:!0}],Os=fd();function aD(a){const e=K([]),t=K([]);function s(i){const[,n]=e,[,r]=t;n(o=>[...o,i]),r([])}return{managers:a.managers,imageSrc:a.imageURL,pixelRatio:Math.min(2,window.devicePixelRatio),renderingPayload:K(),isReady:K(!1),adjustments:nD(),currentTab:K("adjustments"),imageSize:K([0,0]),canvasSize:K(),currentImageRatio:K(0),scale:K(1),rotation:K(0),translation:K([0,0]),flip:K([1,1]),fixedImageRatioKey:K(),finalTransform:K({flip:[1,1],rotation:0,scale:1,translation:[0,0]}),resizableLayersSeed:1,resizableLayers:K([]),currentTextLayerInfo:K({alignment:"left",style:"outline",color:"#ffffff",font:"roboto",size:40}),selectedResizableLayer:K(),textLayersInfo:K({}),stickersLayersInfo:K({}),brushDrawnLines:K([]),imageCanvas:K(),currentBrush:K({brush:"pen",color:"#fe4438",size:18}),previewBrushSize:K(),resizeHandlesContainer:K(),history:e,redoHistory:t,pushToHistory:s,isAdjusting:K(!1),isMoving:K(!1),redrawBrushes:()=>{},abortDrawerSlide:()=>{},resetRotationWheel:()=>{},gifCreationProgress:K(0)}}function rD(a){let e;return{value:Ft(s=>(e=s,aD(a))),dispose:e}}function Qu(){const[a]=us(Os).canvasSize;return()=>{if(!a())return{left:0,top:0,width:0,height:0};const e=a()[0],t=a()[1];return{left:60,top:60,width:e-120,height:t-180}}}function FI({scale:a,translation:e,rotation:t,extendCrop:s=[[0,0],[0,0]]}){const i=us(Os),[n]=i.currentImageRatio,[r]=i.imageSize,o=Qu(),[l,c]=r(),[d,u]=Qa(l/c,o().width,o().height),h=[-d/2,u/2],p=[[h[0],h[1]],[h[0]+d,h[1]],[h[0]+d,h[1]-u],[h[0],h[1]-u]].map(b=>{const S=[Math.sin(t),Math.cos(t)];b=[b[0]*S[1]-b[1]*S[0],b[1]*S[1]+b[0]*S[0]].map(M=>M*a),b=[b[0]+e[0],b[1]+e[1]];const _=[Math.sin(-t),Math.cos(-t)];return b=[b[0]*_[1]-b[1]*_[0],b[1]*_[1]+b[0]*_[0]],b}),[m,g]=Qa(n(),o().width,o().height),f=[-m/2,g/2],v=[[f[0]+s[0][0],f[1]+s[0][1]],[f[0]+m+s[1][0],f[1]+s[0][1]],[f[0]+m+s[1][0],f[1]-g+s[1][1]],[f[0]+s[0][0],f[1]-g+s[1][1]]].map(b=>{const S=[Math.sin(-t),Math.cos(-t)];return[b[0]*S[1]-b[1]*S[0],b[1]*S[1]+b[0]*S[0]]}),y=v.map(b=>b[0]),w=v.map(b=>b[1]);return{cropMinX:Math.min(...y),cropMaxX:Math.max(...y),cropMinY:Math.min(...w),cropMaxY:Math.max(...w),imageMinX:p[0][0],imageMaxX:p[2][0],imageMinY:p[2][1],imageMaxY:p[0][1]}}const Lp=Y("<div>"),oD=Y('<div><div class=media-editor__crop-handles-backdrop></div><div class=media-editor__crop-handles><div class=media-editor__crop-handles-line-h></div><div class=media-editor__crop-handles-line-h></div><div class=media-editor__crop-handles-line-v></div><div class=media-editor__crop-handles-line-v></div><div class="media-editor__crop-handles-side media-editor__crop-handles-side--w"></div><div class="media-editor__crop-handles-side media-editor__crop-handles-side--n"></div><div class="media-editor__crop-handles-side media-editor__crop-handles-side--e"></div><div class="media-editor__crop-handles-side media-editor__crop-handles-side--s"></div><div class="media-editor__crop-handles-circle media-editor__crop-handles-circle--nw"></div><div class="media-editor__crop-handles-circle media-editor__crop-handles-circle--ne"></div><div class="media-editor__crop-handles-circle media-editor__crop-handles-circle--sw"></div><div class="media-editor__crop-handles-circle media-editor__crop-handles-circle--se">'),Ep=20;function lD(){const a=us(Os),[e]=a.canvasSize,[t]=a.currentTab,s=()=>t()==="crop",[i,n]=a.currentImageRatio,[r,o]=a.scale,[l]=a.rotation,[c,d]=a.translation,[u]=a.fixedImageRatioKey,[,h]=a.isMoving,p=Qu(),[m,g]=K([0,0]),[f,v]=K([0,0]),[y,w]=K([0,0]),[b,S]=K([0,0]),_=Kc(FI),M=()=>{const[ie,oe]=Qa(i(),p().width,p().height);return{leftTop:[p().left+(p().width-ie)/2,p().top+(p().height-oe)/2],size:[ie,oe]}};le(Vt(p,()=>{const{leftTop:ie,size:oe}=M();g(ie),w(oe)}));let C;function L(){const ie=b(),oe=f(),ae=m(),ke=y(),re=[0,0],ce=[0,0],{leftTop:Ie,size:Ve}=M();C?.(),C=zi(0,1,200,fe=>{pi(()=>{S(ul(ie,re,fe)),v(ul(oe,ce,fe)),g(ul(ae,Ie,fe)),w(ul(ke,Ve,fe))})})}le(Vt(i,()=>{L()})),Jt(()=>{const ie=[{el:H,left:-1,top:-1},{el:D,left:1,top:-1},{el:U,left:-1,top:1},{el:j,left:1,top:1},{el:q,left:-1,top:0},{el:W,left:0,top:-1},{el:ee,left:1,top:0},{el:z,left:0,top:1}];let oe,ae,ke,re;const ce=ie.map(({el:Ve,left:fe,top:Xe})=>new Qn({element:Ve,setCursorTo:document.body,onStart(){ae=r(),ke=c(),h(!0),Ve.classList.add("media-editor__crop-handles-circle--anti-flicker")},onSwipe(Ye,Ze,Je){if(re||(re=Je.target),re!==Ve)return;const tt=u();let ht=i();fe<0&&(ht=-ht),Xe<0&&(ht=-ht);const[Ee,ve]=y(),Qe=Math.min(Ee,p().width/Ep*Math.min(Ep,ae)),A=Math.min(ve,p().height/Ep*Math.min(Ep,ae));if(Ye=Math.max(Ye*fe,Qe-Ee)*fe,Ze=Math.max(Ze*Xe,A-ve)*Xe,tt)if(Xe===0)Ze=Ye/ht;else if(fe===0)Ye=Ze*ht;else{const te=Ye;Ye=(Ye+Ze*ht)/2,Ze=(te/ht+Ze)/2}S(tt&&Xe===0?[fe*Ye,Ze]:tt&&fe===0?[Ye,Xe*Ze]:[Ye*fe,Ze*Xe]),v([tt&&fe===0?-Ye/2:+(fe<0)*Ye,tt&&Xe===0?-Ze/2:+(Xe<0)*Ze]);const{cropMinX:F,cropMaxX:Q,cropMinY:X,cropMaxY:ge,imageMinX:he,imageMaxX:Le,imageMinY:Se,imageMaxY:xe}=_({scale:ae,rotation:l(),translation:ke,extendCrop:[[tt&&fe===0?-Ye/2:fe===-1?Ye:0,tt&&Xe===0?Ze/2:Xe===1?Ze:0],[tt&&fe===0?Ye/2:fe===1?Ye:0,tt&&Xe===0?-Ze/2:Xe===-1?Ze:0]]}),lt=(Le-he)/2,mt=(xe-Se)/2,at=[he+lt,Se+mt];let kt=1,Us=1;he>F&&(kt*=1+((at[0]-F)/lt-1)/2),Le<Q&&(kt*=1+((Q-at[0])/lt-1)/2),Se>X&&(Us*=1+((at[1]-X)/mt-1)/2),xe<ge&&(Us*=1+((ge-at[1])/mt-1)/2);const Ts=Math.max(kt,Us);Ts>1&&o(ae*Ts);let zs=[0,0];he>F&&(zs[0]+=he-F),Le<Q&&(zs[0]+=Le-Q),Se>X&&(zs[1]+=Se-X),xe<ge&&(zs[1]+=xe-ge);const et=[Math.sin(l()),Math.cos(l())];zs=[zs[0]*et[1]-zs[1]*et[0],zs[1]*et[1]+zs[0]*et[0]],d([ke[0]-zs[0]/2,ke[1]-zs[1]/2])},onReset(){if(re!==Ve)return re=void 0;re=void 0;const Ye=y()[0]+b()[0],Ze=y()[1]+b()[1],Je=Ye/Ze,tt=Math.min(p().width/Ye,p().height/Ze);n(Je),L();const ht=r(),Ee=c(),ve=r()*tt,Qe=[tt*(c()[0]+-b()[0]*fe*.5),tt*(c()[1]+-b()[1]*Xe*.5)];zi(0,1,200,A=>{pi(()=>{o(js(ht,ve,A)),d(ul(Ee,Qe,A))})},{onEnd:()=>h(!1)}),Ve.classList.remove("media-editor__crop-handles-circle--anti-flicker")}})),Ie=new Qn({element:$,onStart(){ke=c(),h(!0)},onSwipe(Ve,fe,Xe){if(re||(re=Xe.target),re!==$)return;const{cropMinX:Ye,cropMaxX:Ze,cropMinY:Je,cropMaxY:tt,imageMinX:ht,imageMaxX:Ee,imageMinY:ve,imageMaxY:Qe}=_({scale:r(),rotation:l(),translation:[ke[0]+Ve,ke[1]+fe]});oe=[0,0],ht>Ye&&(oe[0]=ht-Ye),Ee<Ze&&(oe[0]=Ee-Ze),ve>Je&&(oe[1]=ve-Je),Qe<tt&&(oe[1]=Qe-tt);const A=[Math.sin(l()),Math.cos(l())];oe=[oe[0]*A[1]-oe[1]*A[0],oe[1]*A[1]+oe[0]*A[0]];const F=4;d([ke[0]+Ve-(oe[0]-oe[0]/F),ke[1]+fe-(oe[1]-oe[1]/F)]),oe=[oe[0]/F,oe[1]/F]},onReset(){if(re!==$)return re=void 0;re=void 0;const Ve=c();zi(Ve,[Ve[0]-oe[0],Ve[1]-oe[1]],120,d,{onEnd:()=>h(!1)})}});ze(()=>{ce.forEach(Ve=>Ve.removeListeners()),Ie.removeListeners()})});const E=()=>m()[0]+f()[0],x=()=>m()[1]+f()[1],R=()=>y()[0]+b()[0],B=()=>y()[1]+b()[1],N=()=>E()+R(),G=()=>x()+B(),O=()=>{const[ie,oe]=e();let[ae,ke]=[ie,oe];const re=i();return ae/re>ke?ae=ke*re:ke=ae/re,[(ie-ae)/2,(oe-ke)/2]};let $,H,D,U,j,q,W,ee,z;const Z=()=>({transition:"opacity 0.2s","transition-timing-function":s()?"ease-in":"ease-out","pointer-events":s()?"none":void 0,opacity:s()?0:1}),de=()=>({transition:"transform 0.2s, opacity 0.2s","transition-timing-function":s()?"ease-out":"ease-in","pointer-events":s()?void 0:"none",opacity:s()?1:0,transform:s()?void 0:"scale(1.05)"});return[(()=>{const ie=Lp();return Me(oe=>Ii(ie,{background:"black",position:"absolute",left:"0px",top:"0px",width:"100%",height:O()[1]+"px",...Z()},oe)),ie})(),(()=>{const ie=Lp();return Me(oe=>Ii(ie,{background:"black",position:"absolute",left:"0px",bottom:"0px",width:"100%",height:O()[1]+"px",...Z()},oe)),ie})(),(()=>{const ie=Lp();return Me(oe=>Ii(ie,{background:"black",position:"absolute",left:"0px",top:"0px",height:"100%",width:O()[0]+"px",...Z()},oe)),ie})(),(()=>{const ie=Lp();return Me(oe=>Ii(ie,{background:"black",position:"absolute",right:"0px",top:"0px",height:"100%",width:O()[0]+"px",...Z()},oe)),ie})(),(()=>{const ie=oD(),oe=ie.firstChild,ae=oe.nextSibling,ke=ae.firstChild,re=ke.nextSibling,ce=re.nextSibling,Ie=ce.nextSibling,Ve=Ie.nextSibling,fe=Ve.nextSibling,Xe=fe.nextSibling,Ye=Xe.nextSibling,Ze=Ye.nextSibling,Je=Ze.nextSibling,tt=Je.nextSibling,ht=tt.nextSibling,Ee=$;typeof Ee=="function"?Ue(Ee,ae):$=ae,ke.style.setProperty("top","33%"),re.style.setProperty("top","66%"),ce.style.setProperty("left","33%"),Ie.style.setProperty("left","66%");const ve=q;typeof ve=="function"?Ue(ve,Ve):q=Ve;const Qe=W;typeof Qe=="function"?Ue(Qe,fe):W=fe;const A=ee;typeof A=="function"?Ue(A,Xe):ee=Xe;const F=z;typeof F=="function"?Ue(F,Ye):z=Ye;const Q=H;typeof Q=="function"?Ue(Q,Ze):H=Ze;const X=D;typeof X=="function"?Ue(X,Je):D=Je;const ge=U;typeof ge=="function"?Ue(ge,tt):U=tt;const he=j;return typeof he=="function"?Ue(he,ht):j=ht,Me(Le=>{const Se={position:"absolute",right:"0px",top:"0px",height:"100%",width:"100%",overflow:"hidden",...de()},xe={"clip-path":`polygon(
- 0 0, 0 100%,
- ${E()}px 100%, ${E()}px ${x()}px, ${N()}px ${x()}px,
- ${N()}px ${G()}px, ${E()}px ${G()}px, ${E()}px 100%,
- 100% 100%, 100% 0%
- )`},lt=E()+"px",mt=x()+"px",at=R()+"px",kt=B()+"px";return Le._v$=Ii(ie,Se,Le._v$),Le._v$2=Ii(oe,xe,Le._v$2),lt!==Le._v$3&&((Le._v$3=lt)!=null?ae.style.setProperty("left",lt):ae.style.removeProperty("left")),mt!==Le._v$4&&((Le._v$4=mt)!=null?ae.style.setProperty("top",mt):ae.style.removeProperty("top")),at!==Le._v$5&&((Le._v$5=at)!=null?ae.style.setProperty("width",at):ae.style.removeProperty("width")),kt!==Le._v$6&&((Le._v$6=kt)!=null?ae.style.setProperty("height",kt):ae.style.removeProperty("height")),Le},{_v$:void 0,_v$2:void 0,_v$3:void 0,_v$4:void 0,_v$5:void 0,_v$6:void 0}),ie})()]}function BI(a){const e=us(Os),[t,s]=e.translation,[i,n]=e.scale,[r,o]=e.rotation,[,l]=e.currentImageRatio,[c]=e.fixedImageRatioKey,[d]=e.imageSize,[,u]=e.isMoving,h=Qu(),[p,m]=d();if(!p||!m)return;const g=Math.round(a/Math.PI*2),f=Math.abs(g)&1,v=g*Math.PI/2;let y;if(c()?.includes("x")){const N=c().split("x");y=parseInt(N[0])/parseInt(N[1])}else y=f?m/p:p/m;const w=p/m,[b,S]=Qa(w,h().width,h().height),[_,M]=Qa(y,h().width,h().height),C=i(),L=t(),E=r(),x=f?Math.max(_/S,M/b):Math.max(_/b,M/S),R=[0,0],B=v;l(y),u(!0),zi(0,1,200,N=>{pi(()=>{n(js(C,x,N)),s(ul(L,R,N)),o(js(E,B,N))})},{onEnd:()=>u(!1)})}const cD=Y("<div class=media-editor__rotation-wheel><div class=media-editor__rotation-wheel-swiper-wrapper><div class=media-editor__rotation-wheel-swiper><div class=media-editor__rotation-wheel-labels></div><div class=media-editor__rotation-wheel-dots></div></div></div><div class=media-editor__rotation-wheel-value><div class=media-editor__rotation-wheel-value-number>"),dD=Y("<div class=media-editor__rotation-wheel-label><div class=media-editor__rotation-wheel-label-number>"),hD=Y("<div class=media-editor__rotation-wheel-dot>"),uD=Y('<svg class=media-editor__rotation-wheel-arrow width=6 height=4 viewBox="0 0 6 4"fill=none xmlns=http://www.w3.org/2000/svg><path d="M2.29289 0.707106L0.28033 2.71967C-0.192143 3.19214 0.142482 4 0.81066 4H5.18934C5.85752 4 6.19214 3.19214 5.71967 2.71967L3.70711 0.707107C3.31658 0.316583 2.68342 0.316582 2.29289 0.707106Z"fill=white>'),Bm=42,Dm=15,pD=90,Gf=pD/Dm*Bm,mD=40;function h0(a){return a/Bm*Dm*Math.PI/180}function gD(){const a=us(Os),[e]=a.currentTab,t=()=>e()==="crop",[s,i]=a.rotation,[n,r]=a.flip,[o]=a.fixedImageRatioKey,[l,c]=K(0),[d,u]=K(0),[h,p]=a.scale,[m,g]=a.translation,[,f]=a.isMoving;let v;Jt(()=>{const E=Math.round(s()/Math.PI*2)*Math.PI/2;c((E-s())*180/Math.PI/Dm*Bm),y=h0(l());let x,R,B=H(),N=!1,G=!1,O,$;function H(){return Math.abs(l()+x||0)<mD}function D(j){u(j),b()}function U(){$=window.setTimeout(()=>{G=!1,N=!0;const j=d();O?.(),O=zi(0,1,200,q=>{D(js(j,x,q))},{onEnd:()=>{N=!1}})},750)}new Qn({element:v,onStart(){w=h(),x=d(),R=x,N=!1,G=!1,B=H(),f(!0)},onSwipe(j){R=x=zt(l()+j,-Gf,Gf)-l();const q=H();q&&(R=-l()),B!==q&&(window.clearTimeout($),$=window.setTimeout(()=>{if(H()!==q)return;N=!0;const ee=d();O?.(),O=zi(0,1,200,z=>{D(js(ee,R,z))},{onEnd:()=>{N=!1,G=H(),G&&U()}})},200)),B=q,!(N||G)&&D(x)},onReset(){let j=l()+d();Math.abs(j)===Gf&&(j=0,y=0,B=!1,N=!1),O?.(),window.clearTimeout($),pi(()=>{c(j),u(0),f(!1)})}})});let y=0,w=0;const b=Kc(()=>{const E=h0(l()+d()),x=E-y;i(z=>z-x);const R=[Math.cos(x),Math.sin(x)];if(g(z=>[z[0]*R[0]+z[1]*R[1],z[1]*R[0]-z[0]*R[1]]),y=E,!w)return;const{cropMinX:B,cropMaxX:N,cropMinY:G,cropMaxY:O,imageMinX:$,imageMaxX:H,imageMinY:D,imageMaxY:U}=FI({scale:w,rotation:s(),translation:m()}),j=(H-$)/2,q=(U-D)/2,W=[$+j,D+q];let ee=1;$>B&&(ee=Math.max((W[0]-B)/j,ee)),H<N&&(ee=Math.max((N-W[0])/j,ee)),D>G&&(ee=Math.max((W[1]-G)/q,ee)),U<O&&(ee=Math.max((O-W[1])/q,ee)),ee>1&&p(w*ee)});function S(){y=0,zi([l(),d()],[0,0],200,E=>{pi(()=>{c(E[0]),u(E[1])})})}a.resetRotationWheel=()=>S(),ze(()=>{a.resetRotationWheel=()=>{}});let _=!0;le(Vt(o,()=>{if(_){_=!1;return}S()}));function M(){const E=Math.round(s()/Math.PI*2)*Math.PI/2-Math.PI/2;BI(E),S()}function C(){f(!0);const E=Math.abs(Math.round(s()/Math.PI*2))&1,x=B=>B<0?-1:1,R=[x(n()[0])*(E?1:-1),x(n()[1])*(E?-1:1)];zi(n(),R,200,r,{onEnd:()=>f(!1)})}const L=()=>(-(l()+d())/Bm*Dm).toFixed(1).replace(/\.0$/,"").replace(/^-0$/,"0");return(()=>{const E=cD(),x=E.firstChild,R=x.firstChild,B=R.firstChild,N=B.nextSibling,G=x.nextSibling,O=G.firstChild;k(E,T(Pi,{get onClick(){return Kc(M)},class:"media-editor__rotation-wheel-button",icon:"rotate"}),x);const $=v;return typeof $=="function"?Ue($,R):v=R,k(B,()=>new Array(13).fill(null).map((H,D)=>(()=>{const U=dD(),j=U.firstChild;return k(j,D*15-90),U})())),k(N,()=>new Array(97).fill(null).map(()=>hD())),k(O,L),k(E,T(fD,{}),null),k(E,T(Pi,{onClick:C,class:"media-editor__rotation-wheel-button",icon:"flip_image_horizontal"}),null),Me(H=>{const D=t()?void 0:"none",U={"--moved":l()+d()+"px"};return D!==H._v$&&((H._v$=D)!=null?E.style.setProperty("display",D):E.style.removeProperty("display")),H._v$2=Ii(R,U,H._v$2),H},{_v$:void 0,_v$2:void 0}),E})()}function fD(){return uD()}function vD(a){const[e,t]=K(!1),s=()=>{t(window.matchMedia(a).matches)},i=window.matchMedia(a);return t(i.matches),i.addEventListener("change",s),ze(()=>{i.removeEventListener("change",s)}),e}function Ob(){return vD("(max-width: 800px")}const u0=Y("<div>"),yD=Y("<div class=media-editor__text-layer><div class=media-editor__text-layer-layout contenteditable>");function bD(a){const e=us(Os),[t,s]=e.selectedResizableLayer,[i,n]=e.currentTextLayerInfo,[r,o]=e.textLayersInfo,[,l]=e.resizableLayers,[c,d]=a.layerSignal;if(!c().textInfo)return;const u=()=>{pi(()=>{s(c().id),n({color:c().textInfo.color,alignment:c().textInfo.alignment,style:c().textInfo.style,size:c().textInfo.size,font:c().textInfo.font})})},h=()=>Hh[c().textInfo.font];function p(){let _=-1,M;o(C=>({...C,[c().id]:void 0})),l(C=>(C=[...C],_=C.findIndex(L=>L[0]().id===c().id),_>-1&&(M=C.splice(_,1)?.[0][0]?.()),C)),e.pushToHistory({undo(){pi(()=>{l(C=>(C=[...C],_>-1&&C.splice(_,0,K({...M})),C)),s(M.id)})},redo(){l(C=>(C=[...C],_=C.findIndex(L=>L[0]().id===M.id),_>-1&&(M=C.splice(_,1)[0]?.[0]()),C))}})}function m(){if(y.childNodes.forEach(L=>{if(L instanceof HTMLDivElement&&!L.hasAttributes())L.querySelectorAll("*").forEach(E=>{const x=document.createTextNode(E.textContent);E.replaceWith(x)});else{const E=document.createElement("div");E.textContent=L.textContent,L.replaceWith(E)}}),!y.textContent){y.innerHTML="<div></div>";const L=y.children[0],E=document.createRange(),x=window.getSelection();E.setStart(L,0),E.collapse(!0),x.removeAllRanges(),x.addRange(E)}const _=window.getSelection();if(_.rangeCount>0){const L=_.getRangeAt(0);if(L.startContainer===y&&L.startOffset===0){const E=y.children[0],x=document.createRange();x.selectNodeContents(E),x.collapse(!1),_.removeAllRanges(),_.addRange(x)}}v.querySelector(".media-editor__text-layer-background")?.remove();const M=wD(y,c().textInfo.alignment),C=SD(M);c().textInfo.style==="background"&&CD(v,C.join(" "),c().textInfo),c().textInfo.style==="outline"&&_D(v,y,c().textInfo),o(L=>({...L,[c().id]:{width:v.clientWidth,height:v.clientHeight,path:C,lines:M}}))}function g(){const _=document.createRange();_.selectNodeContents(y.children[0]);const M=window.getSelection();M.removeAllRanges(),M.addRange(_)}le(()=>{m()});const f=V(()=>c().id===t());Jt(()=>{f()&&g()}),le(()=>{f()&&ze(()=>{y.innerText.trim()||p()})}),le(Vt(i,()=>{t()===c().id&&d(_=>({..._,textInfo:i()}))})),Jt(()=>{v.addEventListener("dragstart",_=>{_.preventDefault()})});let v,y;const w=()=>c().textInfo.style==="normal"?c().textInfo.color:bv(c().textInfo.color),b=(()=>{const _=r()[c().id];return _?_.lines.map(M=>(()=>{const C=u0();return k(C,()=>M.content),C})()):(()=>{const M=u0();return k(M,()=>P("MediaEditor.TypeSomething")),M})()})(),S=(()=>{const _=yD(),M=_.firstChild,C=v;typeof C=="function"?Ue(C,_):v=_,M.addEventListener("focus",u),M.$$input=()=>m();const L=y;return typeof L=="function"?Ue(L,M):y=M,k(M,b),Me(E=>{const x=c().textInfo.style==="background",R=w(),B=c().textInfo.size+"px",N=h().fontFamily,G=h().fontWeight,O=ID[c().textInfo.alignment];return x!==E._v$&&_.classList.toggle("media-editor__text-layer--with-bg",E._v$=x),R!==E._v$2&&((E._v$2=R)!=null?_.style.setProperty("color",R):_.style.removeProperty("color")),B!==E._v$3&&((E._v$3=B)!=null?_.style.setProperty("font-size",B):_.style.removeProperty("font-size")),N!==E._v$4&&((E._v$4=N)!=null?_.style.setProperty("font-family",N):_.style.removeProperty("font-family")),G!==E._v$5&&((E._v$5=G)!=null?_.style.setProperty("font-weight",G):_.style.removeProperty("font-weight")),O!==E._v$6&&((E._v$6=O)!=null?_.style.setProperty("--align-items",O):_.style.removeProperty("--align-items")),E},{_v$:void 0,_v$2:void 0,_v$3:void 0,_v$4:void 0,_v$5:void 0,_v$6:void 0}),_})();return T($I,{get layerSignal(){return a.layerSignal},onDoubleClick:()=>g(),children:S})}function wD(a,e){return Array.from(a.children).map(t=>{const s=t;let i=0;return e==="left"?i=0:e==="center"?i=(a.clientWidth-s.clientWidth)/2:i=a.clientWidth-s.clientWidth,{left:i,right:i+s.clientWidth,content:s.innerText,height:s.clientHeight}})}function SD(a){const e=a[0],t=e.height*.3,s=(l,c=1)=>[l,l,0,0,c],i=[];i.push("M",e.left,t),i.push("A",...s(t),e.left+t,0),i.push("L",e.right-t,0),i.push("A",...s(t),e.right,t);let n=e,r=e.height;for(let l=1;l<a.length;l++){const c=a[l],d=c.right>n.right?1:-1,u=Math.min(Math.abs((c.right-n.right)/2),t)*d,h=Math.abs(u);i.push("L",n.right,r-h),i.push("A",...s(h,d===1?0:1),n.right+u,r),i.push("L",c.right-u,r),i.push("A",...s(h,d===1?1:0),c.right,r+h),r+=c.height,n=c}i.push("L",n.right,r-t),i.push("A",...s(t),n.right-t,r),i.push("L",n.left+t,r),i.push("A",...s(t),n.left,r-t);const o=a[a.length-1];r-=o.height;for(let l=a.length-2;l>=0;l--){const c=a[l],d=c.left>n.left?1:-1,u=Math.min(Math.abs((c.left-n.left)/2),t)*d,h=Math.abs(u);i.push("L",n.left,r+h),i.push("A",...s(h,d!==1?0:1),n.left+u,r),i.push("L",c.left-u,r),i.push("A",...s(h,d!==1?1:0),c.left,r-h),r-=c.height,n=c}return i}function CD(a,e,t){const s=gr(`
- <svg width="${a.clientWidth}" height="${a.clientHeight}" viewBox="0 0 ${a.clientWidth} ${a.clientHeight}">
- <path d="${e}" fill="${t.color}" />
- </svg>
- `);return s.classList.add("media-editor__text-layer-background"),a.prepend(s),e}function _D(a,e,t){const s=Hh[t.font];function i(r){r.querySelector(".media-editor__text-layer-svg-outline")?.remove();const o=t.size*.5,l=r.clientWidth+o,c=r.clientHeight+o,d=gr(`
- <div class="media-editor__text-layer-svg-outline" style="width: ${l}px; height: ${c}px;">
- <svg style="width: ${l}px; height: ${c}px;" viewBox="${-o/2} 0 ${r.clientWidth+o/2} ${r.clientHeight+o}">
- <text
- x="${t.size*.2}"
- y="${t.size*1.33*s.baseline}"
- style="font-size:${t.size}px;stroke:${t.color};stroke-width:${r.clientHeight*.15}px;font-family:${s.fontFamily};font-weight:${s.fontWeight};">
- ${r.innerText}
- </text>
- </svg>
- </div>
- `);r.prepend(d)}const n=document.createElement("div");n.classList.add("media-editor__text-layer-background","media-editor__text-layer-background--as-layout"),n.innerHTML=e.innerHTML,a.prepend(n),Array.from(n.children).forEach(r=>{r instanceof HTMLDivElement&&i(r)})}const ID={left:"start",center:"center",right:"end"};Fs(["input"]);const PD=Y("<div class=media-editor__sticker-layer-content>");function MD(a){const e=us(Os),[,t]=e.stickersLayersInfo;let s;const[i]=a.layerSignal;Jt(()=>{const r=ui();ai({div:s,doc:i().sticker,group:"none",width:500,height:500,play:!0,loop:!0,withThumb:!1,middleware:r.get()}),t(o=>({...o,[i().id]:{container:s}})),ze(()=>{r.destroy()})});const n=(()=>{const r=PD(),o=s;return typeof o=="function"?Ue(o,r):s=r,r})();return T($I,{get layerSignal(){return a.layerSignal},children:n})}function jg(){const a=us(Os),[e]=a.canvasSize,[t]=a.finalTransform,s=V(()=>e().map(i=>i*a.pixelRatio));return i=>{const n=t(),[r,o]=s();i=i.map(c=>c*a.pixelRatio),i=[(i[0]-n.translation[0]-r/2)/n.scale,(i[1]-n.translation[1]-o/2)/n.scale];const l=[Math.sin(n.rotation),Math.cos(n.rotation)];return i=[i[0]*l[1]+i[1]*l[0],i[1]*l[1]-i[0]*l[0]],i}}function DI(a=!0){const e=us(Os),[t]=e.canvasSize,[s]=e.finalTransform,i=V(()=>t().map(n=>n*e.pixelRatio));return n=>{const[r,o]=i(),l=s(),c=[Math.sin(-l.rotation),Math.cos(-l.rotation)];return n=[n[0]*c[1]+n[1]*c[0],n[1]*c[1]-n[0]*c[0]],n=[(n[0]*l.scale+r/2+l.translation[0])/(a?1:e.pixelRatio),(n[1]*l.scale+o/2+l.translation[1])/(a?1:e.pixelRatio)],n}}const LD=Y("<div class=media-editor__resizable-layers><div class=media-editor__resizable-layers-inner>"),ED=Y("<div class=media-editor__resizable-container>"),kD=Y('<div class=media-editor__resizable-container-handles><div class="media-editor__resizable-container-border media-editor__resizable-container-border--vertical"></div><div class="media-editor__resizable-container-border media-editor__resizable-container-border--vertical"></div><div class="media-editor__resizable-container-border media-editor__resizable-container-border--horizontal"></div><div class="media-editor__resizable-container-border media-editor__resizable-container-border--horizontal"></div><div class=media-editor__resizable-container-circle></div><div class=media-editor__resizable-container-circle></div><div class=media-editor__resizable-container-circle></div><div class=media-editor__resizable-container-circle>');function TD(){const a=us(Os),[e,t]=a.resizableLayers,[s]=a.currentTab,i=()=>s()==="text",n=()=>["stickers","text","adjustments"].includes(s()),[r]=a.currentTextLayerInfo,[o,l]=a.selectedResizableLayer,[c]=a.isAdjusting,[d]=a.finalTransform;le(Vt(o,()=>{t(m=>{const g=[...m||[]],f=g.findIndex(v=>v[0]().id===o());if(f>-1){const v=g[f];return g.splice(f,1),g.push(v),g}return m})})),le(()=>{s(),ze(()=>{l()})});let u;const h=jg();function p(m){if(m.target!==u)return;if(o()){l();return}if(!i())return;const g=u.getBoundingClientRect(),f=d(),v={id:a.resizableLayersSeed++,position:h([m.clientX-g.left,m.clientY-g.top]),rotation:-f.rotation,scale:1/f.scale,type:"text",textInfo:r()};pi(()=>{t(b=>[...b,K({...v})]),l(v.id)});let y=-1,w;a.pushToHistory({undo(){t(b=>(b=[...b],y=b.findIndex(S=>S[0]().id===v.id),y>-1&&(w=b.splice(y,1)[0]?.[0]()),b))},redo(){t(b=>(b=[...b],y>-1&&b.splice(y,0,K({...w})),b))}})}return(()=>{const m=LD(),g=m.firstChild;Lr(g,"click",Kc(p),!0);const f=u;return typeof f=="function"?Ue(f,g):u=g,k(g,T(Cs,{get each(){return e()},children:v=>[T(Js,{get when(){return v[0]().type==="text"},get children(){return T(bD,{layerSignal:v})}}),T(Js,{get when(){return v[0]().type==="sticker"},get children(){return T(MD,{layerSignal:v})}})]})),Me(v=>{const y=!!n(),w=!o()&&i()?"text":void 0,b=c()?0:1;return y!==v._v$&&m.classList.toggle("media-editor__resizable-layers--active",v._v$=y),w!==v._v$2&&((v._v$2=w)!=null?m.style.setProperty("cursor",w):m.style.removeProperty("cursor")),b!==v._v$3&&((v._v$3=b)!=null?g.style.setProperty("opacity",b):g.style.removeProperty("opacity")),v},{_v$:void 0,_v$2:void 0,_v$3:void 0}),m})()}function $I(a){const e=us(Os),[t]=e.rotation,[s,i]=e.selectedResizableLayer,[n]=e.finalTransform,[r]=e.resizeHandlesContainer,o=Ob(),l=DI(!1),[c]=a.layerSignal,d=()=>{},u=FL({diff:[0,0],containerWidth:0,containerHeight:0,leftTopEl:d(),rightTopEl:d(),leftBottomEl:d(),rightBottomEl:d()}),h=()=>o()?"-6px":"-4px",p=()=>r()&&c().id===s(),m=V(()=>({position:l(c().position),rotation:c().rotation+t(),scale:n().scale*c().scale}));let g;return Jt(()=>{xD({container:g,leftBottomEl:()=>u.leftBottomEl,leftTopEl:()=>u.leftTopEl,rightBottomEl:()=>u.rightBottomEl,rightTopEl:()=>u.rightTopEl,onDiffChange:v=>u.diff=v,layerSignal:a.layerSignal,diff:()=>u.diff,processedLayer:m}),AD({container:g,layer:c});const f=Gy(g,()=>{u.containerWidth=g.clientWidth,u.containerHeight=g.clientHeight});ze(()=>{f()})}),(()=>{const f=ED(),v=g;return typeof v=="function"?Ue(v,f):g=f,f.$$click=()=>{i(c().id)},k(f,()=>a.children,null),k(f,(()=>{const y=V(()=>!!p());return()=>y()&&T(gd,{get mount(){return r()},get children(){const w=kD(),b=w.firstChild,S=b.nextSibling,_=S.nextSibling,M=_.nextSibling,C=M.nextSibling,L=C.nextSibling,E=L.nextSibling,x=E.nextSibling;return b.style.setProperty("left","0"),S.style.setProperty("right","0"),_.style.setProperty("top","0"),M.style.setProperty("bottom","0"),Ue(R=>u.leftTopEl=R,C),Ue(R=>u.rightTopEl=R,L),Ue(R=>u.leftBottomEl=R,E),Ue(R=>u.rightBottomEl=R,x),Me(R=>{const B=m().position[0]+u.diff[0]+"px",N=m().position[1]+u.diff[1]+"px",G=u.containerWidth*m().scale+"px",O=u.containerHeight*m().scale+"px",$=m().rotation/Math.PI*180+"deg",H=h(),D=h(),U=h(),j=h(),q=h(),W=h(),ee=h(),z=h();return B!==R._v$8&&((R._v$8=B)!=null?w.style.setProperty("left",B):w.style.removeProperty("left")),N!==R._v$9&&((R._v$9=N)!=null?w.style.setProperty("top",N):w.style.removeProperty("top")),G!==R._v$10&&((R._v$10=G)!=null?w.style.setProperty("width",G):w.style.removeProperty("width")),O!==R._v$11&&((R._v$11=O)!=null?w.style.setProperty("height",O):w.style.removeProperty("height")),$!==R._v$12&&((R._v$12=$)!=null?w.style.setProperty("--rotation",$):w.style.removeProperty("--rotation")),H!==R._v$13&&((R._v$13=H)!=null?C.style.setProperty("left",H):C.style.removeProperty("left")),D!==R._v$14&&((R._v$14=D)!=null?C.style.setProperty("top",D):C.style.removeProperty("top")),U!==R._v$15&&((R._v$15=U)!=null?L.style.setProperty("right",U):L.style.removeProperty("right")),j!==R._v$16&&((R._v$16=j)!=null?L.style.setProperty("top",j):L.style.removeProperty("top")),q!==R._v$17&&((R._v$17=q)!=null?E.style.setProperty("left",q):E.style.removeProperty("left")),W!==R._v$18&&((R._v$18=W)!=null?E.style.setProperty("bottom",W):E.style.removeProperty("bottom")),ee!==R._v$19&&((R._v$19=ee)!=null?x.style.setProperty("right",ee):x.style.removeProperty("right")),z!==R._v$20&&((R._v$20=z)!=null?x.style.setProperty("bottom",z):x.style.removeProperty("bottom")),R},{_v$8:void 0,_v$9:void 0,_v$10:void 0,_v$11:void 0,_v$12:void 0,_v$13:void 0,_v$14:void 0,_v$15:void 0,_v$16:void 0,_v$17:void 0,_v$18:void 0,_v$19:void 0,_v$20:void 0}),w}})})(),null),Me(y=>{const w=m().position[0]+u.diff[0]+"px",b=m().position[1]+u.diff[1]+"px",S=m().rotation/Math.PI*180+"deg",_=m().scale;return w!==y._v$4&&((y._v$4=w)!=null?f.style.setProperty("left",w):f.style.removeProperty("left")),b!==y._v$5&&((y._v$5=b)!=null?f.style.setProperty("top",b):f.style.removeProperty("top")),S!==y._v$6&&((y._v$6=S)!=null?f.style.setProperty("--rotation",S):f.style.removeProperty("--rotation")),_!==y._v$7&&((y._v$7=_)!=null?f.style.setProperty("--scale",_):f.style.removeProperty("--scale")),y},{_v$4:void 0,_v$5:void 0,_v$6:void 0,_v$7:void 0}),f})()}function xD({container:a,leftTopEl:e,rightTopEl:t,leftBottomEl:s,rightBottomEl:i,diff:n,onDiffChange:r,layerSignal:o,processedLayer:l}){const c=us(Os),[d]=c.rotation,[,u]=c.selectedResizableLayer,[h]=c.finalTransform,p=jg(),[m,g]=o;let f,v=!1;const y=[{el:e,x:-1,y:-1},{el:t,x:1,y:-1},{el:s,x:-1,y:1},{el:i,x:1,y:1}];y.forEach(({el:b,x:S,y:_})=>{le(()=>{const M=b();if(!M)return;const C=new Qn({element:M,onStart(){M.classList.add("media-editor__resizable-container-circle--anti-flicker")},onSwipe(L,E,x){const R=ym(x);if(f||(f=R.target),f!==M)return;const B=[a.clientWidth/2*S*h().scale,a.clientHeight/2*_*h().scale],N=a.getBoundingClientRect(),G=[N.left+N.width/2-R.clientX,N.top+N.height/2-R.clientY],O=Math.atan2(G[1],G[0])-Math.atan2(B[1],B[0])+Math.PI,$=Math.hypot(G[0],G[1])/Math.hypot(B[0],B[1]);g(H=>({...H,rotation:O-d(),scale:$}))},onReset(){M.classList.remove("media-editor__resizable-container-circle--anti-flicker"),f=void 0}});ze(()=>{C.removeListeners()})})});const w=new Qn({element:a,onSwipe(b,S,_){f||(f=_.target),!y.find(({el:M})=>M()===f)&&(v||(v=!0,u(m().id)),r([b,S]))},onReset(){g(b=>({...b,position:p([l().position[0]+n()[0],l().position[1]+n()[1]])})),r([0,0]),v=!1,f=void 0}});ze(()=>{w.removeListeners()})}function AD({container:a,layer:e}){const t=us(Os),[,s]=t.selectedResizableLayer,[,i]=t.resizableLayers;function n(){let o=-1,l;i(c=>(c=[...c],o=c.findIndex(d=>d[0]().id===e().id),o>-1&&(l=c.splice(o,1)?.[0][0]?.()),c)),s(),t.pushToHistory({undo(){i(c=>(c=[...c],o>-1&&c.splice(o,0,K({...l})),c))},redo(){i(c=>(c=[...c],o=c.findIndex(d=>d[0]().id===l.id),o>-1&&(l=c.splice(o,1)[0]?.[0]()),c))}})}const r=Dn({buttons:[{icon:"delete",className:"danger",text:"Delete",onClick:n}],listenTo:a,onElementReady:o=>{o.classList.add("night")}});ze(()=>{r.destroy()})}Fs(["click"]);function RD(a,e,t){const s=a.createBuffer();a.bindBuffer(a.ARRAY_BUFFER,s);const i=[0,0,e,0,0,t,e,t];return a.bufferData(a.ARRAY_BUFFER,new Float32Array(i),a.STATIC_DRAW),s}function FD(a){const e=a.createBuffer();a.bindBuffer(a.ARRAY_BUFFER,e);const t=[0,0,1,0,0,1,1,1];return a.bufferData(a.ARRAY_BUFFER,new Float32Array(t),a.STATIC_DRAW),e}function BD(a,e,t){const s=p0(a,a.VERTEX_SHADER,e),i=p0(a,a.FRAGMENT_SHADER,t),n=a.createProgram();return a.attachShader(n,s),a.attachShader(n,i),a.linkProgram(n),a.getProgramParameter(n,a.LINK_STATUS)?n:(ZC.error(`Unable to initialize the shader program: ${a.getProgramInfoLog(n)}`),null)}function p0(a,e,t){const s=a.createShader(e);return a.shaderSource(s,t),a.compileShader(s),a.getShaderParameter(s,a.COMPILE_STATUS)?s:(ZC.error(`An error occurred compiling the shaders: ${a.getShaderInfoLog(s)}`),a.deleteShader(s),null)}function DD(a,e){const t=a.createTexture();a.bindTexture(a.TEXTURE_2D,t);const s=new Image;return new Promise(i=>{s.addEventListener("load",()=>{a.bindTexture(a.TEXTURE_2D,t),a.texImage2D(a.TEXTURE_2D,0,a.RGBA,a.RGBA,a.UNSIGNED_BYTE,s),a.texParameteri(a.TEXTURE_2D,a.TEXTURE_WRAP_S,a.CLAMP_TO_EDGE),a.texParameteri(a.TEXTURE_2D,a.TEXTURE_WRAP_T,a.CLAMP_TO_EDGE),a.texParameteri(a.TEXTURE_2D,a.TEXTURE_MIN_FILTER,a.LINEAR),a.texParameteri(a.TEXTURE_2D,a.TEXTURE_MAG_FILTER,a.NEAREST),i({texture:t,image:s})}),s.src=e})}async function Ub(a,e){const[{vertexShaderSource:t,fragmentShaderSource:s},{texture:i,image:n}]=await Promise.all([zo(()=>import("./shaderSources-BxWAu5ue.js"),[],import.meta.url),DD(a,e.imageSrc)]),r=BD(a,t,s),o={position:RD(a,n.width,n.height),texture:FD(a)};return{program:r,buffers:o,image:n,texture:i,attribs:{vertexPosition:a.getAttribLocation(r,"aVertexPosition"),textureCoord:a.getAttribLocation(r,"aTextureCoord")},uniforms:{uSampler:a.getUniformLocation(r,"uSampler"),uFlip:a.getUniformLocation(r,"uFlip"),uAngle:a.getUniformLocation(r,"uAngle"),uResolution:a.getUniformLocation(r,"uResolution"),uTranslation:a.getUniformLocation(r,"uTranslation"),uScale:a.getUniformLocation(r,"uScale"),uImageSize:a.getUniformLocation(r,"uImageSize"),...Object.fromEntries(e.adjustments.map(({uniform:l})=>[l,a.getUniformLocation(r,l)]))}}}function Hb(a,e,t){a.viewport(0,0,a.canvas.width,a.canvas.height),a.clearColor(0,0,0,1),a.clear(a.COLOR_BUFFER_BIT),a.bindBuffer(a.ARRAY_BUFFER,e.buffers.position),a.vertexAttribPointer(e.attribs.vertexPosition,2,a.FLOAT,!1,0,0),a.enableVertexAttribArray(e.attribs.vertexPosition),a.bindBuffer(a.ARRAY_BUFFER,e.buffers.texture),a.vertexAttribPointer(e.attribs.textureCoord,2,a.FLOAT,!1,0,0),a.enableVertexAttribArray(e.attribs.textureCoord),a.useProgram(e.program),a.activeTexture(a.TEXTURE0),a.bindTexture(a.TEXTURE_2D,e.texture),a.uniform1i(e.uniforms.uSampler,0),a.uniform1f(e.uniforms.uAngle,-t.rotation),a.uniform2f(e.uniforms.uResolution,a.canvas.width,a.canvas.height),a.uniform1f(e.uniforms.uScale,t.scale),a.uniform2fv(e.uniforms.uTranslation,t.translation),a.uniform2fv(e.uniforms.uImageSize,t.imageSize),a.uniform2fv(e.uniforms.uFlip,t.flip),a.uniform1f(e.uniforms.uSaturation,t.saturation),a.uniform1f(e.uniforms.uBrightness,t.brightness),a.uniform1f(e.uniforms.uContrast,t.contrast),a.uniform1f(e.uniforms.uWarmth,t.warmth),a.uniform1f(e.uniforms.uFade,t.fade),a.uniform1f(e.uniforms.uShadows,t.shadows),a.uniform1f(e.uniforms.uHighlights,t.highlights),a.uniform1f(e.uniforms.uVignette,t.vignette),a.uniform1f(e.uniforms.uGrain,t.grain),a.uniform1f(e.uniforms.uSharpen,t.sharpen),a.uniform1f(e.uniforms.uEnhance,t.enhance),a.drawArrays(a.TRIANGLE_STRIP,0,4)}const dg=class dg{constructor({targetCanvas:e,imageCanvas:t,blurAmount:s=dg.defaultBlurAmount}){this.brushes={pen:(i,n)=>{n.strokeStyle=i.color,this.drawLinePath(i,n)},arrow:(i,n,r)=>{const{points:o}=i;n.strokeStyle=i.color,this.drawLinePath(i,n),r&&(o.length<2||this.drawArrowHead(n,i,this.getArrowHeadLength(i)))},brush:(i,n)=>{n.strokeStyle=`rgba(${JC(i.color).join(",")},0.4)`,this.drawLinePath(i,n)},neon:(i,n)=>{n.strokeStyle="#ffffff",n.shadowBlur=i.size,n.shadowColor=i.color,this.drawLinePath(i,n)},blur:(i,n)=>{const r=n.canvas.width,o=n.canvas.height;this.blurredLineCtx.clearRect(0,0,r,o);const{points:l}=i,c=l.map(g=>g[0]),d=l.map(g=>g[1]),u=Math.max(Math.min(...c)-i.size,0),h=Math.max(...c)+i.size,p=Math.max(Math.min(...d)-i.size,0),m=Math.max(...d)+i.size;this.blurredLineCtx.strokeStyle="white",this.drawLinePath(i,this.blurredLineCtx),this.blurredLineCtx.globalCompositeOperation="source-in",this.blurredLineCtx.drawImage(this.blurredImageCanvas,0,0),n.drawImage(this.blurredLineCanvas,u,p,h,m,u,p,h,m),this.blurredLineCtx.globalCompositeOperation="source-over"},eraser:(i,n)=>{n.strokeStyle="white",n.globalCompositeOperation="destination-out",this.drawLinePath(i,n),n.stroke(),n.globalCompositeOperation="source-over"}},this.targetCtx=e.getContext("2d"),this.imageCanvas=t,this.blurAmount=s,this.cacheCanvas=document.createElement("canvas"),this.blurredImageCanvas=document.createElement("canvas"),this.blurredLineCanvas=document.createElement("canvas"),this.width=this.cacheCanvas.width=this.blurredImageCanvas.width=this.blurredLineCanvas.width=e.width,this.height=this.cacheCanvas.height=this.blurredImageCanvas.height=this.blurredLineCanvas.height=e.height,this.cacheCtx=this.cacheCanvas.getContext("2d"),this.blurredImageCtx=this.blurredImageCanvas.getContext("2d"),this.blurredLineCtx=this.blurredLineCanvas.getContext("2d")}previewLine(e,t=!1){this.targetCtx.clearRect(0,0,this.width,this.height),this.targetCtx.drawImage(this.cacheCanvas,0,0);const s=this.brushes[e.brush];this.targetCtx.save(),s(e,this.targetCtx,t),this.targetCtx.restore()}saveLastLine(){this.cacheCtx.clearRect(0,0,this.width,this.height),this.cacheCtx.drawImage(this.targetCtx.canvas,0,0),this.updateBlurredImage()}updateBlurredImage(){this.blurredImageCtx.clearRect(0,0,this.width,this.height),this.blurredImageCtx.filter=`blur(${this.blurAmount}px)`,this.blurredImageCtx.drawImage(this.imageCanvas,0,0,this.width,this.height),this.blurredImageCtx.drawImage(this.cacheCanvas,0,0)}drawLine(e){this.previewLine(e,!0),this.saveLastLine()}clear(){this.targetCtx.clearRect(0,0,this.width,this.height),this.cacheCtx.clearRect(0,0,this.width,this.height)}drawLinePath(e,t){const{points:s}=e;if(!s.length)return;if(s.length===1){t.fillStyle=t.strokeStyle,t.beginPath(),t.arc(s[0][0],s[0][1],e.size/2,0,2*Math.PI),t.fill();return}t.lineWidth=e.size,t.lineCap="round",t.lineJoin="round",t.beginPath(),t.moveTo(s[0][0],s[0][1]);for(let n=1;n<s.length-2;n++){const r=(s[n][0]+s[n+1][0])/2,o=(s[n][1]+s[n+1][1])/2;t.quadraticCurveTo(s[n][0],s[n][1],r,o)}const i=s.length-1;t.quadraticCurveTo(s[i-1][0],s[i-1][1],s[i][0],s[i][1]),t.stroke()}getArrowHeadLength(e){return Math.sqrt(e.size)+e.size*2.5}drawArrowHead(e,t,s){const{points:i}=t;if(i.length<2)return;const n=i.length-1;let r=n;for(;r>0&&!(e_(i[n],i[r])>t.size*.5);r--);const o=Math.atan2(i[n][0]-i[r][0],i[n][1]-i[r][1])+Math.PI,l=o+Math.PI/4,c=o-Math.PI/4,d=[s*Math.sin(l),s*Math.cos(l)],u=[s*Math.sin(c),s*Math.cos(c)];e.strokeStyle=t.color,e.lineWidth=t.size,e.lineCap="round",e.lineJoin="round",e.beginPath(),e.moveTo(i[n][0],i[n][1]),e.lineTo(i[n][0]+d[0],i[n][1]+d[1]),e.moveTo(i[n][0],i[n][1]),e.lineTo(i[n][0]+u[0],i[n][1]+u[1]),e.stroke()}async animateArrowBrush(e){const{points:t}=e;if(t.length<2)return;const s=this.targetCtx,i=this.getArrowHeadLength(e),n=Mt();zi(.1,i,120,r=>this.drawArrowHead(s,e,r),{onEnd:()=>n.resolve()}),await n}};dg.defaultBlurAmount=10;let _l=dg;const $D=Y("<canvas class=media-editor__brush-canvas>"),m0=Y("<canvas>");function ND(a,e){const t=us(Os),[s]=t.flip;e&&Hb(a,e,{flip:s(),rotation:0,scale:1,translation:[0,0],imageSize:[e.image.width,e.image.height],...Object.fromEntries(t.adjustments.map(({key:i,signal:n,to100:r})=>{const o=n[0]();return[i,o/(r?100:50)]}))})}function OD(){const a=us(Os),[e]=a.imageCanvas,[t]=a.imageSize,[s]=a.canvasSize,[i]=a.currentBrush,[n]=a.currentTab,[,r]=a.selectedResizableLayer,[o,l]=a.brushDrawnLines,[c]=a.isAdjusting,[d]=a.finalTransform,[u]=a.isMoving,[h,p]=K(),m=jg(),g=DI();function f(O){const $=d();return{...O,size:O.size*$.scale,points:O.points.map(g)}}const v=V(()=>o().map(f)),[y,w]=K(),b=(()=>{const O=$D();return Me($=>{const H=n()==="brush",D=c()?0:1,U=s()[0]*a.pixelRatio,j=s()[1]*a.pixelRatio;return H!==$._v$&&O.classList.toggle("media-editor__brush-canvas--active",$._v$=H),D!==$._v$2&&(($._v$2=D)!=null?O.style.setProperty("opacity",D):O.style.removeProperty("opacity")),U!==$._v$3&&Es(O,"width",$._v$3=U),j!==$._v$4&&Es(O,"height",$._v$4=j),$},{_v$:void 0,_v$2:void 0,_v$3:void 0,_v$4:void 0}),O})(),S=b.getContext("2d"),_=()=>Math.min(s()[0]/t()[0],s()[1]/t()[1])*2*a.pixelRatio,M=(()=>{const O=m0();return Me($=>{const H=t()[0],D=t()[1];return H!==$._v$5&&Es(O,"width",$._v$5=H),D!==$._v$6&&Es(O,"height",$._v$6=D),$},{_v$5:void 0,_v$6:void 0}),O})(),C=M.getContext("webgl",{preserveDrawingBuffer:!0}),L=(()=>{const O=m0();return Me($=>{const H=t()[0]*_(),D=t()[1]*_();return H!==$._v$7&&Es(O,"width",$._v$7=H),D!==$._v$8&&Es(O,"height",$._v$8=D),$},{_v$7:void 0,_v$8:void 0}),O})();let E=new _l({imageCanvas:e(),targetCanvas:b}),x;Jt(async()=>{p(await Ub(C,a))}),le(()=>{const O=h();ND(C,O)}),le(Vt(h,()=>{h()&&setTimeout(()=>G(),100)})),le(Vt(s,()=>{E=new _l({imageCanvas:e(),targetCanvas:b}),B()}));function R(){w({color:i().color,brush:i().brush,size:i().size*a.pixelRatio/d().scale,points:[]})}le(()=>{R()}),le(()=>{if(u()){const O=d();S.clearRect(0,0,b.width,b.height),S.save(),S.translate(O.translation[0]+b.width/2,O.translation[1]+b.height/2),S.rotate(O.rotation),S.scale(O.scale,O.scale);const[$,H]=t();S.drawImage(L,-($/2),-(H/2),$,H),S.restore()}else B(),G()});function B(){E.clear(),E.saveLastLine(),v().forEach(O=>E.drawLine(O))}function N(O){return{...O,size:O.size*_(),points:O.points.map($=>[($[0]+t()[0]/2)*_(),($[1]+t()[1]/2)*_()])}}function G(){x&&(x.clear(),x.saveLastLine(),o().forEach(O=>x.drawLine(N(O))))}return le(Vt(t,()=>{t()?.[0]&&(x=new _l({imageCanvas:M,targetCanvas:L,blurAmount:_l.defaultBlurAmount*_()}),B(),G())})),le(()=>{c()&&ze(()=>{B(),G()})}),a.redrawBrushes=()=>{B(),G()},ze(()=>{a.redrawBrushes=()=>{}}),Jt(()=>{let O,$=[],H=0;function D(){const q=[...o()],W=[...o(),y()];l(W),x.updateBlurredImage(),x.drawLine(N(y())),R(),E.saveLastLine(),a.pushToHistory({undo(){l(q),a.redrawBrushes()},redo(){l(W),a.redrawBrushes()}}),$=[],O=void 0}function U(q,W){const ee=b.getBoundingClientRect();O=[q-ee.left,W-ee.top],$=[m(O)],w(Z=>({...Z,points:$})),E.updateBlurredImage(),E.previewLine(f(y())),r()}function j(){$.length===1&&D()}b.addEventListener("mousedown",q=>{U(q.clientX,q.clientY)}),b.addEventListener("touchstart",q=>{U(q.touches[0].clientX,q.touches[0].clientY)}),b.addEventListener("mouseup",()=>{j()}),b.addEventListener("touchend",()=>{j()}),new Qn({element:b,cursor:"",onSwipe:(q,W,ee)=>{const z=m([O[0]+q,O[1]+W]);if($.length>0){const Z=$[$.length-1];H+=e_(g(Z),g(z))}H<Math.min(y().size,12)*a.pixelRatio&&$.length>1?$[$.length-1]=z:($.push(z),H=0),w(Z=>({...Z,points:$})),E.previewLine(f(y()))},onReset(){(async()=>(H=0,y().brush==="arrow"&&await E.animateArrowBrush(f(y())),D()))()}})}),b}const UD=Y("<canvas>");function HD(a){const e=us(Os),[t]=e.renderingPayload,[s]=e.finalTransform,i=t();i&&Hb(a,i,{...s(),imageSize:[i.image.width,i.image.height],...Object.fromEntries(e.adjustments.map(({key:n,signal:r,to100:o})=>{const l=r[0]();return[n,l/(o?100:50)]}))})}function GD(){const a=us(Os),[e]=a.isReady,[t]=a.canvasSize,[s,i]=a.currentImageRatio,[,n]=a.imageSize,[,r]=a.imageCanvas,[,o]=a.renderingPayload,l=(()=>{const u=UD();return Me(h=>{const p=t()[0]*a.pixelRatio,m=t()[1]*a.pixelRatio;return p!==h._v$&&Es(u,"width",h._v$=p),m!==h._v$2&&Es(u,"height",h._v$2=m),h},{_v$:void 0,_v$2:void 0}),u})(),c=l.getContext("webgl",{preserveDrawingBuffer:!0});r(l);async function d(){const u=await Ub(c,a);o(u),n([u.image.width,u.image.height]),s()||i(u.image.width/u.image.height)}return Jt(()=>{e()?d():Or(()=>{d()})(e)}),le(()=>{HD(c)}),l}function VD(){const a=us(Os),[e]=a.canvasSize,[t]=a.currentTab,[s]=a.currentImageRatio,[i,n]=a.translation,[r,o]=a.scale,[l]=a.rotation,[c]=a.flip,[d]=a.renderingPayload,[,u]=a.finalTransform,[,h]=a.isMoving,p=Qu(),m=V(()=>t()==="crop"),[g,f]=K(0);let v=!0;le(Vt(m,()=>{if(v){v=!1;return}h(!0);const N=zi(g(),m()?1:0,200,f,{onEnd:()=>h(!1)});ze(N)}));const[y,w]=K(),[b,S]=K(),[_,M]=K(),C=V(()=>{const N=d();if(!N)return;const[G,O]=e(),$=N.image.width/N.image.height,H=ch($,p().width,p().height,G,O),D=1/ch(s(),p().width,p().height,G,O),U=Math.min(G/N.image.width,O/N.image.height);return{toCropScale:H,fromCroppedScale:D,snappedImageScale:U}}),L=V(()=>{if(!e()||!C())return;const{fromCroppedScale:N}=C();return i().map(G=>G*N-G)}),E=V(()=>{if(!e()||!C())return;const[,N]=e(),{fromCroppedScale:G}=C();return ul(i().map(O=>O*G-O),[0,p().left+p().height/2-N/2],g())});let x,R;function B(){if(!C()||!L())return;const{toCropScale:N,fromCroppedScale:G,snappedImageScale:O}=C();x=N*O*G,R=L()}le(Vt(g,()=>{[0,1].includes(g())&&B()})),le(Vt(s,()=>{B()})),le(Vt(e,()=>{if(!e()||!C())return;const N=e(),{toCropScale:G,fromCroppedScale:O,snappedImageScale:$}=C();x=G*$*O,R=L(),ze(()=>{pi(()=>{w(N),M(x),S(R)})})})),le(Vt(y,()=>{if(!y||!_())return;const N=e(),{toCropScale:G,fromCroppedScale:O,snappedImageScale:$}=C(),H=G*$*O,D=ch(s(),N[0],N[1],y()[0],y()[1]),U=_()/H,j=D*U;pi(()=>{o(q=>q*j),n(q=>(q=q.map(W=>W*j),q))})})),window.setScale=o,window.canvasSize=e,le(()=>{if(!d())return;let{fromCroppedScale:G,toCropScale:O,snappedImageScale:$}=C();O*=js(G,1,g()),u({flip:c(),rotation:l(),scale:r()*a.pixelRatio*$*O,translation:[E()[0]+i()[0],E()[1]+i()[1]].map(H=>H*a.pixelRatio)})})}const zD=Y("<div class=media-editor__resize-handles-overlay>"),WD=Y("<div class=media-editor__main-canvas>"),KD=Y("<div class=media-editor__preview-brush-size>");function jD(){let a;const e=us(Os),[t]=e.isReady,[s,i]=e.canvasSize,[n]=e.previewBrushSize,[r]=e.currentBrush,[,o]=e.resizeHandlesContainer;return VD(),Jt(()=>{const l=()=>{const c=a.getBoundingClientRect();i([c.width,c.height])};l(),window.addEventListener("resize",l),ze(()=>{window.removeEventListener("resize",l)})}),(()=>{const l=WD(),c=a;return typeof c=="function"?Ue(c,l):a=l,k(l,T(Js,{get when(){return s()},get children(){return[T(GD,{}),T(Js,{get when(){return t()},get children(){return[T(OD,{}),T(TD,{}),V(()=>V(()=>!!n())()&&(()=>{const d=KD();return Me(u=>{const h=["blur","eraser"].includes(r().brush)?void 0:Pa(r().color).join(","),p=n()+"px",m=n()+"px";return h!==u._v$&&((u._v$=h)!=null?d.style.setProperty("--color",h):d.style.removeProperty("--color")),p!==u._v$2&&((u._v$2=p)!=null?d.style.setProperty("width",p):d.style.removeProperty("width")),m!==u._v$3&&((u._v$3=m)!=null?d.style.setProperty("height",m):d.style.removeProperty("height")),u},{_v$:void 0,_v$2:void 0,_v$3:void 0}),d})()),(()=>{const d=zD();return Ue(o,d),d})(),T(lD,{}),T(gD,{})]}})]}})),l})()}const qD=Y('<div class=media-editor__finish-button><svg width=18 height=16 viewBox="0 0 18 16"fill=none xmlns=http://www.w3.org/2000/svg><path d="M2 9L6.5 14L16 2"stroke=white stroke-width=2.66 stroke-linecap=round stroke-linejoin=round>');function NI(){const a=us(Os),[e]=a.history,[t]=a.rotation,[s]=a.translation,[i]=a.flip,[n]=a.scale,[r]=a.currentImageRatio,[o]=a.imageSize,[l]=a.renderingPayload;return()=>{if(!l())return!1;function c(h,p){return Math.abs(h-p)<1e-5}const d=o()[0]/o()[1],u=Math.round(t()/(Math.PI*2))*Math.PI*2;return!c(d,r())||!c(t(),u)||!c(i()[0],1)||!c(i()[1],1)||!c(n(),1)||!c(s()[0],0)||!c(s()[1],0)||e().length>0}}function YD(a){let e;Jt(()=>{Ei(e)});const t=NI();return(()=>{const s=qD();Lr(s,"click",a.onClick,!0);const i=e;return typeof i=="function"?Ue(i,s):e=s,Me(()=>s.classList.toggle("media-editor__finish-button--hidden",!t())),s})()}Fs(["click"]);const Vf=2560,zf=400,g0=1280,f0=720;function QD(a){const e=us(Os),[t]=e.currentImageRatio,[s]=e.scale,[i]=e.renderingPayload,n=i().image.width,r=t();let o=n/s(),l=o/r;return Math.max(o,l)<zf&&([o,l]=Qa(r,zf,zf)),a&&(o>g0||l>f0)&&([o,l]=Qa(r,g0,f0)),!a&&Math.max(o,l)>Vf&&([o,l]=Qa(r,Vf,Vf)),o=Math.floor(o),l=Math.floor(l),o=o%2==0?o:o-1,l=l%2==0?l:l-1,[o,l]}function XD({context:a,scaledWidth:e,scaledHeight:t,imageWidth:s,imageHeight:i,cropOffset:n}){const[r]=a.canvasSize,[o]=a.currentImageRatio,[l]=a.translation,[c]=a.scale,[d]=a.rotation,[u]=a.flip,h=r()[0],p=r()[1],m=s/i,g=h/p;let f=e,v=t;e/g<t?f=t*g:v=e/g;let y=ch(m,n().width,n().height,f,v);const w=1/ch(o(),n().width,n().height,f,v);y*=w;const b=Math.min(f/s,v/i),S=l().map(_=>_*w-_);return{flip:u(),rotation:d(),scale:c()*b*y,translation:[S[0]+l()[0],S[1]+l()[1]]}}function ZD(a,e,t,s){const[i]=a.resizableLayers,[n]=a.brushDrawnLines;function r(c){const d=[Math.sin(-e.rotation),Math.cos(-e.rotation)];return c=[c[0]*d[1]+c[1]*d[0],c[1]*d[1]-c[0]*d[0]],c=[c[0]*e.scale+t/2+e.translation[0],c[1]*e.scale+s/2+e.translation[1]],c}const o=n().map(({size:c,points:d,...u})=>({...u,size:c*e.scale,points:d.map(r)})),l=i().map(c=>{const d={...c[0]()};return d.position=r(d.position),d.rotation+=e.rotation,d.scale*=e.scale,d.textInfo&&(d.textInfo={...d.textInfo},d.textInfo.size*=d.scale*a.pixelRatio),d});return{scaledLines:o,scaledLayers:l}}var Gb=(a,e,t)=>{if(!e.has(a))throw TypeError("Cannot "+t)},pe=(a,e,t)=>(Gb(a,e,"read from private field"),t?t.call(a):e.get(a)),is=(a,e,t)=>{if(e.has(a))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(a):e.set(a,t)},cn=(a,e,t,s)=>(Gb(a,e,"write to private field"),e.set(a,t),t),JD=(a,e,t,s)=>({set _(i){cn(a,e,i)},get _(){return pe(a,e,s)}}),Ss=(a,e,t)=>(Gb(a,e,"access private method"),t),As=new Uint8Array(8),Pr=new DataView(As.buffer),Ji=a=>[(a%256+256)%256],Ys=a=>(Pr.setUint16(0,a,!1),[As[0],As[1]]),e5=a=>(Pr.setInt16(0,a,!1),[As[0],As[1]]),OI=a=>(Pr.setUint32(0,a,!1),[As[1],As[2],As[3]]),gt=a=>(Pr.setUint32(0,a,!1),[As[0],As[1],As[2],As[3]]),t5=a=>(Pr.setInt32(0,a,!1),[As[0],As[1],As[2],As[3]]),Nl=a=>(Pr.setUint32(0,Math.floor(a/2**32),!1),Pr.setUint32(4,a,!1),[As[0],As[1],As[2],As[3],As[4],As[5],As[6],As[7]]),Vb=a=>(Pr.setInt16(0,2**8*a,!1),[As[0],As[1]]),dr=a=>(Pr.setInt32(0,2**16*a,!1),[As[0],As[1],As[2],As[3]]),Wf=a=>(Pr.setInt32(0,2**30*a,!1),[As[0],As[1],As[2],As[3]]),_a=(a,e=!1)=>{let t=Array(a.length).fill(null).map((s,i)=>a.charCodeAt(i));return e&&t.push(0),t},$m=a=>a&&a[a.length-1],zb=a=>{let e;for(let t of a)(!e||t.presentationTimestamp>e.presentationTimestamp)&&(e=t);return e},br=(a,e,t=!0)=>{let s=a*e;return t?Math.round(s):s},UI=a=>{let e=a*(Math.PI/180),t=Math.cos(e),s=Math.sin(e);return[t,s,0,-s,t,0,0,0,1]},HI=UI(0),GI=a=>[dr(a[0]),dr(a[1]),Wf(a[2]),dr(a[3]),dr(a[4]),Wf(a[5]),dr(a[6]),dr(a[7]),Wf(a[8])],wh=a=>!a||typeof a!="object"?a:Array.isArray(a)?a.map(wh):Object.fromEntries(Object.entries(a).map(([e,t])=>[e,wh(t)])),ld=a=>a>=0&&a<2**32,Qi=(a,e,t)=>({type:a,contents:e&&new Uint8Array(e.flat(10)),children:t}),bi=(a,e,t,s,i)=>Qi(a,[Ji(e),OI(t),s??[]],i),s5=a=>{let e=512;return a.fragmented?Qi("ftyp",[_a("iso5"),gt(e),_a("iso5"),_a("iso6"),_a("mp41")]):Qi("ftyp",[_a("isom"),gt(e),_a("isom"),a.holdsAvc?_a("avc1"):[],_a("mp41")])},Qv=a=>({type:"mdat",largeSize:a}),i5=a=>({type:"free",size:a}),Yp=(a,e,t=!1)=>Qi("moov",null,[n5(e,a),...a.map(s=>a5(s,e)),t?D5(a):null]),n5=(a,e)=>{let t=br(Math.max(0,...e.filter(r=>r.samples.length>0).map(r=>{const o=zb(r.samples);return o.presentationTimestamp+o.duration})),Jv),s=Math.max(...e.map(r=>r.id))+1,i=!ld(a)||!ld(t),n=i?Nl:gt;return bi("mvhd",+i,0,[n(a),n(a),gt(Jv),n(t),dr(1),Vb(1),Array(10).fill(0),GI(HI),Array(24).fill(0),gt(s)])},a5=(a,e)=>Qi("trak",null,[r5(a,e),o5(a,e)]),r5=(a,e)=>{let t=zb(a.samples),s=br(t?t.presentationTimestamp+t.duration:0,Jv),i=!ld(e)||!ld(s),n=i?Nl:gt,r;return a.info.type==="video"?r=typeof a.info.rotation=="number"?UI(a.info.rotation):a.info.rotation:r=HI,bi("tkhd",+i,3,[n(e),n(e),gt(a.id),gt(0),n(s),Array(8).fill(0),Ys(0),Ys(0),Vb(a.info.type==="audio"?1:0),Ys(0),GI(r),dr(a.info.type==="video"?a.info.width:0),dr(a.info.type==="video"?a.info.height:0)])},o5=(a,e)=>Qi("mdia",null,[l5(a,e),c5(a.info.type==="video"?"vide":"soun"),d5(a)]),l5=(a,e)=>{let t=zb(a.samples),s=br(t?t.presentationTimestamp+t.duration:0,a.timescale),i=!ld(e)||!ld(s),n=i?Nl:gt;return bi("mdhd",+i,0,[n(e),n(e),gt(a.timescale),n(s),Ys(21956),Ys(0)])},c5=a=>bi("hdlr",0,0,[_a("mhlr"),_a(a),gt(0),gt(0),gt(0),_a("mp4-muxer-hdlr",!0)]),d5=a=>Qi("minf",null,[a.info.type==="video"?h5():u5(),p5(),f5(a)]),h5=()=>bi("vmhd",0,1,[Ys(0),Ys(0),Ys(0),Ys(0)]),u5=()=>bi("smhd",0,0,[Ys(0),Ys(0)]),p5=()=>Qi("dinf",null,[m5()]),m5=()=>bi("dref",0,0,[gt(1)],[g5()]),g5=()=>bi("url ",0,1),f5=a=>{const e=a.compositionTimeOffsetTable.length>1||a.compositionTimeOffsetTable.some(t=>t.sampleCompositionTimeOffset!==0);return Qi("stbl",null,[v5(a),T5(a),x5(a),A5(a),R5(a),F5(a),e?B5(a):null])},v5=a=>bi("stsd",0,0,[gt(1)],[a.info.type==="video"?y5(K5[a.info.codec],a):L5(q5[a.info.codec],a)]),y5=(a,e)=>Qi(a,[Array(6).fill(0),Ys(1),Ys(0),Ys(0),Array(12).fill(0),Ys(e.info.width),Ys(e.info.height),gt(4718592),gt(4718592),gt(0),Ys(1),Array(32).fill(0),Ys(24),e5(65535)],[j5[e.info.codec](e),e.info.decoderConfig.colorSpace?C5(e):null]),b5={bt709:1,bt470bg:5,smpte170m:6},w5={bt709:1,smpte170m:6,"iec61966-2-1":13},S5={rgb:0,bt709:1,bt470bg:5,smpte170m:6},C5=a=>Qi("colr",[_a("nclx"),Ys(b5[a.info.decoderConfig.colorSpace.primaries]),Ys(w5[a.info.decoderConfig.colorSpace.transfer]),Ys(S5[a.info.decoderConfig.colorSpace.matrix]),Ji((a.info.decoderConfig.colorSpace.fullRange?1:0)<<7)]),_5=a=>a.info.decoderConfig&&Qi("avcC",[...new Uint8Array(a.info.decoderConfig.description)]),I5=a=>a.info.decoderConfig&&Qi("hvcC",[...new Uint8Array(a.info.decoderConfig.description)]),P5=a=>{if(!a.info.decoderConfig)return null;let e=a.info.decoderConfig;if(!e.colorSpace)throw new Error("'colorSpace' is required in the decoder config for VP9.");let t=e.codec.split("."),s=Number(t[1]),i=Number(t[2]),o=(Number(t[3])<<4)+(0<<1)+Number(e.colorSpace.fullRange);return bi("vpcC",1,0,[Ji(s),Ji(i),Ji(o),Ji(2),Ji(2),Ji(2),Ys(0)])},M5=()=>{let t=(1<<7)+1;return Qi("av1C",[t,0,0,0])},L5=(a,e)=>Qi(a,[Array(6).fill(0),Ys(1),Ys(0),Ys(0),gt(0),Ys(e.info.numberOfChannels),Ys(16),Ys(0),Ys(0),dr(e.info.sampleRate)],[Y5[e.info.codec](e)]),E5=a=>{let e=new Uint8Array(a.info.decoderConfig.description);return bi("esds",0,0,[gt(58753152),Ji(32+e.byteLength),Ys(1),Ji(0),gt(75530368),Ji(18+e.byteLength),Ji(64),Ji(21),OI(0),gt(130071),gt(130071),gt(92307584),Ji(e.byteLength),...e,gt(109084800),Ji(1),Ji(2)])},k5=a=>{let e=3840,t=0;const s=a.info.decoderConfig?.description;if(s){if(s.byteLength<18)throw new TypeError("Invalid decoder description provided for Opus; must be at least 18 bytes long.");const i=ArrayBuffer.isView(s)?new DataView(s.buffer,s.byteOffset,s.byteLength):new DataView(s);e=i.getUint16(10,!0),t=i.getInt16(14,!0)}return Qi("dOps",[Ji(0),Ji(a.info.numberOfChannels),Ys(e),gt(a.info.sampleRate),Vb(t),Ji(0)])},T5=a=>bi("stts",0,0,[gt(a.timeToSampleTable.length),a.timeToSampleTable.map(e=>[gt(e.sampleCount),gt(e.sampleDelta)])]),x5=a=>{if(a.samples.every(t=>t.type==="key"))return null;let e=[...a.samples.entries()].filter(([,t])=>t.type==="key");return bi("stss",0,0,[gt(e.length),e.map(([t])=>gt(t+1))])},A5=a=>bi("stsc",0,0,[gt(a.compactlyCodedChunkTable.length),a.compactlyCodedChunkTable.map(e=>[gt(e.firstChunk),gt(e.samplesPerChunk),gt(1)])]),R5=a=>bi("stsz",0,0,[gt(0),gt(a.samples.length),a.samples.map(e=>gt(e.size))]),F5=a=>a.finalizedChunks.length>0&&$m(a.finalizedChunks).offset>=2**32?bi("co64",0,0,[gt(a.finalizedChunks.length),a.finalizedChunks.map(e=>Nl(e.offset))]):bi("stco",0,0,[gt(a.finalizedChunks.length),a.finalizedChunks.map(e=>gt(e.offset))]),B5=a=>bi("ctts",0,0,[gt(a.compositionTimeOffsetTable.length),a.compositionTimeOffsetTable.map(e=>[gt(e.sampleCount),gt(e.sampleCompositionTimeOffset)])]),D5=a=>Qi("mvex",null,a.map($5)),$5=a=>bi("trex",0,0,[gt(a.id),gt(1),gt(0),gt(0),gt(0)]),v0=(a,e)=>Qi("moof",null,[N5(a),...e.map(O5)]),N5=a=>bi("mfhd",0,0,[gt(a)]),VI=a=>{let e=0,t=0,s=0,i=0,n=a.type==="delta";return t|=+n,n?e|=1:e|=2,e<<24|t<<16|s<<8|i},O5=a=>Qi("traf",null,[U5(a),H5(a),G5(a)]),U5=a=>{let e=0;e|=8,e|=16,e|=32,e|=131072;let t=a.currentChunk.samples[1]??a.currentChunk.samples[0],s={duration:t.timescaleUnitsToNextSample,size:t.size,flags:VI(t)};return bi("tfhd",0,e,[gt(a.id),gt(s.duration),gt(s.size),gt(s.flags)])},H5=a=>bi("tfdt",1,0,[Nl(br(a.currentChunk.startTimestamp,a.timescale))]),G5=a=>{let e=a.currentChunk.samples.map(g=>g.timescaleUnitsToNextSample),t=a.currentChunk.samples.map(g=>g.size),s=a.currentChunk.samples.map(VI),i=a.currentChunk.samples.map(g=>br(g.presentationTimestamp-g.decodeTimestamp,a.timescale)),n=new Set(e),r=new Set(t),o=new Set(s),l=new Set(i),c=o.size===2&&s[0]!==s[1],d=n.size>1,u=r.size>1,h=!c&&o.size>1,p=l.size>1||[...l].some(g=>g!==0),m=0;return m|=1,m|=4*+c,m|=256*+d,m|=512*+u,m|=1024*+h,m|=2048*+p,bi("trun",1,m,[gt(a.currentChunk.samples.length),gt(a.currentChunk.offset-a.currentChunk.moofOffset||0),c?gt(s[0]):[],a.currentChunk.samples.map((g,f)=>[d?gt(e[f]):[],u?gt(t[f]):[],h?gt(s[f]):[],p?t5(i[f]):[]])])},V5=a=>Qi("mfra",null,[...a.map(z5),W5()]),z5=(a,e)=>bi("tfra",1,0,[gt(a.id),gt(63),gt(a.finalizedChunks.length),a.finalizedChunks.map(s=>[Nl(br(s.startTimestamp,a.timescale)),Nl(s.moofOffset),gt(e+1),gt(1),gt(1)])]),W5=()=>bi("mfro",0,0,[gt(0)]),K5={avc:"avc1",hevc:"hvc1",vp9:"vp09",av1:"av01"},j5={avc:_5,hevc:I5,vp9:P5,av1:M5},q5={aac:"mp4a",opus:"Opus"},Y5={aac:E5,opus:k5},qg=class{},zI=class extends qg{constructor(){super(...arguments),this.buffer=null}},WI=class extends qg{constructor(a){if(super(),this.options=a,typeof a!="object")throw new TypeError("StreamTarget requires an options object to be passed to its constructor.");if(a.onData){if(typeof a.onData!="function")throw new TypeError("options.onData, when provided, must be a function.");if(a.onData.length<2)throw new TypeError("options.onData, when provided, must be a function that takes in at least two arguments (data and position). Ignoring the position argument, which specifies the byte offset at which the data is to be written, can lead to broken outputs.")}if(a.chunked!==void 0&&typeof a.chunked!="boolean")throw new TypeError("options.chunked, when provided, must be a boolean.");if(a.chunkSize!==void 0&&(!Number.isInteger(a.chunkSize)||a.chunkSize<=0))throw new TypeError("options.chunkSize, when provided, must be a positive integer.")}},Q5=class extends qg{constructor(a,e){if(super(),this.stream=a,this.options=e,!(a instanceof FileSystemWritableFileStream))throw new TypeError("FileSystemWritableFileStreamTarget requires a FileSystemWritableFileStream instance.");if(e!==void 0&&typeof e!="object")throw new TypeError("FileSystemWritableFileStreamTarget's options, when provided, must be an object.");if(e&&e.chunkSize!==void 0&&(!Number.isInteger(e.chunkSize)||e.chunkSize<=0))throw new TypeError("options.chunkSize, when provided, must be a positive integer")}},al,pc,Wb=class{constructor(){this.pos=0,is(this,al,new Uint8Array(8)),is(this,pc,new DataView(pe(this,al).buffer)),this.offsets=new WeakMap}seek(a){this.pos=a}writeU32(a){pe(this,pc).setUint32(0,a,!1),this.write(pe(this,al).subarray(0,4))}writeU64(a){pe(this,pc).setUint32(0,Math.floor(a/2**32),!1),pe(this,pc).setUint32(4,a,!1),this.write(pe(this,al).subarray(0,8))}writeAscii(a){for(let e=0;e<a.length;e++)pe(this,pc).setUint8(e%8,a.charCodeAt(e)),e%8===7&&this.write(pe(this,al));a.length%8!==0&&this.write(pe(this,al).subarray(0,a.length%8))}writeBox(a){if(this.offsets.set(a,this.pos),a.contents&&!a.children)this.writeBoxHeader(a,a.size??a.contents.byteLength+8),this.write(a.contents);else{let e=this.pos;if(this.writeBoxHeader(a,0),a.contents&&this.write(a.contents),a.children)for(let i of a.children)i&&this.writeBox(i);let t=this.pos,s=a.size??t-e;this.seek(e),this.writeBoxHeader(a,s),this.seek(t)}}writeBoxHeader(a,e){this.writeU32(a.largeSize?1:e),this.writeAscii(a.type),a.largeSize&&this.writeU64(e)}measureBoxHeader(a){return 8+(a.largeSize?8:0)}patchBox(a){let e=this.pos;this.seek(this.offsets.get(a)),this.writeBox(a),this.seek(e)}measureBox(a){if(a.contents&&!a.children)return this.measureBoxHeader(a)+a.contents.byteLength;{let e=this.measureBoxHeader(a);if(a.contents&&(e+=a.contents.byteLength),a.children)for(let t of a.children)t&&(e+=this.measureBox(t));return e}}};al=new WeakMap;pc=new WeakMap;var Qp,xl,nu,sh,Xp,Xv,X5=class extends Wb{constructor(a){super(),is(this,Xp),is(this,Qp,void 0),is(this,xl,new ArrayBuffer(2**16)),is(this,nu,new Uint8Array(pe(this,xl))),is(this,sh,0),cn(this,Qp,a)}write(a){Ss(this,Xp,Xv).call(this,this.pos+a.byteLength),pe(this,nu).set(a,this.pos),this.pos+=a.byteLength,cn(this,sh,Math.max(pe(this,sh),this.pos))}finalize(){Ss(this,Xp,Xv).call(this,this.pos),pe(this,Qp).buffer=pe(this,xl).slice(0,Math.max(pe(this,sh),this.pos))}};Qp=new WeakMap;xl=new WeakMap;nu=new WeakMap;sh=new WeakMap;Xp=new WeakSet;Xv=function(a){let e=pe(this,xl).byteLength;for(;e<a;)e*=2;if(e===pe(this,xl).byteLength)return;let t=new ArrayBuffer(e),s=new Uint8Array(t);s.set(pe(this,nu),0),cn(this,xl,t),cn(this,nu,s)};var Zp,rl,KI=class extends Wb{constructor(a){super(),is(this,Zp,void 0),is(this,rl,[]),cn(this,Zp,a)}write(a){pe(this,rl).push({data:a.slice(),start:this.pos}),this.pos+=a.byteLength}flush(){if(pe(this,rl).length===0)return;let a=[],e=[...pe(this,rl)].sort((t,s)=>t.start-s.start);a.push({start:e[0].start,size:e[0].data.byteLength});for(let t=1;t<e.length;t++){let s=a[a.length-1],i=e[t];i.start<=s.start+s.size?s.size=Math.max(s.size,i.start+i.data.byteLength-s.start):a.push({start:i.start,size:i.data.byteLength})}for(let t of a){t.data=new Uint8Array(t.size);for(let s of pe(this,rl))t.start<=s.start&&s.start<t.start+t.size&&t.data.set(s.data,s.start-t.start);pe(this,Zp).options.onData?.(t.data,t.start)}pe(this,rl).length=0}finalize(){}};Zp=new WeakMap;rl=new WeakMap;var Z5=2**24,J5=2,Nm,qa,ca,Om,Zv,Kb,jI,jb,qI,Sh,Um,YI=class extends Wb{constructor(a){if(super(),is(this,Om),is(this,Kb),is(this,jb),is(this,Sh),is(this,Nm,void 0),is(this,qa,void 0),is(this,ca,[]),cn(this,Nm,a),cn(this,qa,a.options?.chunkSize??Z5),!Number.isInteger(pe(this,qa))||pe(this,qa)<2**10)throw new Error("Invalid StreamTarget options: chunkSize must be an integer not smaller than 1024.")}write(a){Ss(this,Om,Zv).call(this,a,this.pos),Ss(this,Sh,Um).call(this),this.pos+=a.byteLength}finalize(){Ss(this,Sh,Um).call(this,!0)}};Nm=new WeakMap;qa=new WeakMap;ca=new WeakMap;Om=new WeakSet;Zv=function(a,e){let t=pe(this,ca).findIndex(o=>o.start<=e&&e<o.start+pe(this,qa));t===-1&&(t=Ss(this,jb,qI).call(this,e));let s=pe(this,ca)[t],i=e-s.start,n=a.subarray(0,Math.min(pe(this,qa)-i,a.byteLength));s.data.set(n,i);let r={start:i,end:i+n.byteLength};if(Ss(this,Kb,jI).call(this,s,r),s.written[0].start===0&&s.written[0].end===pe(this,qa)&&(s.shouldFlush=!0),pe(this,ca).length>J5){for(let o=0;o<pe(this,ca).length-1;o++)pe(this,ca)[o].shouldFlush=!0;Ss(this,Sh,Um).call(this)}n.byteLength<a.byteLength&&Ss(this,Om,Zv).call(this,a.subarray(n.byteLength),e+n.byteLength)};Kb=new WeakSet;jI=function(a,e){let t=0,s=a.written.length-1,i=-1;for(;t<=s;){let n=Math.floor(t+(s-t+1)/2);a.written[n].start<=e.start?(t=n+1,i=n):s=n-1}for(a.written.splice(i+1,0,e),(i===-1||a.written[i].end<e.start)&&i++;i<a.written.length-1&&a.written[i].end>=a.written[i+1].start;)a.written[i].end=Math.max(a.written[i].end,a.written[i+1].end),a.written.splice(i+1,1)};jb=new WeakSet;qI=function(a){let t={start:Math.floor(a/pe(this,qa))*pe(this,qa),data:new Uint8Array(pe(this,qa)),written:[],shouldFlush:!1};return pe(this,ca).push(t),pe(this,ca).sort((s,i)=>s.start-i.start),pe(this,ca).indexOf(t)};Sh=new WeakSet;Um=function(a=!1){for(let e=0;e<pe(this,ca).length;e++){let t=pe(this,ca)[e];if(!(!t.shouldFlush&&!a)){for(let s of t.written)pe(this,Nm).options.onData?.(t.data.subarray(s.start,s.end),t.start+s.start);pe(this,ca).splice(e--,1)}}};var e4=class extends YI{constructor(a){super(new WI({onData:(e,t)=>a.stream.write({type:"write",data:e,position:t}),chunkSize:a.options?.chunkSize}))}},Jv=1e3,t4=["avc","hevc","vp9","av1"],s4=["aac","opus"],i4=2082844800,n4=["strict","offset","cross-track-offset"],xt,Gt,Hm,na,gn,nn,Sc,Rc,qb,ol,ll,Ch,ey,QI,ty,XI,Yb,ZI,sy,JI,Qb,eP,Jp,iy,rr,Ar,Xb,tP,_h,Gm,Vm,Zb,cd,Xu,em,ny,a4=class{constructor(a){if(is(this,ey),is(this,ty),is(this,Yb),is(this,sy),is(this,Qb),is(this,Jp),is(this,rr),is(this,Xb),is(this,_h),is(this,Vm),is(this,cd),is(this,em),is(this,xt,void 0),is(this,Gt,void 0),is(this,Hm,void 0),is(this,na,void 0),is(this,gn,null),is(this,nn,null),is(this,Sc,Math.floor(Date.now()/1e3)+i4),is(this,Rc,[]),is(this,qb,1),is(this,ol,[]),is(this,ll,[]),is(this,Ch,!1),Ss(this,ey,QI).call(this,a),a.video=wh(a.video),a.audio=wh(a.audio),a.fastStart=wh(a.fastStart),this.target=a.target,cn(this,xt,{firstTimestampBehavior:"strict",...a}),a.target instanceof zI)cn(this,Gt,new X5(a.target));else if(a.target instanceof WI)cn(this,Gt,a.target.options?.chunked?new YI(a.target):new KI(a.target));else if(a.target instanceof Q5)cn(this,Gt,new e4(a.target));else throw new Error(`Invalid target: ${a.target}`);Ss(this,sy,JI).call(this),Ss(this,ty,XI).call(this)}addVideoChunk(a,e,t,s){if(!(a instanceof EncodedVideoChunk))throw new TypeError("addVideoChunk's first argument (sample) must be of type EncodedVideoChunk.");if(e&&typeof e!="object")throw new TypeError("addVideoChunk's second argument (meta), when provided, must be an object.");if(t!==void 0&&(!Number.isFinite(t)||t<0))throw new TypeError("addVideoChunk's third argument (timestamp), when provided, must be a non-negative real number.");if(s!==void 0&&!Number.isFinite(s))throw new TypeError("addVideoChunk's fourth argument (compositionTimeOffset), when provided, must be a real number.");let i=new Uint8Array(a.byteLength);a.copyTo(i),this.addVideoChunkRaw(i,a.type,t??a.timestamp,a.duration,e,s)}addVideoChunkRaw(a,e,t,s,i,n){if(!(a instanceof Uint8Array))throw new TypeError("addVideoChunkRaw's first argument (data) must be an instance of Uint8Array.");if(e!=="key"&&e!=="delta")throw new TypeError("addVideoChunkRaw's second argument (type) must be either 'key' or 'delta'.");if(!Number.isFinite(t)||t<0)throw new TypeError("addVideoChunkRaw's third argument (timestamp) must be a non-negative real number.");if(!Number.isFinite(s)||s<0)throw new TypeError("addVideoChunkRaw's fourth argument (duration) must be a non-negative real number.");if(i&&typeof i!="object")throw new TypeError("addVideoChunkRaw's fifth argument (meta), when provided, must be an object.");if(n!==void 0&&!Number.isFinite(n))throw new TypeError("addVideoChunkRaw's sixth argument (compositionTimeOffset), when provided, must be a real number.");if(Ss(this,em,ny).call(this),!pe(this,xt).video)throw new Error("No video track declared.");if(typeof pe(this,xt).fastStart=="object"&&pe(this,gn).samples.length===pe(this,xt).fastStart.expectedVideoChunks)throw new Error(`Cannot add more video chunks than specified in 'fastStart' (${pe(this,xt).fastStart.expectedVideoChunks}).`);let r=Ss(this,Jp,iy).call(this,pe(this,gn),a,e,t,s,i,n);if(pe(this,xt).fastStart==="fragmented"&&pe(this,nn)){for(;pe(this,ll).length>0&&pe(this,ll)[0].decodeTimestamp<=r.decodeTimestamp;){let o=pe(this,ll).shift();Ss(this,rr,Ar).call(this,pe(this,nn),o)}r.decodeTimestamp<=pe(this,nn).lastDecodeTimestamp?Ss(this,rr,Ar).call(this,pe(this,gn),r):pe(this,ol).push(r)}else Ss(this,rr,Ar).call(this,pe(this,gn),r)}addAudioChunk(a,e,t){if(!(a instanceof EncodedAudioChunk))throw new TypeError("addAudioChunk's first argument (sample) must be of type EncodedAudioChunk.");if(e&&typeof e!="object")throw new TypeError("addAudioChunk's second argument (meta), when provided, must be an object.");if(t!==void 0&&(!Number.isFinite(t)||t<0))throw new TypeError("addAudioChunk's third argument (timestamp), when provided, must be a non-negative real number.");let s=new Uint8Array(a.byteLength);a.copyTo(s),this.addAudioChunkRaw(s,a.type,t??a.timestamp,a.duration,e)}addAudioChunkRaw(a,e,t,s,i){if(!(a instanceof Uint8Array))throw new TypeError("addAudioChunkRaw's first argument (data) must be an instance of Uint8Array.");if(e!=="key"&&e!=="delta")throw new TypeError("addAudioChunkRaw's second argument (type) must be either 'key' or 'delta'.");if(!Number.isFinite(t)||t<0)throw new TypeError("addAudioChunkRaw's third argument (timestamp) must be a non-negative real number.");if(!Number.isFinite(s)||s<0)throw new TypeError("addAudioChunkRaw's fourth argument (duration) must be a non-negative real number.");if(i&&typeof i!="object")throw new TypeError("addAudioChunkRaw's fifth argument (meta), when provided, must be an object.");if(Ss(this,em,ny).call(this),!pe(this,xt).audio)throw new Error("No audio track declared.");if(typeof pe(this,xt).fastStart=="object"&&pe(this,nn).samples.length===pe(this,xt).fastStart.expectedAudioChunks)throw new Error(`Cannot add more audio chunks than specified in 'fastStart' (${pe(this,xt).fastStart.expectedAudioChunks}).`);let n=Ss(this,Jp,iy).call(this,pe(this,nn),a,e,t,s,i);if(pe(this,xt).fastStart==="fragmented"&&pe(this,gn)){for(;pe(this,ol).length>0&&pe(this,ol)[0].decodeTimestamp<=n.decodeTimestamp;){let r=pe(this,ol).shift();Ss(this,rr,Ar).call(this,pe(this,gn),r)}n.decodeTimestamp<=pe(this,gn).lastDecodeTimestamp?Ss(this,rr,Ar).call(this,pe(this,nn),n):pe(this,ll).push(n)}else Ss(this,rr,Ar).call(this,pe(this,nn),n)}finalize(){if(pe(this,Ch))throw new Error("Cannot finalize a muxer more than once.");if(pe(this,xt).fastStart==="fragmented"){for(let e of pe(this,ol))Ss(this,rr,Ar).call(this,pe(this,gn),e);for(let e of pe(this,ll))Ss(this,rr,Ar).call(this,pe(this,nn),e);Ss(this,Vm,Zb).call(this,!1)}else pe(this,gn)&&Ss(this,_h,Gm).call(this,pe(this,gn)),pe(this,nn)&&Ss(this,_h,Gm).call(this,pe(this,nn));let a=[pe(this,gn),pe(this,nn)].filter(Boolean);if(pe(this,xt).fastStart==="in-memory"){let e;for(let s=0;s<2;s++){let i=Yp(a,pe(this,Sc)),n=pe(this,Gt).measureBox(i);e=pe(this,Gt).measureBox(pe(this,na));let r=pe(this,Gt).pos+n+e;for(let o of pe(this,Rc)){o.offset=r;for(let{data:l}of o.samples)r+=l.byteLength,e+=l.byteLength}if(r<2**32)break;e>=2**32&&(pe(this,na).largeSize=!0)}let t=Yp(a,pe(this,Sc));pe(this,Gt).writeBox(t),pe(this,na).size=e,pe(this,Gt).writeBox(pe(this,na));for(let s of pe(this,Rc))for(let i of s.samples)pe(this,Gt).write(i.data),i.data=null}else if(pe(this,xt).fastStart==="fragmented"){let e=pe(this,Gt).pos,t=V5(a);pe(this,Gt).writeBox(t);let s=pe(this,Gt).pos-e;pe(this,Gt).seek(pe(this,Gt).pos-4),pe(this,Gt).writeU32(s)}else{let e=pe(this,Gt).offsets.get(pe(this,na)),t=pe(this,Gt).pos-e;pe(this,na).size=t,pe(this,na).largeSize=t>=2**32,pe(this,Gt).patchBox(pe(this,na));let s=Yp(a,pe(this,Sc));if(typeof pe(this,xt).fastStart=="object"){pe(this,Gt).seek(pe(this,Hm)),pe(this,Gt).writeBox(s);let i=e-pe(this,Gt).pos;pe(this,Gt).writeBox(i5(i))}else pe(this,Gt).writeBox(s)}Ss(this,cd,Xu).call(this),pe(this,Gt).finalize(),cn(this,Ch,!0)}};xt=new WeakMap;Gt=new WeakMap;Hm=new WeakMap;na=new WeakMap;gn=new WeakMap;nn=new WeakMap;Sc=new WeakMap;Rc=new WeakMap;qb=new WeakMap;ol=new WeakMap;ll=new WeakMap;Ch=new WeakMap;ey=new WeakSet;QI=function(a){if(typeof a!="object")throw new TypeError("The muxer requires an options object to be passed to its constructor.");if(!(a.target instanceof qg))throw new TypeError("The target must be provided and an instance of Target.");if(a.video){if(!t4.includes(a.video.codec))throw new TypeError(`Unsupported video codec: ${a.video.codec}`);if(!Number.isInteger(a.video.width)||a.video.width<=0)throw new TypeError(`Invalid video width: ${a.video.width}. Must be a positive integer.`);if(!Number.isInteger(a.video.height)||a.video.height<=0)throw new TypeError(`Invalid video height: ${a.video.height}. Must be a positive integer.`);const e=a.video.rotation;if(typeof e=="number"&&![0,90,180,270].includes(e))throw new TypeError(`Invalid video rotation: ${e}. Has to be 0, 90, 180 or 270.`);if(Array.isArray(e)&&(e.length!==9||e.some(t=>typeof t!="number")))throw new TypeError(`Invalid video transformation matrix: ${e.join()}`);if(a.video.frameRate!==void 0&&(!Number.isInteger(a.video.frameRate)||a.video.frameRate<=0))throw new TypeError(`Invalid video frame rate: ${a.video.frameRate}. Must be a positive integer.`)}if(a.audio){if(!s4.includes(a.audio.codec))throw new TypeError(`Unsupported audio codec: ${a.audio.codec}`);if(!Number.isInteger(a.audio.numberOfChannels)||a.audio.numberOfChannels<=0)throw new TypeError(`Invalid number of audio channels: ${a.audio.numberOfChannels}. Must be a positive integer.`);if(!Number.isInteger(a.audio.sampleRate)||a.audio.sampleRate<=0)throw new TypeError(`Invalid audio sample rate: ${a.audio.sampleRate}. Must be a positive integer.`)}if(a.firstTimestampBehavior&&!n4.includes(a.firstTimestampBehavior))throw new TypeError(`Invalid first timestamp behavior: ${a.firstTimestampBehavior}`);if(typeof a.fastStart=="object"){if(a.video){if(a.fastStart.expectedVideoChunks===void 0)throw new TypeError("'fastStart' is an object but is missing property 'expectedVideoChunks'.");if(!Number.isInteger(a.fastStart.expectedVideoChunks)||a.fastStart.expectedVideoChunks<0)throw new TypeError("'expectedVideoChunks' must be a non-negative integer.")}if(a.audio){if(a.fastStart.expectedAudioChunks===void 0)throw new TypeError("'fastStart' is an object but is missing property 'expectedAudioChunks'.");if(!Number.isInteger(a.fastStart.expectedAudioChunks)||a.fastStart.expectedAudioChunks<0)throw new TypeError("'expectedAudioChunks' must be a non-negative integer.")}}else if(![!1,"in-memory","fragmented"].includes(a.fastStart))throw new TypeError("'fastStart' option must be false, 'in-memory', 'fragmented' or an object.")};ty=new WeakSet;XI=function(){if(pe(this,Gt).writeBox(s5({holdsAvc:pe(this,xt).video?.codec==="avc",fragmented:pe(this,xt).fastStart==="fragmented"})),cn(this,Hm,pe(this,Gt).pos),pe(this,xt).fastStart==="in-memory")cn(this,na,Qv(!1));else if(pe(this,xt).fastStart!=="fragmented"){if(typeof pe(this,xt).fastStart=="object"){let a=Ss(this,Yb,ZI).call(this);pe(this,Gt).seek(pe(this,Gt).pos+a)}cn(this,na,Qv(!0)),pe(this,Gt).writeBox(pe(this,na))}Ss(this,cd,Xu).call(this)};Yb=new WeakSet;ZI=function(){if(typeof pe(this,xt).fastStart!="object")return;let a=0,e=[pe(this,xt).fastStart.expectedVideoChunks,pe(this,xt).fastStart.expectedAudioChunks];for(let t of e)t&&(a+=8*Math.ceil(2/3*t),a+=4*t,a+=12*Math.ceil(2/3*t),a+=4*t,a+=8*t);return a+=4096,a};sy=new WeakSet;JI=function(){if(pe(this,xt).video&&cn(this,gn,{id:1,info:{type:"video",codec:pe(this,xt).video.codec,width:pe(this,xt).video.width,height:pe(this,xt).video.height,rotation:pe(this,xt).video.rotation??0,decoderConfig:null},timescale:pe(this,xt).video.frameRate??57600,samples:[],finalizedChunks:[],currentChunk:null,firstDecodeTimestamp:void 0,lastDecodeTimestamp:-1,timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,compactlyCodedChunkTable:[]}),pe(this,xt).audio&&(cn(this,nn,{id:pe(this,xt).video?2:1,info:{type:"audio",codec:pe(this,xt).audio.codec,numberOfChannels:pe(this,xt).audio.numberOfChannels,sampleRate:pe(this,xt).audio.sampleRate,decoderConfig:null},timescale:pe(this,xt).audio.sampleRate,samples:[],finalizedChunks:[],currentChunk:null,firstDecodeTimestamp:void 0,lastDecodeTimestamp:-1,timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,compactlyCodedChunkTable:[]}),pe(this,xt).audio.codec==="aac")){let a=Ss(this,Qb,eP).call(this,2,pe(this,xt).audio.sampleRate,pe(this,xt).audio.numberOfChannels);pe(this,nn).info.decoderConfig={codec:pe(this,xt).audio.codec,description:a,numberOfChannels:pe(this,xt).audio.numberOfChannels,sampleRate:pe(this,xt).audio.sampleRate}}};Qb=new WeakSet;eP=function(a,e,t){let i=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350].indexOf(e),n=t,r="";r+=a.toString(2).padStart(5,"0"),r+=i.toString(2).padStart(4,"0"),i===15&&(r+=e.toString(2).padStart(24,"0")),r+=n.toString(2).padStart(4,"0");let o=Math.ceil(r.length/8)*8;r=r.padEnd(o,"0");let l=new Uint8Array(r.length/8);for(let c=0;c<r.length;c+=8)l[c/8]=parseInt(r.slice(c,c+8),2);return l};Jp=new WeakSet;iy=function(a,e,t,s,i,n,r){let o=s/1e6,l=(s-(r??0))/1e6,c=i/1e6,d=Ss(this,Xb,tP).call(this,o,l,a);return o=d.presentationTimestamp,l=d.decodeTimestamp,n?.decoderConfig&&(a.info.decoderConfig===null?a.info.decoderConfig=n.decoderConfig:Object.assign(a.info.decoderConfig,n.decoderConfig)),{presentationTimestamp:o,decodeTimestamp:l,duration:c,data:e,size:e.byteLength,type:t,timescaleUnitsToNextSample:br(c,a.timescale)}};rr=new WeakSet;Ar=function(a,e){pe(this,xt).fastStart!=="fragmented"&&a.samples.push(e);const t=br(e.presentationTimestamp-e.decodeTimestamp,a.timescale);if(a.lastTimescaleUnits!==null){let i=br(e.decodeTimestamp,a.timescale,!1),n=Math.round(i-a.lastTimescaleUnits);if(a.lastTimescaleUnits+=n,a.lastSample.timescaleUnitsToNextSample=n,pe(this,xt).fastStart!=="fragmented"){let r=$m(a.timeToSampleTable);r.sampleCount===1?(r.sampleDelta=n,r.sampleCount++):r.sampleDelta===n?r.sampleCount++:(r.sampleCount--,a.timeToSampleTable.push({sampleCount:2,sampleDelta:n}));const o=$m(a.compositionTimeOffsetTable);o.sampleCompositionTimeOffset===t?o.sampleCount++:a.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:t})}}else a.lastTimescaleUnits=0,pe(this,xt).fastStart!=="fragmented"&&(a.timeToSampleTable.push({sampleCount:1,sampleDelta:br(e.duration,a.timescale)}),a.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:t}));a.lastSample=e;let s=!1;if(!a.currentChunk)s=!0;else{let i=e.presentationTimestamp-a.currentChunk.startTimestamp;if(pe(this,xt).fastStart==="fragmented"){let n=pe(this,gn)??pe(this,nn);a===n&&e.type==="key"&&i>=1&&(s=!0,Ss(this,Vm,Zb).call(this))}else s=i>=.5}s&&(a.currentChunk&&Ss(this,_h,Gm).call(this,a),a.currentChunk={startTimestamp:e.presentationTimestamp,samples:[]}),a.currentChunk.samples.push(e)};Xb=new WeakSet;tP=function(a,e,t){const s=pe(this,xt).firstTimestampBehavior==="strict",i=t.lastDecodeTimestamp===-1;if(s&&i&&e!==0)throw new Error(`The first chunk for your media track must have a timestamp of 0 (received DTS=${e}).Non-zero first timestamps are often caused by directly piping frames or audio data from a MediaStreamTrack into the encoder. Their timestamps are typically relative to the age of thedocument, which is probably what you want.
- If you want to offset all timestamps of a track such that the first one is zero, set firstTimestampBehavior: 'offset' in the options.
- `);if(pe(this,xt).firstTimestampBehavior==="offset"||pe(this,xt).firstTimestampBehavior==="cross-track-offset"){t.firstDecodeTimestamp===void 0&&(t.firstDecodeTimestamp=e);let r;pe(this,xt).firstTimestampBehavior==="offset"?r=t.firstDecodeTimestamp:r=Math.min(pe(this,gn)?.firstDecodeTimestamp??1/0,pe(this,nn)?.firstDecodeTimestamp??1/0),e-=r,a-=r}if(e<t.lastDecodeTimestamp)throw new Error(`Timestamps must be monotonically increasing (DTS went from ${t.lastDecodeTimestamp*1e6} to ${e*1e6}).`);return t.lastDecodeTimestamp=e,{presentationTimestamp:a,decodeTimestamp:e}};_h=new WeakSet;Gm=function(a){if(pe(this,xt).fastStart==="fragmented")throw new Error("Can't finalize individual chunks if 'fastStart' is set to 'fragmented'.");if(a.currentChunk){if(a.finalizedChunks.push(a.currentChunk),pe(this,Rc).push(a.currentChunk),(a.compactlyCodedChunkTable.length===0||$m(a.compactlyCodedChunkTable).samplesPerChunk!==a.currentChunk.samples.length)&&a.compactlyCodedChunkTable.push({firstChunk:a.finalizedChunks.length,samplesPerChunk:a.currentChunk.samples.length}),pe(this,xt).fastStart==="in-memory"){a.currentChunk.offset=0;return}a.currentChunk.offset=pe(this,Gt).pos;for(let e of a.currentChunk.samples)pe(this,Gt).write(e.data),e.data=null;Ss(this,cd,Xu).call(this)}};Vm=new WeakSet;Zb=function(a=!0){if(pe(this,xt).fastStart!=="fragmented")throw new Error("Can't finalize a fragment unless 'fastStart' is set to 'fragmented'.");let e=[pe(this,gn),pe(this,nn)].filter(o=>o&&o.currentChunk);if(e.length===0)return;let t=JD(this,qb)._++;if(t===1){let o=Yp(e,pe(this,Sc),!0);pe(this,Gt).writeBox(o)}let s=pe(this,Gt).pos,i=v0(t,e);pe(this,Gt).writeBox(i);{let o=Qv(!1),l=0;for(let d of e)for(let u of d.currentChunk.samples)l+=u.size;let c=pe(this,Gt).measureBox(o)+l;c>=2**32&&(o.largeSize=!0,c=pe(this,Gt).measureBox(o)+l),o.size=c,pe(this,Gt).writeBox(o)}for(let o of e){o.currentChunk.offset=pe(this,Gt).pos,o.currentChunk.moofOffset=s;for(let l of o.currentChunk.samples)pe(this,Gt).write(l.data),l.data=null}let n=pe(this,Gt).pos;pe(this,Gt).seek(pe(this,Gt).offsets.get(i));let r=v0(t,e);pe(this,Gt).writeBox(r),pe(this,Gt).seek(n);for(let o of e)o.finalizedChunks.push(o.currentChunk),pe(this,Rc).push(o.currentChunk),o.currentChunk=null;a&&Ss(this,cd,Xu).call(this)};cd=new WeakSet;Xu=function(){pe(this,Gt)instanceof KI&&pe(this,Gt).flush()};em=new WeakSet;ny=function(){if(pe(this,Ch))throw new Error("Cannot add new video or audio chunks after the file has been finalized.")};class r4{async init(e){const t=await fs.downloadMedia({media:e}),s=this.image=new Image;s.src=URL.createObjectURL(t);const i=Mt();s.addEventListener("load",()=>{i.resolve()}),await i}getTotalFrames(){return 1}getRatio(){return this.image.naturalWidth/this.image.naturalHeight}async renderFrame(){}getRenderedFrame(){return this.image}destroy(){this.image=null}}class o4{constructor(){this.frameCount=0}async init(e,t){const s=await fs.downloadMedia({media:e}),i=this.container=document.createElement("div");i.style.width=t+"px",i.style.height=t+"px",i.style.position="absolute",i.style.opacity="0",i.style.pointerEvents="none",document.body.append(i);const n=this.animation=await Ns.loadAnimationWorker({container:i,autoplay:!1,animationData:s,width:t,height:t,name:"doc"+e.id}),r=Mt();n.addEventListener("ready",()=>{this.frameCount=n.maxFrame,r.resolve()}),n.addEventListener("enterFrame",()=>{this.currentDeferredFrame?.resolve()}),await r}getTotalFrames(){return this.frameCount}getRatio(){return 1/1}async renderFrame(e){this.currentDeferredFrame=Mt(),this.animation.requestFrame(e),await this.currentDeferredFrame}getRenderedFrame(){return this.animation.canvas[0]}destroy(){this.container.remove(),this.animation.remove()}}const tm=60,sP=200;class l4{constructor(){this.duration=0,this.middleware=Ht()}async init(e){const t=await fs.downloadMedia({media:e}),s=this.video=Do({middleware:this.middleware.get()});s.src=await Ae.invoke("createObjectURL",t),s.controls=!1,s.muted=!0,s.preload="auto";const i=ua(s);await mg(s,i),await ka(100),this.duration=s.duration,s.addEventListener("seeked",()=>{this.currentDeferredFrame?.resolve()})}getTotalFrames(){return jc?1:Math.floor(this.duration*60)}async renderFrame(e){jc||(this.currentDeferredFrame=Mt(),this.video.currentTime=1/tm*e,await this.currentDeferredFrame)}getRatio(){return this.video.videoWidth/this.video.videoHeight}getRenderedFrame(){return this.video}destroy(){this.middleware.destroy(),this.video=null}}function iP(a,e,t){if(t.type!=="text")return;const[s]=a.textLayersInfo,i={...s()[t.id]},n=t.scale*a.pixelRatio;if(i.height*=n,i.width*=n,i.lines=i.lines.map(c=>({...c,height:c.height*n,left:c.left*n,right:c.right*n})),i.path){let c=function(u){d[u]=d[u]*n};const d=[...i.path];d.forEach((u,h)=>{u==="M"||u==="L"?(c(h+1),c(h+2)):u==="A"&&(c(h+1),c(h+2),c(h+6),c(h+7))}),i.path=d}e.save(),e.translate(t.position[0],t.position[1]),e.rotate(t.rotation);let r=-i.height/2;const o=-i.width/2,l=Hh[t.textInfo.font];if(t.textInfo.style==="background"){e.translate(o,r),e.fillStyle=t.textInfo.color;const c=new Path2D(i.path.join(" "));e.fill(c),e.translate(-o,-r)}i.lines.forEach(c=>{const d=c.height*l.baseline;let u=.2*t.textInfo.size;t.textInfo.style==="background"&&(u=.3*t.textInfo.size),e.font=`${l.fontWeight} ${t.textInfo.size}px ${l.fontFamily}`;const h=o+u+c.left,p=r+d;t.textInfo.style==="outline"?(e.lineWidth=t.textInfo.size*.15,e.strokeStyle=t.textInfo.color,e.strokeText(c.content,h,p),e.fillStyle=bv(t.textInfo.color),e.fillText(c.content,h,p)):t.textInfo.style==="background"?(e.fillStyle=bv(t.textInfo.color),e.fillText(c.content,h,p)):(e.fillStyle=t.textInfo.color,e.fillText(c.content,h,p)),r+=c.height}),e.restore()}function nP(a,e,t,s,i){const[n]=a.stickersLayersInfo,{container:r}=n()[t.id];if(!r?.lastElementChild)return;const l=sP*t.scale*a.pixelRatio;e.save(),e.translate(t.position[0],t.position[1]),e.rotate(t.rotation);const[c,d]=Qa(i,l,l);e.drawImage(s,-l/2+(l-c)/2,-l/2+(l-d)/2,c,d),e.restore()}async function c4({context:a,scaledWidth:e,scaledHeight:t,scaledLayers:s,ctx:i,imageCanvas:n,brushCanvas:r,resultCanvas:o}){const[,l]=a.gifCreationProgress,c=new Map;let d=0;await Promise.all(s.map(async v=>{if(!v.sticker)return;const y=v.sticker?.sticker;let w;y===1&&(w=new r4),y===2&&(w=new o4),y===3&&(w=new l4),w&&(c.set(v.id,w),await w.init(v.sticker,sP*v.scale*a.pixelRatio),d=Math.max(d,w.getTotalFrames()))}));const u=new a4({target:new zI,video:{codec:"avc",width:e,height:t,frameRate:tm},fastStart:"in-memory"}),h=new VideoEncoder({output:(v,y)=>u.addVideoChunk(v,y),error:v=>console.error(v)});h.configure({codec:"avc1.42001f",width:e,height:t,bitrate:1e6});async function p(v){const y=Array.from(c.values()).map(b=>b.renderFrame(v%(b.getTotalFrames()+1)));await Promise.all(y),i.clearRect(0,0,e,t),i.drawImage(n,0,0),i.drawImage(r,0,0),s.forEach(b=>{if(b.type==="text"&&iP(a,i,b),b.type==="sticker"&&c.has(b.id)){const S=c.get(b.id);nP(a,i,b,S.getRenderedFrame(),S.getRatio())}});const w=new VideoFrame(o,{timestamp:v*1e6/tm,duration:1e6/tm});h.encode(w),w.close()}l(0),await p(0);const m=await new Promise(v=>o.toBlob(v)),g=new Promise(async v=>{await ka(200);for(let w=1;w<=d;w++)await p(w),l(w/d);await h.flush(),u.finalize(),Array.from(c.values()).forEach(w=>w.destroy());const{buffer:y}=u.target;v(new Blob([y],{type:"video/mp4"}))});let f;return g.then(v=>f=v),{preview:m,isGif:!0,getResult:()=>f??g}}async function d4({context:a,scaledLayers:e,ctx:t,imageCanvas:s,brushCanvas:i,resultCanvas:n}){const[r]=a.stickersLayersInfo;t.drawImage(s,0,0),t.drawImage(i,0,0),e.forEach(l=>{if(l.type==="text"&&iP(a,t,l),l.type==="sticker"&&l.sticker?.sticker===1){const{container:c}=r()[l.id],d=c?.lastElementChild;if(!(d instanceof HTMLImageElement))return;const u=d.naturalWidth/d.naturalHeight;nP(a,t,l,d,u)}});const o=await new Promise(l=>n.toBlob(l));return{preview:o,isGif:!1,getResult:()=>o}}async function h4({context:a,cropOffset:e,scaledWidth:t,scaledHeight:s,previewBlob:i}){const[n]=a.currentTab,r=n()==="crop",[o]=a.imageCanvas,l=o().getBoundingClientRect(),c=new Image;c.src=await Ae.invoke("createObjectURL",i),c.style.position="fixed";const d=l.left+(r?e().left+e().width/2:l.width/2),u=l.top+(r?e().top+e().height/2:l.height/2),[h,p]=Qa(t/s,r?e().width:l.width,r?e().height:l.height);c.style.left=d+"px",c.style.top=u+"px",c.style.width=h+"px",c.style.height=p+"px",c.style.transform="translate(-50%, -50%)",c.style.objectFit="cover",c.style.zIndex="1000",document.body.append(c);const m=Mt();return c.addEventListener("load",()=>m.resolve()),await Promise.race([ka(500),m]),c}async function u4(a){const e=us(Os),[t]=e.resizableLayers,s=Qu(),i=!!t().find(b=>[2,3].includes(b[0]().sticker?.sticker)),[n,r]=QD(i),o=document.createElement("canvas");o.width=n,o.height=r;const l=o.getContext("webgl",{preserveDrawingBuffer:!0}),c=await Ub(l,e),d=XD({context:e,scaledWidth:n,scaledHeight:r,imageWidth:c.image.width,imageHeight:c.image.height,cropOffset:s});Hb(l,c,{...d,imageSize:[c.image.width,c.image.height],...Object.fromEntries(e.adjustments.map(({key:b,signal:S,to100:_})=>{const M=S[0]();return[b,M/(_?100:50)]}))});const{scaledLayers:u,scaledLines:h}=ZD(e,d,n,r),p=document.createElement("canvas");p.width=n,p.height=r;const m=new _l({targetCanvas:p,imageCanvas:o});m.saveLastLine(),h.forEach(b=>m.drawLine(b));const g=document.createElement("canvas");g.width=n,g.height=r;const f=g.getContext("2d",{willReadFrequently:!0}),y=await(i?c4({context:e,scaledWidth:n,scaledHeight:r,scaledLayers:u,imageCanvas:o,resultCanvas:g,brushCanvas:p,ctx:f}):d4({context:e,scaledLayers:u,imageCanvas:o,resultCanvas:g,brushCanvas:p,ctx:f})),w=await h4({context:e,cropOffset:s,scaledWidth:n,scaledHeight:r,previewBlob:y.preview});return{...y,animatedPreview:w,width:n,height:r,originalSrc:e.imageSrc,standaloneContext:a}}const p4=/^key[a-zA-Z]$/i;function m4(a,e){return p4.test(e)?a.code.toLowerCase()===e.toLowerCase():a.key.toLowerCase()===e.toLowerCase()}function zm(a,e,t=!0){const s=i=>{const n=a.map(r=>[r,r.toLowerCase().split("+")]).sort((r,o)=>o[1].length-r[1].length);for(const[r,o]of n)if(o.every(c=>c==="ctrl"&&i.ctrlKey||c==="shift"&&i.shiftKey||c==="alt"&&i.altKey||c==="meta"&&i.metaKey||c==="anymeta"&&(i.ctrlKey||i.shiftKey||i.altKey||i.metaKey)||m4(i,c))){t&&i.preventDefault(),e(r,i);break}};return document.addEventListener("keydown",s),()=>document.removeEventListener("keydown",s)}const g4=Y("<div class=media-editor__topbar><div class=media-editor__topbar-title></div><div class=media-editor__topbar-history-controls></div><div class=media-editor__topbar-done>");function f4(a){let e;const t=us(Os),[s,i]=t.history,[n,r]=t.redoHistory;function o(){if(!s().length)return;const d=s()[s().length-1];r(u=>[...u,d]),i(u=>(u.pop(),[...u])),d.undo()}function l(){if(!n().length)return;const d=n()[n().length-1];i(u=>[...u,d]),r(u=>(u.pop(),[...u])),d.redo()}const c=NI();return Jt(()=>{Ei(e);const d=zm(["ctrl+z","ctrl+shift+z","ctrl+y"],u=>{u==="ctrl+z"?o():l()});ze(()=>d())}),(()=>{const d=g4(),u=d.firstChild,h=u.nextSibling,p=h.nextSibling;k(d,T(Pi,{icon:"cross",get onClick(){return a.onClose}}),u),k(u,()=>P("Edit")),k(h,T(Pi,{get disabled(){return!s().length},onClick:o,icon:"undo"}),null),k(h,T(Pi,{get disabled(){return!n().length},onClick:l,icon:"redo"}),null),p.$$click=()=>{c()&&a.onFinish()};const m=e;return typeof m=="function"?Ue(m,p):e=p,k(p,()=>P("Done")),Me(()=>p.classList.toggle("media-editor__topbar-done--disabled",!c())),d})()}Fs(["click"]);const v4=Y("<div class=media-editor__tabs-item>"),y4=Y("<div class=media-editor__tabs><div class=media-editor__tabs-underline>"),aP=[{icon:"equalizer",key:"adjustments"},{icon:"crop",key:"crop"},{icon:"text",key:"text"},{icon:"brush",key:"brush"},{icon:"smile",key:"stickers"}],y0=aP.map(a=>a.key);function b4(){const a=us(Os),[e,t]=a.currentTab;let s,i;const n=aP.map(o=>({...o,element:(()=>{const l=v4();return k(l,T(Pi,{get icon(){return o.icon},onClick:()=>r(o.key)})),Me(()=>l.classList.toggle("media-editor__tabs-item--active",e()===o.key)),l})()}));function r(o){const l=n.find(u=>u.key===o).element,c=s.getBoundingClientRect(),d=l.getBoundingClientRect();i.style.setProperty("--left",d.left+d.width/2-c.left+"px"),t(o)}return(()=>{const o=y4(),l=o.firstChild,c=s;typeof c=="function"?Ue(c,o):s=o,k(o,()=>n.map(u=>u.element),l);const d=i;return typeof d=="function"?Ue(d,l):i=l,o})()}const w4=Y("<div><div class=media-editor__tab-content-scrollable-content>"),S4=Y("<div class=media-editor__tab-content><div><div class=media-editor__tab-content-scrollable-content>"),ay=fd();function C4(a){const e=us(Os),[t]=e.currentTab,[s,i]=K(),[n,r]=K(0);let o,l=t(),c;le(async()=>{if(l===t())return;const h=y0.indexOf(t())>y0.indexOf(l);l=t(),c.destroy();const p=(()=>{const g=w4(),f=g.firstChild;return k(f,T(ay.Provider,{value:{container:s,scrollAmount:n},get children(){return a.tabs[t()]()}})),g})();u(p);const m=(g,f,v)=>g.classList[f]("media-editor__tab-content--"+v);m(o,"add","exit"),h?(m(p,"add","go-right"),s().append(p),await hi(),m(o,"add","go-left"),m(p,"remove","go-right")):(m(p,"add","go-left"),s().append(p),await hi(),m(o,"add","go-right"),m(p,"remove","go-left")),await ka(200),o.remove(),o=p});const d=a.tabs[t()]();function u(h){c=new tn(h),c.setListeners(),c.container.addEventListener("scroll",()=>{a.onScroll(),r(c.container.scrollTop)})}return Jt(()=>{u(o)}),ze(()=>{c.destroy()}),(()=>{const h=S4(),p=h.firstChild,m=p.firstChild;Ue(f=>{i(f),a.onContainer(f)},h);const g=o;return typeof g=="function"?Ue(g,p):o=p,k(m,T(ay.Provider,{value:{container:s,scrollAmount:n},children:d})),h})()}const _4=Y('<div class=media-editor__range-input><div class=media-editor__range-input-row><div class=media-editor__range-input-label></div><div class=media-editor__range-input-value></div></div><div class=media-editor__range-input-wrapper><input type=range step=1><div class="media-editor__range-input-thumb media-editor__range-input-thumb--shadow"></div><div class="media-editor__range-input-progress media-editor__range-input-progress--shadow"></div><div class=media-editor__range-input-progress-background></div><div class=media-editor__range-input-thumb></div><div class=media-editor__range-input-progress>');function Wm(a){const e=()=>Rm(a.value,a.min,a.max,0,1),t=V(()=>Rm(0,a.min,a.max,0,100)),s=()=>a.color&&By(a.color).l<32;let i=null;return(()=>{const n=_4(),r=n.firstChild,o=r.firstChild,l=o.nextSibling,c=r.nextSibling,d=c.firstChild,u=a.ref;return typeof u=="function"?Ue(u,n):a.ref=n,k(o,()=>a.label),k(l,()=>a.value),d.addEventListener("change",()=>{a.onChangeFinish?.(i,a.value),i=null}),d.$$input=h=>{i===null&&(i=a.value);const p=zt(h.currentTarget.valueAsNumber,a.min,a.max);a.onChange(p)},Me(h=>{const p=!!a.passiveLabel,m=!!(!a.passiveLabel&&a.value),g=!!s(),f={"--color":a.color,"--normalized":e(),"--w":Math.abs(a.value-Math.max(0,a.min))/(a.max-a.min)*100+"%","--bar-left":a.value>=0?Math.max(0,t())+"%":void 0,"--bar-right":a.value<0?t()+"%":void 0,...a.style},v=a.min,y=a.max;return p!==h._v$&&n.classList.toggle("media-editor__range-input--passive",h._v$=p),m!==h._v$2&&n.classList.toggle("media-editor__range-input--has-value",h._v$2=m),g!==h._v$3&&n.classList.toggle("media-editor__range-input--bright-shadow",h._v$3=g),h._v$4=Ii(n,f,h._v$4),v!==h._v$5&&Es(d,"min",h._v$5=v),y!==h._v$6&&Es(d,"max",h._v$6=y),h},{_v$:void 0,_v$2:void 0,_v$3:void 0,_v$4:void 0,_v$5:void 0,_v$6:void 0}),Me(()=>d.value=a.value),n})()}Fs(["input"]);const I4=Y('<div class="night media-editor__inherit-color">'),b0=800;function P4(){const a=us(Os),{adjustments:e}=a,[,t]=a.isAdjusting,s=Ob();let i=0;function n(){window.clearTimeout(i),i=window.setTimeout(()=>{t(!1)},b0)}return[T(Kr,{amount:"16px"}),V(()=>e.map(r=>{const[o,l]=r.signal,[c,d]=K(),[u,h]=K(!1);le(Vt(u,()=>{if(!c()||!s()||!u())return;const g=c().getBoundingClientRect(),f=(()=>{const v=I4();return v.style.setProperty("position","fixed"),v.style.setProperty("z-index","100"),k(v,T(Wm,{get value(){return o()},onChange:()=>{},get label(){return r.label()},get min(){return r.to100?0:-50},get max(){return r.to100?100:50}})),Me(y=>{const w=g.left+"px",b=g.top+"px",S=g.width+"px",_=g.height+"px";return w!==y._v$&&((y._v$=w)!=null?v.style.setProperty("left",w):v.style.removeProperty("left")),b!==y._v$2&&((y._v$2=b)!=null?v.style.setProperty("top",b):v.style.removeProperty("top")),S!==y._v$3&&((y._v$3=S)!=null?v.style.setProperty("width",S):v.style.removeProperty("width")),_!==y._v$4&&((y._v$4=_)!=null?v.style.setProperty("height",_):v.style.removeProperty("height")),y},{_v$:void 0,_v$2:void 0,_v$3:void 0,_v$4:void 0}),v})();document.body.append(f),ze(()=>{setTimeout(()=>{f.remove()},200)})}));let p=0;const m=()=>{window.clearTimeout(p),p=window.setTimeout(()=>{h(!1)},b0)};return[T(Wm,{ref:d,get value(){return o()},onChange:g=>{l(g),h(!0),t(!0),m(),n()},get label(){return r.label()},onChangeFinish:(g,f)=>{h(!1),t(!1),a.pushToHistory({undo(){l(g)},redo(){l(f)}})},get min(){return r.to100?0:-50},get max(){return r.to100?100:50}}),T(Kr,{amount:"32px"})]}))]}const M4=Y("<div>");function Jb(a){let e;return Jt(()=>{Ei(e)}),(()=>{const t=M4(),s=e;return typeof s=="function"?Ue(s,t):e=t,so(t,ni(a,{class:"media-editor__large-button",get classList(){return{"media-editor__large-button--active":a.active,[a.class]:!!a.class}}}),!1,!1),t})()}const L4=Y("<svg><rect x=4 y=4 width=16 height=16 rx=2 stroke=white stroke-width=1.66></svg>",!1,!0),E4=Y("<svg><rect x=3 y=6 width=18 height=12 rx=2 stroke=white stroke-width=1.66></svg>",!1,!0),k4=Y("<svg><rect x=3 y=5 width=18 height=14 rx=2 stroke=white stroke-width=1.66></svg>",!1,!0),T4=Y("<svg><rect x=3 y=4.5 width=18 height=15 rx=2 stroke=white stroke-width=1.66></svg>",!1,!0),x4=Y("<svg><rect x=3 y=4 width=18 height=16 rx=2 stroke=white stroke-width=1.66></svg>",!1,!0),A4=Y("<svg><rect x=2.5 y=6.5 width=19 height=11 rx=2 stroke=white stroke-width=1.66></svg>",!1,!0),R4=Y('<svg width=24 height=24 viewBox="0 0 24 24"fill=none xmlns=http://www.w3.org/2000/svg>'),F4=Y("<div class=media-editor__label>"),B4=Y("<div class=media-editor__crop-grid>"),D4={"1x1":()=>L4(),"3x2":()=>E4(),"4x3":()=>k4(),"5x4":()=>T4(),"7x5":()=>x4(),"16x9":()=>A4()},Da=(a,e)=>(()=>{const t=R4();return t.classList.toggle("media-editor__crop-item-icon--rotated",!!e),k(t,()=>D4[a]()),t})();function ta(a){const[e,t]=wa(a,["icon","text"]);return T(Jb,ni(t,{class:"media-editor__crop-item",get children(){return[V(()=>e.icon),V(()=>e.text)]}}))}function $4(){const a=us(Os),[e,t]=a.fixedImageRatioKey,[s]=a.rotation,i=r=>e()===r,n=Kc(r=>{t(r),BI(s()),a.resetRotationWheel()});return[(()=>{const r=F4();return k(r,()=>P("MediaEditor.AspectRatio")),r})(),T(ta,{get icon(){return T(hs,{icon:"free_transform"})},get text(){return P("MediaEditor.Free")},get active(){return i()},onClick:()=>n()}),T(ta,{get icon(){return T(hs,{icon:"image_original"})},get text(){return P("MediaEditor.Original")},get active(){return i("original")},onClick:()=>n("original")}),T(ta,{get icon(){return Da("1x1")},get text(){return P("MediaEditor.Square")},get active(){return i("1x1")},onClick:()=>n("1x1")}),(()=>{const r=B4();return k(r,T(ta,{get icon(){return Da("3x2")},text:"3:2",get active(){return i("3x2")},onClick:()=>n("3x2")}),null),k(r,T(ta,{get icon(){return Da("3x2",!0)},text:"2:3",get active(){return i("2x3")},onClick:()=>n("2x3")}),null),k(r,T(ta,{get icon(){return Da("4x3")},text:"4:3",get active(){return i("4x3")},onClick:()=>n("4x3")}),null),k(r,T(ta,{get icon(){return Da("4x3",!0)},text:"3:4",get active(){return i("3x4")},onClick:()=>n("3x4")}),null),k(r,T(ta,{get icon(){return Da("5x4")},text:"5:4",get active(){return i("5x4")},onClick:()=>n("5x4")}),null),k(r,T(ta,{get icon(){return Da("5x4",!0)},text:"4:5",get active(){return i("4x5")},onClick:()=>n("4x5")}),null),k(r,T(ta,{get icon(){return Da("7x5")},text:"7:5",get active(){return i("7x5")},onClick:()=>n("7x5")}),null),k(r,T(ta,{get icon(){return Da("7x5",!0)},text:"5:7",get active(){return i("5x7")},onClick:()=>n("5x7")}),null),k(r,T(ta,{get icon(){return Da("16x9")},text:"16:9",get active(){return i("16x9")},onClick:()=>n("16x9")}),null),k(r,T(ta,{get icon(){return Da("16x9",!0)},text:"9:16",get active(){return i("9x16")},onClick:()=>n("9x16")}),null),r})()]}var mn;let rP=(mn=class{constructor({buildLayout:e=mn.defaultBuildLayout,pickerBoxWidth:t=380,pickerBoxHeight:s=198,sliderWidth:i=t,thickSlider:n=!1}={}){this.hue=0,this.saturation=100,this.lightness=50,this.alpha=1,this.elements={},this.onGrabStart=()=>{document.documentElement.style.cursor=this.elements.boxDragger.style.cursor="grabbing"},this.onGrabEnd=()=>{document.documentElement.style.cursor=this.elements.boxDragger.style.cursor=""};const r=mn.idSeed++,o=gr(`
- <svg class="${mn.BASE_CLASS+"-box"}" viewBox="0 0 ${t} ${s}" style="width: ${t}px; height: ${s}px;">
- <defs>
- <linearGradient id="color-picker-saturation-${r}" x1="0%" y1="0%" x2="100%" y2="0%">
- <stop offset="0%" stop-color="#fff"></stop>
- <stop offset="100%" stop-color="hsl(0,100%,50%)"></stop>
- </linearGradient>
- <linearGradient id="color-picker-brightness-${r}" x1="0%" y1="0%" x2="0%" y2="100%">
- <stop offset="0%" stop-color="rgba(0,0,0,0)"></stop>
- <stop offset="100%" stop-color="#000"></stop>
- </linearGradient>
- <pattern id="color-picker-pattern-${r}" width="100%" height="100%">
- <rect x="0" y="0" width="100%" height="100%" fill="url(#color-picker-saturation-${r})"></rect>
- <rect x="0" y="0" width="100%" height="100%" fill="url(#color-picker-brightness-${r})"></rect>
- </pattern>
- </defs>
- <rect rx="10" ry="10" x="0" y="0" width="${t}" height="${s}" fill="url(#color-picker-pattern-${r})"></rect>
- <svg class="${mn.BASE_CLASS+"-dragger"} ${mn.BASE_CLASS+"-box-dragger"}" x="0" y="0">
- <circle r="11" fill="inherit" stroke="#fff" stroke-width="2"></circle>
- </svg>
- </svg>
- `),l=gr(`
- <div class="${mn.BASE_CLASS+"-sliders"}" style="width: ${i}px; height: 24px">
- <svg class="${mn.BASE_CLASS+"-color-slider"}" viewBox="0 0 ${i} 24">
- <defs>
- <linearGradient id="hue-${r}" x1="100%" y1="0%" x2="0%" y2="0%">
- <stop offset="0%" stop-color="#f00"></stop>
- <stop offset="16.666%" stop-color="#f0f"></stop>
- <stop offset="33.333%" stop-color="#00f"></stop>
- <stop offset="50%" stop-color="#0ff"></stop>
- <stop offset="66.666%" stop-color="#0f0"></stop>
- <stop offset="83.333%" stop-color="#ff0"></stop>
- <stop offset="100%" stop-color="#f00"></stop>
- </linearGradient>
- </defs>
- <rect rx="${n?10:4}" x="0" y="${n?3:9}" width="${i}" height="${n?20:8}" fill="url(#hue-${r})"></rect>
- <svg class="${mn.BASE_CLASS+"-dragger"} ${mn.BASE_CLASS+"-color-slider-dragger"}" x="0" y="13">
- <circle r="11" fill="inherit" stroke="#fff" stroke-width="2"></circle>
- </svg>
- </svg>
- </div>
- `);this.elements.box=o,this.elements.boxDragger=o.lastElementChild,this.elements.saturation=o.querySelector(`#color-picker-saturation-${r}`),this.elements.sliders=l,this.elements.hue=l.firstElementChild,this.elements.hueDragger=this.elements.hue.lastElementChild,this.hexInputField=new Yt({plainText:!0,label:"Appearance.Color.Hex"}),this.rgbInputField=new Yt({plainText:!0,label:"Appearance.Color.RGB"}),this.container=e({pickerBox:o,slider:l,hexInput:this.hexInputField.container,rgbInput:this.rgbInputField.container}),this.hexInputField.input.addEventListener("input",()=>{let d=this.hexInputField.value.replace(/#/g,"").slice(0,6);const u=d.match(/([a-fA-F\d]+)/),h=u&&u[0].length===d.length&&[6].includes(d.length);this.hexInputField.setState(h?ra.Neutral:ra.Error),d="#"+d,this.hexInputField.setValueSilently(d),h&&this.setColor(d,!1,!0)});const c=/^(?:rgb)?\(?([01]?\d\d?|2[0-4]\d|25[0-5])(?:\W+)([01]?\d\d?|2[0-4]\d|25[0-5])\W+(?:([01]?\d\d?|2[0-4]\d|25[0-5])\)?)$/;this.rgbInputField.input.addEventListener("input",()=>{const d=this.rgbInputField.value.match(c);this.rgbInputField.setState(d?ra.Neutral:ra.Error),d&&this.setColor(wv(+d[1],+d[2],+d[3]),!0,!1)}),this.attachBoxListeners(),this.attachHueListeners()}static defaultBuildLayout(e){const t=document.createElement("div");t.classList.add(mn.BASE_CLASS);const s=document.createElement("div");return s.className=mn.BASE_CLASS+"-inputs",s.append(e.hexInput,e.rgbInput),t.append(e.pickerBox,e.slider,s),t}attachBoxListeners(){Dv(this.elements.box,()=>{this.onGrabStart(),this.boxRect=this.elements.box.getBoundingClientRect()},e=>{this.saturationHandler(e.x,e.y)},()=>{this.onGrabEnd()})}attachHueListeners(){Dv(this.elements.hue,()=>{this.onGrabStart(),this.hueRect=this.elements.hue.getBoundingClientRect()},e=>{this.hueHandler(e.x)},()=>{this.onGrabEnd()})}setColor(e,t=!0,s=!0){if(e===void 0)e={h:0,s:100,l:50,a:1};else if(typeof e=="string")if(e[0]==="#")e=By(e);else{const c=e.match(/[.?\d]+/g);e=wv(+c[0],+c[1],+c[2],c[3]===void 0?1:+c[3])}this.boxRect=this.elements.box.getBoundingClientRect();const i=this.boxRect.width/100*e.s,n=100-e.l/(100-e.s/2)*100,r=this.boxRect.height/100*n;this.saturationHandler(this.boxRect.left+i,this.boxRect.top+r,!1),this.hueRect=this.elements.hue.getBoundingClientRect();const o=e.h/360,l=this.hueRect.left+this.hueRect.width*o;this.hueHandler(l,!1),this.hue=e.h,this.saturation=e.s,this.lightness=e.l,this.alpha=e.a,this.updatePicker(t,s)}getCurrentColor(){const e=BL(this.hue,this.saturation,this.lightness,this.alpha),t=DL(e),s=t.slice(0,-2);return{hsl:`hsl(${this.hue}, ${this.saturation}%, ${this.lightness}%)`,rgb:`rgb(${e[0]}, ${e[1]}, ${e[2]})`,hex:s,hsla:`hsla(${this.hue}, ${this.saturation}%, ${this.lightness}%, ${this.alpha})`,rgba:`rgba(${e[0]}, ${e[1]}, ${e[2]}, ${e[3]})`,hexa:t,rgbaArray:e}}updatePicker(e=!0,t=!0){const s=this.getCurrentColor();this.elements.boxDragger.setAttributeNS(null,"fill",s.hex),e&&(this.hexInputField.setValueSilently(s.hex),this.hexInputField.setState(ra.Neutral)),t&&(this.rgbInputField.setValueSilently(s.rgbaArray.slice(0,-1).join(", ")),this.rgbInputField.setState(ra.Neutral)),this.onChange&&this.onChange(s)}hueHandler(e,t=!0){const i=zt(e-this.hueRect.left,0,this.hueRect.width)/this.hueRect.width;this.hue=Math.round(360*i);const n=`hsla(${this.hue}, 100%, 50%, ${this.alpha})`;this.elements.hueDragger.setAttributeNS(null,"x",i*100+"%"),this.elements.hueDragger.setAttributeNS(null,"fill",n),this.elements.saturation.lastElementChild.setAttributeNS(null,"stop-color",n),t&&this.updatePicker()}saturationHandler(e,t,s=!0){const i=this.boxRect.width,n=this.boxRect.height,r=zt(e-this.boxRect.left,0,i),o=zt(t-this.boxRect.top,0,n),l=r/i*100,c=o/n*100,d=this.elements.boxDragger;d.setAttributeNS(null,"x",l+"%"),d.setAttributeNS(null,"y",c+"%");const u=zt(l,0,100),h=100-u/2,p=100-zt(c,0,100),m=zt(p/100*h,0,100);this.saturation=u,this.lightness=m,s&&this.updatePicker()}},mn.BASE_CLASS="color-picker",mn.idSeed=0,mn);const N4=Y("<div class=media-editor__color-picker-swatch><div class=media-editor__color-picker-swatch-color>"),O4=Y('<div class=media-editor__color-picker><div class=media-editor__color-picker-swatches><div class="media-editor__color-picker-swatch media-editor__color-picker-swatch--gradient"><div class=media-editor__color-picker-swatch-color></div></div><div class=media-editor__color-picker-slider></div></div><div class=media-editor__color-picker-layout-wrapper><div class=media-editor__color-picker-layout><div class=media-editor__color-picker-box></div><div class=media-editor__color-picker-inputs>'),U4=Y("<div>"),Cc=["#ffffff","#fe4438","#ff8901","#ffd60a","#33c759","#62e5e0","#0a84ff","#bd5cf3"],H4=200,G4=120,V4=304,Kf=384;function oP(a){const e=us(Os),[t,s]=K(Cc.includes(a.value)),[i,n]=K(!1),[r,o]=K(Kf);let l;const c=(h,p)=>(()=>{const m=N4();return m.$$click=()=>a.onChange(h),p!=null?m.style.setProperty("--i",p):m.style.removeProperty("--i"),Me(g=>{const f=!!(a.value===h&&t()),v=Pa(h).join(" ");return f!==g._v$&&m.classList.toggle("media-editor__color-picker-swatch--active",g._v$=f),v!==g._v$2&&((g._v$2=v)!=null?m.style.setProperty("--color-rgb",v):m.style.removeProperty("--color-rgb")),g},{_v$:void 0,_v$2:void 0}),m})(),d=async()=>{s(h=>!h),t()&&(n(!0),a.onChange(a.previousColor||Cc[0]),await ka(200),n(!1))},u=V(Vt(r,()=>{const h=new rP({buildLayout:p=>(()=>{const m=O4(),g=m.firstChild,f=g.firstChild,v=f.nextSibling,y=g.nextSibling,w=y.firstChild,b=w.firstChild,S=b.nextSibling;return m.style.setProperty("--picker-height","120px"),k(g,()=>Cc.map(c),f),f.$$click=d,k(v,()=>p.slider),k(b,()=>p.pickerBox),k(S,()=>p.hexInput,null),k(S,()=>p.rgbInput,null),Me(_=>{const M=!!t(),C=!t();return M!==_._v$3&&m.classList.toggle("media-editor__color-picker--collapsed",_._v$3=M),C!==_._v$4&&f.classList.toggle("media-editor__color-picker-swatch--active",_._v$4=C),_},{_v$3:void 0,_v$4:void 0}),m})(),pickerBoxWidth:H4+r()-Kf,pickerBoxHeight:G4,sliderWidth:V4+r()-Kf,thickSlider:!0});return h.onChange=p=>{p.hex!==a.value&&a.onChange(p.hex),e.abortDrawerSlide()},h.container.querySelectorAll(".media-editor__color-picker-swatch").forEach(p=>{Ei(p)}),h}));return Jt(()=>{o(l.clientWidth);const h=new ResizeObserver(()=>{o(l.clientWidth)});h.observe(l),ze(()=>{h.disconnect()})}),le(Vt(()=>a.colorKey,async()=>{await ka(0);const h=Cc.includes(a.value);h!==t()&&(s(h),h&&(n(!0),ka(200).then(()=>n(!1))))})),le(Vt(()=>[i(),u(),a.value],async()=>{await hi(),!i()&&a.value!==u().getCurrentColor().hex&&u().setColor(a.value)})),(()=>{const h=U4(),p=l;return typeof p=="function"?Ue(p,h):l=h,k(h,()=>u().container),h})()}Fs(["click"]);function ih(a,e){const[t,s]=K((()=>{const n=()=>{const r=[Cc.includes(e)?1:2,e,e];return localStorage.setItem(a,JSON.stringify(r)),r};try{const r=JSON.parse(localStorage.getItem(a));return!(r instanceof Array)||typeof r[0]!="number"||typeof r[1]!="string"||typeof r[2]!="string"?n():r}catch{}return n()})());function i(n){let r;Cc.includes(n)?r=[1,n,n]:r=[2,t()[1],n],s(r),localStorage.setItem(a,JSON.stringify(r))}return[()=>({value:t()[t()[0]],previous:t()[1]}),i]}const z4=Y("<div class=media-editor__toggle-button>"),W4=Y("<div class=media-editor__toggle-group-row><div class=media-editor__toggle-group></div><div class=media-editor__toggle-group>"),K4=Y("<div class=media-editor__label>");function j4(){const a=us(Os),[e,t]=a.currentTextLayerInfo,[s,i]=ih("media-editor-text-color","#ffffff");t(u=>({...u,color:s().value})),le(()=>{t(u=>({...u,color:s().value}))});function n(u){t(h=>({...h,size:u}))}function r(u){t(h=>({...h,alignment:u}))}function o(u){t(h=>({...h,style:u}))}function l(u){t(h=>({...h,font:u}))}const c=(u,h,p,m)=>(()=>{const g=z4();return g.$$click=()=>m(h),k(g,T(hs,{icon:u})),Me(()=>g.classList.toggle("media-editor__toggle-button--active",h===p())),g})();Jt(()=>{document.querySelectorAll(".media-editor__toggle-button").forEach(u=>{Ei(u)})});const d=(u,h)=>T(Jb,{get active(){return e()?.font===h},onClick:()=>l(h),get style(){return{"font-family":Hh[h].fontFamily,"font-weight":Hh[h].fontWeight}},children:u});return[T(oP,{get value(){return e()?.color},onChange:i,get previousColor(){return s().previous},get colorKey(){return a.selectedResizableLayer[0]()+""}}),(()=>{const u=W4(),h=u.firstChild,p=h.nextSibling;return k(h,()=>c("align_left","left",()=>e()?.alignment,r),null),k(h,()=>c("align_center","center",()=>e()?.alignment,r),null),k(h,()=>c("align_right","right",()=>e()?.alignment,r),null),k(p,()=>c("fontframe","normal",()=>e()?.style,o),null),k(p,()=>c("fontframe_outline","outline",()=>e()?.style,o),null),k(p,()=>c("fontframe_bg","background",()=>e()?.style,o),null),u})(),T(Wm,{get label(){return P("MediaEditor.Size")},min:16,max:64,get value(){return e()?.size},onChange:n,passiveLabel:!0,get color(){return e()?.color}}),T(Kr,{amount:"16px"}),(()=>{const u=K4();return k(u,()=>P("MediaEditor.Font")),u})(),V(()=>d(P("MediaEditor.Fonts.Roboto"),"roboto")),V(()=>d(P("MediaEditor.Fonts.SuezOne"),"suez")),V(()=>d(P("MediaEditor.Fonts.FugazOne"),"fugaz")),V(()=>d(P("MediaEditor.Fonts.CourierPrime"),"courier")),V(()=>d(P("MediaEditor.Fonts.Chewy"),"chewy")),V(()=>d(P("MediaEditor.Fonts.Sedan"),"sedan")),V(()=>d(P("MediaEditor.Fonts.RubikBubbles"),"bubbles")),V(()=>d(P("MediaEditor.Fonts.Playwrite"),"playwrite"))]}Fs(["click"]);const q4=Y('<svg width=120 height=48 viewBox="0 0 120 48"fill=none xmlns=http://www.w3.org/2000/svg><g clip-path=url(#clip0_6102_2542)><g filter=url(#filter0_iiii_6102_2542)><path d="M0 15H80L110.2 22.4465C112.048 22.9021 112.971 23.1299 113.185 23.4931C113.369 23.806 113.369 24.194 113.185 24.5069C112.971 24.8701 112.048 25.0979 110.2 25.5535L80 33H0V15Z"fill=#3E3F3F></path></g><path d="M112.564 24.9709L103.474 27.2132C103.21 27.2782 102.944 27.121 102.883 26.8566C102.736 26.2146 102.5 25.0296 102.5 24C102.5 22.9705 102.736 21.7855 102.883 21.1434C102.944 20.8791 103.21 20.7219 103.474 20.7868L112.564 23.0291C113.578 23.2792 113.578 24.7208 112.564 24.9709Z"fill=currentColor></path><rect x=76 y=15 width=4 height=18 rx=0.5 fill=currentColor></rect></g><defs><filter id=filter0_iiii_6102_2542 x=0 y=10 width=116.323 height=28 filterUnits=userSpaceOnUse color-interpolation-filters=sRGB><feFlood flood-opacity=0 result=BackgroundImageFix></feFlood><feBlend mode=normal in=SourceGraphic in2=BackgroundImageFix result=shape></feBlend><feColorMatrix in=SourceAlpha type=matrix values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0"result=hardAlpha></feColorMatrix><feOffset dx=1 dy=5></feOffset><feGaussianBlur stdDeviation=3></feGaussianBlur><feComposite in2=hardAlpha operator=arithmetic k2=-1 k3=1></feComposite><feColorMatrix type=matrix values="0 0 0 0 0.137255 0 0 0 0 0.145098 0 0 0 0 0.14902 0 0 0 1 0"></feColorMatrix><feBlend mode=normal in2=shape result=effect1_innerShadow_6102_2542></feBlend><feColorMatrix in=SourceAlpha type=matrix values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0"result=hardAlpha></feColorMatrix><feOffset dx=3 dy=-5></feOffset><feGaussianBlur stdDeviation=3></feGaussianBlur><feComposite in2=hardAlpha operator=arithmetic k2=-1 k3=1></feComposite><feColorMatrix type=matrix values="0 0 0 0 0.137255 0 0 0 0 0.145098 0 0 0 0 0.14902 0 0 0 1 0"></feColorMatrix><feBlend mode=normal in2=effect1_innerShadow_6102_2542 result=effect2_innerShadow_6102_2542></feBlend><feColorMatrix in=SourceAlpha type=matrix values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0"result=hardAlpha></feColorMatrix><feOffset dx=1 dy=-1></feOffset><feGaussianBlur stdDeviation=0.5></feGaussianBlur><feComposite in2=hardAlpha operator=arithmetic k2=-1 k3=1></feComposite><feColorMatrix type=matrix values="0 0 0 0 0.242217 0 0 0 0 0.247242 0 0 0 0 0.247101 0 0 0 1 0"></feColorMatrix><feBlend mode=normal in2=effect2_innerShadow_6102_2542 result=effect3_innerShadow_6102_2542></feBlend><feColorMatrix in=SourceAlpha type=matrix values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0"result=hardAlpha></feColorMatrix><feOffset dx=1 dy=1></feOffset><feGaussianBlur stdDeviation=0.5></feGaussianBlur><feComposite in2=hardAlpha operator=arithmetic k2=-1 k3=1></feComposite><feColorMatrix type=matrix values="0 0 0 0 0.242217 0 0 0 0 0.247242 0 0 0 0 0.247101 0 0 0 1 0"></feColorMatrix><feBlend mode=normal in2=effect3_innerShadow_6102_2542 result=effect4_innerShadow_6102_2542></feBlend></filter><clipPath id=clip0_6102_2542><rect width=20 height=120 fill=white transform="matrix(0 1 -1 0 120 14)">'),Y4=Y('<svg width=120 height=48 viewBox="0 0 120 48"fill=none xmlns=http://www.w3.org/2000/svg><g clip-path=url(#clip0_6102_2543)><path d="M94 24H110M110 24L104 18M110 24L104 30"stroke=url(#paint0_linear_6102_2543) stroke-width=3 stroke-linecap=round stroke-linejoin=round></path><g filter=url(#filter0_iiii_6102_2543)><path d="M0 15H92C94.2091 15 96 16.7909 96 19V29C96 31.2091 94.2091 33 92 33H0V15Z"fill=#3E3F3F></path></g><path d="M92 15V15C94.2091 15 96 16.7909 96 19V29C96 31.2091 94.2091 33 92 33V33V15Z"fill=currentColor></path></g><defs><filter id=filter0_iiii_6102_2543 x=0 y=10 width=99 height=28 filterUnits=userSpaceOnUse color-interpolation-filters=sRGB><feFlood flood-opacity=0 result=BackgroundImageFix></feFlood><feBlend mode=normal in=SourceGraphic in2=BackgroundImageFix result=shape></feBlend><feColorMatrix in=SourceAlpha type=matrix values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0"result=hardAlpha></feColorMatrix><feOffset dx=1 dy=5></feOffset><feGaussianBlur stdDeviation=3></feGaussianBlur><feComposite in2=hardAlpha operator=arithmetic k2=-1 k3=1></feComposite><feColorMatrix type=matrix values="0 0 0 0 0.137255 0 0 0 0 0.145098 0 0 0 0 0.14902 0 0 0 1 0"></feColorMatrix><feBlend mode=normal in2=shape result=effect1_innerShadow_6102_2543></feBlend><feColorMatrix in=SourceAlpha type=matrix values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0"result=hardAlpha></feColorMatrix><feOffset dx=3 dy=-5></feOffset><feGaussianBlur stdDeviation=3></feGaussianBlur><feComposite in2=hardAlpha operator=arithmetic k2=-1 k3=1></feComposite><feColorMatrix type=matrix values="0 0 0 0 0.137255 0 0 0 0 0.145098 0 0 0 0 0.14902 0 0 0 1 0"></feColorMatrix><feBlend mode=normal in2=effect1_innerShadow_6102_2543 result=effect2_innerShadow_6102_2543></feBlend><feColorMatrix in=SourceAlpha type=matrix values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0"result=hardAlpha></feColorMatrix><feOffset dx=1 dy=-1></feOffset><feGaussianBlur stdDeviation=0.5></feGaussianBlur><feComposite in2=hardAlpha operator=arithmetic k2=-1 k3=1></feComposite><feColorMatrix type=matrix values="0 0 0 0 0.242217 0 0 0 0 0.247242 0 0 0 0 0.247101 0 0 0 1 0"></feColorMatrix><feBlend mode=normal in2=effect2_innerShadow_6102_2543 result=effect3_innerShadow_6102_2543></feBlend><feColorMatrix in=SourceAlpha type=matrix values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0"result=hardAlpha></feColorMatrix><feOffset dx=1 dy=1></feOffset><feGaussianBlur stdDeviation=0.5></feGaussianBlur><feComposite in2=hardAlpha operator=arithmetic k2=-1 k3=1></feComposite><feColorMatrix type=matrix values="0 0 0 0 0.242217 0 0 0 0 0.247242 0 0 0 0 0.247101 0 0 0 1 0"></feColorMatrix><feBlend mode=normal in2=effect3_innerShadow_6102_2543 result=effect4_innerShadow_6102_2543></feBlend></filter><linearGradient id=paint0_linear_6102_2543 x1=110 y1=24 x2=94 y2=24 gradientUnits=userSpaceOnUse><stop offset=0.755 stop-color=currentColor></stop><stop offset=1 stop-color=currentColor stop-opacity=0></stop></linearGradient><clipPath id=clip0_6102_2543><rect width=20 height=120 fill=white transform="matrix(0 1 -1 0 120 14)">'),Q4=Y('<svg width=120 height=48 viewBox="0 0 120 48"fill=none xmlns=http://www.w3.org/2000/svg><g clip-path=url(#clip0_6102_2546)><g filter=url(#filter0_iiii_6102_2546)><path d="M0 15H82.3579C83.4414 15 84.5135 15.2201 85.5093 15.6468L91 18H101C101.552 18 102 18.4477 102 19V29C102 29.5523 101.552 30 101 30H91L85.5093 32.3532C84.5135 32.7799 83.4414 33 82.3579 33H0V15Z"fill=#3E3F3F></path></g><rect x=76 y=15 width=4 height=18 rx=0.5 fill=currentColor></rect><path d="M102 19H106.434C106.785 19 107.111 19.1843 107.291 19.4855L112.091 27.4855C112.491 28.152 112.011 29 111.234 29H102V19Z"fill=currentColor></path></g><defs><filter id=filter0_iiii_6102_2546 x=0 y=10 width=105 height=28 filterUnits=userSpaceOnUse color-interpolation-filters=sRGB><feFlood flood-opacity=0 result=BackgroundImageFix></feFlood><feBlend mode=normal in=SourceGraphic in2=BackgroundImageFix result=shape></feBlend><feColorMatrix in=SourceAlpha type=matrix values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0"result=hardAlpha></feColorMatrix><feOffset dx=1 dy=5></feOffset><feGaussianBlur stdDeviation=3></feGaussianBlur><feComposite in2=hardAlpha operator=arithmetic k2=-1 k3=1></feComposite><feColorMatrix type=matrix values="0 0 0 0 0.137255 0 0 0 0 0.145098 0 0 0 0 0.14902 0 0 0 1 0"></feColorMatrix><feBlend mode=normal in2=shape result=effect1_innerShadow_6102_2546></feBlend><feColorMatrix in=SourceAlpha type=matrix values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0"result=hardAlpha></feColorMatrix><feOffset dx=3 dy=-5></feOffset><feGaussianBlur stdDeviation=3></feGaussianBlur><feComposite in2=hardAlpha operator=arithmetic k2=-1 k3=1></feComposite><feColorMatrix type=matrix values="0 0 0 0 0.137255 0 0 0 0 0.145098 0 0 0 0 0.14902 0 0 0 1 0"></feColorMatrix><feBlend mode=normal in2=effect1_innerShadow_6102_2546 result=effect2_innerShadow_6102_2546></feBlend><feColorMatrix in=SourceAlpha type=matrix values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0"result=hardAlpha></feColorMatrix><feOffset dx=1 dy=-1></feOffset><feGaussianBlur stdDeviation=0.5></feGaussianBlur><feComposite in2=hardAlpha operator=arithmetic k2=-1 k3=1></feComposite><feColorMatrix type=matrix values="0 0 0 0 0.242217 0 0 0 0 0.247242 0 0 0 0 0.247101 0 0 0 1 0"></feColorMatrix><feBlend mode=normal in2=effect2_innerShadow_6102_2546 result=effect3_innerShadow_6102_2546></feBlend><feColorMatrix in=SourceAlpha type=matrix values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0"result=hardAlpha></feColorMatrix><feOffset dx=1 dy=1></feOffset><feGaussianBlur stdDeviation=0.5></feGaussianBlur><feComposite in2=hardAlpha operator=arithmetic k2=-1 k3=1></feComposite><feColorMatrix type=matrix values="0 0 0 0 0.242217 0 0 0 0 0.247242 0 0 0 0 0.247101 0 0 0 1 0"></feColorMatrix><feBlend mode=normal in2=effect3_innerShadow_6102_2546 result=effect4_innerShadow_6102_2546></feBlend></filter><clipPath id=clip0_6102_2546><rect width=20 height=120 fill=white transform="matrix(0 1 -1 0 120 14)">'),X4=Y('<svg width=120 height=48 viewBox="0 0 120 48"fill=none xmlns=http://www.w3.org/2000/svg><g clip-path=url(#clip0_6102_2547)><g filter=url(#filter0_f_6102_2547)><path d="M102 19H107.146C108.282 19 109.323 19.6487 109.601 20.7506C109.813 21.593 110 22.703 110 24C110 25.297 109.813 26.407 109.601 27.2494C109.323 28.3513 108.282 29 107.146 29H102V19Z"fill=currentColor></path></g><g filter=url(#filter1_f_6102_2547)><path d="M102 19H107.146C108.282 19 109.323 19.6487 109.601 20.7506C109.813 21.593 110 22.703 110 24C110 25.297 109.813 26.407 109.601 27.2494C109.323 28.3513 108.282 29 107.146 29H102V19Z"fill=currentColor></path></g><g filter=url(#filter2_f_6102_2547)><path d="M102 19H107.146C108.282 19 109.323 19.6487 109.601 20.7506C109.813 21.593 110 22.703 110 24C110 25.297 109.813 26.407 109.601 27.2494C109.323 28.3513 108.282 29 107.146 29H102V19Z"fill=currentColor></path></g><g filter=url(#filter3_iiii_6102_2547)><path d="M0 15H82.3579C83.4414 15 84.5135 15.2201 85.5093 15.6468L91 18H101C101.552 18 102 18.4477 102 19V29C102 29.5523 101.552 30 101 30H91L85.5093 32.3532C84.5135 32.7799 83.4414 33 82.3579 33H0V15Z"fill=#3E3F3F></path></g><rect x=76 y=15 width=4 height=18 rx=0.5 fill=currentCOlor></rect><path d="M102 19H107.146C108.282 19 109.323 19.6487 109.601 20.7506C109.813 21.593 110 22.703 110 24C110 25.297 109.813 26.407 109.601 27.2494C109.323 28.3513 108.282 29 107.146 29H102V19Z"fill=currentCOlor></path></g><defs><filter id=filter0_f_6102_2547 x=96 y=13 width=20 height=22 filterUnits=userSpaceOnUse color-interpolation-filters=sRGB><feFlood flood-opacity=0 result=BackgroundImageFix></feFlood><feBlend mode=normal in=SourceGraphic in2=BackgroundImageFix result=shape></feBlend><feGaussianBlur stdDeviation=3 result=effect1_foregroundBlur_6102_2547></feGaussianBlur></filter><filter id=filter1_f_6102_2547 x=96 y=13 width=20 height=22 filterUnits=userSpaceOnUse color-interpolation-filters=sRGB><feFlood flood-opacity=0 result=BackgroundImageFix></feFlood><feBlend mode=normal in=SourceGraphic in2=BackgroundImageFix result=shape></feBlend><feGaussianBlur stdDeviation=3 result=effect1_foregroundBlur_6102_2547></feGaussianBlur></filter><filter id=filter2_f_6102_2547 x=96 y=13 width=20 height=22 filterUnits=userSpaceOnUse color-interpolation-filters=sRGB><feFlood flood-opacity=0 result=BackgroundImageFix></feFlood><feBlend mode=normal in=SourceGraphic in2=BackgroundImageFix result=shape></feBlend><feGaussianBlur stdDeviation=3 result=effect1_foregroundBlur_6102_2547></feGaussianBlur></filter><filter id=filter3_iiii_6102_2547 x=0 y=10 width=105 height=28 filterUnits=userSpaceOnUse color-interpolation-filters=sRGB><feFlood flood-opacity=0 result=BackgroundImageFix></feFlood><feBlend mode=normal in=SourceGraphic in2=BackgroundImageFix result=shape></feBlend><feColorMatrix in=SourceAlpha type=matrix values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0"result=hardAlpha></feColorMatrix><feOffset dx=1 dy=5></feOffset><feGaussianBlur stdDeviation=3></feGaussianBlur><feComposite in2=hardAlpha operator=arithmetic k2=-1 k3=1></feComposite><feColorMatrix type=matrix values="0 0 0 0 0.137255 0 0 0 0 0.145098 0 0 0 0 0.14902 0 0 0 1 0"></feColorMatrix><feBlend mode=normal in2=shape result=effect1_innerShadow_6102_2547></feBlend><feColorMatrix in=SourceAlpha type=matrix values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0"result=hardAlpha></feColorMatrix><feOffset dx=3 dy=-5></feOffset><feGaussianBlur stdDeviation=3></feGaussianBlur><feComposite in2=hardAlpha operator=arithmetic k2=-1 k3=1></feComposite><feColorMatrix type=matrix values="0 0 0 0 0.137255 0 0 0 0 0.145098 0 0 0 0 0.14902 0 0 0 1 0"></feColorMatrix><feBlend mode=normal in2=effect1_innerShadow_6102_2547 result=effect2_innerShadow_6102_2547></feBlend><feColorMatrix in=SourceAlpha type=matrix values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0"result=hardAlpha></feColorMatrix><feOffset dx=1 dy=-1></feOffset><feGaussianBlur stdDeviation=0.5></feGaussianBlur><feComposite in2=hardAlpha operator=arithmetic k2=-1 k3=1></feComposite><feColorMatrix type=matrix values="0 0 0 0 0.242217 0 0 0 0 0.247242 0 0 0 0 0.247101 0 0 0 1 0"></feColorMatrix><feBlend mode=normal in2=effect2_innerShadow_6102_2547 result=effect3_innerShadow_6102_2547></feBlend><feColorMatrix in=SourceAlpha type=matrix values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0"result=hardAlpha></feColorMatrix><feOffset dx=1 dy=1></feOffset><feGaussianBlur stdDeviation=0.5></feGaussianBlur><feComposite in2=hardAlpha operator=arithmetic k2=-1 k3=1></feComposite><feColorMatrix type=matrix values="0 0 0 0 0.242217 0 0 0 0 0.247242 0 0 0 0 0.247101 0 0 0 1 0"></feColorMatrix><feBlend mode=normal in2=effect3_innerShadow_6102_2547 result=effect4_innerShadow_6102_2547></feBlend></filter><clipPath id=clip0_6102_2547><rect width=20 height=120 fill=white transform="matrix(0 1 -1 0 120 14)">'),Z4=Y('<svg width=120 height=48 viewBox="0 0 120 48"fill=none xmlns=http://www.w3.org/2000/svg><g clip-path=url(#clip0_6102_2544)><g filter=url(#filter0_i_6102_2544)><path d="M95 15H108C110.209 15 112 16.7909 112 19V29C112 31.2091 110.209 33 108 33H95V15Z"fill=#D9D9D9></path><path d="M95 15H108C110.209 15 112 16.7909 112 19V29C112 31.2091 110.209 33 108 33H95V15Z"fill=#F09B99></path></g><g filter=url(#filter1_iiii_6102_2544)><path d="M0 15H77.6464C77.8728 15 78.0899 14.9101 78.25 14.75V14.75C78.4101 14.5899 78.6272 14.5 78.8536 14.5H96C97.1046 14.5 98 15.3954 98 16.5V31.5C98 32.6046 97.1046 33.5 96 33.5H78.8536C78.6272 33.5 78.4101 33.4101 78.25 33.25V33.25C78.0899 33.0899 77.8728 33 77.6464 33H0V15Z"fill=#3E3F3F></path></g><path d="M79 33.5V14.5H78V33.5H79Z"fill=black fill-opacity=0.33></path></g><defs><filter id=filter0_i_6102_2544 x=95 y=13 width=19 height=20 filterUnits=userSpaceOnUse color-interpolation-filters=sRGB><feFlood flood-opacity=0 result=BackgroundImageFix></feFlood><feBlend mode=normal in=SourceGraphic in2=BackgroundImageFix result=shape></feBlend><feColorMatrix in=SourceAlpha type=matrix values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0"result=hardAlpha></feColorMatrix><feOffset dx=2 dy=-2></feOffset><feGaussianBlur stdDeviation=2></feGaussianBlur><feComposite in2=hardAlpha operator=arithmetic k2=-1 k3=1></feComposite><feColorMatrix type=matrix values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.33 0"></feColorMatrix><feBlend mode=normal in2=shape result=effect1_innerShadow_6102_2544></feBlend></filter><filter id=filter1_iiii_6102_2544 x=0 y=9.5 width=101 height=29 filterUnits=userSpaceOnUse color-interpolation-filters=sRGB><feFlood flood-opacity=0 result=BackgroundImageFix></feFlood><feBlend mode=normal in=SourceGraphic in2=BackgroundImageFix result=shape></feBlend><feColorMatrix in=SourceAlpha type=matrix values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0"result=hardAlpha></feColorMatrix><feOffset dx=1 dy=5></feOffset><feGaussianBlur stdDeviation=3></feGaussianBlur><feComposite in2=hardAlpha operator=arithmetic k2=-1 k3=1></feComposite><feColorMatrix type=matrix values="0 0 0 0 0.137255 0 0 0 0 0.145098 0 0 0 0 0.14902 0 0 0 1 0"></feColorMatrix><feBlend mode=normal in2=shape result=effect1_innerShadow_6102_2544></feBlend><feColorMatrix in=SourceAlpha type=matrix values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0"result=hardAlpha></feColorMatrix><feOffset dx=3 dy=-5></feOffset><feGaussianBlur stdDeviation=3></feGaussianBlur><feComposite in2=hardAlpha operator=arithmetic k2=-1 k3=1></feComposite><feColorMatrix type=matrix values="0 0 0 0 0.137255 0 0 0 0 0.145098 0 0 0 0 0.14902 0 0 0 1 0"></feColorMatrix><feBlend mode=normal in2=effect1_innerShadow_6102_2544 result=effect2_innerShadow_6102_2544></feBlend><feColorMatrix in=SourceAlpha type=matrix values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0"result=hardAlpha></feColorMatrix><feOffset dx=1 dy=-1></feOffset><feGaussianBlur stdDeviation=0.5></feGaussianBlur><feComposite in2=hardAlpha operator=arithmetic k2=-1 k3=1></feComposite><feColorMatrix type=matrix values="0 0 0 0 0.242217 0 0 0 0 0.247242 0 0 0 0 0.247101 0 0 0 1 0"></feColorMatrix><feBlend mode=normal in2=effect2_innerShadow_6102_2544 result=effect3_innerShadow_6102_2544></feBlend><feColorMatrix in=SourceAlpha type=matrix values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0"result=hardAlpha></feColorMatrix><feOffset dx=1 dy=1></feOffset><feGaussianBlur stdDeviation=0.5></feGaussianBlur><feComposite in2=hardAlpha operator=arithmetic k2=-1 k3=1></feComposite><feColorMatrix type=matrix values="0 0 0 0 0.242217 0 0 0 0 0.247242 0 0 0 0 0.247101 0 0 0 1 0"></feColorMatrix><feBlend mode=normal in2=effect3_innerShadow_6102_2544 result=effect4_innerShadow_6102_2544></feBlend></filter><clipPath id=clip0_6102_2544><rect width=20 height=120 fill=white transform="matrix(0 1 -1 0 120 14)">'),J4=Y('<svg width=120 height=48 viewBox="0 0 120 48"fill=none xmlns=http://www.w3.org/2000/svg><g clip-path=url(#clip0_6102_2545)><image href=assets/img/media-editor-blurred-color-wheel.png x=91 y=12 width=26 height=24></image><image href=assets/img/media-editor-blurred-color-wheel.png x=91 y=12 width=26 height=24></image><g filter=url(#filter3_iiii_6102_2545)><path d="M-2 15H75.441C75.7836 15 76.0968 15.1936 76.25 15.5V15.5C76.4032 15.8064 76.7164 16 77.059 16H92.941C93.2836 16 93.5968 15.8064 93.75 15.5V15.5C93.9032 15.1936 94.2164 15 94.559 15H98C99.1046 15 100 15.8954 100 17V31C100 32.1046 99.1046 33 98 33H94.559C94.2164 33 93.9032 32.8064 93.75 32.5V32.5C93.5968 32.1936 93.2836 32 92.941 32H77.059C76.7164 32 76.4032 32.1936 76.25 32.5V32.5C76.0968 32.8064 75.7836 33 75.441 33H-2V15Z"fill=#3E3F3F></path></g><mask id=mask0_6102_2545 style=mask-type:alpha maskUnits=userSpaceOnUse x=0 y=15 width=100 height=18><path d="M0 15H75.441C75.7836 15 76.0968 15.1936 76.25 15.5V15.5C76.4032 15.8064 76.7164 16 77.059 16H92.941C93.2836 16 93.5968 15.8064 93.75 15.5V15.5C93.9032 15.1936 94.2164 15 94.559 15H98C99.1046 15 100 15.8954 100 17V31C100 32.1046 99.1046 33 98 33H94.559C94.2164 33 93.9032 32.8064 93.75 32.5V32.5C93.5968 32.1936 93.2836 32 92.941 32H77.059C76.7164 32 76.4032 32.1936 76.25 32.5V32.5C76.0968 32.8064 75.7836 33 75.441 33H0V15Z"fill=#3E3F3F></path></mask><image opacity=1 href=assets/img/media-editor-blurred-color-wheel.png x=91 y=12 width=26 height=24></image></g><defs><filter id=filter3_iiii_6102_2545 x=-2 y=10 width=105 height=28 filterUnits=userSpaceOnUse color-interpolation-filters=sRGB><feFlood flood-opacity=0 result=BackgroundImageFix></feFlood><feBlend mode=normal in=SourceGraphic in2=BackgroundImageFix result=shape></feBlend><feColorMatrix in=SourceAlpha type=matrix values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0"result=hardAlpha></feColorMatrix><feOffset dx=1 dy=5></feOffset><feGaussianBlur stdDeviation=3></feGaussianBlur><feComposite in2=hardAlpha operator=arithmetic k2=-1 k3=1></feComposite><feColorMatrix type=matrix values="0 0 0 0 0.137255 0 0 0 0 0.145098 0 0 0 0 0.14902 0 0 0 1 0"></feColorMatrix><feBlend mode=normal in2=shape result=effect1_innerShadow_6102_2545></feBlend><feColorMatrix in=SourceAlpha type=matrix values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0"result=hardAlpha></feColorMatrix><feOffset dx=3 dy=-5></feOffset><feGaussianBlur stdDeviation=3></feGaussianBlur><feComposite in2=hardAlpha operator=arithmetic k2=-1 k3=1></feComposite><feColorMatrix type=matrix values="0 0 0 0 0.137255 0 0 0 0 0.145098 0 0 0 0 0.14902 0 0 0 1 0"></feColorMatrix><feBlend mode=normal in2=effect1_innerShadow_6102_2545 result=effect2_innerShadow_6102_2545></feBlend><feColorMatrix in=SourceAlpha type=matrix values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0"result=hardAlpha></feColorMatrix><feOffset dx=1 dy=-1></feOffset><feGaussianBlur stdDeviation=0.5></feGaussianBlur><feComposite in2=hardAlpha operator=arithmetic k2=-1 k3=1></feComposite><feColorMatrix type=matrix values="0 0 0 0 0.242217 0 0 0 0 0.247242 0 0 0 0 0.247101 0 0 0 1 0"></feColorMatrix><feBlend mode=normal in2=effect2_innerShadow_6102_2545 result=effect3_innerShadow_6102_2545></feBlend><feColorMatrix in=SourceAlpha type=matrix values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0"result=hardAlpha></feColorMatrix><feOffset dx=1 dy=1></feOffset><feGaussianBlur stdDeviation=0.5></feGaussianBlur><feComposite in2=hardAlpha operator=arithmetic k2=-1 k3=1></feComposite><feColorMatrix type=matrix values="0 0 0 0 0.242217 0 0 0 0 0.247242 0 0 0 0 0.247101 0 0 0 1 0"></feColorMatrix><feBlend mode=normal in2=effect3_innerShadow_6102_2545 result=effect4_innerShadow_6102_2545></feBlend></filter><clipPath id=clip0_6102_2545><rect width=120 height=48 fill=white>');function e6(){return q4()}function t6(){return Y4()}function s6(){return Q4()}function i6(){return X4()}function n6(){return Z4()}function a6(){return J4()}const r6=Y("<div class=media-editor__brush-button-svg-wrapper>"),o6=Y("<div>"),l6=Y("<div class=media-editor__label>");function c6(){const a=us(Os),[e,t]=a.currentBrush,[,s]=a.previewBrushSize,i={pen:ih("media-editor-pen-color","#fe4438"),arrow:ih("media-editor-arrow-color","#ffd60a"),brush:ih("media-editor-brush-color","#ff8901"),neon:ih("media-editor-neon-color","#62e5e0")};function n(h){return i[h]}function r(){const[h]=n(e().brush)||[];!h||e().color===h().value||t(p=>({...p,color:h().value}))}r(),le(()=>{r()});function o(h){const p=e().brush,[,m]=n(p)||[];m?.(h)}const l=(h,p,m)=>T(Jb,{get active(){return e().brush===m},onClick:()=>t(g=>({...g,brush:m})),class:"media-editor__brush-button",get children(){return[(()=>{const g=r6();return k(g,p),Me(()=>n(m)?.[0]().value!=null?g.style.setProperty("color",n(m)?.[0]().value):g.style.removeProperty("color")),g})(),h]}}),c=()=>e().brush in i;let d=0;function u(){window.clearTimeout(d),d=window.setTimeout(()=>{s()},400)}return[(()=>{const h=o6();return k(h,T(oP,{get value(){return e().color},onChange:o,get colorKey(){return V(()=>e().brush)()},get previousColor(){return n(e().brush)?.[0]().previous}})),Me(p=>Ii(h,{transition:"opacity .2s",...c()?void 0:{opacity:.25,"pointer-events":"none"}},p)),h})(),T(Kr,{amount:"16px"}),T(Wm,{get label(){return P("MediaEditor.Size")},min:2,max:32,get value(){return e().size},onChange:h=>{t(p=>({...p,size:h})),s(h),u()},onChangeFinish:()=>{s()},passiveLabel:!0,get color(){return V(()=>!!c())()?e().color:void 0}}),T(Kr,{amount:"16px"}),(()=>{const h=l6();return k(h,()=>P("MediaEditor.Tool")),h})(),V(()=>l(P("MediaEditor.Brushes.Pen"),T(e6,{}),"pen")),V(()=>l(P("MediaEditor.Brushes.Arrow"),T(t6,{}),"arrow")),V(()=>l(P("MediaEditor.Brushes.Brush"),T(s6,{}),"brush")),V(()=>l(P("MediaEditor.Brushes.Neon"),T(i6,{}),"neon")),V(()=>l(P("MediaEditor.Brushes.Blur"),T(a6,{}),"blur")),V(()=>l(P("MediaEditor.Brushes.Eraser"),T(n6,{}),"eraser"))]}const d6=Y("<div class=media-editor__stickers-set-thumb>"),h6=Y("<div class=media-editor__stickers-grid-item>"),u6=Y("<div class=media-editor__label>"),jf=Y("<div class=media-editor__stickers-grid>"),p6=Y("<div class=media-editor__stickers-recent-button>"),m6=Y("<div class=media-editor__stickers-thumb-list-scrollable><div class=media-editor__stickers-thumb-list>"),g6=Y("<div class=media-editor__sticker-search>"),f6=Y("<div class=media-editor__label data-set-id=recent>");function v6(){const{wrapStickerSetThumb:a,EmoticonsSearch:e}=Xy(),t=us(Os),{container:s,scrollAmount:i}=us(ay),{managers:n}=t,[,r]=t.resizableLayers,[o]=t.canvasSize,[,l]=t.selectedResizableLayer,[c]=t.finalTransform,d=jg(),[u]=ma(()=>n.appStickersManager.getRecentStickersStickers()),[h]=ma(()=>n.appStickersManager.getAllStickers()),[p,m]=K(),[g,f]=K(""),[v,y]=K(),[w,b]=K("recent"),[S,_]=K(!1),[M,C]=K(),[L,E]=K(),x=new sr,R=new Id({regularLazyLoadQueue:x,group:"none",managers:n,intersectionObserverInit:{root:s()},withLock:!1});ze(()=>{R.destroy(),x.clear()});async function B(D){b(String(D)),_(!0),s()?.querySelector(`[data-set-id="${D}"]`)?.scrollIntoView({behavior:"smooth",block:"start"}),await ka(1e3),_(!1)}function N(D){let U;const j=ui();Jt(()=>{a({container:U,group:"none",autoplay:!0,width:30,height:30,lazyLoadQueue:x,middleware:j.get(),set:D.set,managers:n,textColor:"white"}),ze(()=>{j.destroy()})});const q=()=>String(D.set.id)===w();return(()=>{const W=d6();W.$$click=()=>B(String(D.set.id));const ee=U;return typeof ee=="function"?Ue(ee,W):U=W,Me(()=>W.classList.toggle("media-editor__stickers-set-thumb--active",!!q())),W})()}function G(D){let U;Jt(()=>{R.renderSticker(D.doc,U),R.observeAnimated(U)});function j(){const q=t.resizableLayersSeed++,W=c(),ee={id:q,position:d([o()[0]/2,o()[1]/2]),rotation:-W.rotation,scale:1/W.scale,type:"sticker",sticker:D.doc};r(de=>[...de,K({...ee})]),l(q);let z=0,Z;t.pushToHistory({undo(){r(de=>(de=[...de],z=de.findIndex(ie=>ie[0]().id===ee.id),z>-1&&(Z=de.splice(z,1)[0]?.[0]()),de))},redo(){r(de=>(de=[...de],z>-1&&de.splice(z,0,K({...Z})),de))}})}return(()=>{const q=h6();q.$$click=j;const W=U;return typeof W=="function"?Ue(W,q):U=q,q})()}function O(D){let U;return le(()=>{M()&&(M().observe(U),ze(()=>{M()?.unobserve(U)}))}),(()=>{const j=u6(),q=U;return typeof q=="function"?Ue(q,j):U=j,k(j,()=>je(D.set.title)),Me(()=>Es(j,"data-set-id",D.set.id)),j})()}function $(D){const[U]=ma(()=>n.appStickersManager.getStickerSet(D.set));return T(Js,{get when(){return U()},get children(){return[T(Kr,{amount:"16px"}),T(O,{get set(){return D.set}}),(()=>{const j=jf();return k(j,T(Cs,{get each(){return U().documents},children:q=>T(G,{doc:q})})),j})()]}})}function H(){let D;Jt(()=>{document.querySelector(".media-editor__tabs")?.append(D),new io(D)}),ze(()=>{D.remove()});const U=()=>h()&&!p();return(()=>{const j=m6(),q=j.firstChild,W=D;return typeof W=="function"?Ue(W,j):D=j,k(q,T(Js,{get when(){return u()?.length},get children(){const ee=p6();return ee.$$click=()=>B("recent"),k(ee,T(hs,{icon:"recent"})),Me(()=>ee.classList.toggle("media-editor__stickers-recent-button--active",w()==="recent")),ee}}),null),k(q,T(Cs,{get each(){return h()?.sets},children:ee=>T(N,{set:ee})}),null),Me(ee=>{const z=!U(),Z=i()>8;return z!==ee._v$&&j.classList.toggle("media-editor__stickers-thumb-list-scrollable--hidden",ee._v$=z),Z!==ee._v$2&&j.classList.toggle("media-editor__stickers-thumb-list-scrollable--has-scroll",ee._v$2=Z),ee},{_v$:void 0,_v$2:void 0}),j})(),[]}return le(()=>{C(new IntersectionObserver(D=>{D.forEach(U=>{if(!S()&&U.isIntersecting){const j=U.target.dataset.setId;j&&b(j)}})},{root:s(),rootMargin:`0px 0px -${s().clientHeight-100}px 0px`})),ze(()=>{M()?.disconnect()})}),le(()=>{M()&&L()&&(M().observe(L()),ze(()=>{M()?.unobserve(L())}))}),le(async()=>{if(g()){m(await n.appStickersManager.searchStickers(g()));return}if(v()){const D=v();if(D._==="emojiGroupPremium"){m(await n.appStickersManager.getPremiumStickers());return}m(await n.appStickersManager.getStickersByEmoticon({emoticon:D.emoticons,includeServerStickers:!0}));return}!v()&&!g()&&m()}),[T(H,{}),T(Kr,{get amount(){return p()?"0px":"48px"}}),T(Kr,{amount:"8px"}),(()=>{const D=g6();return k(D,T(e,{type:"stickers",onValue:U=>{f(U)},onGroup:U=>{y(U)},categoryColor:"white",animatedItemGroup:"none"})),D})(),T(Kr,{amount:"16px"}),T(Js,{get when(){return V(()=>u()?.length>0)()&&!p()},get children(){return[(()=>{const D=f6();return Ue(E,D),k(D,()=>P("MediaEditor.RecentlyUsed")),D})(),(()=>{const D=jf();return k(D,T(Cs,{get each(){return u()},children:U=>T(G,{doc:U})})),D})()]}}),T(Js,{get when(){return p()},get children(){const D=jf();return k(D,T(Cs,{get each(){return p()},children:U=>T(G,{doc:U})})),D}}),T(Js,{get when(){return V(()=>!!h())()&&!p()},get children(){return T(Cs,{get each(){return h().sets},children:D=>T($,{set:D})})}})]}Fs(["click"]);const y6=Y("<div class=media-editor__toolbar><div class=media-editor__toolbar-draggable>");function b6(a){let e;const t=us(Os),[s]=t.isAdjusting,[i]=t.currentTab,[n]=t.renderingPayload,[r,o]=K(0),[l,c]=K(!1),[d,u]=K(),[h,p]=K(0),[m,g]=K(0),f=Ob(),[v,y]=K(f());let w=0,b=!0,S=!1,_=!1;function M(){S||(S=!0,w=0,b=!0,zi(r(),0,200,o),setTimeout(()=>{S=!1},200))}t.abortDrawerSlide=()=>M(),Jt(()=>{function L(R){f()&&(w=R,b=!1,_=!1,setTimeout(()=>{_=!0},100))}function E(R){if(!f()||b||!_)return;const B=R-w;l()?o(Math.min(Math.max(-h(),B),0)):o(Math.max(Math.min(h(),B),0))}function x(){f()&&(b||(b=!0,Math.abs(r())>100?c(R=>!R):M()))}d().addEventListener("input",()=>{M()}),e.addEventListener("touchstart",R=>{L(R.touches[0].clientY)}),e.addEventListener("touchmove",R=>{E(R.touches[0].clientY)}),e.addEventListener("touchend",R=>{x()}),e.addEventListener("mousedown",R=>{L(R.clientY)}),e.addEventListener("mousemove",R=>{E(R.clientY)}),e.addEventListener("mouseup",R=>{x()}),e.addEventListener("mouseout",R=>{x()})}),le(()=>{const L=new ResizeObserver(()=>{p(d()?.clientHeight||0)});L.observe(d()),ze(()=>L.disconnect())}),le(Vt(l,()=>{const L=r(),E=m(),x=l()?h():0;zi(0,1,200,R=>{pi(()=>{o(js(L,0,R)),g(js(E,x,R))})})})),le(()=>{i()!=="crop"&&c(!1)}),le(()=>{n()&&v()&&(async()=>(e.style.transition=".2s",await hi(),y(!1),await ka(200),e.style.removeProperty("transition")))()});const C=()=>m()+r();return(()=>{const L=y6();L.firstChild;const E=e;return typeof E=="function"?Ue(E,L):e=L,k(L,T(f4,{onClose:()=>a.onClose(),get onFinish(){return a.onFinish}}),null),k(L,T(b4,{}),null),k(L,T(C4,{onContainer:u,onScroll:()=>{M()},tabs:{adjustments:()=>T(P4,{}),crop:()=>T($4,{}),text:()=>T(j4,{}),brush:()=>T(c6,{}),stickers:()=>T(v6,{})}}),null),Me(x=>{const R=f()&&s()?0:1,B=v()&&f()?"translate(-50%, 100%)":f()?`translate(-50%, ${C()}px)`:void 0;return R!==x._v$&&((x._v$=R)!=null?L.style.setProperty("opacity",R):L.style.removeProperty("opacity")),B!==x._v$2&&((x._v$2=B)!=null?L.style.setProperty("transform",B):L.style.removeProperty("transform")),x},{_v$:void 0,_v$2:void 0}),L})()}const w6=Y('<div class="media-editor__overlay night"><div class=media-editor__container>');function S6(a){const e=a.standaloneContext||rD(a),[,t]=e.value.isReady,[,s]=e.value.renderingPayload,[,i]=e.value.canvasSize,[,n]=e.value.currentTab;t(!1),s(),i(),n("adjustments");const[r]=e.value.imageCanvas,[o]=e.value.renderingPayload;let l;Jt(()=>{(async()=>(l.classList.add("media-editor__overlay--hidden"),await hi(),l.classList.remove("media-editor__overlay--hidden")))();const u={type:"popup",onPop:()=>c()};Pt.pushItem(u),l.focus(),ze(()=>{Pt.removeItem(u)})}),le(()=>{r()&&a.onCanvasReady(r()).then(()=>t(!0))}),le(()=>{o()&&a.onImageRendered()});function c(u=!1,h=!1){async function p(m=!1){l.classList.add("media-editor__overlay--hidden"),await ka(200),a.onClose(h),m&&e.dispose()}if(u||a.standaloneContext){p();return}if(!e.value.history[0]().length){p(!0);return}return Rt({title:P("MediaEditor.DiscardChanges"),description:P("MediaEditor.DiscardWarning"),button:{text:P("Discard")}}).then(()=>{p(!0)}).catch(()=>{}),!1}let d=!1;return T(Os.Provider,{get value(){return e.value},get children(){const u=w6(),h=u.firstChild,p=l;return typeof p=="function"?Ue(p,u):l=u,k(h,()=>{const m=Kc(async()=>{if(d)return;d=!0;const g=await u4(e).finally(()=>d=!1);a.onEditFinish(g),c(!0,g.isGif)});return[T(jD,{}),T(b6,{onClose:c,onFinish:m}),T(YD,{onClick:m})]}),u}})}function C6(a,e){const t=document.createElement("div");document.body.append(t);const s=wi(()=>T(e,{get children(){return T(S6,ni(a,{onClose:i}))}}),t);function i(n){a.onClose(n),s()}}const _6=Y('<div><svg width=100% height=100% viewBox="0 0 120 120"><circle cx=60 cy=60 r=52 fill=none stroke=white stroke-width=6 stroke-linecap=round></circle><text x=50% y=50% dy=.3em text-anchor=middle>%');function I6(a){const[e]=a.context.gifCreationProgress,s=2*Math.PI*52,i=()=>s-e()*s;return(()=>{const n=_6(),r=n.firstChild,o=r.firstChild,l=o.nextSibling,c=l.firstChild;return Es(o,"stroke-dasharray",s+""),o.style.setProperty("transform","rotate(-90deg)"),o.style.setProperty("transform-origin","50% 50%"),l.style.setProperty("font-size","30px"),l.style.setProperty("font-weight","bolder"),l.style.setProperty("fill","white"),k(l,()=>(e()*100).toFixed(0),c),Me(d=>{const u={display:"flex",position:"absolute",left:"50%",top:"50%",transform:"translate(-50%, -50%)",width:"64px","background-color":"rgba(0, 0, 0, .25)","border-radius":"64px","max-width":"80%","max-height":"80%","aspect-ratio":"1 / 1","z-index":4},h=i();return d._v$=Ii(n,u,d._v$),h!==d._v$2&&Es(o,"stroke-dashoffset",d._v$2=h),d},{_v$:void 0,_v$2:void 0}),n})()}let sm;const w0=384;function au(){return sm}class Ao extends ue{constructor(e,t,s,i){super("popup-send-photo popup-new-media",{closable:!0,withConfirm:"Modal.Send",confirmShortcutIsSendShortcut:!0,body:!0,title:!0,scrollable:!0}),this.chat=e,this.files=t,this.ignoreInputValue=i,this.canShowActions=!1,this.cachedMediaEditorFiles=new WeakMap,this.onScroll=()=>{const{input:n}=this.messageInputField;this.scrollable.onAdditionalScroll(),n.scrollTop>0&&n.scrollHeight>130&&this.scrollable.container.classList.remove("scrolled-end"),this.scrollable.container.addEventListener("scroll",()=>{const r=document.querySelector(".popup-item-media-action-menu");if(!r||!this.activeActionsMenu)return;const o=this.activeActionsMenu.getBoundingClientRect();r.style.left=o.left+o.width/2+"px",r.style.top=o.bottom+"px"})},this.onKeyDown=n=>{const r=n.target,{input:o}=this.messageInputField;if(r!==o){if(r.tagName==="INPUT"||r.isContentEditable)return;o.focus(),Ki(o)}},this.attachFile=(n,r)=>{const o=this.willAttach,l=this.shouldCompress(n.type),c=document.createElement("div");c.classList.add("popup-item");const d={file:n,...r||{}};tD(d,["scaledBlob","middlewareHelper","itemDiv","mediaSpoiler"]),d.middlewareHelper=this.middlewareHelper.get().create(),d.itemDiv=c;const u=l?this.attachMedia(d):this.attachDocument(d);return o.sendFileDetails.push(d),u.catch(h=>{c.style.backgroundColor="#000",console.error("error rendering file",h)})},this.starsState=Ft(n=>{this.middlewareHelper.get().onDestroy(()=>void n());const[r,o]=Qr({hasMessage:!1,isGrouped:!0,attachedFiles:this.files.length,starsAmount:this.chat.starsAmount||0}),l=()=>+r.hasMessage*+(!r.isGrouped&&r.attachedFiles>1),c=V(()=>+l()+r.attachedFiles),d=V(()=>r.starsAmount*c());return le(()=>{this.updateConfirmBtnContent(d())}),{store:r,set:o,totalMessages:c}}),this.animationGroup="NEW-MEDIA",this.construct(s)}static async canSend({peerId:e,onlyVisible:t,threadId:s}){const i=["send_photos","send_videos","send_docs","send_audios","send_gifs"],n=i.map(l=>e.isAnyChat()&&!t?I.managers.appChatsManager.hasRights(e.toChatId(),l,void 0,s?!0:void 0):!0),r={},o=await Promise.all(n);return i.forEach((l,c)=>{r[l]=o[c]}),r}async construct(e){this.willAttach={type:e,sendFileDetails:[],group:!0};const t=await this.managers.apiManager.getLimit("caption");this.captionLengthMax=t;const s=await Ao.canSend({...this.chat.getMessageSendingParams(),onlyVisible:!0}),i=s.send_photos,n=s.send_videos,r=s.send_docs;J(this.btnConfirm,async()=>(await ns(0),this.send()),{listenerSetter:this.listenerSetter});const o=ki({listenerSetter:this.listenerSetter,direction:"bottom-left",buttons:[{icon:"plusround",text:"Add",onClick:()=>{this.chat.input.onAttachClick(!1,!1,!1)},verify:()=>!0},{icon:"image",text:"Popup.Attach.AsMedia",onClick:()=>this.changeType("media"),verify:()=>{if(!this.hasAnyMedia()||this.willAttach.type!=="document"||!i&&!n)return!1;if(!i||!n){const d=i?um:Hp,{media:u,files:h}=this.partition(d);if(h.length)return!1}return!0}},{icon:"document",text:"SendAsFile",onClick:()=>this.changeType("document"),verify:()=>this.files.length===1&&this.willAttach.type!=="document"&&r},{icon:"document",text:"SendAsFiles",onClick:()=>this.changeType("document"),verify:()=>this.files.length>1&&this.willAttach.type!=="document"&&r},{icon:"groupmedia",text:"Popup.Attach.GroupMedia",onClick:()=>this.changeGroup(!0),verify:()=>!this.hasGif()&&!this.willAttach.group&&this.canGroupSomething()},{icon:"groupmediaoff",text:"Popup.Attach.UngroupMedia",onClick:()=>this.changeGroup(!1),verify:()=>!this.hasGif()&&this.willAttach.group&&this.canGroupSomething()},{icon:"mediaspoiler",text:"EnablePhotoSpoiler",onClick:()=>this.changeSpoilers(!0),verify:()=>this.canToggleSpoilers(!0,!0)},{icon:"mediaspoiler",text:"Popup.Attach.EnableSpoilers",onClick:()=>this.changeSpoilers(!0),verify:()=>this.canToggleSpoilers(!0,!1)},{icon:"mediaspoileroff",text:"DisablePhotoSpoiler",onClick:()=>this.changeSpoilers(!1),verify:()=>this.canToggleSpoilers(!1,!0)},{icon:"mediaspoileroff",text:"Popup.Attach.RemoveSpoilers",onClick:()=>this.changeSpoilers(!1),verify:()=>this.canToggleSpoilers(!1,!1)},{icon:"captionup",text:"CaptionAbove",onClick:()=>this.moveCaption(!0),verify:()=>this.canMoveCaption()&&!this.willAttach.invertMedia},{icon:"captiondown",text:"CaptionBelow",onClick:()=>this.moveCaption(!1),verify:()=>this.canMoveCaption()&&!!this.willAttach.invertMedia},{icon:"cash_circle",text:"PaidMedia.Menu.Edit",onClick:()=>{ue.createPopup(d0,d=>{this.setPaidMedia(d)},this.willAttach.stars)},verify:()=>!!this.willAttach.stars&&this.canSendPaidMedia()},{icon:"cash_circle",text:"PaidMedia.Menu",onClick:()=>{ue.createPopup(d0,d=>{this.setPaidMedia(d)})},verify:()=>!this.willAttach.stars&&this.canSendPaidMedia()}]});this.header.append(o),this.btnConfirm.remove(),this.mediaContainer=document.createElement("div"),this.mediaContainer.classList.add("popup-photo"),this.scrollable.container.append(this.mediaContainer);const l=document.createElement("div");l.classList.add("popup-input-container");const c=document.createElement("div");if(c.classList.add("popup-input-inputs","input-message-container"),this.messageInputField=new m1({placeholder:"PreviewSender.CaptionPlaceholder",name:"message",withLinebreaks:!0,maxLength:this.captionLengthMax}),this.messageInputField.input.dataset.animationGroup=this.animationGroup,this.listenerSetter.add(this.scrollable.container)("scroll",this.onScroll),this.listenerSetter.add(this.messageInputField.input)("scroll",this.onScroll),this.listenerSetter.add(this.messageInputField.input)("input",fa(d=>{const{value:u}=xn(this.messageInputField.input);this.starsState.set({hasMessage:!!u.trim()})},120,!0)),this.messageInputField.input.classList.replace("input-field-input","input-message-input"),this.messageInputField.inputFake.classList.replace("input-field-input","input-message-input"),c.append(this.messageInputField.input,this.messageInputField.placeholder,this.messageInputField.inputFake),l.append(c,this.btnConfirm),!this.ignoreInputValue&&!this.chat.input.editMsgId&&(this.wasDraft=this.chat.input.getCurrentInputAsDraft(),this.wasDraft)){const d=xI(this.wasDraft,{wrappingForPeerId:this.chat.peerId,animationGroup:this.animationGroup});this.messageInputField.setValueSilently(d),this.chat.input.messageInputField.value=""}this.container.append(l),this.attachFiles(),this.addEventListener("close",()=>{this.files.length=0,this.willAttach.sendFileDetails.length=0,this.hideActiveActionsMenu(),sm===this&&(sm=void 0)}),this.chat.type!==we.Scheduled&&(Ft(u=>{this.chat.destroyMiddlewareHelper.onDestroy(u);const[h,p]=K(this.wasDraft?.effect);this.effect=h,this.setEffect=p,this.btnConfirm.append(AI({effect:this.effect}))}),new cw({onSilentClick:()=>{this.chat.input.sendSilent=!0,this.send()},onScheduleClick:()=>{this.chat.input.scheduleSending(()=>{this.send()})},onSendWhenOnlineClick:()=>{this.chat.input.setScheduleTimestamp(Nh,()=>{this.send()})},openSide:"top-left",onContextElement:this.btnConfirm,middleware:this.middlewareHelper.get(),canSendWhenOnline:this.chat.input.canSendWhenOnline,onRef:u=>{this.container.append(u)},withEffects:()=>this.chat.peerId.isUser()&&this.chat.peerId!==I.myId,effect:this.effect,onEffect:this.setEffect})?.setPeerParams({peerId:this.chat.peerId,isPaid:!!this.chat.starsAmount})),sm=this}async canSendPaidMedia(){return await this.managers.appPeersManager.isBroadcast(this.chat.peerId)&&!!(await this.managers.appProfileManager.getChannelFull(this.chat.peerId.toChatId())).pFlags.paid_media_allowed}willSendPaidMedia(){return this.willAttach.stars&&this.willAttach.type==="media"&&this.willAttach.sendFileDetails.length<=10}setPaidMedia(e){this.willAttach.stars=e,this.changeSpoilers(!!e),this.setUnlockPlaceholders()}setUnlockPlaceholders(){const{stars:e}=this.willAttach;this.mediaContainer.querySelectorAll(".popup-item-album, .popup-item-media:not(.grouped-item)").forEach(t=>{const s="extended-media-buy";if(t.querySelector(`.${s}`)?.remove(),!this.willSendPaidMedia())return;const i=document.createElement("span");i.classList.add(s),i.append(P("PaidMedia.Unlock",[qi(e,Mo)])),t.append(i)})}async applyMediaSpoiler(e,t){const s=e.itemDiv.querySelector(".spoiler-toggle");s&&(s.dataset.disabled="true");const i=e.middlewareHelper.get(),{width:n,height:r}=e.itemDiv.style;let o,l;if(e.itemDiv.classList.contains("album-item")){const{width:m,height:g}=e.itemDiv.parentElement.style,f=parseInt(m),v=parseInt(g);o=+n.slice(0,-1)/100*f,l=+r.slice(0,-1)/100*v}else o=parseInt(n),l=parseInt(r);const{url:c}=await Fm({media:e.itemDiv.firstElementChild,boxSize:ii(40,40),mediaSize:ii(o,l),toDataURL:!0,quality:.2}),d=$L(c),u={_:"photoStrippedSize",bytes:d,type:"i"};e.strippedBytes=d;const h={_:"photo",sizes:[u],id:0,access_hash:0,date:0,dc_id:0,file_reference:[],pFlags:{}},p=await ju({middleware:i,width:o,height:l,animationGroup:this.animationGroup,media:h});i()&&(t||p.classList.add("is-revealing"),e.mediaSpoiler=p,e.itemDiv.append(p),await hi(),i()&&(Vv({mediaSpoiler:p,reveal:!1}),s&&(s.dataset.toggled="true",delete s.dataset.disabled)))}removeMediaSpoiler(e){const t=e.itemDiv.querySelector(".spoiler-toggle");t&&(t.dataset.disabled="true"),Vv({mediaSpoiler:e.mediaSpoiler,reveal:!0,destroyAfter:!0}),t&&(delete t.dataset.toggled,delete t.dataset.disabled),e.mediaSpoiler=void 0}appendDrops(e){this.body.append(e)}partition(e=Wr){const t=[],s=[],i=[];return this.willAttach.sendFileDetails.forEach(n=>{e.has(n.file.type)?t.push(n):Mp.has(n.file.type)?i.push(n):s.push(n)}),{media:t,files:s,audio:i}}mediaCount(){return this.partition().media.length}hasAnyMedia(){return this.mediaCount()>0}messagesCount(){let e=0;return this.iterate(()=>{++e}),e}canGroupSomething(){const{media:e,files:t,audio:s}=this.partition();return e.length>1||t.length>1||s.length>1}canToggleSpoilers(e,t){if(this.willSendPaidMedia())return!1;let s=this.willAttach.type==="media"&&this.hasAnyMedia();if(t&&s&&(s=this.files.length===1),s){const i=this.willAttach.sendFileDetails.filter(r=>Wr.has(r.file.type)),n=i.filter(r=>r.mediaSpoiler);s=t?!0:i.length>1,s&&(s=e?i.length!==n.length:i.length===n.length)}return s}changeType(e){e==="document"&&this.moveCaption(!1),this.willAttach.type=e,this.attachFiles()}changeGroup(e){this.willAttach.group=e,this.attachFiles(),this.starsState.set({isGrouped:e})}changeSpoilers(e){this.partition().media.forEach(t=>{e&&!t.mediaSpoiler?this.applyMediaSpoiler(t):!e&&t.mediaSpoiler&&this.removeMediaSpoiler(t)})}canMoveCaption(){return!this.messageInputField.isEmpty()&&this.willAttach.type==="media"}moveCaption(e){this.willAttach.invertMedia=e||void 0}addFiles(e){const t=e.filter(s=>!this.files.find(n=>n.lastModified===s.lastModified&&n.name===s.name&&n.size===s.size));t.length&&(this.files.push(...t),this.willSendPaidMedia()&&this.files.length>10&&this.changeSpoilers(!1),this.attachFiles())}prepareEditedFileForSending(e){e.editResult?.standaloneContext?.dispose();const t=e.editResult?.getResult();if(!(!t||t instanceof Promise))return this.wrapMediaEditorBlobInFile(e.file,t,e.editResult?.isGif)}async send(e=!1){let{value:t,entities:s}=xn(this.messageInputField.input,!0,!1);if(t.length>this.captionLengthMax){Wi(Ne.format("Error.PreviewSender.CaptionTooLong",!0));return}if(await this.chat.input.showSlowModeTooltipIfNeeded({sendingFew:this.messagesCount()>1,container:this.btnConfirm.parentElement,element:this.btnConfirm}))return;const{input:n}=this.chat,r=await Ao.canSend(this.chat.getMessageSendingParams()),o=this.willAttach;o.isMedia=o.type==="media"||void 0;const{sendFileDetails:l,isMedia:c}=o;let d=!1;if(this.iterate(g=>{if(d)return;const v=g.map(y=>{const w=[[Mp,"GlobalAttachAudioRestricted","send_audios"],[()=>!Wr.has(y.file.type),"GlobalAttachDocumentsRestricted","send_docs"]];c&&w.unshift([um,"GlobalAttachPhotoRestricted","send_photos"],[()=>Hp.has(y.file.type)&&y.noSound,"GlobalAttachGifRestricted","send_gifs"],[Hp,"GlobalAttachVideoRestricted","send_videos"]);const b=w.find(([S])=>typeof S=="function"?S():S.has(y.file.type));return b?r[b[2]]?void 0:b[1]:!c&&!r.send_docs&&"GlobalAttachDocumentsRestricted"||void 0}).find(y=>typeof y=="string");v&&($e({langPackKey:v}),wt.isAvailable("animations")&&to(this.body)),d||(d=!!v)}),d)return;if(this.chat.type===we.Scheduled&&!e){this.chat.input.scheduleSending(()=>{this.send(!0)});return}const{length:u}=l,h=this.chat.getMessageSendingParams(),p=await this.chat.input.paidMessageInterceptor.prepareStarsForPayment(this.starsState.totalMessages());if(p===Fn)return;h.confirmedPaymentResult=p;let m=this.effect();this.iterate(g=>{t&&g.length!==u&&(this.managers.appMessagesManager.sendText({...h,text:t,entities:s,effect:m}),t=s=m=void 0);const f=this.willSendPaidMedia(),v=g.map(w=>({...w,file:this.prepareEditedFileForSending(w)||w.scaledBlob||w.file,width:w.editResult?.width||w.width,height:w.editResult?.height||w.height,spoiler:f?void 0:!!w.mediaSpoiler,editResult:void 0})),y={...o,sendFileDetails:v};f||delete y.stars,this.managers.appMessagesManager.sendGrouped({...h,caption:t,entities:s,effect:m,isMedia:c,...y}),t=s=m=void 0}),h.replyToMsgId&&n.onHelperCancel(),this.wasDraft=void 0,this.hide()}modifyMimeTypeForTelegram(e){return jw.has(e)?"image/jpeg":e}async scaleImageForTelegram(e,t,s){let n=e.src,r;if(t!=="image/gif"&&(Math.max(e.naturalWidth,e.naturalHeight)>2560||s&&!jw.has(t))){const{blob:o}=await Fm({media:e,boxSize:ii(2560,2560),mediaSize:ii(e.naturalWidth,e.naturalHeight),mimeType:this.modifyMimeTypeForTelegram(t)});r=o,URL.revokeObjectURL(n),n=await Ae.invoke("createObjectURL",o),await Vn(e,n)}return r&&{url:n,blob:r}}async attachMedia(e){const{itemDiv:t}=e;t.classList.add("popup-item-media");const s=e.file,i=s.type.startsWith("video/"),n=e.editResult;let r;if(n){const o=n.getResult();if(o instanceof Blob)if(n.isGif){await l(n.preview),await c(o);const d=P("AttachGif");d.classList.add("gif-label"),t.append(d)}else await l(o,!0);else{await l(n.preview);const d=document.createElement("div"),u=wi(()=>I6({context:n.standaloneContext.value}),d);t.append(d),this.btnConfirmOnEnter.disabled=!0,o.then(async h=>{u(),await c(h);const p=P("AttachGif");p.classList.add("gif-label"),t.append(p),this.btnConfirmOnEnter.disabled=!1})}async function l(d,u=!1){const h=await Ae.invoke("createObjectURL",d);u&&(e.objectURL=h);const p=new Image;await Vn(p,h),p.className="popup-item-media-extend-full",t.append(p),e.width=n.width,e.height=n.height}async function c(d){const u=Do({middleware:e.middlewareHelper.get()}),h=await Ae.invoke("createObjectURL",d);u.src=e.objectURL=h,u.autoplay=!0,u.controls=!1,u.muted=!0,u.loop=!0,u.className="popup-item-media-extend-full",t.append(u),await ua(u),e.width=n.width,e.height=n.height,e.duration=u.duration,e.noSound=!0;const p=await c0(u);e.thumb={url:await Ae.invoke("createObjectURL",p.blob),...p}}}else if(i){const o=Do({middleware:e.middlewareHelper.get()});o.src=e.objectURL=await Ae.invoke("createObjectURL",s),o.autoplay=!0,o.controls=!1,o.muted=!0,o.addEventListener("timeupdate",()=>{o.pause()},{once:!0}),t.append(o);let l;try{const u=ua(o);await mg(o,u)}catch(u){l=u}if(e.width=o.videoWidth,e.height=o.videoHeight,e.duration=Math.floor(o.duration),l)throw l;const c=o.webkitAudioDecodedByteCount;c!==void 0&&(e.noSound=!c);const d=await c0(o);e.thumb={url:await Ae.invoke("createObjectURL",d.blob),...d}}else{const o=new Image;t.append(o);const l=e.objectURL=await Ae.invoke("createObjectURL",s);await Vn(o,l);const c=e.file.type,d=await this.scaleImageForTelegram(o,c,!0);d&&(e.objectURL=d.url,e.scaledBlob=d.blob),e.width=o.naturalWidth,e.height=o.naturalHeight,s.type==="image/gif"&&(e.noSound=!0,r=Promise.all([eD(o).then(u=>{e.duration=Math.ceil(u)}),TI(o).then(async u=>{e.thumb={url:await Ae.invoke("createObjectURL",u.blob),...u}})]).then(()=>{}))}{const o=new $t,l=async()=>{if(this.activeActionsMenu===t||!this.canShowActions)return;c(),this.activeActionsMenu=t;const d=document.createElement("div");d.classList.add("popup-item-media-action-menu");const u="popup-item-media-action";let h;!this.willAttach.stars&&!i&&s.type!=="image/gif"&&(h=Be("equalizer",u),h.addEventListener("click",()=>{c(),this.btnConfirmOnEnter.disabled=!0;const v=t.querySelector("img");if(!v)return;const y=v.cloneNode(),w=t.getBoundingClientRect();y.style.position="fixed";const b=w.left+w.width/2,S=w.top+w.height/2,_=w.width,M=w.height;y.style.left=b+"px",y.style.top=S+"px",y.style.width=_+"px",y.style.height=M+"px",y.style.transform="translate(-50%, -50%)",y.style.objectFit="cover",y.style.zIndex="1000",document.body.append(y),C6({imageURL:e.editResult?.originalSrc||e.objectURL,managers:this.managers,onEditFinish:C=>{e.editResult=C,this.attachFiles()},onCanvasReady:C=>{const L=C.getBoundingClientRect(),E=L.left+L.width/2-b,x=L.top+L.height/2-S,[R,B]=Qa(v.naturalWidth/v.naturalHeight,L.width,L.height),N=Mt();return zi(0,1,200,G=>{y.style.transform=`translate(calc(${G*E}px - 50%), calc(${G*x}px - 50%))`,y.style.width=js(_,R,G)+"px",y.style.height=js(M,B,G)+"px"},{onEnd:()=>N.resolve()}),N},onImageRendered:async()=>{y.style.opacity="1",y.style.transition=".12s",await hi(),y.style.opacity="0",await ka(120),y.remove()},standaloneContext:e.editResult?.standaloneContext,onClose:C=>{C||(this.btnConfirmOnEnter.disabled=!1)}},ep)}));let p;this.willAttach.stars||(p=document.createElement("span"),p.classList.add(u,"spoiler-toggle"),e.mediaSpoiler&&(p.dataset.toggled="true"),p.append(Be("mediaspoiler"),Be("mediaspoileroff")),p.addEventListener("click",()=>{p.dataset.disabled||(p.dataset.toggled=p.dataset.toggled==="true"?"false":"true",e.mediaSpoiler?this.removeMediaSpoiler(e):this.applyMediaSpoiler(e))}));const m=Be("delete",u);m.addEventListener("click",()=>{const v=this.files.findIndex(y=>y===e.file);v>=0&&(c(),this.files.splice(v,1),e.editResult?.standaloneContext?.dispose(),this.files.length?this.attachFiles():this.destroy())}),d.append(...[h,p,m].filter(Boolean));const g=t.getBoundingClientRect();d.style.left=g.left+g.width/2+"px",d.style.top=g.bottom+"px",document.body.append(d),await hi(),d.style.opacity="1";const f=v=>{v.target?.closest?.(".popup-item-media-action-menu")||v.target===t||t.contains(v.target)||c()};o.add(document)("pointermove",f),o.add(document)("keydown",()=>{c()},{capture:!0}),Gi&&o.add(document)("pointerdown",f)},c=()=>{o.removeAll(),this.hideActiveActionsMenu()};t.addEventListener("pointermove",l),t.addEventListener("pointerup",l)}return r}hideActiveActionsMenu(){document.querySelectorAll(".popup-item-media-action-menu")?.forEach(async e=>{this.activeActionsMenu=void 0,e.style.opacity="0",await ka(200),e?.remove()})}wrapMediaEditorBlobInFile(e,t,s){if(this.cachedMediaEditorFiles.has(t))return this.cachedMediaEditorFiles.get(t);let i=e.name;s&&(i=i.replace(/\.[^.]+$/,".mp4"));const n=new File([t],i,{type:t.type});return this.cachedMediaEditorFiles.set(t,n),n}async attachDocument(e){const{itemDiv:t}=e;t.classList.add("popup-item-document");const s=await e.editResult?.getResult(),i=s?this.wrapMediaEditorBlobInFile(e.file,s,e.editResult?.isGif):e.file,n=i.type.startsWith("image/"),r=Mp.has(i.type);(n||r||i.size<2e7)&&(e.objectURL||(e.objectURL=await Ae.invoke("createObjectURL",i)));const o=[];let l;if(n&&e.objectURL){l=new Image,await Vn(l,e.objectURL);const h=await this.scaleImageForTelegram(l,i.type);h&&(e.objectURL=h.url)}if(r&&e.objectURL)try{const h=new Audio;h.src=e.objectURL,h.muted=!0,h.autoplay=!0,await ua(h),e.duration=h.duration,o.push({_:"documentAttributeAudio",duration:e.duration,pFlags:{}})}catch(h){console.error("audio loading error",h)}const c={_:"document",file:i,file_name:i.name||"",size:i.size,type:r?"audio":n?"photo":void 0,access_hash:0,attributes:o,date:0,dc_id:0,file_reference:[],id:0,pFlags:{},duration:e.duration};let d;e.objectURL&&(d={url:e.objectURL,downloaded:i.size,type:Uy});const u=await rd({message:{_:"message",pFlags:{is_outgoing:!0},mid:0,peerId:0,media:{_:"messageMediaDocument",document:c}},cacheContext:d});n&&(e.width=l.naturalWidth,e.height=l.naturalHeight),t.append(u)}shouldCompress(e){return this.willAttach.type==="media"&&Wr.has(e)}onRender(){this.element.classList.contains("active")||(this.listenerSetter.add(document.body)("keydown",this.onKeyDown),Ut.setOnlyOnePlayableGroup(this.animationGroup),this.addEventListener("close",()=>{Ut.setOnlyOnePlayableGroup(),!this.ignoreInputValue&&this.wasDraft&&this.chat.input.setDraft(this.wasDraft,!1,!0)}),this.show())}updateConfirmBtnContent(e){if(!e)return void St(this.btnConfirm,P("Modal.Send"));const t=document.createElement("span");t.classList.add("popup-confirm-btn-inner"),t.append(Be("star","popup-confirm-btn-inner-star"),Jr(e)+""),St(this.btnConfirm,t)}setStarsAmount(e){this.starsState.set({starsAmount:e})}setTitle(){const{willAttach:e,title:t,files:s}=this;let i;const n=[];if(e.type==="document")i="PreviewSender.SendFile",n.push(s.length);else{let r=0,o=0,l=0;s.forEach(c=>{c.type.startsWith("image/")?++r:c.type.startsWith("video/")?++o:++l}),[r,o,l].filter(c=>c>0).length>1?(i="PreviewSender.SendFile",n.push(s.length)):r?(i="PreviewSender.SendPhoto",n.push(r)):o&&(i="PreviewSender.SendVideo",n.push(o))}St(t,P(i,n))}appendMediaToContainer(e){if(this.shouldCompress(e.file.type)){const t=NL(e.width,e.height,w0,320);e.itemDiv.style.width=t.width+"px",e.itemDiv.style.height=t.height+"px"}this.mediaContainer.append(e.itemDiv)}hasGif(){const{sendFileDetails:e}=this.willAttach;return e.some(t=>t.editResult?.isGif)}iterate(e){const{sendFileDetails:t}=this.willAttach;if(!this.willAttach.group||this.hasGif()){t.forEach(i=>e([i]));return}const s=t.length;for(let i=0;i<s;){const n=t[i].file.type;let r=0,o;for(;r<10&&i<s;++i,++r){const l=t[i].file.type,c=Mp.has(l);if(o??(o=c),c!==o||this.shouldCompress(n)!==this.shouldCompress(l))break}e(t.slice(i-r,i))}}attachFiles(){const{files:e,willAttach:t,mediaContainer:s}=this,i=t.sendFileDetails.splice(0,t.sendFileDetails.length);i.forEach(r=>{r.middlewareHelper.destroy()});const n=e.map(r=>{const o=i.find(l=>l.file===r);return this.attachFile(r,o?.editResult?{editResult:o.editResult}:void 0)});this.canShowActions=!1,Promise.all(n).then(()=>{s.replaceChildren(),this.starsState.set({attachedFiles:e.length,isGrouped:this.willAttach?.group&&!this.hasGif()}),e.length&&(this.setTitle(),this.iterate(r=>{const o=this.shouldCompress(r[0].file.type);if(o&&r.length>1){const l=document.createElement("div");l.classList.add("popup-item-album","popup-item"),l.append(...r.map(c=>c.itemDiv)),rI({container:l,items:r.map(c=>({w:c.width,h:c.height})),maxWidth:w0,minWidth:100,spacing:4}),s.append(l)}else r.forEach(l=>{this.appendMediaToContainer(l)});o&&r.forEach(l=>{(i.find(d=>d.file===l.file)?.mediaSpoiler||this.willSendPaidMedia())&&this.applyMediaSpoiler(l,!0)})}),this.setUnlockPlaceholders())}).then(()=>{this.onRender(),this.onScroll(),hi().then(()=>this.afterRender())})}afterRender(){setTimeout(()=>{this.canShowActions=!0},200),this.willAttach.sendFileDetails.forEach(e=>{const t=e.editResult;if(t?.animatedPreview){const s=t.animatedPreview,i=s.getBoundingClientRect(),n=i.left+i.width/2,r=i.top+i.height/2,o=i.width,l=i.height,c=e.itemDiv.getBoundingClientRect(),d=c.left+c.width/2-n,u=c.top+c.height/2-r;zi(0,1,200,h=>{s.style.transform=`translate(calc(${h*d}px - 50%), calc(${h*u}px - 50%))`,s.style.width=js(o,c.width,h)+"px",s.style.height=js(l,c.height,h)+"px"},{onEnd:()=>{s.remove(),t.animatedPreview=void 0}})}})}}window.PopupNewMedia=Ao;const P6=!1,M6=!1,S0=!1,L6=[["messageActionHistoryClear",!0],["messageActionChatCreate",a=>a.pFlags.out],["messageActionChannelMigrateFrom",!0],["messageActionChatMigrateTo",!0],["messageActionContactSignUp",!0]],E6=new Map(L6),ew=new Set;Gh&&ew.add("messageActionPhoneCall");let C0=0;const _0=1,lP=3,I0=300,qf=new Error("peer changed"),k6=!1,T6=dn,Yf=!0,cP={1:96,2:90,3:84,4:72,5:60,6:48,7:36},x6=Object.keys(cP).length,A6={telegram_channel:"Chat.Message.ViewChannel",telegram_megagroup:"OpenGroup",telegram_bot:"Chat.Message.ViewBot",telegram_botapp:"Chat.Message.ViewApp",telegram_user:"Chat.Message.SendMessage",telegram_chatlist:"OpenChatlist",telegram_story:"OpenStory",telegram_channel_boost:"BoostLinkButton",telegram_giftcode:"Open",telegram_chat:"OpenGroup",telegram_livestream:"VoipChannelJoinVoiceChatUrl",telegram_nft:"StarGiftLinkButton"},P0={telegram_livestream:"PeerInfo.Action.LiveStream"};function Qf(a){return Math.min(...a)}const R6=a=>a.photo;function ps(a,e){return typeof a=="object"&&(e=a.mid,a=a.peerId),`${a}_${e}`}function $a(a){if(!(!a||a.dataset.mid===void 0))return ps(a.dataset.peerId.toPeerId(),+a.dataset.mid)}function ti(a){const[e,t]=a.split("_");return{peerId:e.toPeerId(),mid:+t}}const Ci=ps(Wt,0);function Gd(a,e,t){(a.timeAppenders??(a.timeAppenders=[])).unshift({element:e,callback:t}),t()}class F6{constructor(e,t){this.chat=e,this.managers=t,this.unreadOut=new Set,this.needUpdate=[],this.bubbles={},this.skippedMids=new Set,this.bubblesNewByGroupedId={},this.bubblesNew={},this.dateMessages={},this.scrolledDown=!0,this.isScrollingTimeout=0,this.unreaded=new Map,this.unreadedContent=new Map,this.unreadedSeen=new Set,this.unreadedContentSeen=new Set,this.preloader=null,this.messagesQueueOnRenderAdditional=null,this.firstUnreadBubble=null,this.middlewareHelper=Ht(),this.followStack=[],this.isHeavyAnimationInProgress=!1,this.isFirstLoad=!0,this.passEntities={},this.viewsMids=new Set,this.isTopPaddingSet=!1,this.renderingMessages=new Set,this.bubblesToEject=new Set,this.bubblesToReplace=new Map,this.setPeerTempId=0,this.renderNewPromises=new Set,this.extendedMediaMessages=new Set,this.updateLocationOnEdit=new Map,this.unreadedObserverCallback=i=>{if(i.isIntersecting){const n=i.target,r=this.unreaded.get(n);this.onUnreadedInViewport("history",n,r)}},this.unreadedContentObserverCallback=i=>{if(i.isIntersecting){const n=i.target,r=this.unreadedContent.get(n);this.onUnreadedInViewport("content",n,r)}},this.viewsObserverCallback=i=>{if(i.isIntersecting){const n=$a(i.target);if(this.observer.unobserve(i.target,this.viewsObserverCallback),n)this.viewsMids.add(n),this.sendViewCountersDebounced();else{const{sponsoredMessage:r}=this;if(!r||r.viewed)return;r.viewed=!0,this.managers.appMessagesManager.viewSponsoredMessage(r.random_id)}}},this._stickerEffectObserverCallback=(i,n,r)=>{if(i.isIntersecting){this.observer.unobserve(i.target,n);const o=i.target.querySelector(r);vi().then(()=>{mr(o)&&Xs(o)})}},this.stickerEffectObserverCallback=i=>{this._stickerEffectObserverCallback(i,this.stickerEffectObserverCallback,".attachment")},this.messageEffectObserverCallback=i=>{this._stickerEffectObserverCallback(i,this.messageEffectObserverCallback,".time-inner .time-effect")},this.updateMessageReply=async i=>{const n=this.getMiddleware();if(await vi(),!n())return;const r=[],o=i.peerId,l=i.mids||i.ids,c=this.needUpdate,d=i.mids?"replyMid":"replyStoryId",u=l.map(p=>{const m=[];hn(c,(f,v)=>{f[d]===p&&(f.replyToPeerId===o||!o)&&m.push(f)});const g=m.map(async({peerId:f,mid:v,replyMid:y,replyToPeerId:w})=>{const b=ps(f,v),S=this.getBubble(b);if(!S)return;const[_,M]=await Promise.all([this.chat.getMessage(b),y&&this.managers.appMessagesManager.getMessageByPeer(w,y)]);r.push(async()=>{const C=bc.setReply({chat:this.chat,bubble:S,message:_,middleware:S.middlewareHelper.get(),lazyLoadQueue:this.lazyLoadQueue,needUpdate:this.needUpdate,isStandaloneMedia:S.classList.contains("just-media"),isOut:S.classList.contains("is-out"),fromUpdate:!0});if(!M)return C;await C;let L;const E=S.querySelectorAll(".timestamp");(L=yh(M))&&E.forEach(x=>{+x.dataset.timestamp<L?x.classList.remove("is-disabled"):x.removeAttribute("href")})})});return Promise.all(g)});if(await Promise.all(u),!n()||!r.length)return;const h=this.createScrollSaver(!0);h.save(),await Promise.all(r.map(p=>p())),h.restore()},this.onBubblesMouseMove=async i=>{ne(i.target,"media-video-mini")?.onMiniVideoMouseMove?.(i);const r=ne(i.target,"bubble-content");if(!(this.chat.type!==we.Scheduled&&r&&!this.chat.selection.isSelecting&&!ne(i.target,"service")&&!ne(i.target,"bubble-beside-button")&&this.peerId!==I.myId)){this.unhoverPrevious();return}const o=ne(r,"bubble");if(!this.chat.selection.canSelectBubble(o)){this.unhoverPrevious();return}let{hoverBubble:l,hoverReaction:c}=this;if(o===l)return;if(this.unhoverPrevious(),l=this.hoverBubble=o,c=this.hoverReaction,c){c.dataset.loaded&&this.setHoverVisible(c,!0);return}c=this.hoverReaction=document.createElement("div"),c.classList.add("bubble-hover-reaction");const u=(c.middlewareHelper=this.getMiddleware().create()).get(()=>this.hoverReaction===c),h=document.createElement("div");h.classList.add("bubble-hover-reaction-sticker"),c.append(h),r.append(c);let p=this.chat.getMessage($a(o));if(p?._!=="message"){this.unhoverPrevious();return}p=await this.managers.appMessagesManager.getGroupsFirstMessage(p),Promise.all([this.managers.appReactionsManager.getAvailableReactionsByMessage(p,!0),Ae.getAvailableReactions(),ns(400)]).then(async([{reactions:m},g])=>{const f=m.find(w=>w._!=="reactionPaid");if(!f){c.remove();return}const y=(f._==="reactionEmoji"?g.find(w=>w.reaction===f.emoticon):void 0)?.select_animation??await this.managers.appEmojiManager.getCustomEmojiDocument(f.document_id);u()&&ai({div:h,doc:y,width:18,height:18,needUpscale:!0,middleware:u,group:this.chat.animationGroup,withThumb:!1,needFadeIn:!1}).then(({render:w})=>w).then(w=>{const b=()=>{u()&&(c.dataset.loaded="1",this.setHoverVisible(c,!0))};Array.isArray(w)?b():w.addEventListener("firstFrame",b,{once:!0}),J(c,S=>{_e(S),this.chat.sendReaction({message:p,reaction:f}),this.unhoverPrevious()},{listenerSetter:this.listenerSetter})},as)})},this.unhoverPrevious=()=>{const{hoverBubble:i,hoverReaction:n}=this;i&&(this.setHoverVisible(n,!1),this.hoverBubble=this.hoverReaction=void 0)},this.onBubblesClick=async i=>{let n=i.target,r=null,o;try{r=ne(n,"bubble"),r&&(o=$a(r))}catch{}const c={stack:this.chat.appImManager.getStackFromElement(n)};if(!r&&!this.chat.selection.isSelecting){const M=ne(n,"user-avatar");if(!M)return;const C=M.dataset.peerId.toPeerId();C!==Wt?this.chat.appImManager.setInnerPeer({...c,peerId:C}):Wi(Ne.format("HidAccount",!0));return}if(!r)return;if(r.classList.contains("is-date")&&ne(n,"bubble-content")){if(r.classList.contains("is-fake")&&(r=r.previousElementSibling),r.classList.contains("is-sticky")&&!this.chatInner.classList.contains("is-scrolling"))return;for(const M in this.dateMessages)if(this.dateMessages[M].div===r){ue.createPopup(Ng,new Date(+M),this.onDatePick).show();break}return}const d=ne(n,"time-effect");if(d){p2({timeEffect:d,bubble:r,e:i,scrollable:this.scrollable});return}if(!pt&&ne(n,"time")){this.chat.selection.toggleByElement(r);return}if(this.chat.selection.isSelecting&&i.isTrusted){if(r.classList.contains("service")&&o===void 0)return;if(_e(i),pt&&this.chat.selection.selectedText){this.chat.selection.selectedText=void 0;return}this.chat.selection.toggleByElement(ne(n,"grouped-item")||r);return}const u=ne(n,"contact");if(u){const M=u.dataset.peerId.toPeerId();if(M)this.chat.appImManager.setInnerPeer({...c,peerId:M});else{const C=u.querySelector(".contact-number");si(C.innerText.replace(/\s/g,"")),$e({langPackKey:"PhoneCopied"}),_e(i)}return}const h=ne(n,"bubble-call");if(h){this.chat.appImManager.callUser(this.peerId.toUserId(),h.dataset.type);return}if(ne(n,"is-buy")){_e(i);const M=this.chat.getMessage(o);if(!M)return;const C=M.media,L=C?._==="messageMediaPaidMedia"?C:void 0,E=await Ln.create({message:M,inputInvoice:await this.managers.appPaymentsManager.getInputInvoiceByPeerId(M.peerId,M.mid),paidMedia:L});L&&E.addEventListener("finish",async x=>{x==="paid"&&Gu({icon:"cash_circle",title:P("StarsMediaPurchaseCompleted"),textElement:P("StarsMediaPurchaseCompletedInfo",[L.stars_amount,await qe({peerId:M.fwdFromId||M.peerId})]),appendTo:this.container,from:"top",duration:5e3})});return}const m=ne(n,"media-spoiler-container");if(m){X1({event:i,mediaSpoiler:m});return}const g=Mn(n,"REACTION-ELEMENT");if(g){if(ne(n,"tooltip")||(_e(i),g.classList.contains("is-inactive")))return;const M=g.parentElement,C=M.getReactionCount(g),{reaction:L}=C;if(M.getType()===la.Tag){if(!I.premium){rs.show({feature:"saved_tags"});return}const E=this.chat.searchSignal();if(Wn(E?.reaction,L)){this.chat.contextMenu.onContextMenu(i);return}this.chat.initSearch({reaction:L})}else{const E=M.getContext();this.chat.sendReaction({message:E,reaction:L})}return}const f=Zd(n,"data-sticker-emoji");if(f&&f.parentElement.querySelectorAll("[data-sticker-emoji]").length===1&&r.classList.contains("emoji-big")){this.chat.appImManager.onEmojiStickerClick({event:i,container:f,managers:this.managers,middleware:this.getMiddleware(),peerId:this.peerId}).then(M=>{M||this.openEmojiPackByTarget(f)});return}else if(f){this.openEmojiPackByTarget(f);return}const v=ne(n,"quote-like-collapsable");if(v){const M=v.classList.contains("is-truncated"),C=v.classList.contains("is-expanded");if((M||C)&&window.getSelection().isCollapsed){_e(i);const E=wt.isAvailable("animations");E&&(v.ignoreQuoteResize=1/0);const x=this.createScrollSaver(!1);x.save();let R;const B=E?Promise.race([ns(1e3).then(()=>{v.removeEventListener("transitionend",R)}),new Promise(N=>{R=G=>{G.target===v&&(N(),delete v.ignoreQuoteResize)},v.addEventListener("transitionend",R,{once:!0})})]):Promise.resolve();this.animateSomethingWithScroll(B,x),v.classList.toggle("is-expanded"),v.classList.toggle("is-truncated",C);return}}if(ne(n,"replies")){if(this.peerId===Lo){const M=this.chat.getMessage(o),C=it(M.reply_to.reply_to_peer_id),L=M.reply_to.reply_to_top_id,E=M.fwd_from.saved_from_msg_id;this.chat.appImManager.openThread({peerId:C,lastMsgId:E,threadId:L})}else{const M=this.chat.getMessage(o),C=await this.managers.appMessagesManager.getMessageWithReplies(M),L=C.replies;L&&this.managers.appMessagesManager.getDiscussionMessage(this.peerId,C.mid).then(E=>{this.chat.appImManager.setInnerPeer({...c,peerId:L.channel_id.toPeerId(!0),type:we.Discussion,threadId:E.mid})})}return}const w=ne(n,"is-via");if(w){const M=w.querySelector(".peer-title");if(n===M||Mi(n,M)){if(this.chat.input.canSendPlain()){const C=M.innerText+" ";this.managers.appDraftsManager.setDraft(this.peerId,this.chat.threadId,C)}_e(i);return}}const b=ne(n,"peer-title")||Wh(n)||ne(n,"selector-user")||Zd(n,"data-saved-from")||Zd(n,"data-follow");if(b&&b!==r){n=b||n;const M=n.dataset.peerId||n.getAttribute("peer")||n.dataset.key||n.dataset.follow,C=n.dataset.savedFrom;if(typeof M=="string"||C)if(_e(i),C){const{peerId:L,mid:E}=ti(C);if(n.classList.contains("is-receipt-link")){const x=await this.managers.appMessagesManager.getMessageByPeer(L.toPeerId(),+E);if(x){const R=await this.managers.appPaymentsManager.getInputInvoiceByPeerId(x.peerId,x.mid);Ln.create({message:x,inputInvoice:R,isReceipt:!0})}}else this.chat.appImManager.setInnerPeer({...c,peerId:L.toPeerId(),lastMsgId:+E})}else{const L=M.toPeerId();L!==Wt?(this.chat.appImManager.setInnerPeer({...c,peerId:L}),this.chat.appImManager.clickIfSponsoredMessage(r.message)):Wi(Ne.format("HidAccount",!0))}return}if(r.classList.contains("sticker")&&n.parentElement.classList.contains("attachment")){const C=this.chat.getMessage(o).media?.document;C?.stickerSetInput&&ue.createPopup(ga,C.stickerSetInput,void 0,this.chat.input).show();return}const S=ne(n,"media-video-mini");if(this.checkTargetForMediaViewer(n,i)){PI(i);return}const _=ne(n,"webpage");if(_){if(ne(n,"webpage-name-tip"))return;if(ne(n,"webpage-preview-resizer")){i.preventDefault();return}const M=_.dataset.callback;M&&window[M](Mn(n,"A"),i);const C=_.callback;C?.();return}if(["IMG","DIV","SPAN"].indexOf(n.tagName)===-1&&(n=Mn(n,"DIV")),["DIV","SPAN"].indexOf(n.tagName)!==-1){if(n.classList.contains("goto-original")){const C=r.dataset.savedFrom,{peerId:L,mid:E}=ti(C);this.chat.appImManager.setInnerPeer({...c,peerId:L.toPeerId(),lastMsgId:+E});return}else if(n.classList.contains("forward")){const C=this.chat.getMessage(o);ue.createPopup(kr,{[this.peerId]:await this.managers.appMessagesManager.getMidsByMessage(C)});return}let M=!1;try{M=!!ne(i.target,"reply")}catch{}if(M&&r.classList.contains("is-reply")){const C=this.chat.getMessage(o),L=C.reply_to;if(L._==="messageReplyStoryHeader"){const R=r.querySelector(".reply-media"),B=it(L.peer);Fo({target:()=>R,peerId:B,id:L.story_id});return}let E=L.reply_to_msg_id;if(!E){$e({langPackKey:L.pFlags.quote?"QuotePrivate":"ReplyPrivate"});return}let x=L.reply_to_peer_id?it(L.reply_to_peer_id):C.peerId;if(this.chat.type===we.Discussion&&!this.chat.isForum){const R=await this.managers.appMessagesManager.getHistory({peerId:x,threadId:this.chat.threadId,limit:1,offsetId:1,addOffset:-1}),B=this.chat.getMessageByPeer(x,R.history[0]);B.fwd_from?.channel_post===E&&(E=B.mid,x=B.peerId)}this.followStack.push(o),this.chat.appImManager.setInnerPeer({...c,peerId:x,lastMsgId:E,type:this.chat.type,threadId:this.chat.threadId})}}},this.onScroll=(i,n,r)=>{if(this.isHeavyAnimationInProgress){if(this.sliceViewportDebounced?.clearTimeout(),this.scrolledDown&&!i)return}else this.chat.topbar.pinnedMessage?.setCorrectIndexThrottled(this.scrollable.lastScrollDirection),this.sliceViewportDebounced?.(),this.setStickyDateManually();if(n&&n.distanceToEnd<I0&&this.scrolledDown)return;const o=r?0:n?.distanceToEnd??this.scrollable.getDistanceToEnd();(this.scrollable.lastScrollDirection!==0&&o>0||n||r)&&(this.isScrollingTimeout?clearTimeout(this.isScrollingTimeout):this.chatInner.classList.contains("is-scrolling")||this.chatInner.classList.add("is-scrolling"),this.isScrollingTimeout=window.setTimeout(()=>{this.chatInner.classList.remove("is-scrolling"),this.isScrollingTimeout=0},1350+(n?.duration??0))),o<I0&&(r||this.scrollable.loadedAll.bottom||this.chat.setPeerPromise||!this.peerId)?(this.container.classList.add("scrolled-down"),this.scrolledDown=!0):this.container.classList.contains("scrolled-down")&&(this.container.classList.remove("scrolled-down"),this.scrolledDown=!1),this.checkIntersectingVideos()},this.onVideoLoad=async()=>{},this.processBatch=async(...i)=>{let[n,r,o]=i;const l=B=>B.filter(N=>N&&this.getBubble(ps(N.message))===N.bubble&&!this.changedMids.has(N.message.mid));n=l(n),o("messages rendered");const{firstGroup:c,lastGroup:d}=this.bubbleGroups,u=c?.firstMid,h=d?.lastMid,{groups:p,avatarPromises:m}=this.groupBubbles(n.filter(B=>B.updatePosition)),{firstGroup:g,lastGroup:f}=this.bubbleGroups,v=g?.firstMid;let y=f?.lastMid;const w=n.find(({message:B})=>B.pFlags.sponsored);w&&(y=w.message.mid);const b=u!==v,S=!!d&&h!==y,M=n?.[0]?.reverse,L=n.every(({reverse:B})=>B===M)?M:b&&!S;o("changed ends",b,S);const E=n.reduce((B,N)=>{const G=performance.now(),O=N.promises.slice(),$=O.map(async H=>(await H,performance.now()-G));return Promise.all($).then(H=>{o.groupCollapsed("media message time",performance.now()-G,N,H),H.forEach((D,U)=>{o("media message time",D,U,O[U])}),o.groupEnd()}),B.push(...N.promises),B},[]);E.push(...m),E.push(vi()),o("media promises to call",E,n,this.isHeavyAnimationInProgress),await r(Promise.all([...E,this.setUnreadDelimiter()]).catch(as)),await r(Sv()),o("media promises end"),n=l(n);const{restoreScroll:x,scrollSaver:R}=this.prepareToSaveScroll(L,u===v,h===y);n.some(B=>B.canAnimateLadder)&&this.messagesQueueOnRenderAdditional?.(),this.ejectBubbles();for(const[B,N]of this.bubblesToReplace){if(R&&R.replaceSaved(N,B),!n.find(O=>O.bubble===B))continue;const G=this.bubbleGroups.getItemByBubble(B);G?(G.mounted=!1,p.includes(G.group)||p.push(G.group)):this.log.error("NO ITEM BY BUBBLE",B),this.bubblesToReplace.delete(B)}this.chat.selection.isSelecting&&n.forEach(({bubble:B})=>{this.chat.selection.toggleElementCheckbox(B,!0)}),n.forEach(({message:B,bubble:N,updatePosition:G})=>{if(B.pFlags.local&&G){this.chatInner[B.pFlags.sponsored?"append":"prepend"](N);return}}),this.bubbleGroups.mountUnmountGroups(p),this.updatePlaceholderPosition?.(),x?.(),r(ns(this.chat.setPeerPromise?1e3:0)).then(()=>r(vi())).then(()=>{this.lazyLoadQueue.setAllSeen()}).catch(as)},this.modifyBubble=async i=>{const n=!this.batchingModifying;(this.batchingModifying??(this.batchingModifying=[])).push(i),n&&ns(0).then(async()=>{await vi();const r=this.batchingModifying,o=this.createScrollSaver(!1);o.save(),r.forEach(l=>l()),o.restore(),this.batchingModifying=void 0})},this.onDatePick=i=>{const n=this.peerId;this.managers.appMessagesManager.requestHistory({...this.chat.requestHistoryOptionsPart,offsetId:0,limit:2,addOffset:-1,offsetDate:i}).then(r=>{if(r?.messages?.length){if(this.peerId!==n)return}else{this.log.error("no history!");return}this.chat.setMessageId({lastMsgId:r.messages[0].mid})})},this.log=this.chat.log,this.listenerSetter=new $t,this.constructBubbles(),this.batchProcessor=new X_({log:this.log,process:this.processBatch,possibleError:qf}),this.preloader=new Kn({cancelable:!1}),this.lazyLoadQueue=new sr(void 0,!0),this.lazyLoadQueue.queueId=++C0,this.changedMids=new Map,this.listenerSetter.add(I)("history_update",async({storageKey:i,sequential:n,message:r})=>{if(this.chat.messagesStorageKey!==i||this.chat.type===we.Scheduled)return;const{mid:o}=r,l=ps(r),c=this.getBubble(l);if(!c||(this.renderNewPromises.size&&await Promise.all(Array.from(this.renderNewPromises)),this.messagesQueuePromise&&await this.messagesQueuePromise,this.getBubble(l)!==c))return;const d=this.bubbleGroups.getItemByBubble(c);if(d){if(d.mid===o)return}else return;if(n){const h=d.group,p=this.bubbleGroups.createItem(c,r,d.reverse),m=this.bubbleGroups.itemsArr.slice();Vs(m,d);const g=this.bubbleGroups.findGroupSiblingByItem(p,m);if(h===g?.group||h===this.bubbleGroups.lastGroup&&h.items.length===1&&p.dateTimestamp===d.dateTimestamp||this.peerId===I.myId&&n&&p.dateTimestamp===d.dateTimestamp){this.bubbleGroups.changeBubbleMessage(c,r);return}}this.bubbleGroups.removeAndUnmountBubble(c);const{groups:u}=this.groupBubbles([{bubble:c,message:r,reverse:d.reverse}]);this.bubbleGroups.mountUnmountGroups(u),this.scrollingToBubble&&this.scrollToEnd()}),this.listenerSetter.add(I)("dialog_flush",({peerId:i})=>{this.peerId===i&&this.deleteMessagesByIds(this.getRenderedHistory("asc"))}),this.listenerSetter.add(I)("message_sent",i=>{const{storageKey:n,tempId:r,tempMessage:o,mid:l,message:c}=i;if(this.chat.messagesStorageKey!==n)return;this.changedMids.set(r,l),this.needUpdate.forEach(v=>{v.peerId===o.peerId&&v.mid===r&&(v.mid=l)});const d=ps(o),u=ps(c);let h=this.getBubble(d);if(h){const v=h;delete this.bubbles[d],this.bubbles[u]=v,v.dataset.mid=""+l,$s(()=>{const y=+v.dataset.mid;if(this.getBubble(u)!==v||!v.classList.contains("is-outgoing"))return;v.classList.remove("is-outgoing");let w;v.classList.contains("is-out")&&(w=this.peerId===I.myId&&this.chat.type!==we.Scheduled||!this.unreadOut.has(y)?"read":"sent"),this.setBubbleSendingStatus(v,w)})}if(this.unreadOut.has(r)&&(this.unreadOut.delete(r),this.unreadOut.add(l)),this.chat.type===we.Scheduled){const v=Date.now()/1e3|0,y=o.date-10;v>=y&&this.deleteMessagesByIds([u])}let p,m;const g=c.grouped_id;if(g){p=Ae.getMessagesByGroupedId(g);const v=p.map(({mid:w})=>w),y=v[v.length-1];if(y!==l)return;h=this.getBubble(c.peerId,Qf(v)),m=Array.from(h.querySelectorAll(".grouped-item")).map(w=>+w.dataset.mid),h.maxBubbleMid=y}else p=[c],m=[r],h&&(h.maxBubbleMid=l);if(!h)return;const f=Array.from(h.querySelectorAll("reactions-element"));if(f.length){const v=Ae.getGroupsFirstMessage(c);f.forEach(y=>{y.changeContext(v)})}p.forEach((v,y)=>{if(!v)return;const w=m[y],b=v.mid,S=h.querySelector(`.document-container[data-mid="${b}"]`)||h;if(v._!=="message")return;if(v.replies){const E=h.querySelector("replies-element");E&&(E.message=v,E.init())}const _=v.media??{},M=_.document,C=_.poll,L=_.webpage;if(M){const E=S.querySelector(`.document-container[data-mid="${w}"]`),x=E?.querySelector(".document");x&&!o.media?.document?.thumbs?.length&&M.thumbs?.length&&vi().then(async()=>{const B=x.querySelector(".time"),N=await rd({message:v,fontSize:I.settings.messagesTextSize});x.replaceWith(N),B&&(N.querySelector(".document")||N).append(B)}),E&&(E.dataset.mid=""+b);const R=S.querySelector(`audio-element[data-mid="${w}"], .document[data-doc-id="${w}"], .media-round[data-mid="${w}"]`);R&&(R instanceof Pb||R.classList.contains("media-round")?(R.dataset.mid=""+v.mid,delete R.dataset.isOutgoing,R.message=v,R.onLoad(!0)):(R.dataset.docId=""+M.id,R.doc=M))}else if(C){const E=S.querySelector("poll-element");E&&(E.message=v,E.setAttribute("poll-id",""+C.id),E.setAttribute("message-id",""+b))}else L&&!S.querySelector(".web")&&vi().then(()=>{this.safeRenderMessage({message:v,reverse:!0,bubble:S}),this.scrollToBubbleIfLast(S)});if(g){const E=S.querySelector(`.grouped-item[data-mid="${w}"]`)||(S.classList.contains("document-container")?S:void 0);E&&(E.dataset.mid=""+b)}})}),this.listenerSetter.add(I)("message_edit",async({storageKey:i,message:n})=>{if(i!==this.chat.messagesStorageKey)return;const r=ps(n),o=this.getBubble(r);if(!o||(await vi(),this.getBubble(r)!==o))return;const l=this.updateLocationOnEdit.get(o);if(l){l(n);return}o.querySelector(".geo-container")||this.safeRenderMessage({message:n,reverse:!0,bubble:o})}),this.listenerSetter.add(I)("message_error",async({storageKey:i,tempId:n,peerId:r})=>{if(i!==this.chat.messagesStorageKey)return;const o=ps(r,n),l=this.getBubble(o);l&&(await vi(),this.getBubble(o)===l&&(l.classList.remove("is-outgoing"),this.setBubbleSendingStatus(l,"error")))}),this.listenerSetter.add(I)("replies_short_update",i=>{if(this.peerId!==i.peerId)return;const n=this.getBubble(ps(i));n&&this.setBubbleRepliesCount(n,i.replies.replies)}),this.listenerSetter.add(I)("message_transcribed",({peerId:i,mid:n,text:r,pending:o})=>{if(i!==this.peerId)return;const l=this.getBubble(ps(i,n));if(!l)return;const c=l.querySelector("audio-element");if(!c)return;const d=l.querySelector(".document-wrapper, .quote-text.has-document"),u=c.querySelector(".audio-to-text-button span"),h=c.querySelector(".loader");if(d&&u){let p=d.querySelector(".audio-transcribed-text");if(p)o||p.querySelector(".audio-transcribing-dots")?.remove();else if(p=document.createElement("div"),p.classList.add("audio-transcribed-text"),p.append(document.createTextNode("")),d.classList.contains("document-wrapper")?c.after(p):d.append(p),o){const m=document.createElement("span");m.classList.add("audio-transcribing-dots"),p.append(m)}!r&&!o?(p.replaceChildren(P("Chat.Voice.Transribe.Error")),p.classList.add("is-error")):r&&(p.firstChild.textContent=r),u.classList.remove(zr("transcribe")),u.classList.add(zr("up")),!o&&h&&(h.classList.remove("active"),setTimeout(()=>{h.remove()},300)),c.transcriptionState=2}}),this.listenerSetter.add(I)("grouped_edit",({peerId:i,messages:n,deletedMids:r})=>{if(i!==this.peerId)return;const o=n.map(({mid:m})=>m),l=o.concat(Array.from(r)),c=Qf(l),d=ps(i,c),u=this.getBubble(d);if(!u)return;delete this.bubbles[d];const h=Qf(o),p=n.find(m=>m.mid===h);this.safeRenderMessage({message:p,reverse:!0,bubble:u})}),this.listenerSetter.add(I)("messages_reactions",async i=>{if(this.chat.type===we.Scheduled)return;let n;const r=i.map(async({message:l,changedResults:c})=>{if(this.peerId!==l.peerId&&!Yf)return;const d=await this.getMountedBubble(l);if(d)return{bubble:ne(d.bubble,"bubble"),message:l,changedResults:c}}),o=Mt();(await Promise.all(r)).filter(Boolean).forEach(({bubble:l,message:c,changedResults:d})=>{n||(n=this.createScrollSaver(!1),n.save()),l.dataset.ignoreReactions&&(delete l.dataset.ignoreReactions,d=[]);const u=Hf(c);u&&(d=[]);const h=c.peerId+"_"+c.mid,p=wc.get(h);if(p){for(const m of p)if(m.update(c,d,o),!c.reactions||!c.reactions.results.length){const g=m.parentElement;m.remove(),m.querySelector(".time")&&(tr(l.timeAppenders,({element:v})=>v===m),l.timeAppenders[0].callback()),g.classList.contains("document-message")&&!g.childNodes.length&&g.remove()}}else{if(!c.reactions||!c.reactions.results.length)return;this.appendReactionsElementToBubble(l,c,c,d)}u&&this.setUnreadObserver("content",l,c.mid)}),n?.restore(),o.resolve()}),this.listenerSetter.add(I)("messages_downloaded",this.updateMessageReply),this.listenerSetter.add(I)("stories_downloaded",this.updateMessageReply),_d({listenTo:this.scrollable.container,listenerSetter:this.listenerSetter,findTarget:i=>{const n=i.target;return n.closest(".attachment.media-sticker-wrapper, .attachment.media-gif-wrapper")||ne(n,"attachment")&&n.closest(".custom-emoji")}}),J(this.scrollable.container,this.onBubblesClick,{listenerSetter:this.listenerSetter}),this.listenerSetter.add(this.scrollable.container)("mousedown",i=>{if(i.button!==0)return;const n=ne(i.target,"code-header")&&ne(i.target,"code"),r=n?.querySelector(".code-code")||ne(i.target,"monospace-text");if(r){const o=!!ne(i.target,"code-header-toggle-wrap");_e(i),o||$3(r);const c=J(window,d=>{if(_e(d),o){const u=n.classList.toggle("is-scrollable");r.classList.toggle("no-scrollbar",u);return}$e({langPackKey:"CodeCopied",onClose:()=>{c()}})},{listenerSetter:this.listenerSetter,once:!0,capture:!0,ignoreMove:!0});return}}),this.stickyIntersector=new r1(this.scrollable.container,(i,n)=>{for(const r in this.dateMessages){const o=this.dateMessages[r];if(o.container===n){const l=o.div;l.classList.toggle("is-sticky",i),i&&(this.previousStickyDate=l);break}}this.previousStickyDate}),T6||(this.sliceViewportDebounced=$i(this.sliceViewport.bind(this),3e3,!1,!0));let s;yg(()=>{this.isHeavyAnimationInProgress=!0,this.lazyLoadQueue.lock(),s=this.getMiddleware()},()=>{this.isHeavyAnimationInProgress=!1,s?.()&&this.lazyLoadQueue.unlockAndRefresh(),s=null},this.listenerSetter)}constructBubbles(){const e=this.container=document.createElement("div");e.classList.add("bubbles","scrolled-down"),(this.chatInner=document.createElement("div")).classList.add("bubbles-inner");const s=document.createElement("div");s.classList.add("bubbles-remover-container");const i=this.remover=document.createElement("div");i.classList.add("bubbles-remover","bubbles-inner"),s.append(i),this.setScroll(),e.append(s,this.scrollable.container)}attachContainerListeners(){const e=this.container;if(this.chat.contextMenu.attachTo(e),this.chat.selection.attachListeners(e,new $t),_n&&this.listenerSetter.add(e)("dblclick",t=>{const s=ne(t.target,"grouped-item")||ne(t.target,"bubble");if(s){const i=$a(s);this.log("debug message:",this.chat.getMessage(i)),this.highlightBubble(s)}}),!Gi&&!M6)this.listenerSetter.add(e)("dblclick",async t=>{if(this.chat.type===we.Pinned||this.chat.selection.isSelecting||!this.chat.input.canSendPlain()||ne(t.target,"attachment")||ne(t.target,"audio")||ne(t.target,"document")||ne(t.target,"contact")||ne(t.target,"time")||ne(t.target,"code-header-button")||ne(t.target,"reaction"))return;const s=t.target;let i=s.classList.contains("bubble")?s:s.classList.contains("document-selection")?s.parentElement:null;const n=SI();if(!i&&(!n.trim()||/^\s/.test(n))&&(i=ne(s,"bubble")),i&&!i.classList.contains("bubble-first")){const r=this.chat.getMessage($a(i));if(r.pFlags.is_outgoing||r.peerId!==this.peerId)return;this.chat.input.initMessageReply({replyToMsgId:r.mid})}});else if(pt){const t="is-gesturing-reply";let n=!1,r,o,l;this.replySwipeHandler=I1({element:e,verifyTouchTarget:async c=>{if(this.chat.type===we.Pinned||this.chat.selection.isSelecting||!await this.chat.canSend()||(r=ne(c.target,"bubble"),!r||r.classList.contains("service")||r.classList.contains("is-sending")))return!1;if(r){try{const d=r.parentElement.querySelector(".bubbles-group-avatar");d&&Ko(d,r)&&(l=d)}catch{}[r,l].filter(Boolean).forEach(d=>{Dt({element:d,className:t,forwards:!0,duration:250}),d.offsetLeft}),o?(o.classList.remove("is-visible"),o.style.opacity=""):o=Be("reply_filled","bubble-gesture-reply-icon"),r.append(o)}return!!r},onSwipe:c=>{n=c>=48,n&&!o.classList.contains("is-visible")&&o.classList.add("is-visible"),o.style.opacity=""+Math.min(1,c/48);const u=`translateX(${-Math.max(0,Math.min(64,c))}px)`;r.style.transform=u,l&&(l.style.transform=u),W_()},onReset:()=>{const c=r,d=l;r=l=void 0;const u=()=>{o.parentElement===c&&(o.classList.remove("is-visible"),o.remove())};[c,d].filter(Boolean).forEach((h,p)=>{Dt({element:h,className:t,forwards:!1,duration:250,onTransitionEnd:p===0?u:void 0})}),$s(()=>{if(c.style.transform="",d&&(d.style.transform=""),n){const{mid:h}=c.dataset;this.chat.input.initMessageReply({replyToMsgId:+h}),n=!1}})},listenerOptions:{capture:!0}})}}constructPeerHelpers(){this.listenerSetter.add(I)("history_append",async({storageKey:s,message:i})=>{if(!(s!==this.chat.messagesStorageKey||this.chat.type===we.Scheduled)&&(wt.isAvailable("chat_background")&&(this.updateGradient=!0),!(this.chat.threadId&&yr(i,this.chat.isForum)!==this.chat.threadId))){if(!this.chat.threadId&&this.chat.appImManager.chats.some(n=>this.chat!==n&&n.peerId===this.peerId&&n.threadId)){this.renderNewMessage(i);return}this.scrollable.loadedAll.bottom?this.renderNewMessage(i,!0):this.chat.setMessageId()}}),this.listenerSetter.add(I)("history_multiappend",s=>{this.peerId!==s.peerId||this.chat.type===we.Scheduled||this.renderNewMessage(s)}),this.listenerSetter.add(I)("history_delete",({peerId:s,msgs:i})=>{if(s!==this.peerId&&!Yf||this.chat.type===we.Scheduled)return;const n=[...i.keys()],r=n.map(o=>ps(s,o));this.deleteMessagesByIds(r),this.updateMessageReply({peerId:s,mids:n})}),this.listenerSetter.add(I)("history_delete_key",({historyKey:s,mid:i})=>{this.chat.historyStorageKey===s&&this.deleteMessagesByIds([ps(this.peerId,i)])}),this.listenerSetter.add(I)("dialog_unread",({peerId:s})=>{s===this.peerId&&(this.chat.input.setUnreadCount(),vi().then(()=>{this.updateUnreadByDialog()}))}),this.listenerSetter.add(I)("dialogs_multiupdate",s=>{!s.has(this.peerId)||this.chat.type===we.Scheduled||this.chat.type===we.Saved||this.chat.input.setUnreadCount()}),this.listenerSetter.add(I)("dialog_notify_settings",s=>{this.peerId!==s.peerId||this.chat.type===we.Scheduled||this.chat.type===we.Saved||this.chat.input.setUnreadCount()});const e=async()=>{(await Promise.all([this.finishPeerChange(),this.chat.input.finishPeerChange({peerId:this.peerId,middleware:this.getMiddleware()})])).forEach(i=>i())};this.listenerSetter.add(I)("user_full_update",async s=>{if(s.toPeerId(!1)!==this.peerId)return;const n=this.getMiddleware(),{isUserBlocked:r,isPremiumRequired:o,starsAmount:l}=await bb({isUserBlocked:this.managers.appProfileManager.isCachedUserBlocked(s),isPremiumRequired:this.chat.isPremiumRequiredToContact(),starsAmount:this.managers.appUsersManager.getStarsAmount(s)});if(!n())return;const c=this.chat.isUserBlocked,d=this.chat.isPremiumRequired,u=this.chat.starsAmount;let h=!1;(c===void 0?r:c!==r)&&(this.chat.isUserBlocked=r,h=!0);const p=d===void 0?o:d!==o,m=u===void 0?l:u!==l;this.chat.isPremiumRequired=o,this.chat.starsAmount=l,(p||m)&&(h=!0,this.cleanupPlaceholders(),this.checkIfEmptyPlaceholderNeeded()),m&&au()?.setStarsAmount(l),h&&e()}),this.listenerSetter.add(I)("chat_update",async s=>{const{peerId:i}=this;if(i!==s.toPeerId(!0))return;const n=this.getMiddleware(),r=Ae.getChat(s),o=this.chatInner.classList.contains("has-rights"),l=this.chat.input.canSendPlain(),[c,d,u]=await Promise.all([this.chat.canSend("send_messages"),this.chat.canSend("send_plain"),this.chat.canSend("embed_links")]);n()&&((o!==c||l!==d)&&await e(),n()&&((u&&!this.chat.input.willSendWebPage||!u&&this.chat.input.willSendWebPage)&&(this.chat.input.lastUrl="",this.chat.input.onMessageInput()),!!r.pFlags.forum!==this.chat.isForum&&this.chat.type===we.Chat&&(this.chat.peerId=0,this.chat.appImManager.setPeer({peerId:i}))))}),this.listenerSetter.add(I)("history_reload",async s=>{if(s!==this.peerId)return;const i=this.chat.isLikeGroup;this.chat.isLikeGroup=await this.chat._isLikeGroup(s);const n=i!==this.chat.isLikeGroup&&await this.finishPeerChange(),r=this.getRenderedHistory("desc",!0),o=r.map(c=>ti(c).mid),l=this.getMiddleware();this.managers.appMessagesManager.reloadMessages(s,o).then(c=>{if(!l())return;const d=[];c.forEach((u,h)=>{const p=r[h];if(u){const m=this.getBubble(s,u.mid);if(!m)return;this.safeRenderMessage({message:u,reverse:!0,bubble:m})}else d.push(p)}),n?.(),n&&this.bubbleGroups.groups.forEach(u=>{this.chat.isLikeGroup?this.chat.isAvatarNeeded(u.firstItem.message)&&u.createAvatar(u.firstItem.message):u.destroyAvatar()}),this.deleteMessagesByIds(d),this.setLoaded("top",!1),this.setLoaded("bottom",!1),this.scrollable.checkForTriggers()})}),this.listenerSetter.add(I)("settings_updated",({key:s})=>{s==="settings.emoji.big"&&this.getRenderedHistory("desc").map(r=>{const o=this.getBubble(r);if(o.classList.contains("can-have-big-emoji")){const{peerId:l,mid:c}=ti(r);return{bubble:o,message:this.chat.getMessageByPeer(l,c),fullMid:r}}}).filter(Boolean).forEach(({bubble:r,message:o,fullMid:l})=>{this.getBubble(l)===r&&this.safeRenderMessage({message:o,reverse:!0,bubble:r})})}),this.listenerSetter.add(I)("messages_views",s=>{this.chat.type!==we.Scheduled&&$s(()=>{let i;for(const{peerId:n,views:r,mid:o}of s){if(this.peerId!==n&&!Yf)continue;const l=this.getBubble(n,o);if(!l)continue;const c=Array.from(l.querySelectorAll(".post-views"));if(!c.length)continue;const d=un(r,1);let u=!1;c.forEach(h=>{(u||h.textContent!==d)&&(i||(i=this.createScrollSaver(!0),i.save()),u=!0,h.textContent=d)})}i?.restore()})}),this.observer=new D3({root:this.scrollable.container}),this.sendViewCountersDebounced=$i(()=>{const s=[...this.viewsMids];this.viewsMids.clear();const i=new Map;s.forEach(n=>{const{peerId:r,mid:o}=ti(n);let l=i.get(r);l||i.set(r,l=[]),l.push(o)}),i.forEach((n,r)=>{this.managers.appMessagesManager.incrementMessageViews(r,n)})},1e3,!1,!0),this.listenerSetter.add(I)("peer_pinned_messages",({peerId:s,mids:i,pinned:n})=>{this.chat.type!==we.Pinned||s!==this.peerId||i&&(n||this.deleteMessagesByIds(i.map(r=>ps(s,r))))});const t=async()=>{this.chat.topbar.setTitle((await this.managers.appMessagesManager.getScheduledMessagesStorage(this.peerId)).size)};this.listenerSetter.add(I)("scheduled_new",s=>{this.chat.type!==we.Scheduled||s.peerId!==this.peerId||(this.renderNewMessage(s),t())}),this.listenerSetter.add(I)("scheduled_delete",({peerId:s,mids:i})=>{this.chat.type!==we.Scheduled||s!==this.peerId||(this.deleteMessagesByIds(i.map(n=>ps(s,n))),t())})}get peerId(){return this.chat.peerId}get messagesQueuePromise(){return this.batchProcessor.queuePromise}createScrollSaver(e=!0){return new Hg(this.scrollable,".bubble:not(.is-date)",e)}createResizeObserver(){if(!("ResizeObserver"in window)||this.resizeObserver)return;const e=this.scrollable.container;let t=0,s=!1,i=!1,n=0,r=0;const o=()=>{const u=e.offsetHeight,h=this.scrollable.isScrolledToEnd;u!==t&&(!i||!h)&&(n+=t-u),n&&this.scrollable.setScrollPositionSilently(this.scrollable.scrollPosition+Math.round(n)),t=u,r=0,n=0,s=!1,i=!1},l=u=>{r&&window.cancelAnimationFrame(r),r=window.requestAnimationFrame(()=>{r=window.requestAnimationFrame(o)})},c=u=>{if(i){l();return}const p=u[0].contentRect.height;if(!t){t=p;return}const m=t-p;let g=m+n;const f=g%1;if(g-=f,!s&&(s=!0,m<0&&this.scrollable.isScrolledToEnd)){n=-m,i=!0,l();return}if(g){const v=this.scrollable.scrollPosition+g;this.scrollable.setScrollPositionSilently(v)}l(),n=f,t=p};(this.resizeObserver=new ResizeObserver(c)).observe(e)}destroyResizeObserver(){const e=this.resizeObserver;e&&(e.disconnect(),this.resizeObserver=void 0)}setReactionsHoverListeners(){this.listenerSetter.add(Li)("toggle",this.unhoverPrevious),this.listenerSetter.add(vn)("change",this.unhoverPrevious),this.listenerSetter.add(this.chat.selection)("toggle",this.unhoverPrevious),this.listenerSetter.add(this.container)("mousemove",this.onBubblesMouseMove)}setHoverVisible(e,t){e.parentElement&&e.parentElement.classList.toggle("hover-reaction-visible",t),Dt({element:e,className:"is-visible",forwards:t,duration:200,onTransitionEnd:t?void 0:()=>{e.remove(),e.middlewareHelper.destroy()},useRafs:t?2:0})}setStickyDateManually(){}getRenderedLength(){return this.getRenderedHistory().length}onUnreadedInViewport(e,t,s){let{unreadedSeen:i,unreadedObserverCallback:n,unreaded:r}=this;e==="content"&&(i=this.unreadedContentSeen,n=this.unreadedContentObserverCallback,r=this.unreadedContent),i.add(s),this.observer.unobserve(t,n),r.delete(t),this.readUnreaded(e)}readUnreaded(e){const t=e==="history"?"readPromise":"readContentPromise";if(this[t])return;const s=e==="history"?"unreadedSeen":"unreadedContentSeen",i=this.getMiddleware();this[t]=qr.getFocusPromise().then(async()=>{if(!i())return;const{peerId:n,threadId:r}=this.chat;let o;if(e==="history"){let c=Math.max(...Array.from(this[s]));if(this.scrollable.loadedAll.bottom){const d=this.getRenderedHistory("desc",!0),u=d?ti(d[0]).mid:-1;if(c>=u&&(c=Math.max(await this.chat.getHistoryMaxId()||0,c),!i()))return}this.unreaded.forEach((d,u)=>{d<=c&&this.onUnreadedInViewport("history",u,d)}),_n&&this.log("will readHistory by maxId:",c),o=()=>this.managers.appMessagesManager.readHistory(n,c,r)}else{const c=[];for(const d of this.unreadedContentSeen){const u=this.chat.getMessage(d);(WS(u)||Hf(u))&&c.push(d)}_n&&this.log("will readMessages",c),o=()=>this.managers.appMessagesManager.readMessages(n,c)}return this[s].clear(),o().catch(c=>{this.log.error("read err:",e,c),o()}).finally(()=>{i()&&(this[t]=void 0,this[s].size&&this.readUnreaded(e))})})}openEmojiPackByTarget(e){this.managers.appEmojiManager.getCustomEmojiDocument(e.dataset.docId).then(t=>{const s=t.attributes.find(n=>n._==="documentAttributeCustomEmoji");if(!s)return;const i=s.stickerset;ue.createPopup(ga,i,!0,this.chat.input).show()})}checkTargetForMediaViewer(e,t,s){const i=ne(e,"bubble"),n=ne(e,"document-with-thumb");if(e.tagName==="IMG"&&!e.classList.contains("emoji")&&!e.classList.contains("document-thumb")||e.classList.contains("album-item")||e.classList.contains("album-item-media")||e.tagName==="VIDEO"&&!i.classList.contains("round")||n&&!n.querySelector(".preloader-container")||e.classList.contains("canvas-thumbnail")){const r=ne(e,"album-item")||ne(e,"document-container"),o=(r||i).querySelector(".preloader-container");if(o&&t){Xs(o),_e(t);return}_e(t);const l=r?+(r.dataset.index??-1):-1,c=$a(l!==-1?i:r||i);let d=this.chat.getMessage(c),u=!1;if(!d)if(ti(c).mid<0)d=i.message,u=!0;else{this.log.warn("no message by messageId:",c);return}if(i.classList.contains("story")){const y=Zd(e,"data-story-peer-id"),w=y.dataset.storyPeerId.toPeerId(),b=+y.dataset.storyId;Fo({target:()=>y.querySelector(".media-container-aspecter")||e,peerId:w,id:b});return}const h="single-media",p=i.classList.contains(h),m=n?y=>zl.isMediaCompatibleForDocumentViewer(y):y=>y._==="photo"||["video","gif"].includes(y.type),g=[],f=p?[c]:this.getRenderedHistory("asc").map(y=>{const w=this.getBubble(y);if(!p&&w.classList.contains(h))return;const b=this.chat.getMessage(y),S=Vi(b);return S&&m(S)&&y}).filter(Boolean);f.forEach(y=>{let w=this.skippedMids.has(y)?void 0:this.getBubble(y);if(w||(w=this.chatInner.querySelector(`.grouped-item:not(.album-item)[data-mid="${y}"]`),w&&(w=ne(w,"bubble"))),!w)return;let b;if(n)b=".document-container";else{const M=w.classList.contains("with-media-tail");b=".album-item, .webpage-preview, ",M?b+=".bubble__media-container":b+=".attachment"}const S=Array.from(w.querySelectorAll(b)),_=new Set;if(n)S.forEach(M=>{g.push({element:M.querySelector(".document-ico"),mid:+M.dataset.mid,peerId:this.peerId,fullMid:$a(M)})});else{const M=!!w.querySelector(".media-container-aspecter");S.forEach(C=>{if(C=C.querySelector("video, img")||C,M&&!ne(C,"media-container-aspecter"))return;const L=ne(C,"album-item"),E=L||C.parentElement;if(_.has(E))return;_.add(E);const x=l!==-1?y:$a(L||C)||y;g.push({element:C,mid:ti(x).mid,peerId:this.peerId,fullMid:x,index:L&&+(L.dataset.index??-1)})})}}),hn(g,(y,w,b)=>{const S=b.findIndex(_=>_.element===y.element);S!==w&&b.splice(S,1)});const v=l===-1?g.findIndex(y=>y.fullMid===c):g.findIndex(y=>y.index===l);if(_n&&this.log("open mediaViewer single with ids:",f,v,g),!g[v]){this.log("no target for media viewer!",e);return}return new zl(void 0,u).setSearchContext({threadId:this.chat.threadId,peerId:this.peerId,inputFilter:{_:n?"inputMessagesFilterDocument":"inputMessagesFilterPhotoVideo"},useSearch:this.chat.type!==we.Scheduled&&!p,isScheduled:this.chat.type===we.Scheduled}).openMedia({message:d,index:g[v].index,target:g[v].element,fromRight:0,reverse:!0,prevTargets:g.slice(0,v),nextTargets:g.slice(v+1),mediaTimestamp:s}),!0}}async onGoDownClick(){if(!this.followStack.length){this.chat.setMessageId();return}const e=this.getMiddleware(),t=this.followStack.slice(),s=await Promise.all(t.map(r=>this.chat.getMessage(r)));if(!e())return;t.forEach((r,o)=>{const l=s[o],c=this.getBubble(r);let d=!0;if(c){const u=c.getBoundingClientRect();d=It.height/2>u.top}else l&&(d=!1);d&&this.followStack.splice(this.followStack.indexOf(r),1)}),this.followStack.sort((r,o)=>ti(o).mid-ti(r).mid);const i=this.followStack.pop(),{mid:n}=ti(i);this.chat.setMessageId({lastMsgId:n})}getBubbleByPoint(e){const t=this.getViewportSlice();return t.visible[e==="top"?0:t.visible.length-1]?.element}async getGroupedBubble(e,t){const s=await this.managers.appMessagesManager.getMidsByGroupedId(t);for(const i of s){const n=ps(e,i),r=this.getBubble(n);if(r&&!this.skippedMids.has(n))return{bubble:r,peerId:e,mid:i}}}getBubbleGroupedItems(e){return Array.from(e.querySelectorAll(".grouped-item"))}async getMountedBubble(e){let t,s,i;if(typeof e=="string"){const o=ti(e);s=o.peerId,i=o.mid,t=this.chat.getMessageByPeer(s,i)}else t=e,s=t.peerId,i=t.mid,e=ps(s,i);if(!t)return;const n=t.grouped_id;if(n){const o=await this.getGroupedBubble(s,n);if(o)return o.bubble=o.bubble.querySelector(`.document-container[data-mid="${i}"]`)||o.bubble,o}const r=this.getBubble(e);if(!(!r||this.skippedMids.has(e)))return{bubble:r,peerId:s,mid:i}}findNextMountedBubbleByMsgId(e,t){if(this.chat.type===we.Search){const r=this.getRenderedHistory("desc",!0),o=r.indexOf(e);if(o===-1)return;const l=r[o+(t?-1:1)];return this.getBubble(l)}const s=this.getRenderedHistory(t?"desc":"asc");let i;t?i=r=>ti(r).mid<ti(e).mid:i=r=>ti(e).mid<ti(r).mid;const n=s.find(r=>i(r)?!!this.getBubble(r)?.parentElement:!1);return this.getBubble(n)}getRenderedHistory(e="desc",t){let s=va(this.bubbleGroups.groups.map(i=>i.items.map(n=>ps(n.message))));return e==="asc"&&s.reverse(),t&&(s=s.filter(i=>{const{mid:n}=ti(i);return n>0&&OL(n,!1)===n})),s}loadMoreHistory(e,t=!1){if(!this.peerId||this.chat.setPeerPromise||this.isHeavyAnimationInProgress||e&&(this.getHistoryTopPromise||this.scrollable.loadedAll.top)||!e&&(this.getHistoryBottomPromise||this.scrollable.loadedAll.bottom))return;const s=this.getRenderedHistory("asc");s.length||s.push(Ci),e?(_n&&this.log("Will load more (up) history by id:",s[0],"maxId:",s[s.length-1],t),this.getHistory1(s[0],!0,void 0,void 0,t)):(_n&&this.log("Will load more (down) history by id:",s[s.length-1],t),this.getHistory1(s[s.length-1],!1,!0,void 0,t))}checkIntersectingVideos(){}setScroll(){this.scrollable&&this.destroyScrollable(),this.scrollable=new tn(null,"IM",300),this.setLoaded("top",!1,!1),this.setLoaded("bottom",!1,!1),this.scrollable.container.append(this.chatInner),this.scrollable.onAdditionalScroll=this.onScroll,this.scrollable.onScrolledTop=()=>this.loadMoreHistory(!0),this.scrollable.onScrolledBottom=()=>this.loadMoreHistory(!1),pt}async updateUnreadByDialog(){const e=await this.chat.getHistoryStorage(),t=this.peerId===I.myId?e.readMaxId:e.readOutboxMaxId;for(const s of this.unreadOut)if(s>0&&s<=t){const i=ps(this.peerId,s),n=this.getBubble(i);if(!n||(this.unreadOut.delete(s),n.classList.contains("is-outgoing")||n.classList.contains("is-error")))continue;this.setBubbleSendingStatus(n,"read")}}destroyBubble(e,t,s=$a(e)){let i,n,r,o;if(t&&e.isConnected){const c=[".bubbles-date-group",".bubbles-group",".bubble"];n=[e,...lB(e,c[0])].map((d,u,h)=>{const p=h.length,m=c.slice(0,p-u),g=Array.from(h[p-1].parentElement.querySelectorAll(m.join(" "))),f=g[g.indexOf(d)-1];return{element:d,parentElement:d.parentElement,index:Bn(d,!1),rect:d.getBoundingClientRect(),previousElement:d.previousElementSibling,marginBottom:parseInt(window.getComputedStyle(d).marginBottom),previousSameKindElement:f}}),o=this.setTopPadding(),r=this.scrollable.scrollSize,i=document.createElement("div"),i.classList.add("bubble-delete-placeholder")}this.getBubble(s)===e&&delete this.bubbles[s],this.skippedMids.delete(s),this.firstUnreadBubble===e&&(this.firstUnreadBubble=null);const l=n&&this.createScrollSaver(!1);if(l?.save(),this.bubbleGroups.removeAndUnmountBubble(e),this.observer&&(this.observer.unobserve(e,this.unreadedObserverCallback),this.unreaded.delete(e),this.observer.unobserve(e,this.unreadedContentObserverCallback),this.unreadedContent.delete(e),this.observer.unobserve(e,this.viewsObserverCallback),this.viewsMids.delete(s),this.observer.unobserve(e,this.stickerEffectObserverCallback),this.observer.unobserve(e,this.messageEffectObserverCallback)),e.timeAppenders=e.timeSpan=void 0,n){let c;n.forEach(S=>{S.element.parentElement||(c=S)});const d=r-this.scrollable.scrollSize,u=c===n[0],h=e.classList.contains("is-group-last"),p=e.classList.contains("is-group-first");i.style.cssText=`width: 100%; height: ${d}px;`,c.element.style.cssText=`position: absolute; z-index: 0; left: 0; right: 0; top: ${c.rect.top-56}px; height: ${c.rect.height}px;`,this.remover.append(c.element),n.forEach(S=>{S.element.parentElement||di(S.element,S.parentElement,S.index,-1)}),c.previousElement&&!c.previousElement.parentElement&&n[0].previousSameKindElement?n[0].previousSameKindElement.after(i):di(i,c.parentElement,c.index,-1),l.restore(),l.save();const m={duration:300,fill:"forwards",easing:"cubic-bezier(.4, .0, .2, 1)"},g=u&&h&&!p&&c.parentElement.querySelector(".bubbles-group-avatar"),f=i.animate([{height:"0.01px",marginBottom:"0px"}],m),v=c.element.animate([{opacity:0}],m),y=g?g.animate([{transform:`translateY(-${c.marginBottom}px)`},{transform:`translateY(-${c.marginBottom}px)`}],m):void 0,w=[f,v,y].filter(Boolean).map(S=>S.finished),b=Promise.all(w).then(()=>{i.remove(),c.element.remove(),y?.cancel(),e.middlewareHelper.destroy(),vi().then(()=>{o.unsetPadding?.()})});this.animateSomethingWithScroll(b,l)}else e.middlewareHelper.destroy()}animateSomethingWithScroll(e,t){t||(t=this.createScrollSaver(!0),t.save());let s=!1;e.then(()=>{s=!0}),Al(e),t&&Wl(()=>s?!1:(t.restore(),!0),this.scrollable.container)}deleteMessagesByIds(e,t=!0,s){if(e=e.filter(r=>!!this.getBubble(r)),!e.length)return;const i=this.getRenderedHistory("desc"),n={};if(i.forEach((r,o)=>n[r]=o),e.slice().sort((r,o)=>(n[r]??0)-(n[o]??0)).forEach(r=>{const o=this.getBubble(r);this.destroyBubble(o,t&&wt.isAvailable("animations"))}),this.scrollable.ignoreNextScrollEvent(),t&&this.chat.selection.isSelecting){let r;e.forEach(o=>{const{peerId:l,mid:c}=ti(o);r=this.chat.selection.deleteSelectedMids(l,[c],!0)}),r?.()}Ut.checkAnimations(!1,this.chat.animationGroup),this.deleteEmptyDateGroups(),s||this.scrollable.onScroll()}pollExtendedMediaMessages(){const e=Array.from(this.extendedMediaMessages);return this.managers.appMessagesManager.getExtendedMedia(this.peerId,e)}setExtendedMediaMessagesPollInterval(){this.pollExtendedMediaMessagesPromise||!this.extendedMediaMessages.size||(this.pollExtendedMediaMessagesPromise=ns(3e4).then(()=>this.pollExtendedMediaMessages()).then(()=>this.setExtendedMediaMessagesPollInterval()))}setTopPadding(e=this.getMiddleware()){let t=!1,s;if(!this.isTopPaddingSet&&this.chat.type!==we.Scheduled){const{clientHeight:i,scrollHeight:n}=this.scrollable.container;t=i===n,t&&(s=this.chatInner,s.style.paddingTop=i+"px",this.scrollable.setScrollPositionSilently(n),this.isTopPaddingSet=!0)}return{isPaddingNeeded:t,unsetPadding:t?()=>{e()&&(s.style.paddingTop="",this.isTopPaddingSet=!1)}:void 0}}renderNewMessage(e,t){const s=this._renderNewMessage(e,t);return this.renderNewPromises.add(s),s.catch(as).finally(()=>{this.renderNewPromises.delete(s)}),s}async _renderNewMessage(e,t){if(!this.scrollable.loadedAll.bottom){const c=this.chat.setPeerPromise;if(c){const d=this.getMiddleware();c.then(()=>{if(!d())return;const u=this.chat.getMessageByPeer(e.peerId,e.mid);this.renderNewMessage(u)})}return}if(this.chat.threadId&&yr(e,this.chat.isForum)!==this.chat.threadId)return;const{savedReaction:s}=this.chat;if(s?.length){const{reactions:c}=e;if(!(c?.results&&s.every(u=>c.results.some(h=>Wn(h.reaction,u)))))return}const i=ps(e);if(this.getBubble(i))return;t||(t=this.scrolledDown&&(!this.scrollingToBubble||this.scrollingToBubble===this.getLastBubble()||this.scrollingToBubble===this.chatInner));const n=this.getMiddleware(),{isPaddingNeeded:r,unsetPadding:o}=this.setTopPadding(n),l=this.performHistoryResult({history:[e]},!1);return t&&l.then(()=>{if(!n())return;let c;this.chat.type===we.Scheduled&&(c=this.getBubble(i));const d=c?this.scrollToBubbleEnd(c):this.scrollToEnd();r&&d.then(o)}),l}getLastBubble(){return this.bubbleGroups.lastGroup?.lastItem?.bubble}scrollToBubble(e,t,s,i){const n=ne(e,"bubble");e.parentElement||this.log.error("element is not connected",n);let r;if(n&&t!=="end"){const d=this.bubbleGroups.getItemByBubble(n);d&&d.group.firstItem===d&&Bn(d.group.container)===(this.stickyIntersector?lP:1)&&(r=d.group.container.parentElement)}const o=4,l=this.chat.input.messageInput&&this.chat.input.messageInput.classList.contains("is-changing-height")||this.chat.container.classList.contains("is-toggling-helper"),c=this.scrollable.scrollIntoViewNew({element:e,position:t,margin:o,forceDirection:s,forceDuration:i,axis:"y",getNormalSize:l?({rect:d})=>{let u=It.height;return u-=this.container.offsetTop,u-=st.isMobile||It.height<570?58:78,u}:void 0,fallbackToElementStartWhenCentering:r,startCallback:d=>{if(this.onScroll(!0,d),this.updateGradient){const{gradientRenderer:u}=this.chat;u?.toNextPosition(d.getProgress),this.updateGradient=void 0}}});return s===hm.Static&&(this.scrollable.lastScrollPosition=this.scrollable.scrollPosition),c}scrollToEnd(){return this.scrollToBubbleEnd(this.chatInner)}async scrollToBubbleEnd(e){if(e){this.scrollingToBubble=e;const t=this.getMiddleware();if(await this.scrollToBubble(e,"end",void 0,void 0),!t())return;this.scrollingToBubble=void 0}}async scrollToBubbleIfLast(e){if(this.getLastBubble()===e)return this.scrollToEnd()}highlightBubble(e){const t="highlightTimeout";e.dataset[t]&&(clearTimeout(+e.dataset[t]),e.classList.remove("is-highlighted"),e.offsetWidth),e.classList.add("is-highlighted"),e.dataset[t]=""+setTimeout(()=>{e.classList.remove("is-highlighted"),delete e.dataset[t]},2e3)}createDateBubble(e,t=new Date(e*1e3)){let s;const i=new Date;i.setHours(0,0,0,0);const n=this.chat.type===we.Scheduled;i.getTime()===t.getTime()?s=P(n?"Chat.Date.ScheduledForToday":"Date.Today"):n&&e===Nh?s=P("MessageScheduledUntilOnline"):(s=Dy(t,i),n&&(s=P("Chat.Date.ScheduledFor",[s])));const r=document.createElement("div");r.className="bubble service is-date";const o=document.createElement("div");o.classList.add("bubble-content");const l=document.createElement("div");return l.classList.add("service-msg"),l.append(s),o.append(l),r.append(o),r}getDateForDateContainer(e){const t=new Date(e*1e3);return e!==Nh&&t.setHours(0,0,0),{date:t,dateTimestamp:t.getTime()}}getDateContainerByTimestamp(e){const{date:t,dateTimestamp:s}=this.getDateForDateContainer(e);let i=this.dateMessages[s];if(i)return i;const n=this.createDateBubble(e,t),r=this.createDateBubble(e,t);r.classList.add("is-fake");const o=document.createElement("section");o.className="bubbles-date-group",o.append(n,r),i=this.dateMessages[s]={div:n,container:o,firstTimestamp:t.getTime(),groupsLength:0};const l=t_(this.dateMessages,"asc"),c=l.length;let d=0,u;for(;d<l.length;++d){const h=l[d];if(u=this.dateMessages[h].container,s<h)break}return d===c&&u&&(u=u.nextElementSibling),u?this.chatInner.insertBefore(o,u):this.chatInner.append(o),this.stickyIntersector?.observeStickyHeaderChanges(o),this.chatInner.parentElement&&this.container.classList.add("has-groups"),i}destroyScrollable(){this.scrollable.destroy()}destroy(){this.destroyScrollable(),this.listenerSetter.removeAll(),this.lazyLoadQueue.clear(),this.observer&&this.observer.disconnect(),this.stickyIntersector&&this.stickyIntersector.disconnect(),delete this.lazyLoadQueue,this.observer&&delete this.observer,this.stickyIntersector&&delete this.stickyIntersector}cleanup(e=!1){this.log("cleanup"),this.bubbles={},this.setLoaded("top",!1,!1),this.setLoaded("bottom",!1,!1),Zy(this.scrollable.container),UL(),this.skippedMids.clear(),this.dateMessages={},this.bubbleGroups?.cleanup(),this.bubbleGroups=new d2(this.chat),this.unreadOut.clear(),this.needUpdate=[],this.lazyLoadQueue.clear(),this.renderNewPromises.clear(),this.changedMids.clear(),e&&(this.scrollable.replaceChildren(),this.chatInner.replaceChildren(),this.cleanupPlaceholders()),this.firstUnreadBubble=null,this.attachedUnreadBubble=!1,this.batchProcessor.clear(),this.getHistoryTopPromise=this.getHistoryBottomPromise=void 0,this.fetchNewPromise=void 0,this.getSponsoredMessagePromise=void 0,this.updateGradient=void 0,this.stickyIntersector&&this.stickyIntersector.disconnect(),this.observer&&(this.observer.disconnect(),this.unreaded.clear(),this.unreadedContent.clear(),this.unreadedSeen.clear(),this.unreadedContentSeen.clear(),this.readPromise=void 0,this.readContentPromise=void 0,this.viewsMids.clear()),this.middlewareHelper.clean(),this.onAnimateLadder=void 0,this.resolveLadderAnimation=void 0,this.attachPlaceholderOnRender=void 0,this.emptyPlaceholderBubble=void 0,this.sponsoredMessage=void 0,this.previousStickyDate=void 0,this.scrollingToBubble=void 0,this.isTopPaddingSet=!1,this.renderingMessages.clear(),this.bubblesToEject.clear(),this.bubblesToReplace.clear(),this.isScrollingTimeout&&(clearTimeout(this.isScrollingTimeout),this.isScrollingTimeout=0),this.container.classList.remove("has-sticky-dates"),this.scrollable.cancelMeasure()}cleanupPlaceholders(e=this.emptyPlaceholderBubble){e&&this.destroyBubble(e)}tryToForceStartParam(e){const t=this.chat.input.startParam;t!==void 0&&this.chat.isStartButtonNeeded().then(s=>{!e()||s||this.chat.input.startParam!==t||this.chat.input.startBot()})}async setPeer(e){const{samePeer:t,sameSearch:s,peerId:i,stack:n}=e;let{lastMsgId:r,lastMsgPeerId:o,startParam:l}=e;const c=++this.setPeerTempId;let d,u;if(!i)return this.cleanup(!0),this.preloader.detach(),null;const h=performance.now(),p=this.log.bindPrefix("setPeer");p.warn("start");const m=()=>this.setPeerTempId===c,g=Bl(m,qf);t||await g(this.chat.onChangePeer(e,g));const f=this.chat.type;f===we.Scheduled||this.chat.isRestricted?d=Ci:r?d=ps(o??i,r):d=Ci;const v=await g(this.chat.getHistoryStorage());f===we.Pinned?u=ps(i,await g(this.managers.appMessagesManager.getPinnedMessagesMaxId(i,this.chat.threadId))):v.searchHistory?u=v.searchHistory.first[0]??Ci:u=v.maxId?ps(i,v.maxId):Ci;const y=d!==Ci;n&&this.chat.appImManager.clickIfSponsoredMessage(n.message);let w,b=0,S,_;if(!y&&(t||(S=this.chat.appImManager.getChatSavedPosition(this.chat)),!S)){if(this.chat.type===we.Search)d=u;else if(u!==Ci){let z;if(e.savedReaction||([b,z]=await g(Promise.all([this.managers.appMessagesManager.getReadMaxIdIfUnread(i,this.chat.threadId),this.chat.getDialogOrTopic()]))),b&&!t&&(!z||!pr(z)&&z.unread_count!==1)){const Z=v.history.findSliceOffset(b);Z&&Z.slice.isEnd(uc.Bottom)&&(_=Z.slice[Z.offset-25]||Z.slice[0]||b),w=!y,d=ps(i,b)}else d=u}}const M=d===u||d===Ci&&!w,C=d!==u;if(M&&d!==Ci&&(this.chat.getMessage(d)||(this.log("fix going to bottom end without existing message",d),d=Ci)),l===void 0&&await g(this.chat.isStartButtonNeeded())&&(l=s_),t&&s){n&&d!==Ci&&n.peerId===i&&this.followStack.push(ps(n.peerId,n.mid));let Z=(await g(this.getMountedBubble(d)))?.bubble;if(!Z&&this.skippedMids.has(d)&&(Z=this.findNextMountedBubbleByMsgId(d,!1)||this.findNextMountedBubbleByMsgId(d,!0)),Z)return y?(this.scrollToBubble(Z,"center"),this.highlightBubble(Z),this.chat.dispatchEvent("setPeer",r,!1)):u!==Ci&&!C&&(this.scrollToEnd(),this.chat.dispatchEvent("setPeer",r,!0)),l!==void 0&&(this.chat.input.setStartParam(l),this.tryToForceStartParam(m)),e.mediaTimestamp&&vi().then(()=>{this.playMediaWithTimestampAndMid({lastMsgFullMid:d,middleware:m,mediaTimestamp:e.mediaTimestamp})}),e.text&&this.managers.appDraftsManager.setDraft(this.peerId,this.chat.threadId,e.text),null}else this.peerId&&(this.lazyLoadQueue.queueId=++C0,this.managers.apiFileManager.setQueueId(this.chat.bubbles.lazyLoadQueue.queueId)),this.followStack.length=0,this.passEntities={messageEntityBotCommand:await g(this.managers.appPeersManager.isAnyGroup(i))||this.chat.isBot};_n&&p("setPeer peerId:",i,v,d,u);const L=C||[we.Search,we.Scheduled].includes(f)||this.chat.isRestricted?void 0:_??ti(u).mid,E=L?ps(i,L):void 0;let x=Ci;if(t){const z=this.getBubbleByPoint("bottom");z&&(x=$a(z)),x||(x=this.getRenderedHistory("desc",!0)[0]||Ci)}else this.isFirstLoad=!0,this.destroyResizeObserver();const R=this.chatInner,B=this.emptyPlaceholderBubble;this.cleanup();const N=this.chatInner=document.createElement("div");t?(N.className=R.className,N.classList.remove("disable-hover","is-scrolling")):N.classList.add("bubbles-inner"),this.lazyLoadQueue.lock();const G=t&&s,O=G||u!==Ci&&C||y,$=x!==Ci&&(d===Ci||await(async()=>{const z=await this.chat.getHistoryStorage(),Z=z.searchHistory||z.history;if(Z===z.searchHistory){const de=Z.first.indexOf(d),ie=Z.first.indexOf(x);return de<ie}else return ti(x).mid<ti(d).mid})()),H=!$&&G,D=!H&&$&&G;if(this.willScrollOnLoad=H||D,this.setPeerOptions={lastMsgFullMid:d,topMessageFullMid:u,savedPosition:S},!t){this.ranks=void 0,this.processRanks=void 0,this.canShowRanks=!1;let z=this.chat.isMegagroup,Z=this.peerId.toChatId();if(this.chat.type===we.Saved&&!this.chat.threadId.isUser()&&(z=Ae.getChat(Z=this.chat.threadId.toChatId())?._==="channel"),z){this.canShowRanks=!0;const de=this.processRanks=new Set,ie=this.managers.acknowledged.appProfileManager.getParticipants({id:Z,filter:{_:"channelParticipantsAdmins"},limit:100}),oe=await g(ie),ae=oe.result.then(ke=>{if(this.processRanks!==de)return;const re=ke.participants;this.ranks=new Map,re.forEach(ce=>{const Ie=ub(ce);this.ranks.set(ce.user_id.toPeerId(),Ie)}),vi().then(()=>{this.processRanks===de&&(de.forEach(ce=>ce()),this.processRanks=void 0)})},ke=>{ke.type!=="CHAT_ADMIN_REQUIRED"&&this.log.error("ranks error",ke),this.ranks=new Map});oe.cached&&await g(ae)}}let U;S?U={promise:vi().then(()=>this.performHistoryResult({history:S.mids},!0)),cached:!0,waitPromise:Promise.resolve()}:U=await g(this.getHistory1(!C&&!E&&d===u?Ci:d,!0,C,E)),this.setPeerCached=U.cached,p.warn("got history");const{promise:j,cached:q}=U,W={peerId:i,isTarget:y,isJump:C,lastMsgId:r,startParam:l,middleware:m,text:e.text,entities:e.entities};!q&&!t&&(await g(this.chat.finishPeerChange(W)),this.scrollable.replaceChildren(),this.preloader.attach(this.container)),Ut.lockGroup(this.chat.animationGroup);const ee=g(j).then(async()=>{p.warn("promise fulfilled");const z=O?await g(d!==Ci?this.getMountedBubble(d):{bubble:this.getLastBubble()}):void 0;q&&!t&&(p.warn("finishing peer change"),await g(this.chat.finishPeerChange(W)),p.warn("finished peer change")),this.preloader.detach(),this.resolveLadderAnimation&&(this.resolveLadderAnimation(),this.resolveLadderAnimation=void 0),this.setPeerCached=void 0;const Z=this.scrollable;Z.lastScrollDirection=0,Z.lastScrollPosition=0,Z.replaceChildren(N),B&&this.cleanupPlaceholders(B),this.attachPlaceholderOnRender?.(),!y&&this.chat.isPinnedMessagesNeeded()&&this.chat.topbar.pinnedMessage?.setCorrectIndex(0),this.container.classList.toggle("has-groups",!!Object.keys(this.dateMessages).length),p.warn("mounted chat",this.chatInner===N,this.chatInner.parentElement,performance.now()-h),Ut.unlockGroup(this.chat.animationGroup),Ut.checkAnimations(!1,this.chat.animationGroup),this.lazyLoadQueue.unlock();const de=Promise.all([ee,vi()]);if(S)Z.setScrollPositionSilently(S.top);else if(O){let ie;if(H)Z.setScrollPositionSilently(99999);else if(D){const re=this.setTopPadding();re.isPaddingNeeded&&(ie=re.unsetPadding),Z.setScrollPositionSilently(0)}let oe=w&&this.firstUnreadBubble||z?.bubble;const ae=!!oe?.parentElement;ae||(oe=this.findNextMountedBubbleByMsgId(d,!1)||this.findNextMountedBubbleByMsgId(d,!0));let ke;if(oe){const re=this.getLastBubble(),ce=w?"start":!C&&!y&&re===oe?"end":"center";ce==="end"&&re===oe&&t?ke=this.scrollToEnd():ke=this.scrollToBubble(oe,ce,t?void 0:hm.Static),!w&&y&&ae&&this.highlightBubble(oe)}y&&!ae&&de.then(()=>{$e({langPackKey:"MessageNotFound"})}),ie&&(ke||Promise.resolve()).then(()=>{ie()})}else Z.setScrollPositionSilently(99999);Z.updateThumb(Z.lastScrollPosition),this.onRenderScrollSet(),this.onScroll(),de.then(()=>{m()&&(Z.onScroll(),e.mediaTimestamp!==void 0&&(q&&!t&&wt.isAvailable("animations")&&this.chat.appImManager.chats.length>1?ns(400):Promise.resolve()).then(()=>this.playMediaWithTimestampAndMid({lastMsgFullMid:d,middleware:m,mediaTimestamp:e.mediaTimestamp})),this.tryToForceStartParam(m))}),this.chat.dispatchEvent("setPeer",r,!C),Promise.all([this.setFetchReactionsInterval(de),this.setFetchHistoryInterval({afterSetPromise:de,samePeer:t,savedPosition:S})]).then(()=>{p("scrolledAllDown:",Z.loadedAll.bottom),Z.loadedAll.bottom&&u!==Ci&&!this.unreaded.size&&this.onScrolledAllDown()}),f===we.Chat&&!this.chat.isForumTopic&&(await g(this.managers.appMessagesManager.getDialogOnly(i)))?.pFlags.unread_mark&&this.managers.appMessagesManager.markDialogUnread(i,!0)}).catch(z=>{throw p.error("setPeer promise error:",z),m()||this.preloader.detach(),z});return{cached:q,promise:ee}}playMediaWithTimestampAndMid({middleware:e,lastMsgFullMid:t,mediaTimestamp:s}){this.getMountedBubble(t).then(i=>{!e()||!i||this.playMediaWithTimestamp(i.bubble,s)})}playMediaWithTimestamp(e,t){const s=ne(e,"bubble"),i=ne(e,"grouped-item"),n=i?+i.dataset.mid:+s.dataset.textMid;let r=s.querySelector(".attachment");if(r){n&&(r=r.querySelector(`[data-mid="${n}"]`));const d=r.querySelector("img, video, canvas");this.checkTargetForMediaViewer(d,void 0,t);return}const o=(i||s).querySelector(".audio");if(o){o.playWithTimestamp(t);return}const l=s.dataset.replyToPeerId.toPeerId(),c=+s.dataset.replyToMid;l&&c&&(l===this.peerId?this.chat.setMessageId({lastMsgId:c,mediaTimestamp:t}):this.chat.appImManager.setInnerPeer({stack:this.chat.appImManager.getStackFromElement(s),peerId:l,mediaTimestamp:t}))}async setFetchReactionsInterval(e){const t=this.getMiddleware();if(this.chat.isChannel){const i=()=>{if(!t())return;const n=this.getRenderedHistory(void 0,!0),r=new Map;for(const c of n){let d=this.chat.getMessage(c);if(d?._!=="message")continue;d=Ae.getGroupsFirstMessage(d);const{peerId:u,mid:h}=d;let p=r.get(u);p||r.set(u,p=new Set),p.add(h)}const o=[...r.entries()].map(([c,d])=>this.managers.appReactionsManager.getMessagesReactions(c,[...d]));Promise.all(o).then(()=>{setTimeout(i,1e4)})};Promise.all([e,vi(),ns(500)]).then(()=>{i()})}}async setFetchHistoryInterval({afterSetPromise:e,savedPosition:t,samePeer:s}){const i=this.peerId;if(i.isUser())return;const n=this.getMiddleware(),r=await this.managers.appMessagesManager.isFetchIntervalNeeded(i);if(!(t||r)||(await e,!n()))return;const l=i.toChatId();n.onClean(()=>{this.managers.apiUpdatesManager.unsubscribeFromChannelUpdates(l)}),this.managers.apiUpdatesManager.subscribeToChannelUpdates(l)}async onScrolledAllDown(){if(this.chat.type===we.Chat||this.chat.type===we.Discussion){const{peerId:e,threadId:t}=this.chat,s=await this.chat.getHistoryMaxId();this.managers.appMessagesManager.readHistory(e,s,t,!0)}}async finishPeerChange(){const[e,t,s]=await Promise.all([this.chat.isBroadcast,this.chat.canSend(),this.chat.isLikeGroup]);return()=>{this.chatInner.classList.toggle("has-rights",t),this.container.classList.toggle("is-chat-input-hidden",!t),[this.chatInner,this.remover].forEach(i=>{i.classList.toggle("is-chat",s),i.classList.toggle("is-broadcast",e)}),this.createResizeObserver()}}renderMessagesQueue(e){return this.batchProcessor.addToQueue(e)}ejectBubbles(){for(const e of this.bubblesToEject)e.remove();this.bubblesToEject.clear()}groupBubbles(e){let t;this.chat.type===we.Scheduled&&(t=new Set,e.forEach(({bubble:n,message:r})=>{const o=this.bubbleGroups.getItemByBubble(n),l=o?.group;l&&o.message.date!==r.date&&(this.bubbleGroups.removeItem(o),t.add(l))})),e.forEach(({bubble:n,message:r,reverse:o})=>{this.bubbleGroups.prepareForGrouping(n,r,o)});const s=this.bubbleGroups.groupUngrouped(),i=Array.from(s).map(n=>{const r=n.firstItem;if(!r)return;if(this.chat.isAvatarNeeded(r.message))return n.avatar?void 0:n.createAvatar(r.message)}).filter(Boolean);if(t)for(const n of t)s.add(n);return{groups:[...s],avatarPromises:i}}getMiddleware(e){return this.middlewareHelper.get(e)}async wrapMediaSpoiler({media:e,promise:t,middleware:s,attachmentDiv:i}){if(await t,!s())return;const{width:n,height:r}=i.style,o=await ju({media:e,width:parseInt(n),height:parseInt(r),middleware:s,animationGroup:this.chat.animationGroup});s()&&i.append(o)}getBubble(e,t){let s;return t?s=ps(e,t):s=e,this.bubbles[s]}async safeRenderMessage({message:e,reverse:t,bubble:s,updatePosition:i=!0,processResult:n,canAnimateLadder:r}){const o=ps(e);if(!e||this.renderingMessages.has(o)||this.getBubble(o)&&!s)return;const l=Ht(),c=l.get(),d=this.getMiddleware();d.onClean(()=>{(this.chat.destroyPromise||this.chat.setPeerPromise||Promise.resolve()).then(()=>{l.destroy()})});let u;try{this.renderingMessages.add(o);const h=document.createElement("div");h.middlewareHelper=l,h.dataset.mid=""+e.mid,h.dataset.peerId=""+e.peerId,h.dataset.timestamp=""+e.date,s&&(s.middlewareHelper.destroy(),this.skippedMids.delete(o),this.bubblesToEject.add(s),this.bubblesToReplace.delete(s),this.bubblesToReplace.set(h,s),this.bubbleGroups.changeBubbleByBubble(s,h)),s=this.bubbles[o]=h;let p=this.renderMessage(e,t,s,c);n&&(p=n(p,s));const m=p.then(g=>g&&d()?{...g,updatePosition:i,canAnimateLadder:r}:void 0);if(this.renderMessagesQueue(m.catch(()=>{})),u=await m,!d())return;u||this.skippedMids.add(o)}catch(h){this.log.error("renderMessage error:",h)}if(d())return this.renderingMessages.delete(o),u}setBubbleSendingStatus(e,t,s){!s&&e.classList.remove("is-sending","is-error","is-sent","is-read"),t&&e.classList.add("is-"+t),e.querySelectorAll(".time, .time-inner").forEach(i=>{const n=!!i.querySelector(".time-sending-status");if(!t){n&&i.firstElementChild.remove();return}let r;t==="error"?r="sendingerror":t==="sending"?r="sending":t==="sent"?r="check":r="checks";const o=Be(r,"time-sending-status");n?i.firstElementChild.replaceWith(o):i.prepend(o)})}setBubbleRepliesCount(e,t){this.chat.threadId||e.querySelectorAll(".time, .time-inner").forEach(s=>{let i=s.querySelector(".time-replies");if(!t){i?.remove();return}i||(i=document.createElement("span"),i.classList.add("time-replies"),i.append(document.createTextNode(""),Be("reply_filled","time-replies-icon","time-icon"))),i.firstChild.textContent=ln(t),i.parentElement||s.prepend(i)})}setUnreadObserver(e,t,s,i=t){s??(s=t.maxBubbleMid),this.observer.observe(i,e==="history"?this.unreadedObserverCallback:this.unreadedContentObserverCallback),(e==="history"?this.unreaded:this.unreadedContent).set(i,s)}async renderMessage(e,t=!1,s,i){const n=e._==="message",r=n&&e.grouped_id;let o,l;const c=r?Ae.getMessagesByGroupedId(r):void 0,d=this.chat.type!==we.Pinned;if(r&&d){o=c.map(se=>se.mid);const te=xm(c);if(e.mid!==te.mid)return}const u=o?Math.max(...o):e.mid;s.maxBubbleMid=u,n&&(l=r?xm(c):e);const h=this.chat.isOurMessage(e),p=document.createElement("div");p.classList.add("message","spoilers-container");const m=document.createElement("div");m.classList.add("bubble-content-wrapper");const g=document.createElement("div");g.classList.add("bubble-content"),s.classList.add("bubble"),m.append(g),s.append(m),await JB({isAnyGroup:this.chat.isAnyGroup,bubble:s,message:e,our:h,peerId:this.peerId,groupedMessages:c});let f=!h&&!e.pFlags.out&&e.pFlags.unread;const v=WS(e),y=Hf(e);if(!f&&this.chat.peerId.isAnyChat()){const te=await this.managers.appMessagesManager.getReadMaxIdIfUnread(this.chat.peerId,this.chat.threadId);te!==void 0&&te<u&&(f=!0)}const w=[],b={bubble:s,promises:w,message:e,reverse:t},S={lazyLoadQueue:this.lazyLoadQueue,middleware:i,customEmojiSize:this.chat.appImManager.customEmojiSize,animationGroup:this.chat.animationGroup},_=n&&e.media?.pFlags?.via_mention,M=!!_;let C;if(M||!n&&(!e.action||!ew.has(e.action._))){const te=e.action;if(te){const ye=te._,Te=E6.get(ye);if(Te&&(Te===!0||Te(e))||om.hasOwnProperty(ye)&&!om[ye])return}s.className="bubble service",g.replaceChildren();const se=document.createElement("div");if(se.classList.add("service-msg"),te){const ye=te._==="messageActionGiftCode";let Te;if(te._==="messageActionGiftStars"||te._==="messageActionPrizeStars"){const Pe=g.cloneNode(!1);Pe.classList.add("has-service-before"),se.append(await gm({message:e,middleware:i}));const De=e.fromId===I.myId,We=te._==="messageActionPrizeStars";let Ke;We?Ke=P("Action.StarGiveawayPrize",[+te.stars,await qe({peerId:it(te.boost_peer)})]):Ke=P(De?"ActionGiftStarsSubtitle":"ActionGiftStarsSubtitleYou",[await qe({peerId:e.peerId})]),this.wrapSomeSolid(()=>qp({rlottieOptions:{middleware:i},assetName:"Gift3",title:P(We?"BoostingCongratulations":"ActionGiftStarsTitle",[te.stars]),subtitle:Ke,buttonText:P("ActionGiftPremiumView"),buttonCallback:async()=>{Ln.create({message:e,noPaymentForm:!0,transaction:{_:"starsTransaction",date:e.date,id:te.transaction_id||(De?"":"1"),peer:{_:"starsTransactionPeer",peer:We?te.boost_peer:{_:"peerUser",user_id:De?e.peerId:I.myId}},pFlags:{gift:We?void 0:!0},stars:hr(te.stars),giveaway_post_id:We?te.giveaway_msg_id:void 0}})}}),Pe,i),g.after(Pe)}else if(ye&&!fm(te)){const Pe=te.pFlags.unclaimed,De=te.pFlags.via_giveaway,We=P(Pe?"BoostingUnclaimedPrize":"BoostingCongratulations"),Ke=document.createElement("span");Ke.append(P(Pe?"BoostingYouHaveUnclaimedPrize":De?"BoostingReceivedPrizeFrom":te.boost_peer?"BoostingReceivedGiftFrom":"BoostingReceivedGiftNoName",te.boost_peer?[await qe({peerId:it(te.boost_peer)})]:void 0),document.createElement("br"),document.createElement("br"),P(Pe?"BoostingUnclaimedPrizeDuration":De?"BoostingReceivedPrizeDuration":"BoostingReceivedGiftDuration",[Zr(te.months,!0)]));const Bt=Yv(te.months);this.wrapSomeSolid(()=>qp({rlottieOptions:{middleware:i},assetName:Bt,title:We,subtitle:Ke,buttonText:P("BoostingReceivedGiftOpenBtn"),buttonCallback:()=>{ue.createPopup(Ir,te.slug)}}),g,i)}else if(te._==="messageActionChannelMigrateFrom"){const Pe=new Xt;Te=Pe.update({peerId:te.chat_id.toPeerId(!0),wrapOptions:S}),se.append(P("ChatMigration.From",[Pe.element]))}else if(te._==="messageActionChatMigrateTo"){const Pe=new Xt;Te=Pe.update({peerId:te.channel_id.toPeerId(!0),wrapOptions:S}),se.append(P("ChatMigration.To",[Pe.element]))}else if(te._==="messageActionPaidMessagesPrice"){const Pe=!+te.stars;se.append(P(Pe?"PaidMessages.GroupPriceChangedFree":"PaidMessages.GroupPriceChanged",[+te.stars]))}else if(te._==="messageActionPaidMessagesRefunded"){const Pe=new Xt;Te=Pe.update({peerId:this.peerId,onlyFirstName:!0,wrapOptions:S}),se.append(P(h?"PaidMessages.StarsRefundedByYou":"PaidMessages.StarsRefundedToYou",[+te.stars,Pe.element]))}else Te=gm({message:e,...S}).then(Pe=>se.append(Pe));if(te._==="messageActionGiftPremium"||ye&&fm(te)){const Pe=g.cloneNode(!1);Pe.classList.add("has-service-before");const De=te.months,We=Yv(De),Ke=P("ActionGiftPremiumTitle2",[Zr(De,!1)]),Bt=te.message?jt(te.message.text,{entities:te.message.entities}):P("ActionGiftPremiumSubtitle2");this.wrapSomeSolid(()=>qp({rlottieOptions:{middleware:i},assetName:We,title:Ke,subtitle:Bt,buttonText:P(ye&&e.fromId===e.peerId?"GiftPremiumUseGiftBtn":"ActionGiftPremiumView"),buttonCallback:()=>{if(ye){const bt={_:Ct.GIFT_CODE,slug:te.slug,stack:this.chat.appImManager.getStackFromElement(s)};Yu.processGiftCodeLink(bt);return}rs.show({gift:te,peerId:this.peerId,isOut:!!e.pFlags.out})}}),Pe,i),g.after(Pe)}else if(te._==="messageActionChannelJoined"){s.classList.add("is-similar-channels");const Pe=document.createElement("div");Pe.classList.add("bubble-similar-channels");let De=!1;const We=(Tt=!De,ft)=>{if(Tt===De)return;De=Tt,Tt&&!Pe.parentElement&&g.after(Pe),wt.isAvailable("animations")||(ft=!0);let Kt;s.isConnected&&(Kt=this.createScrollSaver(!0),Kt.save());const es={duration:ft?0:300,fill:"forwards",easing:"cubic-bezier(.4, .0, .2, 1)"},ys=[{height:"0"},{height:"9.125rem"}];Tt||ys.reverse();const Ds=Pe.animate(ys,es);Kt&&this.animateSomethingWithScroll(Ds.finished,Kt),Tt||Ds.finished.then(()=>{De===Tt&&Pe.remove()}),Bt(!Tt)},Ke=Mt(),Bt=async Tt=>{const ft=await Ae.getState();Tt?ft.hiddenSimilarChannels.push(bt):Vs(ft.hiddenSimilarChannels,bt),await this.managers.appStateManager.pushToState("hiddenSimilarChannels",ft.hiddenSimilarChannels)},bt=this.chat.peerId;let ct;this.wrapSomeSolid(()=>mB({chatId:bt.toChatId(),onClose:()=>{We(!1)},onAcked:Tt=>{ct=Tt,ct||Ke.resolve()},onReady:async()=>{g.classList.add("is-clickable"),await vi(),(await Ae.getState()).hiddenSimilarChannels.includes(bt)||We(!0,ct),ct&&Ke.resolve(),J(g,()=>{We()})},onEmpty:()=>{Ke.isFulfilled&&We(!1),Ke.resolve()}}),Pe,i),w.push(Ke)}else if(te._==="messageActionStarGift"||te._==="messageActionStarGiftUnique"){const Pe=document.createElement("div");Pe.classList.add("bubble-star-gift-container"),g.after(Pe);const De=await this.managers.appGiftsManager.wrapGiftFromMessage(e);this.wrapSomeSolid(()=>bI({gift:De,fromId:it(De.saved.from_id),asUpgrade:De.isIncoming&&De.isUpgradedBySender&&!(te._==="messageActionStarGift"&&te.pFlags.upgraded),ownerId:De.isIncoming?void 0:e.peerId,wrapStickerOptions:{middleware:i,lazyLoadQueue:this.lazyLoadQueue,group:this.chat.animationGroup,scrollable:this.scrollable,liteModeKey:"stickers_chat",play:!0,loop:!1},onViewClick:async()=>{if(te._==="messageActionStarGift"&&te.upgrade_msg_id){const We=await this.managers.appMessagesManager.getMessageById(te.upgrade_msg_id),Ke=await this.managers.appGiftsManager.wrapGiftFromMessage(We);ue.createPopup(iu,Ke)}else ue.createPopup(iu,De)}}),Pe,i)}w.push(Te)}else if(_){const ye=e.media,Te=it(ye.peer),Pe=ye.id,De=Te===I.myId,We=await Fl(this.managers.acknowledged.appStoriesManager.getStoryById(Te,Pe));if(!We.cached)se.append(P("Loading")),We.result.then(()=>{this.safeRenderMessage({message:e,reverse:!0,bubble:s})});else if(We.result){se.classList.add("bubble-story-mention-wrapper");const Ke=document.createElement("div");Ke.classList.add("bubble-story-mention-avatar-container");const Bt=vs({middleware:i,size:100,peerId:Te,lazyLoadQueue:this.lazyLoadQueue,withStories:!0,storyId:Pe,storyColors:{read:"rgba(255, 255, 255, .3)"}});Bt.node.dataset.storyId=""+Pe,w.push(Bt.readyThumbPromise);const bt=Mt();w.push(bt),en(We.result,ft=>{if(!i()||!ft||ft.pFlags.noforwards){bt.resolve();return}Ft(Kt=>{i.onClean(()=>{bt.resolve(),Kt()});const{container:es,ready:ys}=zu({peerId:Te,storyItem:ft,forPreview:!0,noInfo:!0,lazyLoadQueue:this.lazyLoadQueue,withPreloader:!0,noAspecter:!0});le(()=>{ys()&&(bt.resolve(),es.classList.add("bubble-story-mention-preview"),J(Ke,Ds=>{_e(Ds),Fo({peerId:Te,id:Pe,target:()=>es})},{listenerSetter:this.listenerSetter}),Ke.append(es))})})}),Ke.append(Bt.node);const ct=P(De?"StoryMentionYou":"StoryMention",[await qe({peerId:De?e.peerId:Te})]);ct.classList.add("bubble-story-mention-text");const Tt=ot("bubble-service-button bubble-story-mention-button",{noRipple:!0,text:"StoryMentionView"});J(Tt,()=>{Xs(Bt.node)},{listenerSetter:this.listenerSetter}),se.append(Ke,ct,Tt)}else{let Ke;De?Ke=P("ExpiredStoryMentionYou",[await qe({peerId:e.peerId})]):Ke=P("ExpiredStoryMention");const Bt=Be("bomb","expired-story-icon");se.append(Bt,Ke)}}g.append(se),e.pFlags.is_single&&s.classList.add("is-group-last"),C=!0}const L=f&&this.observer?this.setUnreadObserver.bind(this,"history",s,u):void 0,E=this.chat.isBroadcast;if(C)return L?.(),b;E||L?.(),this.observer&&(v||y)&&this.setUnreadObserver("content",s,l.mid);const x=e.pFlags.sponsored,R=e.sponsoredMessage,B=n&&e.factcheck;let N=n&&e.media,G=!0,O,$,H,D;if(n){if(r&&d){const se=D=aI(c);O=se?.message||"",$=se?.totalEntities||[],H=D}else O=e.message,$=e.totalEntities,H=e;const te=N?.document;te&&(te?.type==="sticker"?O=$=void 0:["video","gif"].includes(te.type)||(G=!1))}else e.action._==="messageActionPhoneCall"&&(N={_:"messageMediaCall",action:e.action});let U=0,j;if($&&!N&&!B){const te=[];for(let Te=0,Pe=$.length;Te<Pe;++Te){const De=$[Te];De._==="messageEntityCustomEmoji"?(++Te,te.push(De)):De._==="messageEntityEmoji"&&te.push(De)}const se=O.replace(/\s/g,"").length;if(te.reduce((Te,Pe)=>Te+Pe.length,0)===se){U=Math.min(x6,te.length),j=st.active.customEmoji;const Te=cP[U];Te&&(j=ii(Te,Te),s.style.setProperty("--emoji-size",Te+"px"))}}j??(j=this.chat.appImManager.customEmojiSize);let q=yh(D||e);D&&G&&(s.dataset.textMid=""+D.mid);let W=e.reply_to;if(W?._==="messageReplyHeader"){const te=W.reply_to_peer_id?it(W.reply_to_peer_id):this.peerId;if(s.dataset.replyToPeerId=""+te,s.dataset.replyToMid=""+e.reply_to_mid,q===void 0){const se=Ae.getMessageByPeer(te,e.reply_to_mid);se?q=yh(se):q=1/0}}else W&&(s.dataset.replyToPeerId=""+it(W.peer),s.dataset.replyToStoryId=""+W.story_id);const ee=te=>({entities:te,passEntities:this.passEntities,loadPromises:w,lazyLoadQueue:this.lazyLoadQueue,customEmojiSize:j,middleware:i,animationGroup:this.chat.animationGroup,maxMediaTimestamp:q,textColor:"primary-text-color",passMaskedLinks:!!e.sponsoredMessage}),z=!U&&!h&&this.chat.type!==we.Search,Z=z?{peerId:e.peerId,middleware:i,observeElement:s,observer:this.observer,onTranslation:this.modifyBubble,richTextOptions:ee()}:void 0,de=O?z?Nu({message:H,...Z}):jt(O,ee($)):void 0;let ie=!O&&!x&&!B,oe=!1,ae=!0,ke=!1,re=!1,ce;if(U){if(I.settings.emoji.big){const te=U===1&&!$.find(se=>se._==="messageEntityCustomEmoji")&&await this.managers.appStickersManager.getAnimatedEmojiSticker(O);U===1&&!N&&te?N={_:"messageMediaDocument",document:te,pFlags:{}}:(ce=document.createElement("div"),ce.classList.add("attachment","spoilers-container"),Qt(ce,de),g.append(ce)),ie=!0,s.classList.add("emoji-big"),re=!0,ae=!1,G=!1}s.classList.add("can-have-big-emoji")}G&&Qt(p,de);const Ie=this.chat.isOutMessage(e),Ve=q3(O);let fe,Xe;if(x)s.classList.add("is-sponsored");else{fe=s.timeSpan=bc.setTime({chat:this.chat,chatType:this.chat.type,groupedMessagesCount:c?.length,message:e,reactionsMessage:l,isOut:Ie,middleware:i,loadPromises:w});let te;Gd(s,p,()=>{p.append(fe,te??(te=i0()))}),(Ne.isRTL?!Y3(O):Ve)&&fe.classList.add("is-block"),E&&L?.(fe)}g.prepend(p);let Ye;if(n&&(this.chat.isAllMessagesForum||this.chat.hashtagType==="my"&&Ie)){const te=await cI({peerId:e.peerId,threadId:yr(e,this.chat.isForum),lastMsgId:e.mid,wrapOptions:{middleware:i},withIcons:!0,dialog:!0,noLink:this.chat.type===we.Search}),{element:se}=te;Ye=document.createElement("div"),Ye.classList.add("topic-name-button-container"),Ye.append(se)}if(n&&e.views){if(s.classList.add("channel-post"),!e.fwd_from?.saved_from_msg_id&&this.chat.type!==we.Pinned){const te=document.createElement("div");te.classList.add("bubble-beside-button","with-hover","forward"),te.append(Be("forward_filled")),g.append(te),s.classList.add("with-beside-button")}!e.pFlags.is_outgoing&&this.observer&&this.observer.observe(s,this.viewsObserverCallback)}const Ze=n&&e.reply_markup;let Je=Ze?._==="replyInlineMarkup"&&Ze.rows;if(Je&&(Je=Je.filter(te=>te.buttons.length)),Je){const te=document.createElement("div");te.classList.add("reply-markup");const se=new Map;Je.forEach((Te,Pe,De)=>{const We=Te.buttons,Ke=Pe===De.length-1,Bt=document.createElement("div");Bt.classList.add("reply-markup-row"),We.forEach((bt,ct,Tt)=>{const ft=ct===0,Kt=ct===Tt.length-1,{text:es,buttonEl:ys,buttonIcon:Ds,onClick:Tn}=EI({button:bt,chat:this.chat,message:e,noTextInject:!0});if(!ys)return;Tn&&se.set(ys,Tn),Ke&&(ft&&ys.classList.add("is-first"),Kt&&ys.classList.add("is-last")),ys.classList.add("reply-markup-button","rp");const ts=document.createElement("span");ts.classList.add("reply-markup-button-text"),ts.append(es),Ei(ys),ys.append(...[Ds,ts].filter(Boolean)),Bt.append(ys)}),Bt.childElementCount&&te.append(Bt)});const ye=!!te.childElementCount;ye&&J(te,Te=>{let Pe=Te.target;Pe=ne(Pe,"reply-markup-button");const De=se.get(Pe);De&&(De(Te),_e(Te))}),ye&&(s.classList.add("with-reply-markup"),m.append(te))}const tt=e.pFlags.is_outgoing;tt&&!e.error&&(s.classList.add("is-outgoing"),e.reactions&&(s.dataset.ignoreReactions="1"));const ht=n&&await this.managers.appMessagesManager.getMessageWithCommentReplies(e),Ee=!!ht&&e.mid>0;Ee&&s.classList.add("with-replies");const ve=n&&e.fwd_from,Qe=n&&e.fwdFromId,A=this.chat.isForwardOfForward(e);let F=g;const Q=n&&e.post_author&&!this.chat.isLikeGroup,X=!e.viaBotId&&(e.fromId===I.myId||!e.pFlags.out)&&(!Q||!ve)&&!A,ge=n&&e.pFlags.invert_media;ge&&s.classList.add("invert-media");let he;B&&(Ft(se=>{i.onDestroy(se);const ye=()=>Ne.countriesList.find(Ke=>Ke.iso2===B.country),Te=()=>{const Ke=ye();return Ke.name||Ke.default_name},[Pe,De]=K(),We=Ke=>{De(Ke.text)};B.text?We(B):this.managers.appMessagesManager.getFactCheck(e.peerId,e.mid).then(Ke=>{this.modifyBubble(()=>{We(Ke)})}),s0({footer:{content:P("FactCheckFooter",[Te()]),text:!0},name:{content:P("FactCheck"),tip:{content:P("FactCheckWhat"),onClick:Ke=>{Ra({element:Ke.target,container:this.container,vertical:"top",textElement:P("FactCheckToast",[Te()])})}}},get text(){if(!Pe())return P("Loading");const{text:Ke,entities:Bt}=Yc(Pe());return jt(Ke,{entities:Bt})},ref:Ke=>{he=Ke,fe?fe.before(Ke):p.append(Ke)},minContent:!0})}),document.createElement("div").classList.add("bubble-fact-check","quote-like","quote-like-hoverable"));const Le=ie||ge;let Se,xe=!1,lt=!1,mt=!1,at;const kt=Mt();if(N){switch(ce=document.createElement("div"),ce.classList.add("attachment"),N._){case"messageMediaPhotoExternal":case"messageMediaPhoto":{const te=N.photo;if(ke=Le,X&&s.classList.add("hide-name"),s.classList.add("photo"),d&&r&&o.length!==1){s.classList.add("is-album","is-grouped"),Df({messages:c,attachmentDiv:ce,middleware:this.getMiddleware(),isOut:h,lazyLoadQueue:this.lazyLoadQueue,chat:this.chat,loadPromises:w,autoDownload:this.chat.autoDownload});break}const se=!fv&&ae&&!Ee&&S0;se&&s.classList.add("with-media-tail");const ye=Bi({photo:te,message:e,container:ce,withTail:se,isOut:Ie,lazyLoadQueue:this.lazyLoadQueue,middleware:this.getMiddleware(),loadPromises:w,autoDownloadSize:this.chat.autoDownload.photo});N.pFlags?.spoiler&&w.push(this.wrapMediaSpoiler({media:te,promise:ye,middleware:i,attachmentDiv:ce}));break}case"messageMediaWebPage":{xe=!0,ce=void 0;const te=N.webpage;if(te._!=="webPage")break;lt=!0;const se=te.attributes?.find(qt=>qt._==="webPageAttributeStory"),ye=se&&it(se.peer),Te=se?.id;if(se&&await this.getStoryReplyIfExpired(ye,Te,!0)===null)break;const Pe=te.attributes?.find(qt=>qt._==="webPageAttributeUniqueStarGift"),De={},We=[],Ke=Bo(te.url);if(Ke.onclick&&!Q3.has(Ke.onclick)||x)if(We.push(qt=>{qt.setAttribute("safe","1")}),x){p.classList.add("margin-bigger");const qt=Bo(R.url);De.footer={content:je(R.button_text),link:!qt.onclick,ref:ri=>this.observer.observe(ri,this.viewsObserverCallback)},We.push(ri=>{ri.callback=()=>{this.chat.appImManager.onSponsoredBoxClick(e)}})}else{const qt=A6[te.type]||"OpenMessage";De.footer={content:P(qt)},We.push(ri=>{ri.dataset.callback=Ke.onclick})}else{const qt=!N.pFlags.safe;We.push(ri=>{jl(ri),qt&&(ri.dataset.callback="showMaskedAlert")})}Ke?.url&&!x&&We.push(qt=>{qt.href=Ke.url}),s.classList.add("has-webpage","single-media");const bt=R?.media;let ct;const Tt=te.document,ft=!!te.pFlags.has_large_media,Kt=!!(ft&&N.pFlags.force_small_media),es=R&&R6(R),ys=es||te.photo,Ds=!!es;!!(ys||Tt||se||Ds||Pe)&&(ct=document.createElement("div"),De.media={content:ct,position:"top"});const ts=bt?void 0:this.lazyLoadQueue;if(Tt)if(Tt.type==="gif"||Tt.type==="video"||Tt.type==="round"){const qt=Tt.type==="round"?st.active.round:st.active.webpage;Tt.type==="round"?(s.classList.add("round"),ct.classList.add("is-round")):s.classList.add("video"),Xa({doc:Tt,container:ct,message:e,boxWidth:qt.width,boxHeight:qt.height,lazyLoadQueue:ts,middleware:this.getMiddleware(),isOut:Ie,group:this.chat.animationGroup,loadPromises:w,autoDownload:this.chat.autoDownload,noInfo:e.mid<0&&!bt,observer:this.observer,onLoad:this.onVideoLoad,setShowControlsOn:s})}else{const qt=await rd({message:e,autoDownloadSize:this.chat.autoDownload.file,lazyLoadQueue:ts,loadPromises:w,sizeType:"documentName",searchContext:{useSearch:!1,peerId:this.peerId,inputFilter:{_:"inputMessagesFilterEmpty"}},fontSize:I.settings.messagesTextSize,canTranscribeVoice:!0});ct.append(qt),De.media.hasDocument=!0}if(te.site_name||R){let qt;if(R?(qt=P(R.pFlags.recommended?"SponsoredMessageRecommended":"SponsoredMessage"),qt.classList.add("text-capitalize")):P0[te.type]?qt=P(P0[te.type]):qt=je(te.site_name),!R){const ri=jt(te.url),sc=$u(ri).firstElementChild;sc.replaceChildren(qt),qt=sc}De.name={content:qt,tip:R&&R.pFlags.can_report&&{content:P("SponsoredMessageAdWhatIsThis"),onClick:ri=>{_e(ri),ue.createPopup(MI)}}}}const $n=nI(te);($n.textContent||R)&&(De.title=R?je(R.title):$n);const Ba=Db(te,ee(te.entities),x);Ba.textContent&&(De.text=Ba);let Oi=!1;if(Ds||ys&&!Tt&&!Pe){s.classList.add("photo");const qt=48,ri=(!R||bt)&&ys.sizes[ys.sizes.length-1];(!ri||ri.w===ri.h&&!ft||Kt)&&(De.name||De.title||De.text)?(s.classList.add("is-square-photo"),De.media.photoSize="square",Oi=!0,ct.style.width=ct.style.height=`${qt}px`):ri.h>ri.w&&!ft&&(s.classList.add("is-vertical-photo"),De.media.photoSize="vertical"),Bi({photo:ys,message:e,container:ct,boxWidth:Oi?0:st.active.webpage.width,boxHeight:Oi?0:st.active.webpage.height,isOut:Ie,lazyLoadQueue:ts,middleware:i,loadPromises:w,withoutPreloader:Oi,autoDownloadSize:this.chat.autoDownload.photo})}if(se){s.classList.add("photo","story");const qt=st.active.webpage;Tc({photo:{_:"photo",id:0,sizes:[{_:"photoSize",w:180,h:320,type:"q",size:0}],pFlags:{},access_hash:0,file_reference:[],date:0,dc_id:0},element:ct,boxWidth:qt.width,boxHeight:qt.height,message:e}),this.wrapStory({message:e,bubble:s,storyPeerId:ye,storyId:Te,container:ct,middleware:i,loadPromises:w,boxWidth:qt.width,boxHeight:qt.height})}if(Pe){s.classList.add("gift");const qt=await this.managers.appGiftsManager.wrapGiftFromWebPage(Pe);ct.style.width="240px",ct.style.height="240px",this.wrapSomeSolid(()=>mF({gift:qt,wrapStickerOptions:{play:!0,loop:!1,managers:this.managers,middleware:i,lazyLoadQueue:ts,group:this.chat.animationGroup}}),ct,i),De.text=void 0}ct&&(De.media.position=ge||Oi?"top":"bottom"),Ft(qt=>{i.onDestroy(qt),s0({...De,ref:ri=>{We.forEach(sc=>sc(ri)),he&&!ge?he.before(ri):fe?ge?(fe.parentElement.prepend(ri),ri.parentElement.classList.add("mt-bigger")):fe.before(ri):p.append(ri)},clickable:!0})});break}case"messageMediaDocument":{const te=N.document;if(te.sticker){s.classList.add("sticker"),ae=!1,re=!0,te.animated&&s.classList.add("sticker-animated");const se=st.active,ye=s.classList.contains("emoji-big"),Te=ye?se.emojiSticker:te.animated?se.animatedSticker:se.staticSticker;Tc({photo:te,element:ce,boxWidth:Te.width,boxHeight:Te.height}),g.style.minWidth=ce.style.width,g.style.minHeight=ce.style.height;const Pe=N?.pFlags?.nopremium;ai({doc:te,div:ce,middleware:i,lazyLoadQueue:this.lazyLoadQueue,group:this.chat.animationGroup,play:!0,liteModeKey:"stickers_chat",loop:!0,emoji:ye?O:void 0,withThumb:!0,loadPromises:w,isOut:Ie,noPremium:Pe,scrollable:this.scrollable,showPremiumInfo:()=>{const We=xi(()=>{no(),ue.createPopup(ga,te.stickerSetInput,void 0,this.chat.input).show()});$e({langPackKey:"Sticker.Premium.Click.Info",langPackArguments:[We]})}}),(ql(te)||ye)&&(f||tt)&&this.observer.observe(s,this.stickerEffectObserverCallback)}else if(te.type==="video"||te.type==="gif"||te.type==="round")if(mt=te.type==="round",mt&&(re=!0),mt||(ke=Le),X&&s.classList.add("hide-name"),s.classList.add(mt?"round":"video"),d&&r&&o.length!==1)s.classList.add("is-album","is-grouped"),Df({messages:c,attachmentDiv:ce,middleware:i,isOut:h,lazyLoadQueue:this.lazyLoadQueue,chat:this.chat,loadPromises:w,autoDownload:this.chat.autoDownload});else{const se=!fv&&!$o&&!mt&&ae&&!Ee&&S0;se&&s.classList.add("with-media-tail");const ye=Xa({doc:te,container:ce,message:e,boxWidth:st.active.regular.width,boxHeight:st.active.regular.height,withTail:se,isOut:Ie,lazyLoadQueue:this.lazyLoadQueue,middleware:i,group:this.chat.animationGroup,loadPromises:w,autoDownload:this.chat.autoDownload,searchContext:mt?at={peerId:this.peerId,inputFilter:{_:"inputMessagesFilterRoundVoice"},threadId:this.chat.threadId,useSearch:!e.pFlags.is_scheduled,isScheduled:e.pFlags.is_scheduled}:void 0,noInfo:e.mid<=0,noAutoplayAttribute:!!N.pFlags.spoiler,observer:this.observer,onLoad:this.onVideoLoad,setShowControlsOn:s,onGlobalMedia:Te=>{kt.resolve(Te)}});N.pFlags.spoiler&&w.push(this.wrapMediaSpoiler({media:te,promise:ye,middleware:i,attachmentDiv:ce}))}else{const se=await W3({albumMustBeRenderedFull:d,message:e,bubble:s,messageDiv:p,chat:this.chat,loadPromises:w,autoDownloadSize:this.chat.autoDownload.file,lazyLoadQueue:this.lazyLoadQueue,searchContext:te.type==="voice"||te.type==="audio"?{peerId:this.peerId,inputFilter:{_:te.type==="voice"?"inputMessagesFilterRoundVoice":"inputMessagesFilterMusic"},threadId:this.chat.threadId,useSearch:!e.pFlags.is_scheduled,isScheduled:e.pFlags.is_scheduled}:void 0,sizeType:"documentName",fontSize:I.settings.messagesTextSize,richTextFragment:de,richTextOptions:ee(),canTranscribeVoice:!0,translatableParams:Z,factCheckBox:he,isOut:Ie}),ye=document.createElement("div");ye.classList.add("bubble-content-background"),g.prepend(ye),se&&(F=se);const Te=p.lastElementChild.querySelector(".document-message")||p.lastElementChild.querySelector(".document, .audio");Te&&Gd(s,Te,()=>Te.append(fe,Xe??(Xe=i0()))),oe=!0;const Pe=(["photo","pdf"].includes(te.type)?"document":te.type||"document")+"-message";s.classList.add(Pe),Pe!=="document-message"&&s.classList.add("min-content"),s.classList.contains("is-multiple-documents")||s.classList.add("is-single-document"),xe=!0}break}case"messageMediaCall":{const te=N.action,se=document.createElement("div");se.classList.add("bubble-call"),se.append(Be(te.pFlags.video?"videocamera":"phone","bubble-call-icon"));const ye=te.pFlags.video?"video":"voice";se.dataset.type=ye;const Te=document.createElement("div");Te.classList.add("bubble-call-title"),ks(Te,Ie?te.pFlags.video?"CallMessageVideoOutgoing":"CallMessageOutgoing":te.pFlags.video?"CallMessageVideoIncoming":"CallMessageIncoming");const Pe=document.createElement("div");if(Pe.classList.add("bubble-call-subtitle"),te.duration!==void 0)Pe.append(Gp(te.duration));else{let De;switch(te.reason._){case"phoneCallDiscardReasonBusy":De="Call.StatusBusy";break;case"phoneCallDiscardReasonMissed":De="Chat.Service.Call.Missed";break;default:De="Chat.Service.Call.Cancelled";break}Pe.classList.add("is-reason"),ks(Pe,De)}Pe.prepend(Be("arrow_next","bubble-call-arrow","bubble-call-arrow-"+(te.duration!==void 0?"green":"red"))),Gd(s,Pe,()=>Pe.append(fe)),se.append(Te,Pe),xe=!0,oe=!0,s.classList.add("call-message"),p.append(se);break}case"messageMediaContact":{const te=N,se=document.createElement("div");se.classList.add("contact"),se.dataset.peerId=""+te.user_id,xe=!0;const ye=document.createElement("div");ye.className="contact-details";const Te=document.createElement("div");Te.className="contact-name";const Pe=[te.first_name,te.last_name].filter(Boolean).join(" ");Te.append(Pe.trim()?je(Pe):P("AttachContact"));const De=document.createElement("div");De.className="contact-number",De.textContent=te.phone_number?"+"+bd(te.phone_number).formatted:"Unknown phone number",se.append(ye),ye.append(Te,De);const We=vs({middleware:i,size:54,lazyLoadQueue:this.lazyLoadQueue,peerId:te.user_id.toPeerId(),peerTitle:te.user_id?void 0:Pe.trim()?Pe:Ne.format("AttachContact",!0)[0]});se.prepend(We.node),oe=!0,s.classList.add("contact-message"),p.append(se);break}case"messageMediaPoll":{oe=!0;const te=K3({message:e,managers:this.managers,middleware:i,translatableParams:Z,richTextOptions:ee()});p.prepend(te),s.classList.add("poll-message");break}case"messageMediaPaidMedia":case"messageMediaInvoice":{const se=(N.pFlags||{}).test,ye=N._==="messageMediaInvoice",Te=(Array.isArray(N.extended_media)?N.extended_media:[N.extended_media]).filter(Boolean),Pe=Te[0]?._==="messageExtendedMedia",De=Te[0]?._==="messageExtendedMediaPreview";ye||(s.classList.add("single-media"),X&&s.classList.add("hide-name"),ke=Le);let We,Ke;ye?We=N.photo:Pe&&(We=Te.map(ft=>Vi(ft)));const Bt=ye?qi(N.total_amount,N.currency):qi(N.stars_amount,Mo);let bt;if(!Te.length||!ye&&Pe){bt=document.createElement(We?"span":"div");const ft=document.createDocumentFragment(),Kt=P(N.receipt_msg_id?"PaymentReceipt":se?"PaymentTestInvoice":"PaymentInvoice");Kt.classList.add("text-uppercase");const es=" "+Ab,ys=document.createElement("span");if(ys.classList.add("text-bold"),ys.append(Bt),ft.append(ys),ye?(ys.append(es),ft.append(Kt)):bt.classList.add("other-side"),se&&N.receipt_msg_id){const Ds=document.createElement("span");Ds.classList.add("text-uppercase","pre-wrap"),Ds.append(es+"(Test)"),ft.append(Ds)}Qt(bt,ft)}else De&&(ce.classList.add("is-buy"),bt=document.createElement("span"),bt.classList.add("extended-media-buy"),ye?bt.append(Be("premium_lock","extended-media-buy-icon"),P("Checkout.PayPrice",[Bt])):bt.append(P("PaidMedia.Unlock",[Bt])),Ke=Te.map(ft=>{const Kt=ft.video_duration;if(Kt===void 0)return;const es=document.createElement("span");return es.classList.add("video-time"),es.textContent=bn(Kt,!1),es}),Ke.length===1&&Ke[0]&&ce.append(Ke[0]));if(De&&(We=Te.map(ft=>Cb(ft))),Array.isArray(We)&&We.length===1&&(We=We[0]),We){const ft=Te.length?st.active.extendedInvoice:st.active.invoice;Array.isArray(We)?(s.classList.add("is-album","photo"),Df({media:We,attachmentDiv:ce,middleware:this.getMiddleware(),isOut:h,lazyLoadQueue:this.lazyLoadQueue,chat:this.chat,loadPromises:w,autoDownload:this.chat.autoDownload,spoilered:!Pe,videoTimes:Ke,uploadingFileName:e.uploadingFileName})):We._==="document"?(Xa({doc:We,container:ce,withTail:!1,isOut:Ie,lazyLoadQueue:this.lazyLoadQueue,middleware:i,loadPromises:w,boxWidth:ft.width,boxHeight:ft.height,group:this.chat.animationGroup,message:e,observer:this.observer,onLoad:this.onVideoLoad,setShowControlsOn:s,uploadingFileName:e.uploadingFileName[0]}),s.classList.add("video")):(Bi({photo:We,container:ce,withTail:!1,isOut:Ie,lazyLoadQueue:this.lazyLoadQueue,middleware:i,loadPromises:w,boxWidth:ft.width,boxHeight:ft.height,message:Pe?e:void 0}),s.classList.add("photo")),bt&&((!Te.length||!ye&&Pe)&&bt.classList.add("video-time"),ce.append(bt))}else ce=void 0;if(De){const{mid:ft}=e;if(this.extendedMediaMessages.add(ft),i.onClean(()=>{this.extendedMediaMessages.delete(ft)}),this.setExtendedMediaMessagesPollInterval(),Te.length===1){const{width:Kt,height:es}=ce.style,{canvas:ys,readyResult:Ds}=Fu.create({width:parseInt(Kt),height:parseInt(es),middleware:i,animationGroup:this.chat.animationGroup});w?.push(Ds),ce.append(ys)}}let ct;ye&&(ct=document.createElement("div"),ct.classList.add("bubble-primary-color"),Qt(ct,je(N.title)));let Tt;ye&&(Tt=Pe?void 0:je(N.description)),p.prepend(...[ct,Tt].filter(Boolean)),ce.append(...[(!We||!ye)&&bt].filter(Boolean)),ye&&(Tt?oe=!0:ae=!1),s.classList.add("is-invoice");break}case"messageMediaGeoLive":case"messageMediaVenue":case"messageMediaGeo":{const te=bB({attachmentDiv:ce,bubble:s,loadPromises:w,message:e,messageDiv:p,messageMedia:N,middleware:i,timeSpan:fe,updateLocationOnEdit:this.updateLocationOnEdit,wrapOptions:S});te!==void 0&&(ae=te);break}case"messageMediaStory":{const te=N.id,se=it(N.peer),ye=await this.getStoryReplyIfExpired(se,te,!1,!0);if(ye){s.classList.add("is-expired-story"),oe=!0,p.append(ye),p.classList.add("expired-story-message","is-empty");break}s.classList.add("photo","story"),Ee?Tc({size:ii(Fv,st.active.regular.height),boxWidth:st.active.regular.width,boxHeight:st.active.regular.height,message:e,element:ce}):this.setStoryContainerDimensions(ce),ie&&(ae=!1),Se=se,this.wrapStory({message:e,bubble:s,storyPeerId:se,storyId:te,container:ce,middleware:i,loadPromises:w});break}case"messageMediaGiveawayResults":case"messageMediaGiveaway":{const te=N;te._==="messageMediaGiveawayResults"&&(W=void 0),oe=!0,s.classList.add("is-giveaway"),xe=!0;const se=this.makeViewButton({text:"BoostingHowItWork"}),ye=document.createElement("div");p.before(ye,se),J(se,()=>{rB(e)}),this.wrapSomeSolid(()=>oB({giveaway:te,loadPromises:w}),ye,i);break}default:ce=void 0,oe=!0,xe=!0,p.replaceChildren(P(mv)),s.timeAppenders[0].callback(),this.log.warn("unrecognized media type:",N._,e);break}if(xe)ce=void 0;else{ge?p.after(ce):p.before(ce);const te=ce.style.width;te&&(g.style.maxWidth=`min(100%, ${te})`)}ke&&!Ee&&s.classList.add("has-plain-media-tail")}const Us=fe&&(ie&&!oe||ge&&!lt);if(ie&&!oe?(p.remove(),s.classList.add("is-message-empty")):ce&&(ce.classList.add(ge?"no-brt":"no-brb"),p.classList.add(ge?"mb-shorter":"mt-shorter")),Us&&(fe.classList.add("is-floating"),s.classList.add("has-floating-time"),Gd(s,g,()=>g.append(fe))),re&&s.classList.add("just-media"),R){const te=R.pFlags.can_report,se=document.createElement("div");se.classList.add("bubble-beside-button","bubble-beside-button-top");let ye;if(te){se.classList.add("bubble-sponsored-buttons"),ye=yt("close bubble-sponsored-buttons-button",{noRipple:!0});const Te=document.createElement("div");Te.classList.add("bubble-sponsored-buttons-delimiter");const Pe=yt("more bubble-sponsored-buttons-button",{noRipple:!0});se.append(ye,Te,Pe),J(Pe,De=>{this.chat.contextMenu.onContextMenu(De)})}else ye=se,ye.append(Be("close")),se.classList.add("bubble-sponsored-hide");g.prepend(se),s.classList.add("with-beside-button"),J(ye,()=>{rs.show({feature:"no_ads"})})}let Ts="";(re||!Ie||e.fwdFromId)&&this.chat.appImManager.setPeerColorToElement({peerId:e.fwdFromId||e.fromId,element:s,messageHighlighting:re,colorAsOut:Ie,color:R?.color});const zs=(e.fromId!==I.myId||!Ie)&&this.chat.isLikeGroup||e.viaBotId||Se;if(zs||ve||W||Ye){let te,se;const ye=e.fromId,Te=e.from_id?._==="peerChannel"&&e.fromId===Qe,Pe=Aa(ve),De=A&&!Ie&&ve.from_name&&ve.saved_from_name;let We=!!e.viaBotId||Se;const Ke=!!(ve&&(!ve.from_id||Pe));e.viaBotId&&(se=document.createElement("span"),se.innerText="@"+await this.managers.appPeersManager.getPeerUsername(e.viaBotId),se.classList.add("peer-title"));let Bt=!!(Se||Qe||ve);if(Bt&&this.chat.type===we.Saved&&Qe===I.myId&&(Bt=!1),Ke&&!Qe)te=document.createElement("span"),te.classList.add("peer-title"),Qt(te,je(ve.from_name||Pe)),s.classList.add("hidden-profile");else{const ft=Se||Qe||e.fromId;te=this.createTitle(ft,S,Bt).element}let bt;n&&(W?._==="messageReplyStoryHeader"||e.reply_to_mid&&e.reply_to_mid!==this.chat.threadId||W?.reply_from)&&(!this.chat.isAllMessagesForum||W.reply_to_top_id)&&(bt=await bc.setReply({chat:this.chat,bubble:s,bubbleContainer:g,message:e,appendCallback:ft=>{F.prepend(ft),!ie&&(!ce||ge)&&ft.classList.add("mb-shorter"),ce&&ce.classList.add("no-brt")},middleware:i,lazyLoadQueue:this.lazyLoadQueue,needUpdate:this.needUpdate,isStandaloneMedia:re,isOut:Ie}));let ct;if(Bt){const ft=this.peerId===I.myId&&(!this.chat.threadId||!II(e));!ft&&!Te&&s.classList.add("forwarded"),e.savedFrom&&(Ts=e.savedFrom,te.dataset.savedFrom=Ts),ct=document.createElement("div");const Kt=Se||Qe;if(te.dataset.peerId=""+Kt,(ft||this.peerId===Lo||Te)&&!re&&!De&&!A&&!Se)ct.classList.add("colored-name"),ct.append(te);else{We||(We=!0),s.classList.remove("hide-name");const es=[te];if(Kt){const ts=vs({middleware:i,size:20,lazyLoadQueue:this.lazyLoadQueue,peerId:Kt,isDialog:!1});ts.node.classList.add("bubble-name-forwarded-avatar"),es.unshift(ts.node)}else te.classList.add("text-normal");{const ts=document.createElement("br");ts.classList.add("hide-ol"),es.unshift(ts)}let ys;const Ds=[es];if(ve?.post_author){ys=Se?"ForwardedStoryFromAuthor1":"ForwardedFromAuthor";const ts=document.createElement("span");ts.append(je(ve.post_author)),Ds.push(ts)}else ys=Se?"ForwardedStoryFrom1":"ForwardedFrom";const Tn=P(ys,Ds);if(Tn.classList.add("bubble-name-forwarded"),ct.append(Tn),De){let ts;if(Pe)ts=document.createElement("span"),ts.classList.add("peer-title"),ts.style.color="var(--message-primary-color)",ts.dataset.peerId=""+Wt,ts.append(je(Pe));else{const Ba=it(ve.saved_from_id),{element:Oi,textColorProperty:qt}=this.createTitle(Ba,S,!1);Oi.style.color=`rgb(var(--${qt}))`,ts=Oi}const $n=document.createElement("div");$n.classList.add("name-first-line"),$n.append(ts),ct.prepend($n)}}}else if(!e.viaBotId)if(!re&&zs){ct=document.createElement("div"),ct.append(te);{const Kt=Ae.getPeer(ye)?.pFlags;Kt&&(Kt.scam||Kt.fake)&&ct.append(y_(Kt.scam)),h||ct.classList.add("colored-name"),ct.dataset.peerId=""+ye}}else s.classList.add("hide-name");if(e.viaBotId){ct?ct.append(" "):ct=document.createElement("div");const ft=document.createElement("span");ft.append(P("ViaBot")," ",se),ft.classList.add("is-via"),ct.append(ft)}if(Ye&&(re?Ye.classList.add("floating-part"):(ct||(ct=document.createElement("div")),ct.append(Ye),s.classList.remove("hide-name"))),ct&&!s.classList.contains("hide-name")){ct.classList.add("name"),Xr(ct);const ft=Kt=>{p&&Kt.nextElementSibling===p&&Kt.classList.add("next-is-message")};if(re){const Kt=document.createElement("div");Kt.classList.add("name-with-reply","floating-part"),F.prepend(Kt),ft(Kt),F=Kt}else ct.classList.add("floating-part");F.prepend(ct),re||ft(ct),re&&bt&&ct.after(bt)}else re&&bt&&bt.classList.add("floating-part");const Tt=ct?.firstElementChild||te;if(this.canShowRanks&&te&&!Ke&&!Qe){const ft=()=>{const es=this.ranks.get(e.fromId);es&&this.wrapTitleAndRank(Tt,es)},Kt=Q&&e.post_author;if(Kt)this.wrapTitleAndRank(Tt,Kt);else if(this.ranks)ft();else{const es=this.processRanks;es.add(ft),i.onDestroy(()=>{es.delete(ft)})}}else this.chat.isMegagroup&&!e.fromId.isUser()&&e.views&&this.wrapTitleAndRank(Tt,0);if(Ye&&re)if(ce)ce.after(Ye);else{this.log.error("no attachment div?",s,e);debugger}We&&s.classList.add("must-have-name")}else s.classList.add("hide-name");if(this.chat.type===we.Pinned&&(Ts=ps(this.chat.peerId,e.mid)),ht&&ht.mid===this.chat.threadId&&s.classList.add("is-thread-starter","is-group-last"),Ts&&(this.chat.type===we.Pinned||ve.saved_from_msg_id)&&this.peerId!==Lo){const te=document.createElement("div");te.classList.add("bubble-beside-button","with-hover","goto-original"),te.append(Be("arrow_next")),g.append(te),s.dataset.savedFrom=Ts,s.classList.add("with-beside-button")}if(s.classList.add(Ie?"is-out":"is-in"),Ee)bc.renderReplies({bubble:s,bubbleContainer:g,message:ht,messageDiv:p,loadPromises:w,lazyLoadQueue:this.lazyLoadQueue,middleware:i})?ae=!0:s.classList.add("with-beside-replies");else if(n&&e.replies&&this.chat.isAnyGroup){const te=e.replies;this.setBubbleRepliesCount(s,te.replies)}if(n&&this.appendReactionsElementToBubble(s,e,l,void 0,w),ae&&!mt&&s.classList.add("can-have-tail"),(ae||mt)&&g.append(dP()),h&&(this.peerId!==I.myId||Ie)){(e.pFlags.unread||tt)&&this.unreadOut.add(e.mid);let te;e.error?te="error":tt?te="sending":te=e.pFlags.unread||e.pFlags.is_scheduled?"sent":"read",(Ie||te!=="sent"&&te!=="read")&&this.setBubbleSendingStatus(s,te,!0)}return n&&Ft(te=>{i.onDestroy(te),le(()=>{s.classList.toggle("no-forwards",!this.canForward(e))})}),n&&e.effect&&(f||tt)&&this.observer.observe(s,this.messageEffectObserverCallback),mt&&TB({bubble:s,message:e,globalMediaDeferred:kt,searchContext:at}),this.addMessageSpoilerOverlay({mid:e.mid,messageDiv:p,middleware:i,loadPromises:w,canTranslate:z}),b}async addMessageSpoilerOverlay({mid:e,messageDiv:t,middleware:s,loadPromises:i,canTranslate:n}){if(jc||(n&&i&&await Promise.all(i),!t.querySelector(".spoiler-text")))return;const r=ZB({mid:e,messageElement:t,animationGroup:this.chat.animationGroup},ep);t.append(r.element),s.onDestroy(()=>{r.dispose()}),await Promise.all(i),r.controls.update()}canForward(e){return e?._!=="message"||e.pFlags.noforwards?!1:e.peerId.isUser()?!0:!Qy(e.peerId).pFlags.noforwards}appendReactionsElementToBubble(e,t,s,i,n){if(this.peerId.isUser()&&P6||!s?.reactions||!s.reactions.results.length)return;const r=new Wg;if(r.init({context:s,type:la.Block,middleware:e.middlewareHelper.get(),animationGroup:this.chat.animationGroup,lazyLoadQueue:this.lazyLoadQueue}),r.render(i),e.classList.contains("has-floating-time"))e.querySelector(".bubble-content-wrapper").append(r);else{const o=e.timeSpan,l=e.querySelector(".message");if(Gd(e,r,()=>r.append(o)),e.classList.contains("is-multiple-documents")){const c=l.lastElementChild;let d=c.querySelector(".document-message");d||(d=document.createElement("div"),d.classList.add("document-message"),c.querySelector(".document-wrapper").append(d)),d.append(r)}else l.append(r)}}setStoryContainerDimensions(e){e.style.width="144px",e.style.height="256px"}async getStoryReplyIfExpired(e,t,s,i){const n=await this.managers.acknowledged.appStoriesManager.getStoryById(e,t);if(n.cached&&!await n.result){if(s)return null;const r=await qe({peerId:e}),{container:o,fillPromise:l}=Hu({title:s?r:void 0,subtitle:s?void 0:P("ExpiredStorySubtitle",[r]),isStoryExpired:!0,noBorder:i});return o}}wrapSomeSolid(e,t,s){const i=wi(e,t);s.onClean(i)}wrapStory({message:e,bubble:t,storyPeerId:s,storyId:i,container:n,middleware:r,loadPromises:o,boxWidth:l,boxHeight:c}){n.dataset.storyPeerId=""+s,n.dataset.storyId=""+i,this.wrapSomeSolid(()=>EA({message:e,peerId:s,storyId:i,boxWidth:l,boxHeight:c,lazyLoadQueue:this.lazyLoadQueue,autoDownload:this.chat.autoDownload,loadPromises:o,canAutoplay:!1,onExpiredStory:async()=>{await vi(),e=this.chat.getMessageByPeer(e.peerId,e.mid),this.safeRenderMessage({message:e,reverse:!0,bubble:t})},withPreloader:!0}),n,r)}wrapTitleAndRank(e,t){const s=this.createBubbleNameRank(t),i=document.createElement("div");i.classList.add("title-flex"),e.replaceWith(i),i.append(e,s)}createBubbleNameRank(e){const t=document.createElement("span");return t.classList.add("bubble-name-rank"),t.append(J_(e)),t}createTitle(e,t,s){const i=i_(Ae.getPeer(e));let n;return i!==-1&&(n=`peer-${i}-color-rgb`),{element:new Xt({peerId:e,withPremiumIcon:!s,wrapOptions:{...t,textColor:n}}).element,textColorProperty:n}}prepareToSaveScroll(e,t,s){if(!!!this.chatInner.parentElement)return{};const n=this.log.bindPrefix("prepareToSaveScroll");n("save");const r=this.createScrollSaver(e);if(r.save(),(t||s)&&this.getRenderedLength()&&!this.chat.setPeerPromise){const o=this.getViewportSlice(!0);t||(o.invisibleTop.length=0),s||(o.invisibleBottom.length=0),this.deleteViewportSlice(o,!0)}return{restoreScroll:()=>{n("restore"),r.restore(e),this.onRenderScrollSet(r.getSaved())},scrollSaver:r}}async performHistoryResult(e,t){const s=this.log.bindPrefix("perform-"+(Math.random()*1e3|0));s?.("start",this.chatInner.parentElement,e);let i=e.messages||e.history;i=i.slice(),this.needReflowScroll&&(S2(this.scrollable.container),this.needReflowScroll=!1);const n=d=>{if(d)return d.pFlags.local?this.processLocalMessageRender(d):this.safeRenderMessage({message:d,reverse:t,canAnimateLadder:!0})},r=i.map(d=>typeof d=="number"?this.chat.getMessage(d):d),o=[];if(!this.scrollable.loadedAll.bottom||!this.scrollable.loadedAll.top){let d=e.isEnd;if(!d){const u=await this.chat.getHistoryStorage(),h=u.history.first,p=u.history.last;d={top:!1,bottom:!1,both:!1},h.isEnd(uc.Bottom)&&(!h.length||i.includes(h[0]))&&(d.bottom=!0),p.isEnd(uc.Top)&&(!p.length||i.includes(p[p.length-1]))&&(d.top=!0)}if(!d.bottom&&this.setPeerOptions){const{lastMsgFullMid:u,topMessageFullMid:h,savedPosition:p}=this.setPeerOptions;this.setPeerOptions=void 0,(u===Ci&&!p||h!==Ci&&this.getBubble(h)||u===h)&&(d.bottom=!0)}d.top&&o.push(this.setLoaded("top",!0)),d.bottom&&o.push(this.setLoaded("bottom",!0))}o.length&&await Promise.all(o);let l=[];this.chat.type,we.Search,l=r.map(n),l.length&&await Promise.all(l),await this.messagesQueuePromise;const c=this.checkIfEmptyPlaceholderNeeded();c&&await c,this.messagesQueuePromise&&await this.messagesQueuePromise,this.scrollable.loadedAll.top&&this.messagesQueueOnRenderAdditional&&(this.messagesQueueOnRenderAdditional(),this.messagesQueueOnRenderAdditional?.()),s?.("performHistoryResult end")}onRenderScrollSet(e){const t="has-sticky-dates";if(!this.container.classList.contains(t)&&(!this.preloader.detached||(e??(e={scrollHeight:this.scrollable.scrollSize,clientHeight:this.scrollable.clientSize}),e.scrollHeight!==e.clientHeight))){const i=this.getMiddleware(),n=()=>{i()&&this.container.classList.add(t)};this.willScrollOnLoad?n():setTimeout(n,600);return}this.willScrollOnLoad=void 0}requestHistory(e,t,s){let i;if(typeof e=="string"){const{peerId:n,mid:r}=ti(e);i=n,e=r}if([we.Chat,we.Discussion,we.Saved,we.Search].includes(this.chat.type))return this.managers.acknowledged.appMessagesManager.getHistory({...this.chat.requestHistoryOptionsPart,offsetPeerId:i,offsetId:e,limit:t,backLimit:s});if(this.chat.type===we.Pinned)return this.managers.acknowledged.appMessagesManager.getHistory({peerId:this.peerId,inputFilter:{_:"inputMessagesFilterPinned"},offsetPeerId:i,offsetId:e,limit:t,backLimit:s});if(this.chat.type===we.Scheduled)return this.managers.acknowledged.appMessagesManager.getScheduledMessages(this.peerId).then(n=>({cached:n.cached,result:Promise.resolve(n.result).then(r=>({history:r.slice().reverse(),count:r.length,isEnd:{both:!0,bottom:!0,top:!0}}))}))}async animateAsLadder(e,t,s,i,n){const r=this.log.bindPrefix("ladder");if(this.chat.setPeerPromise&&!this.resolveLadderAnimation){r.warn("will be delayed"),this.resolveLadderAnimation=this.animateAsLadder.bind(this,e,t,s,i,n);return}const o=this.getRenderedHistory("desc");if(!o.length){r.warn("no bubbles");return}let l=o.slice();s&&t.length&&(l=l.filter(M=>!t.includes(M)));let c;i?c=n||l[0]:e?c=e:c=l[0];const d=l.slice(l.findIndex(M=>c>M)),u=s?[]:[c],h=s?[]:l.slice(0,l.findIndex(M=>c>=M)).reverse();_n&&r("targeting mid:",c,n,e,d,h);const p=[];this.chatInner.classList.add("zoom-fading");const m=s?10:40,g=s?0:1,f=(M,C=0)=>{const L=Mt();let E=0;return M.forEach((x,R)=>{const B=this.getBubble(x);if(!B||this.skippedMids.has(x)){r.warn("no bubble by mid:",x);return}E=(R+C||.1)*m;const N=B.lastElementChild;if(!N){r.warn("bubble not ready yet",x,this.batchProcessor);return}const G=[N],O=this.bubbleGroups.getItemByBubble(B);if(O&&O.group.avatar&&O.group.lastItem===O&&G.push(O.group.avatar.node),G.forEach($=>{$.classList.add("zoom-fade","can-zoom-fade"),$.style.setProperty("transition-delay",E+"ms","important")}),R===M.length-1){const $=H=>{H.target===N&&(L.resolve(),N.removeEventListener("transitionend",$))};N.addEventListener("transitionend",$)}p.push(...G)}),M.length||L.resolve(),{lastMsDelay:E,animationPromise:L}},v=f(d,g),y=f(u),w=f(h,g),b=[v.animationPromise,y.animationPromise,w.animationPromise],S=[v.lastMsDelay,y.lastMsDelay,w.lastMsDelay];this.onAnimateLadder&&await this.onAnimateLadder(),$s(()=>{this.setStickyDateManually(),p.forEach(M=>{M.classList.remove("zoom-fade")})});let _;if(d.length||u.length||h.length){_=Promise.all(b);const C=Math.max(...S)+300;Al(_,C).then(()=>{$s(()=>{p.forEach(L=>{L.style.transitionDelay="",L.classList.remove("can-zoom-fade")}),this.chatInner.classList.remove("zoom-fading")})})}return _}async renderEmptyPlaceholder(e,t,s,i){const n="empty-bubble-placeholder";t.classList.add(n,n+"-"+e);let r;e==="group"?r=P("GroupEmptyTitle1"):e==="saved"?r=P("ChatYourSelfTitle"):e==="noMessages"||e==="greeting"?r=P("NoMessages"):e==="noScheduledMessages"?r=P("NoScheduledMessages"):e==="restricted"&&(r=document.createElement("span"),r.innerText=await this.managers.appPeersManager.getRestrictionReasonText(this.peerId)),r&&(r.classList.add("center",n+"-title"),i.push(r));let o;if(e==="group")i.push(P("GroupEmptyTitle2")),o=[P("GroupDescription1"),P("GroupDescription2"),P("GroupDescription3"),P("GroupDescription4")];else if(e==="saved")o=[P("ChatYourSelfDescription1"),P("ChatYourSelfDescription2"),P("ChatYourSelfDescription3"),P("ChatYourSelfDescription4")];else if(e==="greeting"){let l=P("NoMessagesGreetingsDescription");const c=document.createElement("div");c.classList.add(n+"-sticker");const d=this.getMiddleware();await Promise.all([this.managers.appStickersManager.getGreetingSticker(),this.managers.appProfileManager.getProfile(s.peerId.toUserId())]).then(async([h,p])=>{if(!d())return;const m=p.business_intro;if(m){if(m.title){const w=document.createElement("span");w.append(je(m.title)),w.className=r.className,i[i.indexOf(r)]=w}m.description&&(l=document.createElement("span"),l.append(je(m.description))),m.sticker&&(h=m.sticker);const f=t.querySelector(".bubble-content"),v=f.cloneNode(!1),y=f.querySelector(".service-msg").cloneNode(!1);y.append(P(m.title||m.description?"ChatEmpty.BusinessIntro.How":"ChatEmpty.BusinessIntro.Sticker.How",[await qe({peerId:s.peerId,onlyFirstName:!0}),xi(()=>{rs.show()})])),v.classList.add("has-service-before"),v.append(y),f.after(v),t.classList.add("wider")}const g=[];return await ai({doc:h,div:c,middleware:d,lazyLoadQueue:this.lazyLoadQueue,group:this.chat.animationGroup,play:!0,loop:!0,withThumb:!0,loadPromises:g,liteModeKey:"stickers_chat"}),J(c,f=>{_e(f),this.chat.input.emoticonsDropdown.onMediaClick({target:f.target},void 0,void 0,!0)}),Promise.all(g)}),l.classList.add("center",n+"-subtitle"),i.push(l,c)}else if(e==="premiumRequired"){const l=document.createElement("div");l.classList.add(n+"-sticker"),l.append(Be("premium_restrict"));const c=P("Chat.PremiumRequired",[await qe({peerId:this.peerId,onlyFirstName:!0})]);c.classList.add("center",n+"-subtitle");const d=ot("bubble-service-button",{noRipple:!0,text:"Chat.PremiumRequiredButton"});J(d,()=>{rs.show()}),i.push(l,c,d)}else if(e==="paidMessages"){const l=document.createElement("div");l.classList.add(n+"-sticker"),l.append(Be("premium_restrict"));const c=await this.managers.appPeersManager.getStarsAmount(this.peerId),d=document.createElement("span");d.classList.add(n+"-stars"),d.append(Be("star",n+"-star-icon"),Jr(c));const u=P("PaidMessages.NewChatDescription",[await qe({peerId:this.peerId,onlyFirstName:!0}),d]);u.classList.add("center",n+"-subtitle");const h=ot("bubble-service-button overflow-hidden",{noRipple:!0,text:"BuyStars"});h.append(Rl({isDiv:!0,mode:"button"})),J(h,()=>{ue.createPopup(ba)}),i.push(l,u,h)}o&&(i.push(...o.map(l=>{const c=document.createElement("span");return c.classList.add(n+"-list-item"),c.append(l),c})),e==="group"?o.forEach(l=>{const c=Be("check",n+"-list-check");l.prepend(c)}):e==="saved"&&o.forEach(l=>{const c=document.createElement("span");c.classList.add(n+"-list-bullet"),c.innerText="•",l.prepend(c)})),i.length>1&&t.classList.add("has-description"),i.forEach(l=>l.classList.add(n+"-line"))}async processLocalMessageRender(e,t){const s=!!e.pFlags.sponsored,i=()=>{this.log.warn("local message was cleared before render",e)},n=async r=>{const{bubble:o}=await r;if(!o)return i(),r;const l=ps(e),c=o.middlewareHelper.get(),d=Bl(c);o.message=e,o.classList.add("is-group-last","is-group-first");const u=()=>{if(this.updatePlaceholderPosition===u&&(this.updatePlaceholderPosition=void 0),!c()||this.getBubble(l)!==o){i();return}f[v](m)};s||(o.classList.add("bubble-first"),o.classList.remove("can-have-tail","is-in"));const h=[],p=this.chat.isBot,m=o;let g,f=this.container,v="append";if(this.chat.isRestricted)g=this.renderEmptyPlaceholder("restricted",o,e,h);else if(s)o.classList.add("avoid-selection"),this.sponsoredMessage=e.sponsoredMessage,f=this.chatInner,v="append",t=!1;else if(p&&e._==="message"){const b=document.createElement("b");b.append(P("BotInfoTitle")),h.push(b,`
- `),f=this.chatInner,v="prepend"}else if(this.chat.isAnyGroup&&Ae.getPeer(this.peerId).pFlags.creator)g=this.renderEmptyPlaceholder("group",o,e,h);else if(this.chat.type===we.Scheduled)g=this.renderEmptyPlaceholder("noScheduledMessages",o,e,h);else if(I.myId===this.peerId)g=this.renderEmptyPlaceholder("saved",o,e,h);else if(this.peerId.isUser()&&!p&&await d(this.chat.canSend())&&this.chat.type===we.Chat){const b=await this.managers.appUsersManager.getRequirementToContact(this.peerId.toUserId());b._==="requirementToContactPremium"?g=this.renderEmptyPlaceholder("premiumRequired",o,e,h):b._==="requirementToContactPaidMessages"&&!(await this.managers.appProfileManager.hasBussinesIntro(this.peerId.toUserId())&&this.chat.starsAmount<=+this.chat.stars())?g=this.renderEmptyPlaceholder("paidMessages",o,e,h):g=this.renderEmptyPlaceholder("greeting",o,e,h)}else g=this.renderEmptyPlaceholder("noMessages",o,e,h);g&&await g,h.length&&o.querySelector(".message, .service-msg").prepend(...h);const y=!!this.messagesQueueOnRenderAdditional,w=this.setPeerCached&&!y;if(w){const b=o.firstElementChild;b.classList.add("no-transition"),this.chat.setPeerPromise&&this.chat.setPeerPromise.catch(as).finally(()=>{b.classList.remove("no-transition")})}if(t===void 0&&!w&&(t=!0),y||t?(this.updatePlaceholderPosition=u,this.onAnimateLadder=()=>{if(this.onAnimateLadder=void 0,!this.messagesQueuePromise)return Sv()}):this.chat.setPeerPromise?this.attachPlaceholderOnRender=()=>{this.attachPlaceholderOnRender=void 0,u()}:this.updatePlaceholderPosition=u,!y&&t){await d(vi());const b=this.getRenderedHistory("asc");Vs(b,l),this.animateAsLadder(l,b,!1,0,Ci)}return o.middlewareHelper.onDestroy(()=>{this.emptyPlaceholderBubble===o&&(this.emptyPlaceholderBubble=void 0)}),this.emptyPlaceholderBubble=o,r};return this.safeRenderMessage({message:e,reverse:!s,updatePosition:!1,processResult:n,canAnimateLadder:!0})}makeViewButton(e){const t=ot("btn-primary btn-primary-transparent bubble-view-button",e),s=t.querySelector(".i18n");return s&&s.classList.add("bubble-view-button-text"),t}generateLocalMessageId(e=0){const t=(this.chat.type===we.Scheduled?-1:0)+e,s=-Math.abs(t);return{id:s,mid:s}}async generateLocalFirstMessage(e,t,s=0){const{id:i,mid:n}=this.generateLocalMessageId(s);let r={_:e?"messageService":"message",date:0,id:i,mid:n,peer_id:await this.managers.appPeersManager.getOutputPeer(this.peerId),pFlags:{local:!0}};return e||(r.message=""),t?.(r),r=(await this.managers.appMessagesManager.saveMessages([r],{storage:new Map}))[0],r.mid=n,r}getViewportSlice(e){return n_({overflowElement:this.scrollable.container,selector:".bubbles-date-group .bubble:not(.is-date)",extraSize:e?Math.max(700,It.height)*2:void 0,extraMinLength:e?5:void 0})}deleteViewportSlice(e,t){const{invisibleTop:s,invisibleBottom:i}=e,n=s.concat(i);if(!n.length)return;const r=this.log.bindPrefix("VIEWPORT-SLICE");s.length&&(this.setLoaded("top",!1),this.getHistoryTopPromise=void 0,r("will slice top",n)),i.length&&(this.setLoaded("bottom",!1),this.getHistoryBottomPromise=void 0,r("will slice bottom",n));const o=n.map(({element:c})=>$a(c));let l;t||(l=this.createScrollSaver(!!s.length),l.save()),r("slicing mids",o),this.deleteMessagesByIds(o,!1,!0),l?l.restore():s.length&&(this.scrollable.lastScrollPosition=this.scrollable.scrollPosition)}sliceViewport(e){if(dn||this.isHeavyAnimationInProgress&&!e||k6)return;const t=this.getViewportSlice(!0);this.deleteViewportSlice(t)}async setLoaded(e,t,s=!0){if(!(!(this.scrollable.loadedAll[e]!==t)||(this.log.bindPrefix("setLoaded")("change",e,t),this.scrollable.loadedAll[e]=t,this.scrollable.onScroll(),this.scrollable.loadedAll.bottom&&this.scrollable.loadedAll.top&&bk(this.peerId),!s)))return!this.chat.isRestricted&&(e==="bottom"&&this.chat.isBroadcast&&this.chat.type===we.Chat&&this.toggleSponsoredMessage(t),e==="top"&&t&&this.chat.isBot)?this.renderBotPlaceholder():this.checkIfEmptyPlaceholderNeeded()}async toggleSponsoredMessage(e){const t=this.log.bindPrefix("sponsored-"+(Math.random()*1e3|0));t("checking",e);const{mid:s}=this.generateLocalMessageId(_0),i=ps(this.peerId,s);if(e){const n=this.getMiddleware(()=>this.scrollable.loadedAll.bottom&&this.getSponsoredMessagePromise===r),r=this.getSponsoredMessagePromise=this.managers.appMessagesManager.getSponsoredMessage(this.peerId).then(o=>{if(!n()||o._==="messages.sponsoredMessagesEmpty")return;const l=o.messages[0];if(!l){t("no message");return}const c=this.generateLocalFirstMessage(!1,d=>{d.message="",d.from_id={_:"peerUser",user_id:Wt},d.pFlags.sponsored=!0,d.pFlags.invert_media=!0,d.sponsoredMessage=l;const u=l.media,h={_:"webPage",id:d.mid,pFlags:{has_large_media:!!u||void 0},url:"",display_url:"",hash:0,description:l.message,entities:l.entities,document:u?.document,photo:u?.photo};d.media={_:"messageMediaWebPage",pFlags:{force_large_media:!!u||void 0},webpage:h}},_0);return Promise.all([c,this.getHistoryTopPromise,this.messagesQueuePromise]).then(([d])=>{if(n())return t("rendering",d),this.performHistoryResult({history:[d]},!1)})}).finally(()=>{this.getSponsoredMessagePromise===r&&(this.getSponsoredMessagePromise=void 0)})}else t("clearing rendered",s),this.getSponsoredMessagePromise=void 0,this.deleteMessagesByIds([i],!1)}async renderBotPlaceholder(){const e=this.log.bindPrefix("bot placeholder"),t=this.getMiddleware(),s=await this.managers.acknowledged.appProfileManager.getProfile(this.peerId.toUserId());e("getting profile, cached:",s.cached);const i=s.result.then(async n=>{if(!t())return;if(!n.bot_info?.description)return e.warn("no description"),this.checkIfEmptyPlaceholderNeeded();const r=await this.generateLocalFirstMessage(!1,l=>{const c=n.bot_info;l.message=c.description,c.description_document&&(l.media={_:"messageMediaDocument",document:c.description_document,pFlags:{}}),c.description_photo&&(l.media={_:"messageMediaPhoto",photo:c.description_photo,pFlags:{}})});return t()?(e("rendering"),{renderPromise:this.processLocalMessageRender(r,!s.cached).then(()=>{e("done")})}):void 0});if(s.cached)return i}async checkIfEmptyPlaceholderNeeded(){if(this.scrollable.loadedAll.top&&this.scrollable.loadedAll.bottom&&this.emptyPlaceholderBubble===void 0&&(this.chat.isRestricted||Object.keys(this.bubbles).length&&!this.getRenderedLength()||this.chat.type===we.Scheduled&&!this.getRenderedLength()||!(await this.chat.getHistoryStorage()).count)){this.log("inject empty peer placeholder");const e=await this.generateLocalFirstMessage(!0);return{renderPromise:this.processLocalMessageRender(e)}}}getHistory1(e,t,s,i,n){const r=this.getMiddleware(n?void 0:()=>(t?this.getHistoryTopPromise:this.getHistoryBottomPromise)===l),o=this.getHistory(e,t,s,i,n,r),l=o.then(c=>c&&(c.waitPromise||c.promise));return t?this.getHistoryTopPromise=l:this.getHistoryBottomPromise=l,l.then(()=>{r()&&(t?this.getHistoryTopPromise=void 0:this.getHistoryBottomPromise=void 0,n||this.chat.type===we.Chat&&setTimeout(()=>{t?this.loadMoreHistory(!0,!0):this.loadMoreHistory(!1,!0)},0))}),o}async getHistory(e=Ci,t=!1,s=!1,i,n=!1,r){const o=this.peerId,l=this.chat.isBroadcast,c=Math.min(40,It.height/40|0);let u=l?20:this.getRenderedHistory(void 0,!0).length>0?Math.max(35,c):c,h=0;s&&(h=u,t||(u=0));let p;if(i&&!s)if(this.chat.type===we.Pinned)p=[i];else{const L=(await this.chat.getHistoryStorage()).history,E=L.slice;if(E.isEnd(uc.Bottom)&&!E.isEnd(uc.Both)){const{mid:x,peerId:R}=ti(i),B=L.sliceMe(x,0,u);B?p=[i,...B.slice.map(N=>ps(R,N))]:p=E.slice(0,u).map(N=>ps(R,N));for(let N=p.length-1;N>=0&&this.chat.getMessage(p[N])?.grouped_id;--N)p.splice(N,1);u=Math.max(0,u-p.length),e=p[p.length-1]||e}}let m=await this.requestHistory(e,u,h),g;this.log("i vin brehnya",m,e,u,h);const f=!!p?.length,v=this.isFirstLoad&&!m.cached&&(f||u>0);f&&(g=m.result,m={cached:!0,result:Promise.resolve({history:p.map(C=>ti(C).mid)})}),this.isFirstLoad=!1;const y=async C=>{C.isEnd?.top&&await this.managers.appProfileManager.getProfileByPeerId(o)},w=C=>vi().then(()=>y(C)).then(()=>(!f&&i&&C.history.unshift(ti(i).mid),this.performHistoryResult(C,t))),b=C=>Promise.resolve(C).then(E=>{if(r&&!r())throw qf;if(n){this.scrollable.onScroll();return}return w(E)},E=>{throw this.log.error("getHistory error:",E),E});let S,_;if(!m.cached)_=!1,S=b(m.result);else{if(n)return this.scrollable.onScroll(),null;_=!0,S=w(await m.result)}const M=f?b(g):S;if(v&&wt.isAvailable("animations")){let C=f?2:1;this.messagesQueueOnRenderAdditional=()=>{if(this.log("messagesQueueOnRenderAdditional"),--C)return;this.messagesQueueOnRenderAdditional=void 0,this.animateAsLadder(i,p,f,h,e).then(()=>{setTimeout(()=>{this.loadMoreHistory(t,!0)},0)})}}else this.messagesQueueOnRenderAdditional=void 0;return n?null:{cached:_,promise:S,waitPromise:M}}async setUnreadDelimiter(){if(!(this.chat.type===we.Chat||this.chat.type===we.Discussion)||this.attachedUnreadBubble)return;const e=this.getMiddleware(),{peerId:t,threadId:s}=this.chat,i=await this.chat.getHistoryMaxId();let n=await this.managers.appMessagesManager.getReadMaxIdIfUnread(t,s);if(!n||!e()||(n=this.getRenderedHistory("asc",!0).filter(o=>!this.getBubble(o).classList.contains("is-out")).map(o=>ti(o).mid).find(o=>o>n),!n))return;const r=this.getBubble(t,n);r&&(this.firstUnreadBubble&&this.firstUnreadBubble!==r&&(this.firstUnreadBubble.classList.remove("is-first-unread"),this.firstUnreadBubble=null),n!==i&&r.classList.add("is-first-unread"),this.firstUnreadBubble=r,this.attachedUnreadBubble=!0)}deleteEmptyDateGroups(){let e=!1;for(const t in this.dateMessages){const s=this.dateMessages[t];s.groupsLength||(s.container.remove(),this.stickyIntersector?.unobserve(s.container,s.div),delete this.dateMessages[t],e=!0)}e&&(Object.keys(this.dateMessages).length||this.container.classList.remove("has-groups"),this.checkIfEmptyPlaceholderNeeded(),this.setStickyDateManually())}}function dP(a){if(a){const s=document.createElement("span");return s.classList.add("bubble-tail"),s}const e=document.createElementNS("http://www.w3.org/2000/svg","svg");e.setAttributeNS(null,"viewBox","0 0 11 20"),e.setAttributeNS(null,"width","11"),e.setAttributeNS(null,"height","20"),e.classList.add("bubble-tail");const t=document.createElementNS("http://www.w3.org/2000/svg","use");return t.setAttributeNS(null,"href","#message-tail-filled"),e.append(t),e}class hP extends mi{constructor(e,t,s){super("popup-delete-chat",{title:`Send Message${t.length>1?"s":""} Now`,description:t.length>1?"Send "+t.length+" messages now?":"Send message now?",buttons:[{langKey:"Send",callback:()=>{s&&s(),this.managers.appMessagesManager.sendScheduledMessages(e,t)}}]}),this.show()}}function ml(){window.getSelection?window.getSelection().empty?window.getSelection().empty():window.getSelection().removeAllRanges&&window.getSelection().removeAllRanges():document.selection&&document.selection.empty()}const B6=window.matchMedia("(display-mode: standalone)").matches,M0=a=>[...a.values()].reduce((e,t)=>e+t.size,0);class uP extends pn{constructor(e){super(!1),this.selectedMids=new Map,this.isSelecting=!1,this.onMouseDown=t=>{const s=ne(t.target,this.targetLookupClassName);if(t.button!==0||this.verifyTarget&&!this.verifyTarget(t,s))return;const i=new Map;let n,r=s;const o=(h,p=!0)=>{const m=+h.dataset.mid;if(!m||!h.dataset.peerId)return;const g=h.dataset.peerId.toPeerId();mr(r)||(r=h);let f=i.get(g);if(f||i.set(g,f=new Set),f.has(m))return;const v=this.isMidSelected(g,m);if(n===void 0&&(n=!v),f.add(m),n&&!v||!n&&v){const y=M0(i);if(this.toggleByElement&&p){y<2&&Mi(h,r)&&(r=h);const w=this.getElementsBetween(r,h);w.length&&w.forEach(b=>{o(b,!1)})}if(this.selectedMids.size)this.toggleByElement&&this.toggleByElement(h);else if(y===2&&this.toggleByMid)for(const[w,b]of i)for(const S of b)this.toggleByMid(w,S)}};let l=!1;const c=h=>{l||(ml(),l=!0,document.body.classList.add("no-select"));const p=this.getElementFromTarget(h.target);if(p){if(this.verifyMouseMoveTarget&&!this.verifyMouseMoveTarget(h,p,n)){this.listenerSetter.removeManual(this.listenElement,"mousemove",c),this.listenerSetter.removeManual(document,"mouseup",d,u);return}o(p)}},d=h=>{document.body.classList.remove("no-select"),i.size&&J(window,_e,{capture:!0,once:!0,passive:!1}),this.listenerSetter.removeManual(this.listenElement,"mousemove",c),ml()},u={once:!0};this.listenerSetter.add(this.listenElement)("mousemove",c),this.listenerSetter.add(document)("mouseup",d,u)},this.getElementsBetween=(t,s)=>{if(t===s)return[];const i=t.getBoundingClientRect(),n=s.getBoundingClientRect(),o=(i.top-n.top||i.left-n.left)<0,l=ne(t,this.lookupBetweenParentClassName);if(!l)return[];const c=Array.from(l.querySelectorAll(this.lookupBetweenElementsQuery));let d=c.indexOf(t),u=c.indexOf(s);return o||([u,d]=[d,u]),c.slice(d+1,u)},this.cancelSelection=t=>{t&&(this.doNotAnimate=!0),this.onCancelSelection?.(),this.selectedMids.clear(),this.toggleSelection(),ml(),t&&(this.doNotAnimate=void 0)},Nt(this,e),this.navigationType="multiselect-"+xu()}attachListeners(e,t){if(this.listenElement&&this.listenerSetter.removeAll(),this.listenElement=e,this.listenerSetter=t,!!e){if(pt){t.add(e)("touchend",()=>{this.isSelecting&&(this.selectedText=SI())}),Er({element:e,callback:s=>{if(this.isSelecting||this.verifyTouchLongPress&&!this.verifyTouchLongPress())return;this.onTouchLongPress?.(s),document.body.classList.add("no-select"),e.addEventListener("touchend",n=>{_e(n),document.body.classList.remove("no-select")},{once:!0,capture:!0}),wr&&B6&&e.addEventListener("mousedown",_e,{once:!0,capture:!0}),ml(),_e(s);const i=this.getElementFromTarget(s.target);i&&this.toggleByElement(i)},listenerSetter:t});return}t.add(e)("mousedown",this.onMouseDown)}}isElementShouldBeSelected(e){return this.isMidSelected(e.dataset.peerId.toPeerId(),+e.dataset.mid)}appendCheckbox(e,t){e.prepend(t.label)}toggleElementCheckbox(e,t){const s=!!this.getCheckboxInputFromElement(e);if(t){if(s)return!1;const i=new _t({name:e.dataset.mid,round:!0});this.isSelecting&&this.isElementShouldBeSelected(e)&&(i.input.checked=!0,e.classList.add("is-selected")),this.appendCheckbox(e,i)}else s&&(this.getCheckboxInputFromElement(e).parentElement.remove(),Dt({element:e,className:"is-selected",forwards:!1,duration:200}));return!0}getCheckboxInputFromElement(e){return e.firstElementChild?.tagName==="LABEL"&&e.firstElementChild.firstElementChild}async updateContainer(e=!1){const t=this.selectedMids.size;if(!t&&!e)return;let s=!t,i=!t,n=!t,r=!t;if(this.isStories){s=!0,n=!0;const o=this.selectedMids.keys().next().value,l=await this.managers.appStoriesManager.cantPinDeleteStories(o,Array.from(this.selectedMids.get(o)));r=l.cantPin,i=l.cantDelete}else for(const[o,l]of this.selectedMids){const c=this.getStorageKey(o),d=await this.managers.appMessagesManager.cantForwardDeleteMids(c,Array.from(l));if(s=d.cantForward,i=d.cantDelete,s&&i)break}this.onUpdateContainer?.(s,i,n,r)}getStorageKey(e){return`${e}_${this.isScheduled?"scheduled":"history"}`}getSelectedMids(){return va([...this.selectedMids.values()].map(e=>[...e])).sort((e,t)=>e-t)}getSelectedMessages(){const e=[];return this.selectedMids.forEach((t,s)=>{const i=this.getStorageKey(s),n=Array.from(t).map(r=>this.managers.appMessagesManager.getMessageFromStorage(i,r));e.push(...n)}),Promise.all(e)}toggleSelection(e=!0,t=!1){const s=this.isSelecting,i=this.selectedMids.size;if(this.isSelecting=!!i||t,s===this.isSelecting)return!1;this.dispatchEvent("toggle",this.isSelecting),pt||(this.listenElement.classList.toggle("no-select",this.isSelecting),s&&ml()),Fa();const n=!!i||t,r=this.onToggleSelection?.(n,!this.doNotAnimate);return wr||(n?Pt.pushItem({type:this.navigationType,onPop:()=>{this.cancelSelection()}}):Pt.removeByType(this.navigationType)),t&&(r||Promise.resolve()).then(()=>this.updateContainer(t)),!0}cleanup(){this.doNotAnimate=!0,this.selectedMids.clear(),this.toggleSelection(!1),this.doNotAnimate=void 0}updateElementSelection(e,t){this.toggleElementCheckbox(e,!0);const s=this.getCheckboxInputFromElement(e);s.checked=t,this.toggleSelection(),this.updateContainer(),Dt({element:e,className:"is-selected",forwards:t,duration:200})}isMidSelected(e,t){return!!this.selectedMids.get(e)?.has(t)}length(){return M0(this.selectedMids)}toggleMid(e,t,s){let i=this.selectedMids.get(e);return s||s===void 0&&i?.has(t)?i&&(i.delete(t),i.size||this.selectedMids.delete(e)):(i||(i=new Set,this.selectedMids.set(e,i)),i.add(t)),!0}deleteSelectedMids(e,t,s){const i=this.selectedMids.get(e);if(!i)return;t.forEach(r=>{i.delete(r)}),i.size||this.selectedMids.delete(e);const n=()=>{this.updateContainer(),this.toggleSelection()};return s||n(),n}}class D6 extends uP{constructor(e,t,s){super({managers:t,verifyTarget:(i,n)=>!!n&&this.isSelecting,getElementFromTarget:i=>ne(i,"search-super-item"),targetLookupClassName:"search-super-item",lookupBetweenParentClassName:"tabs-tab",lookupBetweenElementsQuery:".search-super-item"}),this.searchSuper=e,this.toggleByElement=i=>{const n=+i.dataset.mid,r=i.dataset.peerId.toPeerId();this.toggleMid(r,n)&&this.updateElementSelection(i,this.isMidSelected(r,n))},this.toggleByMid=(i,n)=>{const r=this.searchSuper.mediaTab.contentTab.querySelector(`.search-super-item[data-peer-id="${i}"][data-mid="${n}"]`);this.toggleByElement(r)},this.onDeleteStoriesClick=async i=>{const n=[...this.selectedMids.keys()][0];i||(i=[...this.selectedMids.get(n)]),await Rt({titleLangKey:i.length===1?"DeleteStoryTitle":"DeleteStoriesTitle",descriptionLangKey:i.length===1?"DeleteStorySubtitle":"DeleteStoriesSubtitle",descriptionLangArgs:[i.length],button:{langKey:"Delete",isDanger:!0}}),this.cancelSelection(),this.managers.appStoriesManager.deleteStories(n,i)},this.onPinClick=(i,n)=>{const r=[...this.selectedMids.keys()][0];i||(i=[...this.selectedMids.get(r)]);const o=this.managers.appStoriesManager.togglePinned(r,i,n);this.cancelSelection(),o.then(()=>{i.length===1?$e({langPackKey:n?"StoryPinnedToProfile":"StoryArchivedFromProfile"}):$e({langPackKey:n?"StorySavedTitle":"StoryArchived",langPackArguments:[i.length]})})},this.onPinToTopClick=(i,n)=>{const r=[...this.selectedMids.keys()][0]||this.searchSuper.searchContext.peerId,o=this.managers.appStoriesManager.togglePinnedToTop(r,i,n);this.cancelSelection(),o.catch(l=>{l.type==="STORY_ID_TOO_MANY"&&$e({langPackKey:"StoriesPinLimit",langPackArguments:[+l.message]})})},this.onUpdateContainer=(i,n,r,o)=>{const l=this.length();St(this.selectionCountEl,P(this.isStories?"StoriesCount":"messages",[l])),this.selectionPinBtn.classList.toggle("hide",!this.isStories||o),this.selectionGotoBtn.classList.toggle("hide",this.isStories||l!==1),this.selectionForwardBtn.classList.toggle("hide",i),this.selectionDeleteBtn&&this.selectionDeleteBtn.classList.toggle("hide",n)},this.onToggleSelection=(i,n)=>{if(Dt({element:this.searchSuper.navScrollableContainer,className:"is-selecting",forwards:i,duration:n?200:0,onTransitionEnd:()=>{this.isSelecting||(this.selectionContainer.remove(),this.selectionContainer=this.selectionForwardBtn=this.selectionDeleteBtn=null,this.selectedText=void 0)}}),Dt({element:this.searchSuper.container,className:"is-selecting",forwards:i,duration:200}),this.isSelecting&&!this.selectionContainer){const r="search-super-selection";this.selectionContainer=document.createElement("div"),this.selectionContainer.classList.add(r+"-container");const o=yt(`close ${r}-cancel`,{noRipple:!0});J(o,()=>this.cancelSelection(),{listenerSetter:this.listenerSetter,once:!0}),this.selectionCountEl=document.createElement("div"),this.selectionCountEl.classList.add(r+"-count");const l={listenerSetter:this.listenerSetter};this.selectionPinBtn=yt(`${this.isStoriesArchive?"pin":"unpin"} ${r}-pin`),J(this.selectionPinBtn,()=>this.onPinClick(void 0,this.isStoriesArchive),l),this.selectionGotoBtn=yt(`message ${r}-goto`),J(this.selectionGotoBtn,()=>{const d=[...this.selectedMids.keys()][0],u=[...this.selectedMids.get(d)][0];this.cancelSelection(),Ce.setInnerPeer({peerId:d,lastMsgId:u,threadId:this.searchSuper.mediaTab.type==="saved"?this.searchSuper.searchContext.peerId:this.searchSuper.searchContext.threadId})},l),this.selectionForwardBtn=yt(`forward ${r}-forward`),J(this.selectionForwardBtn,()=>{const d={};for(const[u,h]of this.selectedMids)d[u]=Array.from(h).sort((p,m)=>p-m);ue.createPopup(kr,d,()=>{this.cancelSelection()})},l),this.isPrivate&&(this.selectionDeleteBtn=yt(`delete danger ${r}-delete`),J(this.selectionDeleteBtn,()=>{if(this.isStories){this.onDeleteStoriesClick();return}const d=this.searchSuper.searchContext.peerId;ue.createPopup(Md,d,this.getSelectedMids(),we.Chat,()=>{this.cancelSelection()})},l)),this.selectionContainer.append(...[o,this.selectionCountEl,this.selectionPinBtn,this.selectionGotoBtn,this.selectionForwardBtn,this.selectionDeleteBtn].filter(Boolean));const c=this.selectionContainer;c.style.opacity="0",this.searchSuper.navScrollableContainer.append(c),c.offsetLeft,c.style.opacity=""}},this.isPrivate=!e.showSender,!pt&&this.attachListeners(e.container,s)}toggleSelection(e=!0,t=!1){const s=super.toggleSelection(e,t);return s&&e&&Array.from(this.searchSuper.tabsContainer.querySelectorAll(".search-super-item")).forEach(n=>{this.toggleElementCheckbox(n,this.isSelecting)}),s}}class $6 extends uP{constructor(e,t,s,i){super({managers:i,getElementFromTarget:n=>ne(n,"grouped-item")||ne(n,"bubble"),verifyTarget:(n,r)=>!(!this.selectedMids.size&&!n.target.classList.contains("bubble")&&!n.target.classList.contains("document-selection")&&r),verifyMouseMoveTarget:(n,r,o)=>!(n.target!==r&&!n.target.classList.contains("document-selection")&&o===void 0&&!this.selectedMids.size),verifyTouchLongPress:()=>!this.chat.input.recording,targetLookupClassName:"bubble",lookupBetweenParentClassName:"bubbles-inner",lookupBetweenElementsQuery:".bubble:not(.is-multiple-documents), .grouped-item",onTouchLongPress:()=>{const{replySwipeHandler:n}=this.chat.bubbles;n?.reset()}}),this.chat=e,this.bubbles=t,this.input=s,this.toggleByElement=n=>{if(!this.canSelectBubble(n))return;const r=+n.dataset.mid,o=n.dataset.peerId.toPeerId();if(n.classList.contains("is-grouped")){if(!this.isGroupedBubbleSelected(n)){const d=this.selectedMids.get(o);d&&this.getMidsFromGroupContainer(n).forEach(({mid:h})=>d.delete(h))}this.bubbles.getBubbleGroupedItems(n).map(this.toggleByElement);return}if(!this.toggleMid(o,r))return;if(n.classList.contains("grouped-item")){const d=ne(n,"bubble"),u=this.isGroupedBubbleSelected(d),h=this.isGroupedMidsSelected(d);(h||u)&&this.updateElementSelection(d,h)}this.updateElementSelection(n,this.isMidSelected(o,r))},this.toggleByMid=async(n,r)=>{const o=await this.bubbles.getMountedBubble(ps(n,r));o&&this.toggleByElement(o.bubble)},this.onToggleSelection=async(n,r)=>{const{needTranslateX:o,widthFrom:l,widthTo:c}=await this.chat.input.center(r);Dt({element:this.listenElement,className:"is-selecting",forwards:n,duration:r?200:0,onTransitionEnd:()=>{this.isSelecting||(this.selectionInputWrapper.remove(),this.selectionInputWrapper=this.selectionContainer=this.selectionSendNowBtn=this.selectionForwardBtn=this.selectionDeleteBtn=this.selectionLeft=this.selectionRight=null,this.selectedText=void 0)}});const d=l<c?void 0:o*2;if(this.isSelecting){if(!this.selectionContainer){this.selectionInputWrapper=document.createElement("div"),this.selectionInputWrapper.classList.add("chat-input-wrapper","selection-wrapper"),this.selectionContainer=document.createElement("div"),this.selectionContainer.classList.add("selection-container");const u={listenerSetter:this.listenerSetter},h=yt("close",{noRipple:!0});J(h,()=>this.cancelSelection(),{once:!0,listenerSetter:this.listenerSetter}),this.selectionCountEl=document.createElement("div"),this.selectionCountEl.classList.add("selection-container-count"),this.chat.type===we.Scheduled?(this.selectionSendNowBtn=ot("btn-primary btn-transparent btn-short text-bold selection-container-send",{icon:"send2"}),this.selectionSendNowBtn.append(P("MessageScheduleSend")),J(this.selectionSendNowBtn,()=>{ue.createPopup(hP,this.chat.peerId,[...this.selectedMids.get(this.chat.peerId)],()=>{this.cancelSelection()})},u)):(this.selectionForwardBtn=ot("btn-primary btn-transparent text-bold selection-container-forward",{icon:"forward"}),this.selectionForwardBtn.append(P("Forward")),J(this.selectionForwardBtn,()=>{const g={};for(const[f,v]of this.selectedMids)g[f]=Array.from(v).sort((y,w)=>y-w);ue.createPopup(kr,g,()=>{this.cancelSelection()})},u)),this.selectionDeleteBtn=ot("btn-primary btn-transparent danger text-bold selection-container-delete",{icon:"delete"}),this.selectionDeleteBtn.append(P("Delete")),J(this.selectionDeleteBtn,()=>{ue.createPopup(Md,this.chat.peerId,this.getSelectedMids(),this.chat.type,()=>{this.cancelSelection()})},u);const p=this.selectionLeft=document.createElement("div");p.classList.add("selection-container-left"),p.append(h,this.selectionCountEl);const m=this.selectionRight=document.createElement("div");m.classList.add("selection-container-right"),m.append(...[this.selectionSendNowBtn,this.selectionForwardBtn,this.selectionDeleteBtn].filter(Boolean)),d!==void 0&&(p.style.transform=`translateX(${-d}px)`,m.style.transform=`translateX(${d}px)`),this.selectionContainer.append(p,m),this.selectionInputWrapper.style.opacity="0",this.selectionInputWrapper.append(this.selectionContainer),this.input.inputContainer.append(this.selectionInputWrapper),this.selectionInputWrapper.offsetLeft,this.selectionInputWrapper.style.opacity=""}this.selectionLeft.style.transform="",this.selectionRight.style.transform=""}else this.selectionLeft&&d!==void 0&&(this.selectionLeft.style.transform=`translateX(-${d}px)`,this.selectionRight.style.transform=`translateX(${d}px)`)},this.onUpdateContainer=(n,r,o)=>{St(this.selectionCountEl,P("messages",[this.length()])),this.selectionSendNowBtn?.toggleAttribute("disabled",o),this.selectionForwardBtn?.toggleAttribute("disabled",n),this.selectionDeleteBtn?.toggleAttribute("disabled",r)},this.onCancelSelection=async()=>{}}appendCheckbox(e,t){t.label.classList.add("bubble-select-checkbox"),e.classList.contains("document-container")?e.querySelector(".document, audio-element").append(t.label):super.appendCheckbox(e,t)}toggleSelection(e=!0,t=!1){const s=super.toggleSelection(e,t);if(s&&e){const i=this.bubbles.getRenderedHistory("asc");for(const n of i){if(this.bubbles.skippedMids.has(n))continue;const r=this.bubbles.getBubble(n);this.toggleElementCheckbox(r,this.isSelecting)}}return s}toggleElementCheckbox(e,t){if(!this.canSelectBubble(e))return;const s=super.toggleElementCheckbox(e,t);return s&&e.classList.contains("is-grouped")&&this.bubbles.getBubbleGroupedItems(e).forEach(n=>this.toggleElementCheckbox(n,t)),s}isElementShouldBeSelected(e){const t=e.classList.contains("is-grouped");return super.isElementShouldBeSelected(e)&&(!t||this.isGroupedMidsSelected(e))}isGroupedBubbleSelected(e){return this.getCheckboxInputFromElement(e)?.checked}getMidsFromGroupContainer(e){const t=this.chat.bubbles.getBubbleGroupedItems(e);return t.length||t.push(e),t.map(s=>({mid:+s.dataset.mid,peerId:s.dataset.peerId.toPeerId()}))}isGroupedMidsSelected(e){const t=this.getMidsFromGroupContainer(e),s=t.filter(({peerId:i,mid:n})=>this.isMidSelected(i,n));return t.length===s.length}getCheckboxInputFromElement(e){return e.classList.contains("document-container")?e.querySelector("label input"):super.getCheckboxInputFromElement(e)}canSelectBubble(e){return e&&!e.classList.contains("service")&&!e.classList.contains("is-outgoing")&&!e.classList.contains("is-error")&&!e.classList.contains("bubble-first")&&!e.classList.contains("avoid-selection")}}const tl="pinned-container";class Pd{constructor(e){this.floating=!1,Nt(this,e);const{divAndCaption:t,className:s}=this;t?(this.container=t.container,t.title.classList.add(tl+"-title"),t.subtitle.classList.add(tl+"-subtitle"),t.content.classList.add(tl+"-content")):(this.container=document.createElement("div"),this.container.classList.add("pinned-"+this.className)),this.container.classList.add(tl,"hide"),this.btnClose=yt(`close ${tl+"-close"} pinned-${s}-close`,{noRipple:!0}),this.wrapper=document.createElement("div"),this.wrapper.classList.add(tl+"-wrapper",`pinned-${s}-wrapper`),Ei(this.wrapper),this.wrapperUtils=document.createElement("div"),this.wrapperUtils.classList.add(tl+"-wrapper-utils",`pinned-${s}-wrapper-utils`),this.wrapperUtils.append(this.btnClose),this.wrapper.append(...t?Array.from(t.container.children):[],this.wrapperUtils),t&&t.container.append(this.wrapper),this.attachOnCloseEvent(this.btnClose)}destroy(){}attachOnCloseEvent(e){J(e,t=>{_e(t),((this.onClose?this.onClose():null)||Promise.resolve(!0)).then(s=>{s&&this.toggle(!0)})},{listenerSetter:this.listenerSetter})}toggle(e){const t=this.container.classList.contains("hide");if(e===void 0)e=!t;else if(e===t)return;const s=(this.floating||st.isMobile)&&!e;this.container.classList.toggle("is-floating",s),this.container.classList.toggle("hide",e),this.topbar.container.classList.toggle(`is-pinned-${this.className}-shown`,!e),this.topbar.setFloating(),this.topbar.setUtilsWidth()}isVisible(){return!this.container.classList.contains("hide")}isFloating(){return this.container.classList.contains("is-floating")}fill(e){const{message:t}=e;this.container.dataset.peerId=""+t.peerId,this.container.dataset.mid=""+t.mid,this.divAndCaption.fill(e),this.topbar.setUtilsWidth()}}const N6=a=>{const e=[.5,1,1.5,2],t=["playback_05","playback_1x","playback_15","playback_2x"],s=yt(" btn-menu-toggle",{noRipple:!0}),i=()=>{const l=s;let c=e.indexOf(rt.playbackRate);c===-1&&(c=e.indexOf(1));const d=Be(t[c]);l.firstElementChild?l.firstElementChild.replaceWith(d):l.append(d)},n=()=>{const l=e.map((d,u)=>({regularText:d+"x",onClick:()=>{rt.playbackRate=d}})),c=xa({buttons:l});c.classList.add(a.direction,"playback-rate-menu"),n1({el:s,onOpen:a.onPlaybackRateMenuToggle?()=>{a.onPlaybackRateMenuToggle(!0)}:void 0,onClose:a.onPlaybackRateMenuToggle?()=>{a.onPlaybackRateMenuToggle(!1)}:void 0}),i(),s.append(c)},r=l=>{const c=rt.playbackRate,u=e.indexOf(c)+l;u>=0&&u<e.length&&(rt.playbackRate=e[u])},o=()=>s.classList.contains("menu-open");return n(),{element:s,setIcon:i,addRate:r,isMenuOpen:o}};class O6 extends Pd{constructor(e,t,s){super({topbar:e,chat:t,listenerSetter:e.listenerSetter,className:"audio",divAndCaption:new Og("pinned-audio",h=>{St(this.divAndCaption.title,h.title),this.divAndCaption.subtitle.replaceChildren(this.time," • ",h.subtitle)}),onClose:()=>{rt.stop(void 0,!0)},floating:!0,height:52}),this.topbar=e,this.chat=t,this.managers=s,this.onPlaybackParams=h=>{this.playbackRateButton.setIcon(),this.playbackRateButton.element.classList.toggle("active",h.playbackRate!==1),this.repeatEl.querySelector(".button-icon").replaceWith(Be(h.loop?"audio_repeat_single":"audio_repeat","button-icon")),this.repeatEl.classList.toggle("active",h.loop||h.round)},this.onPause=()=>{this.setPlayIcon(!0)},this.onStop=()=>{this.toggle(!0)},this.onMediaPlay=({doc:h,message:p,media:m,playbackParams:g})=>{let f,v;const y=h.type!=="voice"&&h.type!=="round";if(!y)f=new Xt({peerId:p.fromId,fromName:Aa(p.fwd_from)}).element,v=gs(p.date);else{const w=h.attributes.find(b=>b._==="documentAttributeAudio");f=je(w?.title??h.file_name),v=w?.performer?je(w.performer):P("AudioUnknownArtist")}this.repeatEl.classList.toggle("hide",!y),this.onPlaybackParams(g),this.volumeSelector.setGlobalVolume(),this.progressLine.setMedia({media:m,duration:this.duration=h.duration}),this.fill({title:f,subtitle:v,message:p}),this.setPlayIcon(m.paused),this.toggle(!1)},this.divAndCaption.border.remove();const i=yt("fast_rewind active",{noRipple:!0}),n=yt("fast_forward active",{noRipple:!0});this.time=document.createElement("span"),this.time.classList.add("pinned-audio-time");const r=(h,p)=>{J(h,m=>{_e(m),p()},{listenerSetter:this.topbar.listenerSetter})};r(i,()=>{rt.previous()}),r(n,()=>{rt.next()}),this.toggleEl=yt("",{noRipple:!0}),this.toggleEl.classList.add("active","pinned-audio-ico"),r(this.toggleEl,()=>{rt.toggle()}),this.wrapper.prepend(this.wrapper.firstElementChild,i,this.toggleEl,n),this.volumeSelector=new Cm({listenerSetter:this.listenerSetter,vertical:!0,useGlobalVolume:"auto"});const o=document.createElement("div");o.classList.add("progress-line-container"),o.append(this.volumeSelector.container);const l=document.createElement("div");l.classList.add("pinned-audio-volume-tunnel"),this.volumeSelector.btn.classList.add("pinned-audio-volume","active"),this.volumeSelector.btn.prepend(l),this.volumeSelector.btn.append(o),this.repeatEl=yt("audio_repeat",{noRipple:!0}),r(this.repeatEl,()=>{const h=rt.getPlaybackParams();h.round?h.loop?(rt.round=!1,rt.loop=!1):rt.loop=!rt.loop:rt.round=!0}),this.playbackRateButton=N6({direction:"bottom-left"}),this.wrapperUtils.prepend(this.volumeSelector.btn,this.playbackRateButton.element,this.repeatEl);const c=document.createElement("div");c.classList.add("pinned-audio-progress-wrapper"),this.progressLine=new Jc({withTransition:!0,useTransform:!0,onTimeUpdate:h=>{this.time.textContent=bn(h,!0)}}),this.progressLine.container.classList.add("pinned-audio-progress"),c.append(this.progressLine.container),this.wrapper.insertBefore(c,this.wrapperUtils);const d=h=>{Ae.invokeVoid("toggleUninteruptableActivity",{activity:"PlayingMedia",active:h})};this.topbar.listenerSetter.add(rt)("play",()=>{d(!0)}),this.topbar.listenerSetter.add(rt)("pause",()=>{d(!1)}),this.topbar.listenerSetter.add(rt)("stop",()=>{d(!1)}),this.topbar.listenerSetter.add(rt)("play",this.onMediaPlay),this.topbar.listenerSetter.add(rt)("pause",this.onPause),this.topbar.listenerSetter.add(rt)("stop",this.onStop),this.topbar.listenerSetter.add(rt)("playbackParams",this.onPlaybackParams);const u=rt.getPlayingDetails();u&&(this.onMediaPlay(u),this.onPlaybackParams(u.playbackParams))}destroy(){super.destroy(),this.progressLine?.removeListeners()}setPlayIcon(e){Wo(this.toggleEl,e?"play":"pause")}}class ru{constructor(e,t,s,i){this.peerId=e,this.mid=t,this.unpin=s,this.onConfirm=i,this.construct()}async construct(){const{peerId:e,mid:t,unpin:s,onConfirm:i}=this;let n,r,o;const l=[],c=[],d=ue.MANAGERS,u=await d.appPeersManager.canPinMessage(e),h=(m,g,f,v)=>{setTimeout(()=>{let y;s&&!t?u?y=d.appMessagesManager.unpinAllMessages(e):y=d.appMessagesManager.hidePinnedMessages(e):y=d.appMessagesManager.updatePinnedMessage(e,t,s,v,f),i&&y.then(i)},300)};if(s){let m="UnpinMessage";t?(n="UnpinMessageAlertTitle",r="Chat.Confirm.Unpin"):u?(n="Popup.Unpin.AllTitle",r="Chat.UnpinAllMessagesConfirmation",o=[""+(await d.appMessagesManager.getPinnedMessagesCount(e)||1)]):(n="Popup.Unpin.HideTitle",r="Popup.Unpin.HideDescription",m="Popup.Unpin.Hide"),l.push({langKey:m,isDanger:!0,callback:h})}else{n="PinMessageAlertTitle";const m="PinMessage";e.isAnyChat()?(l.push({langKey:m,callback:(g,f)=>h(g,f,!1,!f.size)}),await d.appChatsManager.isBroadcast(e.toChatId())?r="PinMessageAlertChannel":(r="PinMessageAlert",c.push({text:"PinNotify",checked:!0}))):(r="PinMessageAlertChat",e===I.myId?l.push({langKey:m,callback:h}):(l.push({langKey:m,callback:(g,f)=>h(g,f,!f.size)}),c.push({text:"PinAlsoFor",textArgs:[await qe({peerId:e})],checked:!0})))}Go(l),ue.createPopup(mi,"popup-delete-chat",{peerId:e,titleLangKey:n,descriptionLangKey:r,descriptionLangArgs:o,buttons:l,checkboxes:c}).show()}}const ho=1,Xf=2,rc="pinned-message-border";class U6{constructor(){this.drawRect=(e,t,s,i,n)=>`M${e},${t+n}a${n},${n},0,0,1,${s},0v${i-2*n}a${n},${n},0,0,1,${-s},0Z`,this.getClipPath=(e,t,s)=>{let n="";if(s===2)n=this.drawRect(0,0,Xf,t,1)+this.drawRect(0,t+ho*2,Xf,t,1);else for(let r=0;r<s;++r)n+=this.drawRect(0,(t+ho)*r,Xf,t,1);return this.clipPath||(this.clipPath=document.createElementNS("http://www.w3.org/2000/svg","clipPath"),this.path=document.createElementNS("http://www.w3.org/2000/svg","path"),this.clipPath.append(this.path)),this.clipPath.id=e,this.path.setAttributeNS(null,"d",n),this.clipPath},this.getBarHeight=(e,t)=>{let s;return e<=1?s=32:e===2?s=15:e===3?s=10:(e===4||e>3)&&(s=8),s},this.getMarkHeight=(e,t)=>{let s;return e<=1?s=32:e===2?s=15:e===3?s=10:(e===4||e>3)&&(s=8),s},this.getMarkTranslateY=(e,t,s)=>{if(s===1)return 0;if(s===2)return e?t+ho:0;if(s===3){if(e){if(e===1)return t+ho}else return 0;return t*2+ho*2+1}else return(t+ho)*e},this.getTrackTranslateY=(e,t,s,i)=>t<=4||e<=1?0:e>=t-2?i-32-s:(e-2)*s+e*ho,this.getTrackHeight=(e,t)=>e<=3?32:t*e+ho*(e-1)}render(e,t){if(this.border||(this.border=document.createElement("div"),this.border.classList.add(rc),this.wrapper=document.createElement("div"),this.border.append(this.wrapper)),e===1)return this.count!==e&&(this.wrapper.className=rc+"-wrapper-1",this.border.classList.remove(rc+"-mask"),this.wrapper.replaceChildren(),this.wrapper.style.cssText=""),this.border;const s=this.getBarHeight(e,t),i=this.getMarkHeight(e,t),n=this.getTrackHeight(e,s),r=`clipPath_${e}`,o=this.getClipPath(r,s,e),l=this.getMarkTranslateY(t,s,e),c=this.getTrackTranslateY(t,e,s,n);return this.border.classList.toggle(rc+"-mask",e>4),t<=1?(this.border.classList.add("mask-bottom"),this.border.classList.remove("mask-top")):t>=e-2?(this.border.classList.add("mask-top"),this.border.classList.remove("mask-bottom")):this.border.classList.add("mask-top","mask-bottom"),this.wrapper.className=rc+"-wrapper",this.wrapper.style.cssText=`clip-path: url(#${r}); width: 2px; height: ${n}px; transform: translateY(-${c}px);`,this.svg||(this.svg=document.createElementNS("http://www.w3.org/2000/svg","svg"),this.svg.setAttributeNS(null,"height","0"),this.svg.setAttributeNS(null,"width","0"),this.defs=document.createElementNS("http://www.w3.org/2000/svg","defs"),this.defs.append(o),this.svg.append(this.defs),this.mark=document.createElement("div"),this.mark.classList.add(rc+"-mark")),this.svg.parentElement||this.wrapper.append(this.svg,this.mark),this.mark.style.cssText=`height: ${i}px; transform: translateY(${l}px);`,this.count=e,this.index=t,this.border}}function H6(a,e,t,s){if(pt){let i;const n={passive:!0};s.add(a)("touchstart",l=>{if(l.touches.length>1){o();return}i=l.touches[0].clientY,s.add(a)("touchmove",r,n),s.add(a)("touchend",o,n)},n);const r=l=>{const c=l.touches[0].clientY;c<i&&t(),i=c},o=()=>{s.removeManual(a,"touchmove",r,n),s.removeManual(a,"touchend",o,n)}}else s.add(a)("wheel",i=>{i.deltaY>0&&t()},{passive:!0})}const G6=!1,Br=class Br{constructor(e,t,s){this.topbar=e,this.chat=t,this.managers=s,this.pinnedMaxMid=0,this.pinnedMid=0,this.pinnedIndex=-1,this.wasPinnedIndex=0,this.wasPinnedMediaIndex=0,this.locked=!1,this.waitForScrollBottom=!1,this.count=0,this.mids=[],this.offsetIndex=0,this.loading=!1,this.loadedBottom=!1,this.loadedTop=!1,this.hidden=!1,this.listenerSetter=new $t,this.log=Ni("PM"),this.debug=!0,this.isStatic=!1;const i=new g1("pinned-message");this.pinnedMessageContainer=new Pd({topbar:e,chat:t,listenerSetter:this.listenerSetter,className:"message",divAndCaption:i,onClose:async()=>(await s.appPeersManager.canPinMessage(this.chat.peerId)?ue.createPopup(ru,this.chat.peerId,this.pinnedMid,!0):ue.createPopup(ru,this.chat.peerId,0,!0),!1),floating:G6,height:52}),this.pinnedMessageBorder=new U6,i.border.replaceWith(this.pinnedMessageBorder.render(1,0)),this.animatedSubtitle=new nd,i.subtitle.append(this.animatedSubtitle.container),this.animatedMedia=new nd,this.animatedMedia.container.classList.add("pinned-message-media-container"),i.content.prepend(this.animatedMedia.container),this.animatedCounter=new ad({reverse:!0}),i.title.append(P("PinnedMessage")," ",this.animatedCounter.container);const n=this.pinnedMessageContainer.btnClose.cloneNode(!0);this.pinnedMessageContainer.attachOnCloseEvent(n),i.container.prepend(n),this.btnOpen=yt("pinlist pinned-container-close pinned-message-pinlist",{noRipple:!0}),this.pinnedMessageContainer.wrapperUtils.prepend(this.btnOpen),J(this.btnOpen,r=>{_e(r),this.topbar.openPinned(!0)},{listenerSetter:this.listenerSetter}),this.listenerSetter.add(I)("peer_pinned_messages",({peerId:r})=>{r===this.chat.peerId&&(this.hidden&&this.pinnedMessageContainer.toggle(this.hidden=!1),this.loadedTop=this.loadedBottom=!1,this.pinnedIndex=-1,this.pinnedMid=0,this.count=0,this.mids=[],this.offsetIndex=0,this.pinnedMaxMid=0,this.setCorrectIndex(0))}),this.listenerSetter.add(I)("peer_pinned_hidden",({peerId:r})=>{r===this.chat.peerId&&this.pinnedMessageContainer.toggle(this.hidden=!0)}),this.setPinnedMessage=$i(()=>this._setPinnedMessage(),100,!0,!0),this.setCorrectIndexThrottled=fa(this.setCorrectIndex.bind(this),100,!1),this.isStatic=!this.chat.isPinnedMessagesNeeded()}destroy(){this.animatedMedia.destroy(),this.animatedSubtitle.destroy(),this.animatedCounter.destroy(),this.pinnedMessageContainer.container.remove(),this.pinnedMessageContainer.toggle(!0),this.listenerSetter.removeAll(),this.unsetScrollDownListener(!1)}setCorrectIndex(e){if(this.isStatic||(this.debug&&this.log("setCorrectIndex",e),this.locked||this.hidden)||(this.loadedBottom||this.loadedTop)&&!this.count)return;const t=this.chat.bubbles.getBubbleByPoint("bottom");if(!t)return;const s=t.dataset.mid;s!==void 0&&this.testMid(+s,e)}testMid(e,t){if(this.isStatic||this.hidden)return;let s=this.mids.findIndex(n=>n<=e);if(s!==-1&&!this.isNeededMore(s))s+=this.offsetIndex;else if(this.loadedTop&&e<this.mids[this.mids.length-1])s=this.mids.length-1+this.offsetIndex;else return this.getCurrentIndexPromise??(this.getCurrentIndexPromise=this.getCurrentIndex(e,t!==void 0));if(this.pinnedIndex!==s)return this.waitForScrollBottom&&t!==void 0&&(this.pinnedIndex===0||this.pinnedIndex>s)?void 0:(this.pinnedIndex=s,this.pinnedMid=this.mids.find(n=>n<=e)||this.mids[this.mids.length-1],this.setPinnedMessage())}isNeededMore(e){return this.count>Br.LOAD_COUNT&&(!this.loadedBottom&&e<=Br.LOAD_OFFSET||!this.loadedTop&&this.count-1-e<=Br.LOAD_OFFSET)}async getCurrentIndex(e,t=!0){if(!this.loading){this.loading=!0;try{const s=this.debug?this.log.bindPrefix("getCurrentIndex"):void 0;s&&s("start",e,t);let i=!1;const n=[this.managers.appMessagesManager.getHistory({peerId:this.chat.peerId,inputFilter:{_:"inputMessagesFilterPinned"},offsetId:e,limit:Br.LOAD_COUNT,backLimit:Br.LOAD_COUNT,threadId:this.chat.threadId,needRealOffsetIdOffset:!0}).then(c=>(i=!0,c))];if(!this.pinnedMaxMid){const c=this.managers.appMessagesManager.getPinnedMessage(this.chat.peerId,this.chat.threadId).then(d=>{d.maxId&&(this.pinnedMaxMid=d.maxId,!i&&t&&(this.mids=[this.pinnedMaxMid],this.count=d.count,this.pinnedIndex=0,this.pinnedMid=this.mids[0],this.setPinnedMessage()))});n.push(c)}const r=(await Promise.all(n))[0],o=r.history;let l=o.findIndex(c=>c<=e);l===-1&&(l=o.length),this.offsetIndex=Math.max(0,r.offsetIdOffset)?r.offsetIdOffset-l:0,this.mids=o.slice(),this.count=r.count,this.count||this.pinnedMessageContainer.toggle(!0),this.loadedTop=this.offsetIndex+this.mids.length===this.count,this.loadedBottom=!this.offsetIndex,s&&s("result",e,r,l,this.offsetIndex,this.loadedTop,this.loadedBottom)}catch(s){this.log.error("getCurrentIndex error",s)}this.loading=!1,this.locked?this.testMid(e):t&&this.setCorrectIndex(0),this.getCurrentIndexPromise=void 0}}setScrollDownListener(){this.waitForScrollBottom=!0,this.scrollDownListenerSetter||(this.scrollDownListenerSetter=new $t,H6(this.chat.bubbles.scrollable.container,"bottom",()=>{this.unsetScrollDownListener()},this.scrollDownListenerSetter))}unsetScrollDownListener(e=!0){this.waitForScrollBottom=!1,this.scrollDownListenerSetter&&(this.scrollDownListenerSetter.removeAll(),this.scrollDownListenerSetter=void 0),e&&this.setCorrectIndex(0)}async handleFollowingPinnedMessage(){this.locked=!0,this.debug&&this.log("handleFollowingPinnedMessage");try{this.setScrollDownListener();const e=this.chat.setPeerPromise;e instanceof Promise&&await e,await vi(),this.getCurrentIndexPromise&&await this.getCurrentIndexPromise,this.debug&&this.log("handleFollowingPinnedMessage: unlock"),this.locked=!1}catch(e){this.log.error("handleFollowingPinnedMessage error:",e),this.locked=!1,this.waitForScrollBottom=!1,this.setCorrectIndex(0)}}followPinnedMessage(e){this.chat.getMessage(e)&&(this.chat.setMessageId({lastMsgId:e}),(this.chat.setPeerPromise||Promise.resolve()).then(()=>{this.handleFollowingPinnedMessage(),this.testMid(this.pinnedIndex>=this.count-1?this.pinnedMaxMid:e-1)}))}async _setPinnedMessage(){const e=this.count;if(e){const t=this.pinnedIndex,s=this.chat.getMessage(this.pinnedMid),i=t===0;this.animatedCounter.container.classList.toggle("is-last",i),i||this.animatedCounter.setCount(e-t),this.pinnedMessageContainer.toggle(!1);const n=t>this.wasPinnedIndex;this.debug&&this.log("setPinnedMessage: fromTop",n,t,this.wasPinnedIndex);const r=this.animatedSubtitle.getRow(t),o=this.animatedMedia.getRow(t);o.classList.add("pinned-message-media");const l=[],c=await Eb({titleEl:null,subtitleEl:r,message:s,mediaEl:o,loadPromises:l,animationGroup:this.chat.animationGroup,textColor:"primary-text-color",canTranslate:!s.pFlags.out,middleware:this.animatedSubtitle.getRow(t).middlewareHelper.get()});await Promise.all(l),this.pinnedMessageContainer.container.classList.toggle("is-media",c),this.animatedSubtitle.animate(t,this.wasPinnedIndex),c?(this.animatedMedia.animate(t,this.wasPinnedMediaIndex),this.wasPinnedMediaIndex=t):this.animatedMedia.clearRows(),this.pinnedMessageBorder.render(e,e-t-1),this.wasPinnedIndex=t,this.pinnedMessageContainer.container.dataset.mid=""+s.mid}else this.pinnedMessageContainer.toggle(!0),this.wasPinnedIndex=0;this.pinnedMessageContainer.container.classList.toggle("is-many",this.count>1)}};Br.LOAD_COUNT=50,Br.LOAD_OFFSET=5;let Km=Br;function tw(a){return"+"+bd(a).formatted}class ry extends Zt{async init(){const{peerId:e}=this,t=e.toUserId();this.container.classList.add("edit-peer-container","edit-contact-container");const[s,i]=await Promise.all([this.managers.appUsersManager.isContact(t),this.managers.appPrivacyManager.getPrivacy("inputPrivacyKeyPhoneNumber")]),n=!s;this.setTitle(n?"AddContactTitle":"Edit");{const r=new Oe({noDelimiter:!0}),o=[],l=document.createElement("div");if(l.classList.add("input-wrapper"),this.nameInputField=new Yt({label:"FirstName",name:"contact-name",maxLength:70,required:!0}),this.lastNameInputField=new Yt({label:"LastName",name:"contact-lastname",maxLength:70}),t){const c=await this.managers.appUsersManager.getUser(t);n?(this.nameInputField.setDraftValue(c.first_name),this.lastNameInputField.setDraftValue(c.last_name)):(this.nameInputField.setOriginalValue(c.first_name),this.lastNameInputField.setOriginalValue(c.last_name))}if(l.append(this.nameInputField.container,this.lastNameInputField.container),o.push(this.nameInputField,this.lastNameInputField),this.editPeer=new Ou({peerId:e,inputFields:o,listenerSetter:this.listenerSetter,doNotEditAvatar:!0,middleware:this.middlewareHelper.get()}),this.content.append(this.editPeer.nextBtn),e){const c=document.createElement("div");c.classList.add("avatar-edit"),c.append(this.editPeer.avatarElem.node);const d=new _t({text:"Notifications"});d.input.addEventListener("change",p=>{p.isTrusted&&this.managers.appMessagesManager.togglePeerMute({peerId:e})}),this.listenerSetter.add(I)("notify_settings",async p=>{if(p.peer._!=="notifyPeer")return;const m=it(p.peer.peer);if(m===m){const g=!await this.managers.appNotificationsManager.isMuted(p.notify_settings);g!==d.checked&&(d.checked=g)}});const u=document.createElement("div");u.classList.add("profile-name"),u.append(new Xt({peerId:e}).element);const h=document.createElement("div");if(h.classList.add("profile-subtitle"),h.append(P("EditContact.OriginalName")),r.content.append(c,u,h,l),n){const p=await this.managers.appUsersManager.getUser(t),m=new Fe({icon:"phone",titleLangKey:p.phone?void 0:"MobileHidden",title:p.phone?tw(p.phone):void 0,subtitleLangKey:p.phone?"Phone":"MobileHiddenExceptionInfo",subtitleLangArgs:p.phone?void 0:[new Xt({peerId:e}).element]});r.content.append(m.container)}else{const p=new Fe({checkboxField:d,withCheckboxSubtitle:!0,listenerSetter:this.listenerSetter}),m=!await this.managers.appNotificationsManager.isPeerLocalMuted({peerId:e,respectType:!1});d.checked=m,r.content.append(p.container)}}else r.content.append(l);this.scrollable.append(r.container)}if(n){if(i.some(r=>r._==="privacyValueDisallowAll")&&!i.some(r=>r._==="privacyValueAllowUsers"&&r.users.includes(t))){const r=new Oe({caption:"NewContact.Exception.ShareMyPhoneNumber.Desc",captionArgs:[await qe({peerId:this.peerId})]}),o=this.sharePhoneCheckboxField=new _t({text:"NewContact.Exception.ShareMyPhoneNumber",checked:!0}),l=jr(o);r.content.append(l.container),this.scrollable.append(r.container)}}else{const r=new Oe,o=ot("btn-primary btn-transparent danger",{icon:"delete",text:"PeerInfo.DeleteContact"});J(o,()=>{ue.createPopup(mi,"popup-delete-contact",{peerId:e,titleLangKey:"DeleteContact",descriptionLangKey:"AreYouSureDeleteContact",buttons:Go([{langKey:"Delete",callback:()=>{const l=os([o],!0);this.managers.appUsersManager.deleteContacts([t]).then(()=>{this.close()},()=>{l()})},isDanger:!0}])}).show()},{listenerSetter:this.listenerSetter}),r.content.append(o),this.scrollable.append(r.container)}J(this.editPeer.nextBtn,async()=>{this.editPeer.nextBtn.disabled=!0,this.managers.appUsersManager.addContact(t,this.nameInputField.value,this.lastNameInputField.value,(await this.managers.appUsersManager.getUser(t)).phone,this.sharePhoneCheckboxField?.checked).finally(()=>{this.editPeer.nextBtn.removeAttribute("disabled"),this.close()})},{listenerSetter:this.listenerSetter})}}const V6="assets/audio/";class pP{constructor(e){this.assets=e,this.tempId=0}playSound(e,t=!1){++this.tempId,this.assetName=e;try{const s=this.createAudio();s.autoplay=!0,s.src=V6+e,s.loop=t,Sn(s)}catch(s){console.error("playSound",e,s)}}playSoundIfDifferent(e,t){this.assetName!==e&&this.playSound(e,t)}createAudio(){let{audio:e}=this;return e||(e=this.audio=new Audio,Sn(e),e)}stopSound(){this.audio&&this.audio.pause()}cancelDelayedPlay(){++this.tempId}playSoundWithTimeout(e,t,s){const i=++this.tempId;setTimeout(()=>{this.tempId===i&&this.playSound(e,t)},s)}}let z6;function W6(){return z6??(z6=new pP(["group_call_connect.mp3","group_call_end.mp3","group_call_start.mp3","voip_onallowtalk.mp3"]))}function K6(a){return(!!navigator?.mediaDevices?.getSupportedConstraints())[a]}function mP(){const a={channelCount:2};return["noiseSuppression","echoCancellation","autoGainControl"].forEach(t=>{K6(t)&&(a[t]=!0)}),a}function gP(a){const e={video:{width:{max:1920},height:{max:1080},frameRate:{max:30}}};return a||(e.audio=!0),e}async function fP(a){const e=await navigator.mediaDevices.getDisplayMedia(a),t=e.getVideoTracks()[0];return t.contentHint="text",e}async function Yg(a,e){const t=await navigator.mediaDevices.getUserMedia(a);return t.getTracks().forEach(s=>{s.enabled=!e}),t}window.getStream=Yg;function vP(){const a={main:{},screen:{}};return async e=>{const{isScreen:t,constraints:s}=e,i=a[t?"screen":"main"];let n=i[s.audio?"audio":"video"];n||(n=(t?fP:Yg)(s,e.muted),s.audio&&!i.audio&&(i.audio=n.finally(()=>i.audio=void 0)),s.video&&!i.video&&(i.video=n.finally(()=>i.video=void 0)));try{return await n}catch(r){throw r}}}window.getStreamCached=vP;function sw(){return{width:{min:1280,max:1920},height:{min:720,max:1080},frameRate:{min:24,max:30}}}function Qg(a){a.stop(),md(a,"ended")}const j6=50,yP=100,L0=1,q6=2;class oy{constructor(e=`\r
- `){this.joiner=e,this.lines=[],this.newLine=[]}add(...e){return this.lines.push(...e),this}push(e){return this.newLine.push(e),this}addJoined(e=""){return this.add(this.newLine.join(e)),this.newLine=[],this}join(){return this.lines.join(this.joiner)}finalize(){return this.join()+this.joiner}}function iw(a){return a<<0}function E0(a){return a>>>0}function Y6(a,e=3){if(!a)return 0;const{length:t}=a;let s=0;for(let n=0;n<t;++n)s+=a[n]*a[n];const i=Math.sqrt(s/t)/255;return Math.min(1,i*e)}const bP="9";function Xg(a){return a==="screencast"?"video":a}function Q6(a){const e=[];return e.push("a=candidate:"),e.push(`${a.foundation} ${a.component} ${a.protocol.toUpperCase()} ${a.priority} ${a.ip} ${a.port} typ ${a.type}`),a["rel-addr"]!==void 0&&e.push(` raddr ${a["rel-addr"]} rport ${a["rel-port"]}`),e.push(` generation ${a.generation}`),e.join("")}function wP(a){return a==="application"?"DTLS/SCTP":"UDP/TLS/RTP/SAVPF"}function SP(a,e=bP,t){const s=wP(a);return`m=${Xg(a)} ${e} ${s} ${t.join(" ")}`}class Zg extends oy{addCandidate(e){return this.add(Q6(e))}addHeader(e,t){const s=t.join(" ");return this.add("v=0",`o=- ${e} 2 IN IP4 0.0.0.0`,"s=-","t=0 0","a=extmap-allow-mixed",`a=group:BUNDLE ${s}`,"a=ice-options:trickle","a=msid-semantic:WMS *")}addTransport(e,t){this.add(`a=ice-ufrag:${e.ufrag}`,`a=ice-pwd:${e.pwd}`,"a=ice-options:trickle");for(const s of e.fingerprints)this.add(`a=fingerprint:${s.hash} ${s.fingerprint}`,`a=setup:${s.setup}`);if(!t&&e.candidates)for(const s of e.candidates)this.addCandidate(s);return this}addSsrc(e){let t="stream",{type:s,sourceGroups:i}=e;const n=E0(e.source);t+=n,s+=n;const r=()=>{this.add(`a=msid:${t} ${s}`)},o=l=>{this.add(`a=ssrc:${l} cname:${t}`,`a=ssrc:${l} msid:${t} ${s}`,`a=ssrc:${l} mslabel:${t}`,`a=ssrc:${l} label:${s}`)};return r(),i?.length?i.forEach(l=>{if(l.sources.length){const c=l.sources.map(E0);this.add(`a=ssrc-group:${l.semantics} ${c.join(" ")}`),c.forEach(o)}}):o(n),this}addSsrcEntry(e,t,s){const i=(...f)=>this.add(...f),{type:n,mid:r,direction:o,port:l}=e,c=t.transport,d=n==="application",u=d?void 0:t[n],h=o==="inactive";if(e.shouldBeSkipped(s))return i(`m=${Xg(n)} 0 ${wP(n)} 0`,"c=IN IP4 0.0.0.0","a=inactive",`a=mid:${r}`);const p=d?[{id:5e3}]:u["payload-types"],m=p.map(f=>f.id);i(SP(n,l,m),"c=IN IP4 0.0.0.0",`a=rtcp:${l} IN IP4 0.0.0.0`),c["rtcp-mux"]&&i("a=rtcp-mux"),i(`a=mid:${r}`);let g=o;if(o!=="sendrecv"&&s&&!(h||d)&&(g=o==="sendonly"?"recvonly":"sendonly"),i(`a=${g}`),this.addTransport(c),d)i(`a=sctpmap:${p[0].id} webrtc-datachannel 256`);else{const f=u["rtp-hdrexts"];f?.length&&f.forEach(v=>{i(`a=extmap:${v.id} ${v.uri}`)}),p.forEach(v=>{i(`a=rtpmap:${v.id} ${v.name}/${v.clockrate}${v.channels&&v.channels>1?`/${v.channels}`:""}`);const y=v.parameters;if(Array.isArray(y))y.length&&console.error("parameters is array???",y);else if(y&&Object.keys(y).length){const b=[];for(const S in y)b.push(`${S}=${y[S]}`);i(`a=fmtp:${v.id} ${b.join(";")}`)}const w=v["rtcp-fbs"];w?.length&&w.forEach(b=>{i(`a=rtcp-fb:${v.id} ${b.type}${b.subtype?" "+b.subtype:""}`)})})}return e.source&&(g==="sendonly"||g==="sendrecv")&&this.addSsrc(e),this}addConference(e){const{conference:t,entries:s,bundle:i,isAnswer:n}=e;this.addHeader(t.sessionId,i),jc&&this.addTransport(t.transport);for(const r of s)this.addSsrcEntry((n?r.recvEntry||r.sendEntry:r.sendEntry||r.recvEntry)||r,t,n);return this}static fromConference(e){return new Zg().addConference(e).finalize()}}class X6{constructor(e,t){const s=this.streamSource=e.createMediaStreamSource(t),i=this.analyser=e.createAnalyser();this.gain=e.createGain(),i.minDecibels=-100,i.maxDecibels=-30,i.smoothingTimeConstant=.05,i.fftSize=1024,s.connect(i)}}const xh=class xh{constructor(e){this.interval=e,this.getAmplitude=t=>{const{streamAnalyser:s,stream:i,track:n,source:r,type:o}=t,l=s.analyser;if(!l)return;const c=new Uint8Array(l.frequencyBinCount);l.getByteFrequencyData(c);const d=Y6(c);return{type:o,source:r,stream:i,track:n,value:d}},this.analyse=()=>{const t=this.counter%3===0,n=(t?this.items:this.items.filter(r=>r.type==="input")).filter(r=>r.kind==="audio").slice(0,j6).map(this.getAmplitude);++this.counter>=1e3&&(this.counter=0),xh.ANALYSER_LISTENER.dispatchEvent("amplitude",{amplitudes:n,type:t?"all":"input"})},this.context=new(window.AudioContext||window.webkitAudioContext),this.items=[],this.outputStream=new MediaStream,this.inputStream=new MediaStream,this.counter=0,this.log=Ni("SM"),this.direction="sendonly",this.canCreateConferenceEntry=!0,this.types=["audio","video"]}addStream(e,t){e.getTracks().forEach(s=>{this.addTrack(e,s,t)})}addTrack(e,t,s){this.log("addTrack",s,t,e);const{context:i,items:n,inputStream:r,outputStream:o}=this,l=t.kind,c=xh.getSource(e,s);switch(s){case"input":{r?r.addTrack(t):this.inputStream=e;break}case"output":{for(let d=0;d<n.length;++d){const{track:u,type:h,source:p}=n[d];if(p===c&&h==="input"){n.splice(d,1),o.removeTrack(u);break}}l!=="video"&&o.addTrack(t);break}}this.finalizeAddingTrack({type:s,source:c,stream:e,track:t,kind:l,streamAnalyser:l==="audio"?new X6(i,e):void 0}),l==="audio"&&this.interval&&this.changeTimer()}finalizeAddingTrack(e){const{track:t}=e;t.addEventListener("ended",()=>{this.removeTrack(t)},{once:!0}),this.items.push(e)}hasInputTrackKind(e){return this.items.find(t=>t.type==="input"&&t.kind===e)}static getSource(e,t){return t==="input"?e.source||e.id:""+iw(+e.id.substring(6))}removeTrack(e){this.log("removeTrack",e);const{items:t}=this;let s=!1;for(let i=0,n=t.length;!s&&i<n;++i){const{track:r,type:o}=t[i];switch(o){case"output":{r===e&&(t.splice(i,1),this.outputStream.removeTrack(e),s=!0);break}case"input":{r===e&&(t.splice(i,1),this.inputStream.removeTrack(e),s=!0);break}}}e.kind==="audio"&&this.interval&&this.changeTimer()}replaceInputAudio(e,t){this.removeTrack(t),this.addStream(e,"input")}changeTimer(){this.timer!==void 0&&clearInterval(this.timer),this.items.length&&(this.timer=window.setInterval(this.analyse,this.interval))}appendToConference(e){if(this.locked)return;const{inputStream:t,direction:s,canCreateConferenceEntry:i}=this,n={direction:s,streams:[t]},r=this.types.map(l=>[l,n]),o=t.getTracks();for(const[l,c]of r){let d=e.findEntry(f=>f.direction===s&&f.type===l);if(!d){if(!i)continue;d=e.createEntry(l)}let{transceiver:u}=d;u||(u=d.createTransceiver(e.connection,c)),d.direction!==u.direction&&(u.direction=d.direction);const h=Xg(l),p=o.findIndex(f=>f.kind===h),m=p!==-1?o.splice(p,1)[0]:void 0,g=u.sender;g.track!==m&&g.replaceTrack(m).catch(f=>{this.log.error(f)})}}stop(){try{this.inputStream.getTracks().concat(this.outputStream.getTracks()).forEach(t=>{Qg(t)})}catch(e){this.log.error(e)}}};xh.ANALYSER_LISTENER=new pn;let Ol=xh;class CP extends pn{constructor(){super(!1);const e=this.player=document.createElement("div");e.classList.add("call-player"),e.style.display="none",document.body.append(e),this.elements=new Map;const t=this.audio=new Audio;t.autoplay=!0,t.volume=1,this.player.append(t),this.elements.set("audio",t),this.fixSafariAudio(),this.getStream=vP()}get isSharingAudio(){return!!this.streamManager.hasInputTrackKind("audio")}get isSharingVideo(){return!!this.streamManager.hasInputTrackKind("video")}fixSafariAudio(){Sn(this.audio)}requestAudioSource(e){return this.requestInputSource(!0,!1,e)}requestInputSource(e,t,s){const{streamManager:i}=this;if(i){const r=!e||this.isSharingAudio,o=!t||this.isSharingVideo;if(r&&o)return Promise.resolve()}const n={audio:e&&mP(),video:t&&sw()};return this.getStream({constraints:n,muted:s}).then(r=>{this.onInputStream(r)})}requestScreen(){return this.getStream({isScreen:!0,constraints:gP(!0)}).then(e=>{this.onInputStream(e)})}getElement(e){return this.elements.get(""+e)}cleanup(){this.player.textContent="",this.player.remove(),this.elements.clear(),this.streamManager.stop(),super.cleanup()}onTrack(e){this.tryAddTrack({stream:e.streams[0],track:e.track,type:"output"})}saveInputVideoStream(e,t){const s=e.getVideoTracks()[0];this.tryAddTrack({stream:e,track:s,type:"input",source:t||"main"})}tryAddTrack({stream:e,track:t,type:s,source:i}){i||(i=Ol.getSource(e,s)),this.log("tryAddTrack",e,t,s,i);const n=s==="output",{player:r,elements:o,streamManager:l}=this,c=t.kind,d=c==="video",u=d?i:c;let h=o.get(u);d&&t.addEventListener("ended",()=>{this.log("[track] onended"),o.delete(u)},{once:!0}),n&&l.addTrack(e,t,s);const p=d?e:l.outputStream;if(h)h.paused&&Sn(h),h.srcObject=p;else{if(h=document.createElement(c),h.autoplay=!0,h.srcObject=p,h.volume=1,h.sinkId!=="undefined"){const{outputDeviceId:m}=this;m&&h.setSinkId(m)}d?(h.setAttribute("playsinline","true"),h.muted=!0):r.appendChild(h),o.set(u,h)}return i}setMuted(e){this.streamManager.inputStream.getAudioTracks().forEach(t=>{t?.kind==="audio"&&(t.enabled=e===void 0?!t.enabled:!e)})}onInputStream(e){if(this.isClosing)e.getTracks().forEach(t=>{Qg(t)});else{e.getVideoTracks().length&&this.saveInputVideoStream(e,"main");const{streamManager:s,description:i}=this;s.addStream(e,"input"),i&&s.appendToConference(i)}}}function Z6(a,e,t){t||(t=Ni("RTCDataChannel"));const s=a.createDataChannel("data",e);return s.addEventListener("message",i=>{t("onmessage",i)}),s.addEventListener("open",()=>{t("onopen")}),s.addEventListener("close",()=>{t("onclose")}),s.log=t,s}function J6(a,e){e||(e=Ni("RTCPeerConnection")),e("constructor");const t=new RTCPeerConnection(a);return t.addEventListener("track",s=>{e("ontrack",s)}),t.addEventListener("signalingstatechange",()=>{e("onsignalingstatechange",t.signalingState)}),t.addEventListener("connectionstatechange",()=>{e("onconnectionstatechange",t.connectionState)}),t.addEventListener("negotiationneeded",()=>{e("onnegotiationneeded",t.signalingState)}),t.addEventListener("icecandidate",s=>{e("onicecandidate",s)}),t.addEventListener("iceconnectionstatechange",()=>{e("oniceconnectionstatechange",t.iceConnectionState)}),t.addEventListener("datachannel",()=>{e("ondatachannel")}),t.log=e,{connection:t}}class Jg{constructor(e,t){this.mid=e,this.type=t,this.port=bP}setDirection(e){return this.originalDirection||(this.originalDirection=e),this.direction=e}setPort(e){return this.port=e}setEndpoint(e){return this.endpoint=e}setPeerId(e){return this.peerId=e}createTransceiver(e,t){return t?.direction&&this.setDirection(t.direction),this.transceiver=e.addTransceiver(Xg(this.type),t)}setSource(e){let t;if(Array.isArray(e)){if(!e[0])return;t=e,e=t[0].sources[0]}return this.sourceGroups=t,this.source=e}shouldBeSkipped(e){return e&&this.direction==="inactive"}}function im(a,e,t){let s;if(Array.isArray(e)){if(!e[0])return;s=e,e=s[0].sources[0]}return{endpoint:t,type:a,source:e,sourceGroups:s}}class e7{constructor(e){this.connection=e,this.sessionId=""+Date.now(),this.maxSeenId=-1,this.entries=[],this.entriesByMid=new Map,this.entriesBySource=new Map,this.entriesByPeerId=new Map}setData(e){return Nt(this,e)}createEntry(e){const t=""+ ++this.maxSeenId,s=new Jg(t,e);return this.entries.push(s),this.entriesByMid.set(t,s),s}deleteEntry(e){Vs(this.entries,e),this.entriesByMid.delete(e.mid),this.entriesBySource.delete(e.source);const t=this.entriesByPeerId.get(e.peerId);t&&(t.delete(e),t.size||this.entriesByPeerId.delete(e.peerId))}setEntrySource(e,t){e.setSource(t),this.entriesBySource.set(e.source,e)}setEntryPeerId(e,t){e.setPeerId(t);let s=this.entriesByPeerId.get(t);s||this.entriesByPeerId.set(t,s=new Set),s.add(e)}findEntry(e){return this.entries.find(e)}findFreeSendRecvEntry(e,t){let s=this.entries.find(i=>i.direction==="sendrecv"&&i.type===e&&!(t?i.sendEntry:i.recvEntry));return s||(s=this.createEntry(e),s.setDirection("sendrecv")),s}getEntryByMid(e){return this.entriesByMid.get(e)}getEntryBySource(e){return this.entriesBySource.get(e)}getEntriesByPeerId(e){return this.entriesByPeerId.get(e)}generateSdp(e){return Zg.fromConference({conference:this,...e})}}class _P{constructor(e){Nt(this,e),this.log||(this.log=this.connection?.log||Ni("CALL-CONNECTION-BASE")),this.sources={}}createPeerConnection(e){return this.connection||(this.connection=J6(e,this.log.bindPrefix("connection")).connection)}createDataChannel(e){return this.dataChannel||(this.dataChannel=Z6(this.connection,e,this.log.bindPrefix("data")))}createDescription(){return this.description||(this.description=new e7(this.connection))}appendStreamToConference(){return this.streamManager.appendToConference(this.description)}closeConnection(){const{connection:e}=this;if(e)try{e.log("close"),e.close()}catch(t){this.log.error(t)}}closeConnectionAndStream(e){this.closeConnection(),e&&this.streamManager.stop()}negotiate(){const e=this.negotiating;return e||(this.negotiating=this.negotiateInternal().finally(()=>{this.negotiating=void 0}))}sendDataChannelData(e){this.dataChannel.readyState==="open"&&this.dataChannel.send(JSON.stringify(e))}}function t7(a,e){const t=i=>{const n={};return i.attributes.get("extmap").forEach(o=>{const l=o.key.split("/",1)[0];n[l]=o.value}),n};["audio","video"].filter(i=>e[i]).map(i=>[e[i],i]).forEach(([i,n])=>{const r=a.find(l=>l.mediaType===n);if(!r)return;const o=t(r);hn(i["rtp-hdrexts"],(l,c,d)=>{o[l.id]!==l.uri&&(d.splice(c,1),console.log("[sdp] filtered extmap:",l,c,n))})})}var hu,uu;class s7{constructor(e,t){Ks(this,hu,void 0);Ks(this,uu,void 0);ss(this,hu,e),ss(this,uu,t)}get session(){return ls(this,hu)}get media(){return ls(this,uu)}get bundle(){return this.session.lines.find(t=>t.parsed?.key==="group").value.split(" ").slice(1)}toString(){return this.session.lines.concat(...this.media.map(e=>e.lines)).map(e=>e.toString()).join(`\r
- `)+`\r
- `}}hu=new WeakMap,uu=new WeakMap;function nw(a,e,t){const s=a.split(e),i=[];for(;t>0&&s.length;)i.push(s.shift()),--t;return s.length&&i.push(s.join(e)),i}var Nc,pu,mu;class i7{constructor(e,t){Ks(this,Nc,void 0);Ks(this,pu,void 0);Ks(this,mu,void 0);ss(this,Nc,new Set),ss(this,pu,e),ss(this,mu,t)}generate(){const e=ls(this,pu),t=ls(this,mu),s=ls(this,Nc),i=t-e+1;let n=Math.floor(e+i*Math.random()),r=0;for(;s.has(n);)if(n<t?++n:n=e,++r>=i)return null;return s.add(n),n}add(e){ls(this,Nc).add(e)}}Nc=new WeakMap,pu=new WeakMap,mu=new WeakMap;var gu,fu;class Zf{constructor(e,t){Ks(this,gu,void 0);Ks(this,fu,void 0);ss(this,gu,e),ss(this,fu,t)}get key(){return ls(this,gu)}get value(){return ls(this,fu)}}gu=new WeakMap,fu=new WeakMap;var vu,yu,bu,wu;class k0{constructor(e,t,s,i){Ks(this,vu,void 0);Ks(this,yu,void 0);Ks(this,bu,void 0);Ks(this,wu,void 0);ss(this,vu,e),ss(this,yu,t),ss(this,bu,s),ss(this,wu,i)}get type(){return ls(this,vu)}get port(){return ls(this,yu)}get protocol(){return ls(this,bu)}get ids(){return ls(this,wu)}toString(){return this.type+" "+this.port+" "+this.protocol+" "+this.ids.join(" ")}}vu=new WeakMap,yu=new WeakMap,bu=new WeakMap,wu=new WeakMap;var Su,Pl,Oc,Uc;class n7{constructor(e,t){Ks(this,Su,void 0);Ks(this,Pl,void 0);Ks(this,Oc,void 0);Ks(this,Uc,void 0);if(ss(this,Su,e),typeof t=="string"){if(ss(this,Pl,t),e==="m"){const s=t.split(" ");ss(this,Oc,new k0(s[0],s[1],s[2],s.slice(3)))}else if(e==="a"){const s=nw(t,":",1);t=s[0],ss(this,Uc,s.length===1?new Zf(t,null):new Zf(t,s[1]))}}else t instanceof k0?(ss(this,Oc,t),ss(this,Pl,t.toString())):t instanceof Zf&&(ss(this,Uc,t),ss(this,Pl,t.value?`${t.key}:${t.value}`:t.key))}get key(){return ls(this,Su)}get value(){return ls(this,Pl)}get parsed(){return ls(this,Uc)}get mediaLineParts(){return ls(this,Oc)}toString(){return`${this.key}=${this.value}`}}Su=new WeakMap,Pl=new WeakMap,Oc=new WeakMap,Uc=new WeakMap;var Cu,_u,Iu,Co,Hc,Gc;const bo=class bo{constructor(e,t,s=":",i=!1){Ks(this,Cu,void 0);Ks(this,_u,void 0);Ks(this,Iu,void 0);Ks(this,Co,void 0);Ks(this,Hc,void 0);Ks(this,Gc,void 0);ss(this,Cu,e),ss(this,_u,t),ss(this,Iu,s),ss(this,Hc,i),ss(this,Co,i?new Map:null),ss(this,Gc,i?[]:null)}get lines(){return ls(this,_u)}get value(){return ls(this,Hc)||!this.lines.length?null:this.lines[0]}get exists(){return!ls(this,Hc)}get key(){return ls(this,Cu)}get keys(){return bo.fill(this),ls(this,Gc)}forEach(e){bo.fill(this),ls(this,Co).forEach(e)}get(e){return bo.fill(this),ls(this,Co).get(e)||new bo(e,[],":",!0)}static fill(e){if(ls(e,Co)!==null)return;const t=new Map;e.lines.forEach(i=>{const[n,r]=nw(i,ls(e,Iu),1),o=t.get(n)||[];t.set(n,[...o,r||""])});const s=ss(e,Co,bo.makeAttributes(t));ss(e,Gc,Array.from(s.keys()))}static makeAttributes(e){const t=new Map;return e.forEach((s,i)=>{t.set(i,new bo(i,s))}),t}};Cu=new WeakMap,_u=new WeakMap,Iu=new WeakMap,Co=new WeakMap,Hc=new WeakMap,Gc=new WeakMap;let jm=bo;var Pu,Vc;const Tw=class Tw{constructor(e){Ks(this,Pu,void 0);Ks(this,Vc,void 0);ss(this,Pu,e),ss(this,Vc,new Map),Tw.fillAttributes(this)}get(e){return ls(this,Vc).get(e)||new jm(e,[]," ",!0)}static fillAttributes(e){const t=new Map;ls(e,Pu).forEach(s=>{if(s.key==="a"){const{key:i,value:n}=s.parsed;let r=t.get(i);r||(r=[],t.set(i,r)),r.push(n||"")}}),t.forEach((s,i)=>{ls(e,Vc).set(i,new jm(i,s," ",!1))})}};Pu=new WeakMap,Vc=new WeakMap;let ly=Tw;var Mu,zc,Ml,Ll;class IP{constructor(e){Ks(this,Mu,void 0);Ks(this,zc,void 0);Ks(this,Ml,void 0);Ks(this,Ll,void 0);ss(this,Mu,e),ss(this,zc,e[0]),ss(this,Ml,ss(this,Ll,null))}get lines(){return ls(this,Mu)}get mediaLine(){return ls(this,zc)}get mediaLineParts(){return ls(this,zc).mediaLineParts}get mediaType(){return this.mediaLineParts.type}get direction(){if(!ls(this,Ll)){const e=this.attributes;let t;e.get("sendonly").exists?t="sendonly":e.get("recvonly").exists?t="recvonly":e.get("inactive").exists?t="inactive":t="sendrecv",ss(this,Ll,t)}return ls(this,Ll)}get isSending(){return this.direction==="sendrecv"||this.direction==="sendonly"}get isReceiving(){return this.direction==="sendrecv"||this.direction==="recvonly"}get attributes(){return ls(this,Ml)||ss(this,Ml,new ly(this.lines)),ls(this,Ml)}get mid(){return this.attributes.get("mid").value}lookupAttributeKeys(e){const t={};for(const s in e){const i=this.attributes.get(s),n=!e[s];i?t[s]=n?i.lines:i.value:t[s]=n?[]:void 0}return t}}Mu=new WeakMap,zc=new WeakMap,Ml=new WeakMap,Ll=new WeakMap;var Lu,Eu;class a7{constructor(e){Ks(this,Lu,void 0);Ks(this,Eu,void 0);ss(this,Lu,e),ss(this,Eu,e.filter(t=>t.key==="o").map(t=>t.value.split(" ")[1])[0])}get lines(){return ls(this,Lu)}get sessionId(){return ls(this,Eu)}}Lu=new WeakMap,Eu=new WeakMap;function qm(a){function e(){t?i.push(new IP(s)):t=new a7(s)}let t=null,s=[];const i=[];return a.split(/\r?\n/).forEach(n=>{if(!r7(n)){const r=nh(n);r.key==="m"&&(e(),s=[]),s.push(r)}}),e(),new s7(t,i)}function r7(a){return/^[\s\xa0]*$/.test(a)}function nh(a){const e=nw(a,"=",1);return new n7(e[0],e[1])}function o7(a){let e;return a.media.forEach((t,s)=>{if(t.mediaType==="video"&&t.isSending&&!t.attributes.get("ssrc-group").get("SIM").exists){e||(e=new i7(2,4294967295));const i=t.attributes.get("ssrc-group").get("FID").value.split(" "),n=t.lines;i.forEach(c=>e.add(+c));const r=[i[0],e.generate(),e.generate()],o=[i[1],e.generate(),e.generate()];n.push(nh("a=ssrc-group:SIM "+r.join(" ")));const l=t.attributes.get("ssrc").get(i[0]).lines;r.forEach((c,d)=>{const u=o[d];d>0&&(n.push(nh("a=ssrc-group:FID "+c+" "+u)),l.forEach(h=>{n.push(nh("a=ssrc:"+c+" "+h))}),l.forEach(h=>{n.push(nh("a=ssrc:"+u+" "+h))}))}),a.media[s]=new IP(n)}}),!!e}function l7(a){const e=a.map(t=>{const[s,...i]=t.split(" ");return{_:"groupCallParticipantVideoSourceGroup",semantics:s,sources:i.map(r=>iw(+r))}});return e.length?e:void 0}function Ym(a,e){const t=e.lookupAttributeKeys({"ice-ufrag":!0,"ice-pwd":!0,fingerprint:!0,setup:!0,ssrc:!0,mid:!0,"ssrc-group":!1});if(!t.fingerprint){const o=a.session.lines.find(l=>l.parsed?.key==="fingerprint");t.fingerprint=o.parsed.value}const s=l7(t["ssrc-group"]),[i,n]=t.fingerprint.split(" ",2),r=t.ssrc&&iw(+t.ssrc.split(" ",1)[0]);return{raw:t,ufrag:t["ice-ufrag"],pwd:t["ice-pwd"],fingerprint:{fingerprint:n,setup:t.setup,hash:i},source:r,sourceGroups:s,mid:t.mid}}function c7(a){const{offer:e,data:t}=a,s=qm(e.sdp);let i=!1;if(a.skipAddingMulticast||(i=o7(s)||i),hn(s.media,(n,r,o)=>{if(n.isSending||n.mediaType==="application")return;const l=n.mediaLine,c=l.mediaLineParts;c.ids;const d=l.toString(),p=t[n.mediaType]["payload-types"].map(g=>""+g.id),m=SP(n.mediaType,void 0,p);if(d!==m){const g=Ym(s,n),f={...t};f.transport=kn(f.transport),f.transport.ufrag=g.ufrag,f.transport.pwd=g.pwd,f.transport.fingerprints=[g.fingerprint],f.transport.candidates=[];const v=new Jg(g.mid,c.type);v.setPort(c.port),g.source&&v.setSource(g.sourceGroups||g.source),v.setDirection(n.direction);const y=new Zg().addSsrcEntry(v,f).finalize(),w=qm(y).media[0];o[r]=w,i=!0}}),i){const n=s.toString();e.sdp=n}return{offer:e,sdp:s}}function d7(a,e){const t=Ym(a,e),s=e.mediaType,i={source:t.source,sourceGroups:t.sourceGroups,type:s};t.fingerprint.setup="active";const n={fingerprints:[t.fingerprint],pwd:t.pwd,ssrc:t.source,"ssrc-groups":t.sourceGroups||[],ufrag:t.ufrag};return{params:{_:"dataJSON",data:JSON.stringify(n)},source:t.source,media:e,sourceGroups:t.sourceGroups,entry:i}}class h7 extends _P{constructor(e){super(e),this.negotiateThrottled=fa(this.negotiate.bind(this),0,!1)}createPeerConnection(){return this.connection||super.createPeerConnection({iceServers:[],iceTransportPolicy:"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",iceCandidatePoolSize:0})}createDataChannel(){if(this.dataChannel)return this.dataChannel;const e=super.createDataChannel();return e.addEventListener("open",()=>{this.maybeUpdateRemoteVideoConstraints()}),e.addEventListener("close",()=>{this.updateConstraintsInterval&&(clearInterval(this.updateConstraintsInterval),this.updateConstraintsInterval=void 0)}),e}createDescription(){return this.description?this.description:super.createDescription()}appendStreamToConference(){super.appendStreamToConference()}async invokeJoinGroupCall(e,t,s){const{groupCall:i,description:n}=this,r=i.id,o=t.map(f=>{const v=d7(e,f);return this.sources[v.entry.type]=v.entry,v}),l=o.find(f=>f.media.mediaType==="audio"),c=o.find(f=>f.media.mediaType==="video");let{source:d,params:u}=l||{};const h=c||l,p={audio:l,video:c};if(n.entries.forEach(f=>{if(f.direction==="sendonly"){const v=p[f.type];if(!v)return;n.setEntrySource(f,v.sourceGroups||v.source),n.setEntryPeerId(f,I.myId)}}),u!==h.params){const f=JSON.parse(h.params.data);d?f.ssrc=d:delete f.ssrc,u={_:"dataJSON",data:JSON.stringify(f)}}const m=await this.managers.appGroupCallsManager.joinGroupCall(r,u,s),g=JSON.parse(m.params.data);return g.audio=g.audio||i.connections.main.description.audio,n.setData(g),t7(t,g),g}async negotiateInternal(){const{connection:e,description:t}=this,s=e.iceConnectionState==="new"&&!t.getEntryByMid("0").source,i=this.log.bindPrefix("startNegotiation");i("start");const n=await e.createOffer({iceRestart:!1});s&&this.dataChannel&&t.createEntry("application").setDirection("sendrecv");const{sdp:r,offer:o}=c7({offer:n,data:t});i("[sdp] setLocalDescription",o.sdp),await e.setLocalDescription(o);const l=r.media.filter(m=>m.mediaType!=="application"&&m.isSending);if(s)try{await this.invokeJoinGroupCall(r,l,this.options)}catch(m){this.log.error("[tdweb] joinGroupCall error",m)}const c=!0,d=[],u=r.bundle;hn(u,(m,g,f)=>{const v=t.getEntryByMid(m);v.shouldBeSkipped(c)&&(f.splice(g,1),d.push(v))});const h=r.media.map(m=>{const g=m.mid;let f=t.getEntryByMid(g);return f||(f=new Jg(g,m.mediaType),f.setDirection("inactive")),f}),p={type:"answer",sdp:t.generateSdp({bundle:u,entries:h,isAnswer:c})};d.forEach(m=>{t.deleteEntry(m)}),i(`[sdp] setRemoteDescription signaling=${e.signalingState} ice=${e.iceConnectionState} gathering=${e.iceGatheringState} connection=${e.connectionState}`,p.sdp),await e.setRemoteDescription(p),i("end")}negotiate(){let e=this.negotiating;return e||(e=super.negotiate(),this.updateConstraints&&e.then(()=>{this.maybeUpdateRemoteVideoConstraints(),this.updateConstraints=!1}),this.options.type==="presentation"&&e.then(()=>{this.connection.getTransceivers().find(t=>{t.sender?.track?.kind==="video"&&t.sender.setParameters({...t.sender.getParameters(),degradationPreference:"maintain-resolution"})})}),e)}maybeUpdateRemoteVideoConstraints(){if(this.dataChannel.readyState!=="open")return;this.log("maybeUpdateRemoteVideoConstraints");const e={colibriClass:"ReceiverVideoConstraints",constraints:{},defaultConstraints:{maxHeight:0},onStageEndpoints:[]};for(const t of this.description.entries){if(t.direction!=="recvonly"||t.type!=="video")continue;const{endpoint:s}=t;e.onStageEndpoints.push(s),e.constraints[s]={minHeight:180,maxHeight:720}}this.sendDataChannelData(e),e.onStageEndpoints.length?this.updateConstraintsInterval||(this.updateConstraintsInterval=window.setInterval(this.maybeUpdateRemoteVideoConstraints.bind(this),5e3)):this.updateConstraintsInterval&&(clearInterval(this.updateConstraintsInterval),this.updateConstraintsInterval=void 0)}addInputVideoStream(e){this.groupCall.saveInputVideoStream(e,this.type),this.streamManager.addStream(e,"input"),this.appendStreamToConference()}}var qs=(a=>(a[a.UNMUTED=0]="UNMUTED",a[a.MUTED=1]="MUTED",a[a.MUTED_BY_ADMIN=2]="MUTED_BY_ADMIN",a[a.CONNECTING=3]="CONNECTING",a[a.CLOSED=4]="CLOSED",a))(qs||{});class cl extends CP{constructor(e){super(),Nt(this,e),this.log||(this.log=Ni("GROUP-CALL")),this.connections||(this.connections={}),this.isSpeakingMap||(this.isSpeakingMap=new Map),this.pinnedSources=[],this.participantsSsrcs=new Map,this.hadAutoPinnedSources=new Set,this.dispatchPinnedThrottled=fa(()=>{this.dispatchEvent("pinned",this.pinnedSource)},0,!1),this.addEventListener("state",t=>{t===qs.CLOSED&&this.cleanup()})}get connectionState(){return this.connections.main.connection.iceConnectionState}get state(){const{connectionState:e}=this;if(e==="closed")return qs.CLOSED;if(e!=="connected"&&(!dn||e!=="completed"))return qs.CONNECTING;{const{participant:t}=this;return t.pFlags.can_self_unmute?t.pFlags.muted?qs.MUTED:qs.UNMUTED:qs.MUTED_BY_ADMIN}}get participants(){return this.managers.appGroupCallsManager.getCachedParticipants(this.id)}get isSharingScreen(){return!!this.connections.presentation}get pinnedSource(){return this.pinnedSources[this.pinnedSources.length-1]}get isMuted(){return this.state!==qs.UNMUTED}get isClosing(){const{state:e}=this;return e===qs.CLOSED}get streamManager(){return this.connections.main.streamManager}get description(){return this.connections.main.description}pinSource(e){Vs(this.pinnedSources,e),this.pinnedSources.push(e),this.dispatchPinnedThrottled()}unpinSource(e){this.hadAutoPinnedSources.delete(e),Vs(this.pinnedSources,e),this.dispatchPinnedThrottled()}unpinAll(){this.pinnedSources.length=0,this.dispatchPinnedThrottled()}async getParticipantByPeerId(e){return Wt===e?this.participant:(await this.participants).get(e)}toggleMuted(){return this.requestAudioSource(!0).then(()=>this.changeUserMuted(Wt))}async changeUserMuted(e,t){const s=await this.getParticipantByPeerId(e);return Wt===e&&s.pFlags.can_self_unmute&&(t=t===void 0?!s.pFlags.muted:t),this.editParticipant(s,{muted:t})}getElement(e){return super.getElement(e)}getVideoElementFromParticipantByType(e,t){let s;e.pFlags.self?s=t==="video"?"main":"presentation":s=e[t].source_groups[0].sources[0];const i=this.getElement(s);if(!i)return;const n=i.cloneNode();return n.srcObject=i.srcObject,{video:n,source:s}}createConnectionInstance(e){return this.connections[e.type]=new h7({groupCall:this,log:this.log.bindPrefix(e.type),managers:this.managers,...e})}changeRaiseHand(e){return this.editParticipant(this.participant,{raiseHand:e})}async startScreenSharingInternal(){try{const e="presentation",t=await fP(gP()),s=new Ol,i=this.createConnectionInstance({streamManager:s,type:e,options:{type:e}});i.createPeerConnection().addEventListener("negotiationneeded",()=>{i.negotiate()}),t.getVideoTracks()[0].addEventListener("ended",()=>{this.connections.presentation&&this.stopScreenSharing()},{once:!0}),i.createDescription(),i.addInputVideoStream(t)}catch(e){this.log.error("start screen sharing error",e)}}startScreenSharing(){return this.startScreenSharingPromise??(this.startScreenSharingPromise=this.startScreenSharingInternal().finally(()=>{this.startScreenSharingPromise=void 0}))}stopScreenSharing(){const e=this.connections.presentation;return e?(delete this.connections.presentation,this.unpinSource("presentation"),e.closeConnectionAndStream(!0),delete this.participant.presentation,this.managers.appGroupCallsManager.saveApiParticipant(this.id,this.participant),this.managers.appGroupCallsManager.leaveGroupCallPresentation(this.id)):Promise.resolve()}toggleScreenSharing(){return this.isSharingScreen?this.stopScreenSharing():this.startScreenSharing()}async startVideoSharingInternal(){const e={video:sw()};try{const t=await Yg(e,!1);this.connections.main.addInputVideoStream(t),await this.editParticipant(this.participant,{videoPaused:!1,videoStopped:!1})}catch(t){this.log.error("startVideoSharing error",t,e)}}startVideoSharing(){return this.startVideoSharingPromise??(this.startVideoSharingPromise=this.startVideoSharingInternal().finally(()=>{this.startVideoSharingPromise=void 0}))}async stopVideoSharing(){const e=this.connections.main,t=e.streamManager.inputStream.getVideoTracks()[0];t&&(Qg(t),e.streamManager.appendToConference(e.description),await this.editParticipant(this.participant,{videoStopped:!0}))}toggleVideoSharing(){return this.isSharingVideo?this.stopVideoSharing():this.startVideoSharing()}async hangUp(e=!1,t=!1,s=!1){for(const i in this.connections)this.connections[i].closeConnectionAndStream(!t);if(this.dispatchEvent("state",this.state),!s&&!t){const i=e||(this.joined?this.connections.main.sources.audio.source:void 0);this.managers.appGroupCallsManager.hangUp(this.id,i)}}tryAddTrack(e){const{description:t}=this,s=super.tryAddTrack(e);if(e.type==="output"){const i=t.getEntryBySource(+s);this.getParticipantByPeerId(i.peerId).then(n=>{n&&I.dispatchEvent("group_call_participant",{groupCallId:this.id,participant:n})})}return s}async editParticipant(e,t){if(Object.keys(t).length){if(e){const s=e.pFlags.self;if(s&&t.muted!==void 0&&!this.isSharingAudio&&(delete t.muted,!Object.keys(t).length))return;const i=t.muted;i!==void 0&&e.pFlags.self&&(i?e.pFlags.muted=!0:e.pFlags.can_self_unmute&&delete e.pFlags.muted),t.raiseHand!==void 0&&(t.raiseHand?e.raise_hand_rating="1":delete e.raise_hand_rating),s&&(t.videoStopped!==void 0&&(t.videoStopped?delete e.video:e.video=g7(this.connections.main.sources.video)),!e.pFlags.muted&&e.pFlags.can_self_unmute&&this.setMuted(!1),this.dispatchEvent("state",this.state))}return this.managers.appGroupCallsManager.editParticipant(this.id,e,t)}}onParticipantUpdate(e,t){const s=this.connections.main,{connection:i,description:n}=s,r=it(e.peer),o=!!e.pFlags.left,l=this.participantsSsrcs.get(r)||[];if(e.presentation&&!o){const{source:u}=mc(e,"video",e.presentation.source_groups,e.presentation.endpoint);this.hadAutoPinnedSources.has(u)||(this.hadAutoPinnedSources.add(u),this.pinSource(e.pFlags.self?"presentation":u))}if(e.pFlags.self){this.participant=e,s.sources.audio.source!==e.source&&this.hangUp();let u=!1;e.pFlags.can_self_unmute?e.pFlags.muted&&(u=!0):(this.stopScreenSharing(),this.stopVideoSharing(),u=!0),u&&this.setMuted(!0),t!==r&&this.dispatchEvent("state",this.state);return}const c=o?[]:m7(e);o?this.participantsSsrcs.delete(r):this.participantsSsrcs.set(r,c);const d=new Set;l.forEach(u=>{const h=u.source;if(!c.find(m=>m.source===h)){this.unpinSource(h);const m=n.getEntryBySource(h);m&&m.direction!=="inactive"&&(m.setDirection("inactive"),d.add(m.type))}}),c.forEach(u=>{let h=n.getEntryBySource(u.source);if(h){h.direction==="inactive"&&(h.setDirection(h.originalDirection),d.add(h.type));return}h=n.createEntry(u.type),n.setEntrySource(h,u.sourceGroups||u.source),n.setEntryPeerId(h,r),u.type==="video"&&h.setEndpoint(u.endpoint),h.createTransceiver(i,{direction:"recvonly"}),d.add(h.type)}),d.size&&(d.has("video")&&(s.updateConstraints=!0),s.negotiateThrottled())}}async function u7(a,e){const t={audio:mP(),video:e&&sw()},s=new Ol(yP);try{const i=await Yg(t,a);s.addStream(i,"input")}catch(i){console.error("joinGroupCall getStream error",i,t),s.inputStream=new MediaStream}return s}const p7=!0;function m7(a){return[mc(a,"audio",a.source),a.video?.audio_source&&mc(a,"audio",a.video.audio_source),a.video&&mc(a,"video",a.video.source_groups,a.video.endpoint),a.presentation?.audio_source&&mc(a,"audio",a.presentation.audio_source),a.presentation&&mc(a,"video",a.presentation.source_groups,a.presentation.endpoint)].filter(Boolean)}function mc(a,e,t,s){return im(e,t,s)}function g7(a,e){return a&&{_:"groupCallParticipantVideo",pFlags:{},endpoint:"",source_groups:a.sourceGroups,audio_source:e}}class f7 extends pn{construct(e){this.managers=e,this.audioAsset=W6(),this.log=Ni("GCC"),I.addEventListener("group_call_update",t=>{const{currentGroupCall:s}=this;s?.id===t.id&&(s.groupCall=t,t._==="groupCallDiscarded"&&s.hangUp(!1,!1,!0))}),I.addEventListener("group_call_participant",({groupCallId:t,participant:s})=>{const{currentGroupCall:i}=this;i?.id===t&&i.onParticipantUpdate(s)})}get groupCall(){return this.currentGroupCall}setCurrentGroupCall(e){this.currentGroupCall=e,e&&this.dispatchEvent("instance",e)}startConnectingSound(){this.stopConnectingSound(),this.audioAsset.playSoundWithTimeout("group_call_connect.mp3",!0,2500)}stopConnectingSound(){this.audioAsset.stopSound(),this.audioAsset.cancelDelayedPlay()}async joinGroupCall(e,t,s=p7,i,n){this.audioAsset.createAudio(),this.log(`joinGroupCall chatId=${e} id=${t} muted=${s} rejoin=${i}`);let r;return i?r=this.currentGroupCall.connections.main.streamManager:r=await u7(s,n),this.joinGroupCallInternal(e,t,r,s,i,n).then(()=>{const{currentGroupCall:o}=this;o.participants.then(l=>{this.currentGroupCall!==o||o.state===qs.CLOSED||l.forEach(c=>{c.pFlags.self||o.onParticipantUpdate(c)})})})}async joinGroupCallInternal(e,t,s,i,n=!1,r){const o=this.log.bindPrefix("joinGroupCallInternal");o("start",t);const l="main";let{currentGroupCall:c}=this;if(c&&n)c.handleUpdateGroupCallParticipants=!1,c.updatingSdp=!1,o("update currentGroupCall",t,c);else{c=new cl({chatId:e,id:t,managers:this.managers}),c.fixSafariAudio(),c.addEventListener("state",h=>{this.currentGroupCall===c&&h===qs.CLOSED&&(this.setCurrentGroupCall(null),this.stopConnectingSound(),this.audioAsset.playSound("group_call_end.mp3"),I.dispatchEvent("chat_update",c.chatId))}),c.groupCall=await this.managers.appGroupCallsManager.getGroupCallFull(t);const d=c.createConnectionInstance({streamManager:s,type:l,options:{type:l,isMuted:i,joinVideo:r,rejoin:n}}),u=d.createPeerConnection();return u.addEventListener("negotiationneeded",()=>{d.negotiate()}),u.addEventListener("track",h=>{o("ontrack",h),c.onTrack(h)}),u.addEventListener("iceconnectionstatechange",()=>{c.dispatchEvent("state",c.state);const{iceConnectionState:h}=u;switch(h==="disconnected"||h==="checking"||h==="new"?this.startConnectingSound():this.stopConnectingSound(),h){case"checking":break;case"closed":{c.hangUp();break}case"completed":break;case"connected":{c.joined||(c.joined=!0,this.audioAsset.playSound("group_call_start.mp3"),this.managers.appGroupCallsManager.getGroupCallParticipants(t));break}case"disconnected":break;case"failed":{c.hangUp();break}}}),d.createDescription(),d.createDataChannel(),d.appendStreamToConference(),this.setCurrentGroupCall(c),o("set currentGroupCall",t,c),this.startConnectingSound(),d.negotiate()}}}const Wa=new f7;Di&&(Di.groupCallController=Wa);function ef(a){const{listenTo:e,appendTo:t,onOpen:s,onClose:i,slider:n,chatId:r,participants:o,middleware:l}=a;let c,d,u,h,p,m,g,f;const v=y=>{Qh.openTab(n,r,d,y)};return Dn({listenTo:e,appendTo:t,middleware:l,findElement:y=>c=ne(y.target,"chatlist-chat"),onOpen:async()=>(u=c.dataset.peerId.toPeerId(),d=o.get(u),[h,p,g,f]=await Promise.all([I.managers.appChatsManager.getChat(r),I.managers.appChatsManager.isBroadcast(r),I.managers.appChatsManager.hasRights(r,"change_permissions"),I.managers.appChatsManager.hasRights(r,"change_permissions")]),c.classList.add("menu-open"),m=g&&d._==="channelParticipantBanned"&&d.pFlags.left,s?.()),onClose:()=>(c.classList.remove("menu-open"),i?.()),buttons:[{icon:"message",text:"SendMessage",onClick:()=>{Ce.setInnerPeer({peerId:u})}},{icon:"adduser",text:p?"AddToChannel":"AddToGroup",onClick:()=>{m&&I.managers.appChatsManager.addToChat(r,u)},verify:()=>!!m},{icon:"promote",text:"SetAsAdmin",onClick:()=>v(!0),verify:()=>f&&d._==="channelParticipant"},{icon:"admin",text:"EditAdminRights",onClick:()=>v(!0),verify:()=>d._==="channelParticipantAdmin"&&hh(h,d,I.myId)},{icon:"restrict",text:"KickFromSupergroup",onClick:()=>v(!1),verify:()=>g&&(d._==="channelParticipant"||d._==="channelParticipantBanned"&&!d.pFlags.left)},{icon:"delete",text:"Delete",onClick:()=>{m&&I.managers.appChatsManager.editBanned(r,d,{_:"chatBannedRights",pFlags:{},until_date:0})},verify:()=>!(!m||!g||u===I.myId)},{icon:"delete",text:"KickFromGroup",onClick:()=>{I.managers.appChatsManager.kickFromChat(r,u)},verify:()=>g&&u!==I.myId&&d._!=="channelParticipantCreator"&&(d._!=="channelParticipantAdmin"||hh(h,d,I.myId))&&(d._==="channelParticipant"||!m)}]})}const PP=fd({collect:()=>{}}),cy=a=>T(PP.Provider,{get value(){return{collect:a.onCollect}},get children(){return a.children}});cy.createHelper=()=>{const a=[];let e=t=>{a.push(t)};return{onCollect:t=>e(t),await:()=>(e=()=>{},Promise.all(a))}};const $U=()=>us(PP),MP=fd(),v7=a=>T(MP.Provider,{get value(){return[a.self,a.allTabs]},get children(){return a.children}}),NU=()=>us(MP);function aw({title:a,getComponentModule:e,onOpenAfterTimeout:t}){return class extends Zt{async init(s,i){this.setTitle(i||a),this.payload=s;const n=document.createElement("div"),{default:r}=await e(),o=cy.createHelper();this.dispose=wi(()=>{const l=this;return T(ep,{get children(){return T(cy,{get onCollect(){return o.onCollect},get children(){return T(v7,{self:l,allTabs:tf,get children(){return T(r,{})}})}})}})},n),this.scrollable.append(n),await o.await()}onCloseAfterTimeout(){this.dispose?.(),super.onCloseAfterTimeout()}onOpenAfterTimeout(){t?.call?.(this)}}}const dy=aw({title:"PasscodeLock.Title",getComponentModule:()=>zo(()=>import("./mainTab-RurqNRXZ.js"),__vite__mapDeps([2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21]),import.meta.url),onOpenAfterTimeout:async function(){this.slider.sliceTabsUntilTab(tf.AppPrivacyAndSecurityTab,this)}}),LP=aw({title:"PasscodeLock.Title",getComponentModule:()=>zo(()=>import("./enterPasswordTab-CiYs0tJz.js"),__vite__mapDeps([22,3,4,5,8,9,10,11,12,13,14,15,16,17,18,19,20]),import.meta.url)}),y7=aw({title:"PrivacyMessages",getComponentModule:()=>zo(()=>import("./tab--r1i_QxL.js"),__vite__mapDeps([23,3,4,8,9,24,25,12,13,14,15,16,17,18,19,20,26]),import.meta.url)});let tf={AppPasscodeLockTab:dy,AppPasscodeEnterPasswordTab:LP};class Zu extends Zt{init(e){this.container.classList.add("add-members-container"),this.nextBtn=Cn({icon:"arrow_next"}),this.content.append(this.nextBtn),this.scrollable.container.remove(),this.nextBtn.addEventListener("click",()=>{const s=this.selector.getSelected().map(n=>n.toPeerId()),i=this.takeOut(s);this.skippable&&!(i instanceof Promise)?this.close():i instanceof Promise?this.attachToPromise(i):i===void 0&&this.close()}),this.setTitle(e.title),this.peerType=e.type,this.takeOut=e.takeOut,this.skippable=e.skippable;const t=this.peerType==="privacy";this.selector=new wn({middleware:this.middlewareHelper.get(),appendTo:this.content,onChange:this.skippable?null:s=>{this.nextBtn.classList.toggle("is-visible",!!s)},peerType:[t?"dialogs":"contacts"],placeholder:e.placeholder,exceptSelf:t,filterPeerTypeBy:t?["isAnyGroup","isUser"]:void 0,managers:this.managers,design:"square"}),e.selectedPeerIds&&this.selector.addInitial(e.selectedPeerIds),this.nextBtn.disabled=!1,this.nextBtn.classList.toggle("is-visible",this.skippable)}attachToPromise(e){const t=tb(this.nextBtn,"arrow_next");e.then(()=>{this.close()},()=>{t()})}}tf.AppAddMembersTab=Zu;async function EP({peerId:a,slider:e}){const t=a.toChatId(),s=await I.managers.appChatsManager.isChannel(t),i=await I.managers.appChatsManager.isBroadcast(t),n=async(o,l)=>{let c,d,u,h,p;if(o.length>1){const m=await Promise.all(o.map(async g=>{const f=document.createElement("b");return f.append(await qe({peerId:g})),f}));c="AddMembersAlertTitle",d=[P(i?"Subscribers":"Members",[o.length])],u="AddMembersAlertCountText",h=[Yi(m)],s||(p=[{text:"AddMembersForwardMessages",checked:!0}])}else{c="AddOneMemberAlertTitle",u="AddMembersAlertNamesText";const m=document.createElement("b");m.append(await qe({peerId:o[0]})),h=[m],s||(p=[{text:"AddOneMemberForwardMessages",textArgs:[await qe({peerId:o[0]})],checked:!0}])}h.push(await qe({peerId:a})),ue.createPopup(mi,"popup-add-members",{peerId:a,titleLangKey:c,titleLangArgs:d,descriptionLangKey:u,descriptionLangArgs:h,buttons:[{langKey:"Add",callback:l}],checkboxes:p}).show()},r=o=>{o.type==="USER_PRIVACY_RESTRICTED"&&$e({langPackKey:"InviteToGroupError"})};if(s){const o=e.createTab(Zu);o.open({type:"channel",skippable:!1,takeOut:l=>(n(l,()=>{const c=I.managers.appChatsManager.inviteToChannel(t,l);c.catch(r),o.attachToPromise(c)}),!1),title:i?"ChannelAddSubscribers":"GroupAddMembers",placeholder:"SendMessageTo"})}else ue.createPopup(Rs,{peerType:["contacts"],placeholder:"Search",onSelect:o=>{setTimeout(()=>{n([o],(l,c)=>{I.managers.appChatsManager.addChatUser(t,o,c.size?void 0:0).catch(r)})},0)}})}function kP(a){const e=Mt();return{selector:new wn({...a,multiSelect:!1,headerSearch:!0,placeholder:"SearchPlaceholder",meAsSaved:!1,noShadow:!1,onFirstRender:()=>{e.resolve()}}),loadPromise:e}}function TP(a){return kP({...a,peerType:["channelParticipants"]})}class b7 extends Bs{async init(e){const t=await this.managers.appChatsManager.getChat(e),s=await this.managers.appChatsManager.isBroadcast(e),i=await this.managers.appProfileManager.getChannelFull(e).catch(()=>{});this.container.classList.add("edit-peer-container","chat-members-container"),this.setTitle(s?"PeerInfo.Subscribers":"GroupMembers"),this.addBtn=Cn({icon:"addmember_filled",className:"is-visible"}),this.content.append(this.addBtn),J(this.addBtn,()=>{EP({peerId:e.toPeerId(!0),slider:this.slider})},{listenerSetter:this.listenerSetter});const n=t.participants_count,r=!s&&n>=((await this.managers.apiManager.getAppConfig()).hidden_members_group_size_min||0)&&!!t.admin_rights,{selector:o,loadPromise:l}=TP({appendTo:this.content,managers:this.managers,middleware:this.middlewareHelper.get(),peerId:e.toPeerId(!0),channelParticipantsUpdateFilter:c=>!!c});if(this.selector=o,r){const c=new Oe({noDelimiter:!0,caption:"ChannelHideMembersInfo"}),d=!!i?.pFlags?.participants_hidden,u=new Fe({titleLangKey:"ChannelHideMembers",icon:"hide",checkboxField:new _t({name:"hide-members",toggle:!0,listenerSetter:this.listenerSetter,checked:d}),listenerSetter:this.listenerSetter});this.eventListener.addEventListener("destroy",()=>{const h=u.checkboxField.checked;h!==d&&this.managers.appChatsManager.toggleParticipantsHidden(e,h)},{once:!0}),c.content.append(u.container),this.selector.scrollable.append(c.container,this.selector.scrollable.container.lastElementChild)}return ef({chatId:e,listenTo:this.selector.scrollable.container,participants:this.selector.participants,slider:this.slider,middleware:this.middlewareHelper.get()}),l}}function T0(a,e){return a.map((s,i)=>({idx:i,diff:Math.abs(s-e)})).sort((s,i)=>s.diff-i.diff)[0]}class x0 extends Bs{async init({chatId:e,invite:t}){this.setTitle(t?"InviteLinks.Edit":"NewLink"),this.confirmBtn=Cn({className:"is-visible",icon:"check"}),this.content.append(this.confirmBtn),J(this.confirmBtn,async()=>{tb(this.confirmBtn);const p=d.value,m=p instanceof Date?p.getTime()/1e3|0:p?Qs(!0)+p:0,g=s.value,f=l.checked,v=f?0:u.value??0;let y;t?y=(await this.managers.appChatInvitesManager.editExportedChatInvite({chatId:e,link:t.link,expireDate:m,requestNeeded:f,title:g,usageLimit:v})).invite:y=await this.managers.appChatInvitesManager.exportChatInvite({chatId:e,title:g,requestNeeded:f,usageLimit:v,expireDate:m,stars:r?.checked?+o.value:void 0}),this.eventListener.dispatchEvent("finish",y),this.close()},{listenerSetter:this.listenerSetter});let s;{const p=new Oe({caption:"LinkNameHelp"}),m=document.createElement("div");m.classList.add("input-wrapper"),s=new Yt({label:"LinkNameHint",maxLength:32}),t?.title&&s.setOriginalValue(t.title),m.append(s.container),p.content.append(m),this.scrollable.append(p.container)}const i=await this.managers.appChatsManager.isBroadcast(e),n=await this.managers.apiManager.getAppConfig();let r,o;if(i){const p=new Oe({caption:t?"InviteLink.Subscription.Edit":"InviteLink.Subscription.Caption"}),m=new Fe({titleLangKey:"InviteLink.Subscription.Title",checkboxField:r=new _t({toggle:!0})});this.listenerSetter.add(r.input)("change",()=>{const y=r.checked;l.toggleDisability(y),c.caption.replaceChildren(P(y?"ApproveNewMembersDescription":"InviteLink.AdminApproval.Disabled")),g.classList.toggle("hide",!y)});const g=document.createElement("div");g.classList.add("input-wrapper");const f=o=RI({label:"InviteLink.Subscription.Placeholder",max:n.stars_subscription_amount_max,middleware:this.middlewareHelper.get(),onValue:y=>{v.replaceChildren(...y?[P("InviteLink.Subscription.Price",["$"+(n.stars_usd_sell_rate_x1000/1e3*y/100).toFixed(2)])]:[])}}),v=document.createElement("span");v.classList.add("input-field-right-label"),f.container.append(v),this.listenerSetter.add(f.input)("input",()=>{}),g.append(f.container),p.content.append(m.container,g),f.value="500",this.scrollable.append(p.container)}let l,c;if(i){const p=c=new Oe({caption:!0}),m=new Fe({titleLangKey:"ApproveNewMembers",checkboxField:l=new _t({toggle:!0})});p.content.append(m.container),this.scrollable.append(p.container)}let d;{const p=new Oe({name:"LimitByPeriod",caption:"TimeLimitHelp"}),m=d=new wm({generateStep:b=>{const S=Yl(b instanceof Date?(b.getTime()/1e3|0)-Qs(!0):b,1);return[wd(S,!1),b]},generateSteps:b=>[...b.map(m.generateStep),["∞",void 0]],onValue:b=>{if(!b)v();else{let S;b instanceof Date?S=b:(S=new Date,S.setSeconds(S.getSeconds()+b)),v(S.getTime()/1e3)}},middleware:this.middlewareHelper.get()}),g=new Fe({titleLangKey:"EditInvitation.ExpiryDate",titleRightSecondary:!0,clickable:()=>{let b;const S=m.value;S?b=new Date(S instanceof Date?S:Qs()+S*1e3):(b=new Date,b.setDate(b.getDate()+7)),new Fb({initDate:b,onPick:f,btnConfirmLangKey:"Save"}).show()},listenerSetter:this.listenerSetter}),f=b=>{const S=b-Qs(!0),_=T0(y,S),M=w.slice();M[_.idx]=m.generateStep(new Date(b*1e3)),m.setSteps(M,_.idx)},v=b=>{b?g.titleRight.replaceChildren(gs(b)):g.titleRight.replaceChildren(P("EditInvitation.Never"))},y=[3600,86400,86400*7],w=m.generateSteps(y);m.setSteps(w,w.length-1),t&&t.expire_date&&t.expire_date>Qs(!0)&&f(t.expire_date),p.content.append(m.container,g.container),this.scrollable.append(p.container)}let u,h;{const p=h=new Oe({name:"LimitNumberOfUses",caption:"UsesLimitHelp"}),m=u=new wm({generateStep:C=>[""+C,C],generateSteps:C=>[...C.map(m.generateStep),["∞",void 0]],onValue:C=>{S(C)},middleware:this.middlewareHelper.get()}),g=new Fe({titleLangKey:"EditInvitation.NumberOfUsers",titleRightSecondary:!0,clickable:!0,listenerSetter:this.listenerSetter,noRipple:!0}),f=new D1,{input:v}=f;this.listenerSetter.add(g.container)("mousedown",C=>{m.value||w(_[0]),Mi(C.target,v)||Ki(v)});const y=()=>{let C=f.value;const L=!C.trim();C=C.replace(/\D/g,"");const E=zt(L?0:+C,_[0],9999);L||(f.value=""+E),b=!0,w(E)};this.listenerSetter.add(v)("input",y);const w=C=>{const L=T0(_,C),E=M.slice();E[L.idx]=m.generateStep(C),m.setSteps(E,L.idx)};let b=!1;const S=C=>{if(b){b=!1;return}C?(f.value=""+C,g.titleRight.replaceChildren(v)):g.titleRight.replaceChildren(P("EditInvitation.Unlimited"))},_=[1,10,50,100],M=m.generateSteps(_);if(m.setSteps(M,M.length-1),t?.usage_limit){const C=Math.max(_[0],t.usage_limit-(t.usage||0));S(C),w(C)}p.content.append(m.container,g.container),this.scrollable.append(p.container)}if(l&&(this.listenerSetter.add(l.input)("change",()=>{h.container.classList.toggle("hide",l.checked)}),t&&(l.checked=t?.pFlags?.request_needed)),r){const p=!!t?.subscription_pricing;r.setValueSilently(!p),r.checked=p,p&&(o.value=""+t.subscription_pricing?.amount),t&&(r.toggleDisability(!0),o.container.classList.add("disable-hover"))}}}function hy(a){return!(a.pFlags.revoked||a.expire_date&&a.expire_date<=Qs(!0)||a.usage_limit&&a.usage_limit<=(a.usage||0))}class xP extends Uu{constructor(e){super({...e}),this.options=e,e.withSubtitle&&(this.subtitle=document.createElement("div"),this.subtitle.classList.add("invite-link-subtitle","hide"),this.container.append(this.subtitle))}setChatInvite(e){const t=typeof e=="string",s=typeof e=="string"?e:void 0;this.setUrl(t?"t.me/"+s:e.link),this.subtitle&&(!t&&e?.usage&&this.subtitle.replaceChildren(P("InviteLink.JoinedNew",[e.usage])),this.subtitle.classList.toggle("hide",t||!e?.usage));let i;t||(e.pFlags.revoked?(this.onButtonClick=()=>this.options.actions.deleteLink(),i="DeleteLink"):hy(e)||(this.onButtonClick=()=>this.options.actions.editLink(),i="InviteLinks.Reactivate")),i||(i="ShareLink",this.onButtonClick=void 0),this.buttonText.replaceChildren(P(i))}}class ou extends Bs{static getInitArgs(e,t){return{animationData:!t&&Ns.loadAnimationFromURLManually("UtyanLinks"),invites:I.managers.appChatInvitesManager.getExportedChatInvites({chatId:e,adminId:t}),invitesRevoked:I.managers.appChatInvitesManager.getExportedChatInvites({chatId:e,adminId:t,revoked:!0}),adminsInvites:!t&&I.managers.appChatInvitesManager.getAdminsWithInvites(e),chatFull:I.managers.appProfileManager.getChatFull(e)}}async init({chatId:e,adminId:t,p:s=ou.getInitArgs(e,t)}){this.chatId=e,this.adminId=t,this.actions={};const i=[],n=this.middlewareHelper.get(),[r,o]=await Promise.all([this.managers.appChatsManager.getChat(this.chatId),s.chatFull]),l=ji(r);this.setTitle("InviteLinks"),this.container.classList.add("chat-folders-container","chat-discussion-container");let c,d;this.adminId||(c=document.createElement("div"),c.classList.add("sticker-container"),d=document.createElement("div"),d.classList.add("caption"),d.append(P("ChannelLinkInfo")));const u=B=>B.title?je(B.title):Oo(B.link.split("://").pop());let h,p,m,g,f;const v=this.menuButtons=[{icon:"copy",text:"CopyLink",onClick:()=>h.copyLink(p?.link),verify:()=>!p?.pFlags?.revoked},{icon:"forward",text:"ShareLink",onClick:()=>{const B=p?.link||h.url;h.shareLink(B)},verify:()=>p?hy(p):!0},{icon:"edit",text:"InviteLinks.Edit",onClick:this.actions.editLink=async()=>{const B=m,N=this.slider.createTab(x0);N.eventListener.addEventListener("finish",G=>{B.destroy(),B.row.container.replaceWith(E(G).container)}),await N.open({chatId:this.chatId,invite:p}),f&&this.slider.removeTabFromHistory(f)},verify:()=>p&&!p.pFlags.revoked},{icon:"delete",className:"danger",text:"RevokeLink",onClick:this.actions.revokeLink=async()=>{const B=m;await Rt({titleLangKey:"RevokeLink",descriptionLangKey:"RevokeAlert",button:{langKey:"RevokeButton",isDanger:!0}});const N=B?.invite||g,G=await this.managers.appChatInvitesManager.editExportedChatInvite({chatId:this.chatId,link:N.link,revoked:!0}),O=G.invite,$=G.new_invite;if(B)$&&B.row.container.replaceWith(E($).container),S.content.prepend(B.row.container),B.update(O);else{const H=E(O);S.content.prepend(H.container),g=$,h.setChatInvite(g)}x(),f?.close()},verify:()=>p?!p.pFlags.revoked:!!g},{icon:"delete",className:"danger",text:"DeleteLink",onClick:this.actions.deleteLink=()=>{const B=m;this.managers.appChatInvitesManager.deleteExportedChatInvite(this.chatId,B.invite.link).then(()=>{B.destroy(!0),x(),f?.close()})},verify:()=>!!p?.pFlags?.revoked}];let y;{const B=y=new Oe({name:"InviteLink",caption:this.adminId?"ManageLinks.Admin.Permanent.Desc":void 0,captionArgs:this.adminId?await Promise.all([qe({peerId:this.adminId.toPeerId(!1)}),qe({peerId:this.chatId.toPeerId(!0)})]):void 0});h=new xP({buttons:v,listenerSetter:this.listenerSetter,actions:this.actions,withSubtitle:!0}),J(h.subtitle,()=>{_(g)},{listenerSetter:this.listenerSetter}),B.content.append(h.container)}let w;{const B=w=new Oe({name:this.adminId?"LinksCreatedByThisAdmin":"InviteLinks.Additional",caption:this.adminId?void 0:"InviteLinks.Description"});if(!this.adminId){const N=ot("btn-primary btn-transparent primary",{icon:"plus",text:"CreateNewLink"});J(N,()=>{const G=this.slider.createTab(x0);G.eventListener.addEventListener("finish",O=>{const $=E(O);g?B.content.prepend($.container):B.content.firstElementChild.after($.container)}),G.open({chatId:this.chatId})},{listenerSetter:this.listenerSetter}),B.content.append(N),B.content=B.generateContentElement()}}let b;if(!this.adminId){const B=b=new Oe({name:"LinksCreatedByOtherAdmins"}),N=s.adminsInvites.then(G=>{let{admins:O}=G;if(O=O.filter(D=>D.admin_id.toPeerId(!1)!==I.myId),!O.length){B.container.classList.add("hide");return}const $=nt.createChatList(),H=[];return O.forEach(D=>{const U=D.admin_id.toPeerId(!1),{dom:j}=nt.addDialogNew({peerId:U,container:$,rippleEnabled:!0,avatarSize:"abitbigger",append:!0,loadPromises:H,wrapOptions:{middleware:this.middlewareHelper.get()}});j.lastMessageSpan.append(P("InviteLinkCount",[D.invites_count]))}),J($,D=>{const U=ne(D.target,"chatlist-chat");if(!U)return;const j=U.dataset.peerId.toPeerId();this.slider.createTab(ou).open({chatId:this.chatId,adminId:j.toUserId()})},{listenerSetter:this.listenerSetter}),B.content.append($),Promise.all(H)},()=>{B.container.remove()});i.push(N)}let S;{const B=S=new Oe({name:"RevokedLinks"}),N=ot("btn-primary btn-transparent danger",{icon:"delete",text:"DeleteAllRevokedLinks"});J(N,async()=>{await Rt({titleLangKey:"DeleteAllRevokedLinks",descriptionLangKey:"ManageLinks.DeleteAll.Confirm",button:{langKey:"Delete",isDanger:!0}});const G=os(N,!0);await this.managers.appChatInvitesManager.deleteRevokedExportedChatInvites(this.chatId,this.adminId),G(),Array.from(B.content.children).forEach(O=>{C.get(O).destroy(!0)}),x()},{listenerSetter:this.listenerSetter}),B.content.append(N),B.content=B.generateContentElement()}this.scrollable.append(...[c,d,y.container,w.container,b?.container,S.container].filter(Boolean));const _=B=>{const N=f=this.slider.createTab(w7);N.eventListener.addEventListener("close",()=>{f=m=p=void 0}),N.open(this.chatId,B,this,m?.update)};J(this.scrollable.container,B=>{const N=ne(B.target,"is-link");N&&(m=C.get(N),p=m.invite,_(p))},{listenerSetter:this.listenerSetter}),Dn({buttons:v,listenTo:this.scrollable.container,findElement:B=>{const N=ne(B.target,"is-link");return N&&(m=C.get(N),p=m.invite),N},onClose:()=>m=p=void 0,middleware:n,listenerSetter:this.listenerSetter});const M=c&&s.animationData.then(async B=>{const N=await B({container:c,loop:!0,autoplay:!0,width:120,height:120});return Ns.waitForFirstFrame(N)}),C=new Map,L=new Set,E=B=>{let N,G;B.subscription_pricing&&(N=zg({stars:B.subscription_pricing.amount}),G=P("Stars.Subscriptions.PerMonth"));const O=new gb(!0,B.subscription_pricing?"link_paid":void 0,B.subscription_pricing?"green":void 0,N,G);O.title.replaceChildren(u(B)),!B.expire_date&&!B.pFlags.revoked&&!B.subscription_pricing&&delete O.media.dataset.color;let $;const H=W=>{$?.(),C.delete(O.container),W&&O.container.remove()},D=W=>{W&&(B=U.invite=W);const ee=[],z=B.usage||0,Z=B.requested||0,de=Qs(!0),ie=B.expire_date,oe=ie&&ie<=de,ae=z&&z>=B.usage_limit,ke=ie?Math.max(0,ie-de):void 0;if(B.pFlags.revoked?(ee.push(P("InviteLink.JoinedRevoked"),P("ExportedInvitation.Status.Revoked")),O.media.dataset.color="archive",j&&(j.parentElement.remove(),j=void 0),$?.()):z?(ee.push(P("InviteLink.JoinedNew",[z])),ae?(ee.push(P("InviteLinks.LimitReached")),O.media.dataset.color="red"):B.usage_limit?ee.push(P("PeopleJoinedRemaining",[B.usage_limit-z])):Z&&ee.push(P("JoinRequests",[Z]))):Z?ee.push(P("JoinRequests",[Z])):B.usage_limit&&!oe?ee.push(P("CanJoin",[B.usage_limit])):ee.push(P(oe?"InviteLink.JoinedRevoked":"Chat.VoiceChat.JoinLink.Participants_ZeroValueHolder")),!B.pFlags.revoked&&ie&&(oe?(O.media.dataset.color="red",ee.push(P("ExportedInvitation.Status.Expired")),$?.()):ee.push(P("InviteLink.Sticker.TimeLeft",[w_(ke)]))),!B.pFlags.revoked&&(ie&&!oe||B.usage_limit&&!ae)){const re=B.usage_limit?z/B.usage_limit:void 0,ce=ie?1-ke/(ie-(B.start_date||B.date)):void 0,Ie=Math.max(re??0,ce??0),Ve=Pa(yi.getProperty("green-color")),fe=Pa(yi.getProperty("danger-color")),Xe=Jd(fe,Ve,Ie),Ye=wv(...Xe);if(Ye.s=Math.max(55,Ye.s),O.media.style.setProperty("--color",HL(Ye)),j&&(q??(q=j.getTotalLength()),j.style.strokeDasharray=`${q*(1-Ie)}, ${q}`,oe)){const Ze=()=>{Je.parentElement.remove()},Je=j;j=void 0,setTimeout(Ze,400)}}O.subtitle.replaceChildren(...Kl(ee," • "))},U={row:O,invite:B,update:D,destroy:H};C.set(O.container,U);let j,q=146.70338439941406;return(B.expire_date||B.usage_limit)&&hy(B)&&(B.expire_date&&($=()=>{L.delete(D)},L.add(D),n.onDestroy($)),O.media.insertAdjacentHTML("beforeend",`
- <svg class="usernames-username-icon-svg" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 51 51">
- <circle class="usernames-username-icon-circle" cx="25.5" cy="25.5" r="23.5"/>
- </svg>
- `),j=O.media.lastElementChild.firstElementChild),D(),O},x=()=>{S.container.classList.toggle("hide",!S.content.childElementCount)},R=Promise.all([s.invites,s.invitesRevoked]).then(([B,N])=>{this.adminId?g=B.invites[0]:l.length||(g=o.exported_invite),h.setChatInvite(g||l[0]),[[B,w],[N,S]].forEach(([$,H])=>{$.invites.forEach(D=>{if(g?.link===D.link)return;const U=E(D);H.content.append(U.container)})}),x();const O=setInterval(()=>{L.forEach($=>$())},1e3);n.onDestroy(()=>{C.forEach(({destroy:$})=>$()),clearInterval(O)}),this.listenerSetter.add(I)("theme_changed",()=>{C.forEach(({update:$})=>$())})});return i.push(M,R),Promise.all(i)}}function uy({chatId:a,managers:e,link:t,requested:s}){const i=[],n=new Map;let r="";return{importers:i,importersMap:n,load:async c=>{r!==c&&(i.length=0,n.clear(),r=c);const d=50,u=i[i.length-1],h=await e.appChatInvitesManager.getChatInviteImporters({chatId:a,limit:d,link:t,requested:s,offsetDate:u?.date,offsetUserId:u?.user_id,q:c});return i.push(...h.importers),{result:h.importers.map(p=>{const m=p.user_id.toPeerId(!1);return n.set(m,p),m}),isEnd:h.importers.length<d}},deleteImporter:c=>{i.splice(i.findIndex(d=>d.user_id.toPeerId(!1)===c),1),n.delete(c)}}}class w7 extends Bs{async init(e,t,s,i){const n=await this.managers.appChatsManager.isBroadcast(e);t.title?this.title.replaceChildren(je(t.title)):this.setTitle("InviteLink");{const o=t.expire_date&&t.expire_date>Qs(!0),l=t.usage_limit&&t.usage_limit<=(t.usage||0),c=new Oe({name:"InviteLink",caption:l?"LinkIsExpiredLimitReached":o?"InviteLinks.ExpiresCaption":t.expire_date?"LinkIsExpired":void 0,captionArgs:o?[gs(t.expire_date)]:void 0}),d=new xP({buttons:s.menuButtons,listenerSetter:this.listenerSetter,url:t.link,actions:s.actions});d.setChatInvite(t),c.content.append(d.container),this.scrollable.append(c.container)}{const o=new Oe({name:"LinkCreatedeBy"}),l=document.createElement("div");l.classList.add("chatlist-container"),o.content.append(l);const c=nt.createChatList({new:!0});l.append(c);const d=t.admin_id.toPeerId(!1),{dom:u}=nt.addDialogNew({peerId:d,container:c,rippleEnabled:!0,avatarSize:"abitbigger",meAsSaved:!1,wrapOptions:{middleware:this.middlewareHelper.get()}});u.titleSpan.classList.add("text-bold"),J(u.listEl,()=>{Ce.setInnerPeer({peerId:d})},{listenerSetter:this.listenerSetter}),u.lastMessageSpan.append(gs(t.date)),this.scrollable.append(o.container)}if(t.subscription_pricing){const o=new Oe({name:"InviteLink.Observe.Fee"}),l=new gb(!0,"link_paid","green"),c=t.subscription_pricing.amount,d=t.usage??0,u=P("InviteLink.Observe.Fee.Title",[zg({stars:c}),d]),h=P("InviteLink.Observe.Fee.Subtitle",["$"+(d*+c*.02).toFixed(2)]);l.title.append(u),l.subtitle.append(h),o.content.append(l.container),this.scrollable.append(o.container)}if(t.usage_limit&&!t.usage&&(!t.expire_date||t.expire_date>Qs(!0))){const o=new Oe({}),l=new Fe({title:P("PeopleCanJoinViaLinkCount",[t.usage_limit])});o.content.append(l.container),this.scrollable.append(o.container)}const r=[];if(t.requested){const o=new Oe({name:"JoinRequests",nameArgs:[t.requested]}),{importersMap:l,load:c}=uy({chatId:e,managers:this.managers,link:t.link,requested:!0}),d=new Map,u=async g=>{const f=[];return g.result.forEach(v=>{const y=nt.addDialogNew({peerId:v,container:h,rippleEnabled:!0,avatarSize:"abitbigger",append:!0,loadPromises:f,wrapOptions:{middleware:this.middlewareHelper.get()}});d.set(v,y),y.dom.lastMessageSpan.append(gs(l.get(v).date))}),Promise.all(f)},h=nt.createChatList();o.content.append(h),this.scrollable.append(o.container);let p;const m=async g=>{const f=p.dataset.peerId.toPeerId(),v=d.get(f),y=v.toggleDisability(!0);try{await this.managers.appChatsManager.hideChatJoinRequest(e,f,g),v.remove(),d.delete(f),g&&(t.usage=(t.usage||0)+1),--t.requested||(delete t.requested,o.container.remove()),i?.(t)}catch{y()}};Dn({buttons:[{icon:"adduser",text:n?"AddToChannel":"AddToGroup",onClick:()=>m(!0)},{icon:"crossround",text:"Dismiss",onClick:()=>m(!1)}],listenTo:h,listenerSetter:this.listenerSetter,middleware:this.middlewareHelper.get(),findElement:g=>p=ne(g.target,"chatlist-chat")}),r.push(c("",()=>!0).then(u))}if(t.usage){const{importersMap:o,load:l}=uy({chatId:e,managers:this.managers,link:t.link,requested:!1}),c=Mt(),d=new wn({middleware:this.middlewareHelper.get(),appendTo:this.container,onSelect:u=>{Ce.setInnerPeer({peerId:u})},peerType:["custom"],getMoreCustom:l,getSubtitleForElement:u=>gs(o.get(u)?.date),sectionNameLangPackKey:P("PeopleJoined",[t.usage]),onFirstRender:()=>{c.resolve()},managers:this.managers,noSearch:!0,multiSelect:!1});if(this.content.remove(),d.scrollable.attachBorderListeners(this.container),d.scrollable.prepend(...Array.from(this.scrollable.container.children)),t.usage_limit){const u=P("PeopleJoinedRemaining",[t.usage_limit-t.usage]);u.classList.add("sidebar-left-section-name-right"),d.section.title.append(u)}r.push(c)}return Promise.all(r)}}class py extends Bs{async init(e,t){const s=await this.managers.appChatsManager.isBroadcast(e);this.container.classList.add("edit-peer-container","chat-members-container","chat-requests-container"),this.setTitle(s?"SubscribeRequests":"MemberRequests");const{importersMap:i,deleteImporter:n,load:r}=uy({chatId:e,managers:this.managers,requested:!0,link:t}),o=new Map,{selector:l,loadPromise:c}=kP({appendTo:this.content,managers:this.managers,middleware:this.middlewareHelper.get(),peerId:e.toPeerId(!0),peerType:["custom"],getMoreCustom:r,getSubtitleForElement:u=>P("RequestedToJoinAt",[gs(i.get(u)?.date)]),processElementAfter:(u,h)=>{const p=document.createElement("div");p.classList.add("chatlist-chat-buttons");const m=ot("btn-primary btn-control-small btn-color-primary",{text:s?"AddToChannel":"AddToGroup"}),g=ot("btn-transparent btn-control-small primary",{text:"Dismiss"});p.append(m,g),h.container.append(p),o.set(u,h)},placeholderElementsGap:36});let d=0;return J(l.scrollable.container,async u=>{const h=ne(u.target,"chatlist-chat");if(!h)return;const p=h.dataset.peerId.toPeerId(),m=o.get(p),g=ne(u.target,"btn-color-primary"),f=ne(u.target,"btn-transparent"),v=g?!0:f?!1:void 0;if(v===void 0){Ce.setInnerPeer({peerId:p});return}const y=m.toggleDisability(!0);try{await this.managers.appChatsManager.hideChatJoinRequest(e,p,v),++d,l.deletePeerId(p),o.delete(p),n(p)}catch{y()}},{listenerSetter:this.listenerSetter}),this.eventListener.addEventListener("close",()=>{this.eventListener.dispatchEvent("finish",d)}),c}}class S7 extends Pd{constructor(e,t,s){super({topbar:e,chat:t,listenerSetter:e.listenerSetter,className:"requests",divAndCaption:new Og("pinned-requests",i=>{}),onClose:()=>{Ae.getState().then(i=>{i.hideChatJoinRequests[this.peerId]=Date.now(),this.managers.appStateManager.pushToState("hideChatJoinRequests",i.hideChatJoinRequests)})},floating:!0,height:52}),this.topbar=e,this.chat=t,this.managers=s,J(this.wrapper,async i=>{if(_e(i),Gs.isTabExists(py))return;await Gs.createTab(py).open(this.chat.peerId.toChatId()),Gs.toggleSidebar(!0)},{listenerSetter:this.topbar.listenerSetter}),this.divAndCaption.border.remove(),this.divAndCaption.content.remove(),this.titleElement=new Ne.IntlElement({key:"Chat.Header.RequestToJoin",args:[0],element:this.divAndCaption.title})}unset(e){this.peerId=e,this.stackedAvatars&&(this.stackedAvatars.container.remove(),this.stackedAvatarsMiddlewareHelper.destroy()),this.toggle(!0)}async set(e,t,s){if(!t.length)return()=>this.unset(e);const i=this.stackedAvatars,n=this.stackedAvatarsMiddlewareHelper;this.stackedAvatarsMiddlewareHelper=Ht();const r=this.stackedAvatars=new Zl({avatarSize:32,middleware:this.stackedAvatarsMiddlewareHelper.get()}),o=[];return r.render(t,o),await Promise.all(o),()=>{this.peerId=e,this.titleElement.compareAndUpdate({args:[s]}),this.wrapperUtils.before(r.container,this.titleElement.element),i&&(i.container.remove(),n?.destroy()),this.toggle(!1)}}setPeerId(e){return Promise.all([this.chat.managers.acknowledged.appProfileManager.getProfileByPeerId(e),Ae.getState()]).then(([t,s])=>({cached:t.cached,result:en(t.result,i=>{const n=i?.recent_requesters;return n&&(!s.hideChatJoinRequests[e]||Date.now()-s.hideChatJoinRequests[e]>=$y)?this.set(e,n.slice(0,3).map(r=>r.toPeerId(!1)),i.requests_pending):this.set(e,[],0)})}))}}class C7 extends Pd{constructor(e,t,s){super({topbar:e,chat:t,listenerSetter:e.listenerSetter,className:"actions",divAndCaption:new Og("pinned-actions",n=>{}),onClose:()=>{this.managers.appProfileManager.hidePeerSettingsBar(this.peerId)},floating:!0,height:52}),this.topbar=e,this.chat=t,this.managers=s,this.wrapper.firstElementChild.remove(),this.divAndCaption.border.remove(),this.divAndCaption.content.remove(),((n,r)=>{J(n,o=>{_e(o),r(o)},{listenerSetter:this.topbar.listenerSetter})})(this.wrapper,n=>{const r=ne(n.target,"pinned-actions-button");if(!r)return;const o=r.dataset.key;this.actions.find(c=>c.key===o).onClick()}),this.actions=[{key:"autoarchived",onClick:async()=>{const n=this.managers.appMessagesManager.editPeerFolders([this.peerId],0);this.freeze(n)}},{key:"block_contact",onClick:()=>{this.chat.topbar.blockUser(this.filteredActions.some(n=>n.key==="report_spam"),!0,n=>{this.freeze(n)})},danger:!0},{key:"add_contact",onClick:()=>{this.chat.topbar.addContact()}},{key:"report_spam",onClick:async()=>{const n=this.peerId;if(n.isUser())this.actions.find(r=>r.key==="block_contact").onClick();else{await Rt({titleLangKey:"Chat.Confirm.ReportSpam.Header",descriptionLangKey:this.managers.appPeersManager.isBroadcast(n)?"Chat.Confirm.ReportSpam.Channel":"Chat.Confirm.ReportSpam.Group",button:{langKey:"ReportChat"}});const r=Promise.all([this.managers.appMessagesManager.reportSpam(n),this.managers.appChatsManager.leave(n.toChatId())]);this.freeze(r)}},danger:!0}]}async freeze(e){this.wrapper.classList.add("is-disabled");try{await e}catch{}this.wrapper.classList.remove("is-disabled")}unset(e){this.peerId=e,this.toggle(!0)}set(e,t){const s=t?.pFlags?this.actions.filter(i=>t.pFlags[i.key]):[];return s.length?()=>{this.peerId=e,this.filteredActions=s;const i={add_contact:"AddContact",autoarchived:"Unarchive",block_contact:"BlockUser",report_spam:"DeleteReportSpam"},n=[];for(let r=0,o=Math.min(2,s.length);r<o;++r){const l=s[r],c=document.createElement("div");c.classList.add("pinned-actions-button",l.danger?"danger":"primary"),o>1&&c.classList.add("half",r===0?"is-first":"is-last"),c.dataset.key=l.key,n.push(c);const d=P(i[l.key]);d.classList.add("pinned-actions-button-text"),Ei(c),c.append(d)}this.wrapper.replaceChildren(...n,this.wrapperUtils),this.toggle(!1)}:()=>this.unset(e)}setPeerId(e){return Promise.all([this.chat.managers.acknowledged.appProfileManager.getPeerSettings(e)]).then(([t])=>({cached:t.cached,result:en(t.result,s=>this.set(e,s))}))}}function Ro(a,e){St(a,e),a.classList.toggle("is-badge-empty",!e)}const Ih=(a="")=>`pinned-live${a}`,_7=Y("<div>"),I7=Y("<button><div>"),P7=a=>{const e=wt.isAvailable("animations"),[t,s]=K(e);return e&&le(Vt(a.animationTrigger,()=>{s(!0)})),(()=>{const i=I7(),n=i.firstChild,r=a.ref;return typeof r=="function"?Ue(r,i):a.ref=i,k(i,T(Js,{get when(){return t()},get children(){const o=_7();return o.addEventListener("animationend",()=>s(!1)),Me(()=>be(o,Ih("-button-animation"))),o}}),n),k(n,()=>P("Rtmp.Topbar.Join")),Me(o=>{const l=Ih("-button-wrap"),c=Ih("-button");return l!==o._v$&&be(i,o._v$=l),c!==o._v$2&&be(n,o._v$2=c),o},{_v$:void 0,_v$2:void 0}),i})()},M7=Y("<div>"),L7=Y("<div class=skeleton-child>"),Qm=a=>{const e=()=>typeof a.children=="function"?a.children():a.children,t=()=>typeof a.loading=="function"?a.loading():a.loading,s=T(Js,{get when(){return t()},get fallback(){return V(()=>!!e())()&&(()=>{const i=L7();return k(i,e),i})()},get children(){const i=M7();return Me(()=>be(i,`skeleton ${a.class??""}`)),i}});return T(Du,{name:"fade",mode:"outin",duration:100,children:s})},E7=Y("<div>"),k7=a=>{const e=()=>a.watching>0?P("Rtmp.Watching",[hb(Math.max(0,a.watching))]):P("Rtmp.Topbar.NoViewers"),t=(()=>{const r=E7();return k(r,T(Qm,{get loading(){return a.watching===void 0},get children(){return e()}})),r})(),{container:s}=Hu({title:P("Rtmp.Topbar.Title"),subtitle:t}),i=document.createElement("div");i.classList.add(Ih()+"-background"),s.prepend(i),s.classList.remove("quote-like-hoverable"),s.classList.add(Ih()+"-wrapper"),ze(J(s,a.onJoin));let n;return T(P7,{ref(r){const o=n;typeof o=="function"?o(r):n=r},get animationTrigger(){return a.animationTrigger}}),s.append(n),s};var qn=(a=>(a[a.PLAYING=0]="PLAYING",a[a.BUFFERING=1]="BUFFERING",a[a.CONNECTING=2]="CONNECTING",a[a.CLOSED=3]="CLOSED",a))(qn||{});class Na extends pn{constructor(e){super(!1),Object.assign(this,e),this._state=qn.CONNECTING}cleanup(){super.cleanup()}get state(){return this._state}set state(e){this._state=e,this.dispatchEvent("state",e)}}class T7 extends pn{constructor(){super(...arguments),this.onGroupCallUpdate=e=>{if(e.id===this.currentCall?.call.id){if(e._==="groupCallDiscarded"){this.currentCall=void 0;return}this.currentCall.call=e,this.dispatchEvent("currentCallChanged",this.currentCall)}}}construct(e){this.managers=e,I.addEventListener("group_call_update",this.onGroupCallUpdate),Ae.serviceMessagePort.addEventListener("rtmpStreamTime",({callId:t,time:s})=>{this.currentCall?.call.id===t&&(this.currentCall.lastKnownTime=s)})}get currentCall(){return this._currentCall}set currentCall(e){this.currentCall!==e&&(this._currentCall?.cleanup(),this.dispatchEvent("currentCallChanged",this._currentCall=e))}randomSsrc(){return(Math.random()<.5?-1:1)*GL(16)}getJoinPayload(e){return{_:"dataJSON",data:JSON.stringify({fingerprints:[],pwd:"",ssrc:e,"ssrc-groups":[],ufrag:""})}}async joinCall(e){if(this.currentCall)throw new Error("Already in rtmp call");const t=e.toPeerId(!0);this.dispatchEvent("startedJoining",t);const s=this.randomSsrc(),i=this.getJoinPayload(s),n=await this.managers.appProfileManager.getChatFull(e);if(n._!=="channelFull")throw new Error("Not a chat");const r=await this.managers.appGroupCallsManager.getGroupCallFull(n.call.id);if(r._!=="groupCall")throw new Error("Not a group call");const o=await this.managers.appGroupCallsManager.joinGroupCall(n.call.id,i,{type:"main"});if(JSON.parse(o.params.data).rtmp!==!0)throw new Error("Not an rtmp call");this.currentCall=new Na({call:r,inputCall:{_:"inputGroupCall",id:r.id,access_hash:r.access_hash},chatId:e,peerId:t,ssrc:s,pip:!1,admin:!!n.pFlags?.can_delete_channel,lastKnownTime:"0"})}async leaveCall(e=!1){if(!this.currentCall)return;const t=this.currentCall;this.currentCall=void 0,Ae.serviceMessagePort.invokeVoid("leaveRtmpCall",[t.call.id,!0]),await this.managers.appGroupCallsManager.hangUp(t.call.id,e?!0:t.ssrc)}async isCurrentCallDead(e=!1,t=!1){if(!this.currentCall)return"dead";const s=await this.managers.appGroupCallsManager.fetchRtmpState(this.currentCall.inputCall);if(!e)return s.channels.length===0?"dead":"alive";const i=s.channels.find(n=>n.channel===L0);if(!i)return"dead";try{const n=this.currentCall.lastKnownTime==="0"?i.last_timestamp_ms:this.currentCall.lastKnownTime;return await this.managers.appGroupCallsManager.fetchRtmpPart({_:"inputGroupCallStream",call:this.currentCall.inputCall,video_channel:L0,video_quality:q6,scale:i.scale,time_ms:n},s.dcId),"alive"}catch(n){if(n.type==="GROUPCALL_JOIN_MISSING"&&!t)try{return await this.rejoinCall(),this.isCurrentCallDead(!0,!0)}catch{}}return"dying"}async rejoinCall(){if(!this.currentCall)return;this.currentCall.ssrc=this.randomSsrc();const e=this.getJoinPayload(this.currentCall.ssrc);await this.managers.appGroupCallsManager.joinGroupCall(this.currentCall.call.id,e,{type:"main"})}}const cs=new T7;Di&&(Di.rtmpCallsController=cs);function x7(){const[a,e]=K(cs.currentCall,{equals:!1}),[t,s]=K(Wt);return Ta(cs)("currentCallChanged",i=>{e(i),s(i?.peerId)}),Ta(cs)("startedJoining",i=>{s(i)}),{call:a,peerId:t}}class A7 extends Pd{constructor(e,t,s){super({topbar:e,chat:t,listenerSetter:e.listenerSetter,className:"live",floating:!0,height:56}),this.topbar=e,this.chat=t,this.managers=s,[this.peerId,this.setPeerId]=K(Wt),this.dispose=wi(()=>this.init(),this.container)}init(){const{peerId:e}=this,[t,s]=K(),i=qC(()=>e().toChatId()),n=x7(),r=V(()=>{const d=i();return!!(d&&d.pFlags.broadcast&&d.pFlags.call_active&&d.pFlags.call_not_empty)}),o=V(()=>r()&&n.peerId()!==e()),l=()=>I.managers.appProfileManager.getChatFull(e().toChatId());Ta(I)("group_call_update",async d=>{if(!r()||d._!=="groupCall")return;const u=await l();u?._==="channelFull"&&d.id===u.call?.id&&s(d.participants_count)}),le(d=>{if(!(!i()||!i().pFlags.broadcast))return d!==e()&&s(),le(async()=>{r()||s();const u=await l();if(u?._!=="channelFull"||!u.call)return;const h=await I.managers.appGroupCallsManager.getGroupCallFull(u.call.id);h?._==="groupCall"&&s(h.participants_count)}),e()}),le(()=>{this.toggle(!o())});const c=()=>{Ce.joinLiveStream(e())};return T(Js,{get when(){return o()},get children(){return T(k7,{get watching(){return t()},animationTrigger:e,onJoin:c})}})}destroy(){super.destroy(),this.dispose()}}const R7=Y("<div><div><div>"),F7=Y("<div><div><div><div></div><div></div></div></div><div><div><div></div><div>"),Ui=(a="")=>`rtmp-data${a}`,AP=a=>{const[e,t]=K(!1),s=()=>e()?a.key:a.key.slice(0,20).replace(/./g,"·"),i=r=>{r.stopPropagation(),t(!e())},n=(r,o)=>{si(r),$e({langPackKey:o})};return(()=>{const r=F7(),o=r.firstChild,l=o.firstChild,c=l.firstChild,d=c.nextSibling,u=o.nextSibling,h=u.firstChild,p=h.firstChild,m=p.nextSibling;return o.$$click=()=>n(a.url,"Rtmp.StreamPopup.URLCopied"),k(o,T(hs,{icon:"link",get class(){return Ui("-row-icon")}}),l),k(c,T(Qm,{get loading(){return a.loading},get children(){return a.url}})),k(d,()=>P("Rtmp.StreamPopup.ServerURL")),k(o,T(hs,{icon:"copy",get class(){return Ui("-row-icon")}}),null),u.$$click=()=>n(a.key,"Rtmp.StreamPopup.KeyCopied"),k(u,T(hs,{icon:"lock",get class(){return Ui("-row-icon")}}),h),k(p,T(Qm,{get loading(){return a.loading},get children(){return s()}})),k(m,()=>P("Rtmp.StreamPopup.StreamKey"),null),k(m,T(Pi,{get icon(){return e()?"eye2":"eye1"},onClick:i,get class(){return Ui("-row-item-show")}}),null),k(u,T(hs,{icon:"copy",get class(){return Ui("-row-icon")}}),null),k(r,T(Js,{get when(){return a.showRevoke},get children(){const g=R7(),f=g.firstChild,v=f.firstChild;return Lr(g,"click",a.onRevoke,!0),k(g,T(hs,{icon:"rotate_left",get class(){return Ui("-row-icon")}}),f),k(v,()=>P("Rtmp.StreamPopup.RevokeStreamKey")),Me(y=>{const w=Ge(Ui("-row"),Ui("-row_danger")),b=Ui("-row-item"),S=Ui("-row-item-label");return w!==y._v$&&be(g,y._v$=w),b!==y._v$2&&be(f,y._v$2=b),S!==y._v$3&&be(v,y._v$3=S),y},{_v$:void 0,_v$2:void 0,_v$3:void 0}),g}}),null),Me(g=>{const f={[Ui()]:!0,[Ui("_contrast")]:a.contrast},v=Ui("-row"),y=Ui("-row-item"),w=Ui("-row-item-text"),b=Ui("-row-item-label"),S=Ui("-row"),_=Ui("-row-item"),M={[Ui("-row-item-text")]:!0,[Ui("-row-item-text_hidden")]:!e()},C=Ui("-row-item-label");return g._v$4=er(r,f,g._v$4),v!==g._v$5&&be(o,g._v$5=v),y!==g._v$6&&be(l,g._v$6=y),w!==g._v$7&&be(c,g._v$7=w),b!==g._v$8&&be(d,g._v$8=b),S!==g._v$9&&be(u,g._v$9=S),_!==g._v$10&&be(h,g._v$10=_),g._v$11=er(p,M,g._v$11),C!==g._v$12&&be(m,g._v$12=C),g},{_v$4:void 0,_v$5:void 0,_v$6:void 0,_v$7:void 0,_v$8:void 0,_v$9:void 0,_v$10:void 0,_v$11:void 0,_v$12:void 0}),r})()};Fs(["click"]);const B7=Y("<div>"),D7=Y("<button>"),$7=Y("<div><div>"),gc=(a="")=>`rtmp-popup${a}`;class RP extends ue{constructor(e){super(gc(),{overlayClosable:!0,closable:!0,title:!0,body:!0}),this.props=e;const{active:t}=e;t||(this.btnMore=ki({buttons:[{icon:"stop",regularText:"Revoke",danger:!0,onClick:()=>this._revokeKey()}],direction:"bottom-left"}),this.header.append(this.btnMore)),this.title.append(t?P("Rtmp.StreamPopup.TitleSettings"):P("Rtmp.StreamPopup.Title")),this._render()}_render(){this._dispose=Ft(e=>{const[t,s]=K(""),[i,n]=K(""),[r,o]=K(!0);this._setLoading=o,this._setUrl=s,this._setKey=n;const l=wi(()=>{const c=this;return T(N7,{get url(){return t()},get key(){return i()},get loading(){return r()},get active(){return!!c.props.active},onStreamStart:()=>c._onStreamStart(),onRevoked:()=>c._revokeKey()})},this.body);return this._fetchData(),()=>{s(""),n(""),o(!1),l(),e()}})}_revokeKey(){this._setLoading(!0),this._fetchData(!0)}_fetchData(e=!1){this.managers.appGroupCallsManager.fetchRtmpUrl(this.props.peerId,e).then(({url:t,key:s})=>{this._setUrl(t),this._setKey(s),this._setLoading(!1)}).catch(()=>{$e({langPackKey:"Error.AnError"}),this.forceHide()})}_onStreamStart(){if(this.forceHide(),this.props.active){this.props.onEndStream();return}const e=this.props.peerId.toChatId();this.managers.appGroupCallsManager.createGroupCall(e,void 0,void 0,!0).then(()=>{cs.joinCall(e)})}cleanup(){super.cleanup(),this._dispose()}}const N7=a=>(()=>{const e=$7(),t=e.firstChild;return k(t,()=>P("Rtmp.StreamPopup.Description")),k(e,T(AP,{get key(){return a.key},get url(){return a.url},get loading(){return a.loading},get showRevoke(){return a.active},get onRevoke(){return a.onRevoked}}),null),k(e,T(Js,{get when(){return!a.active},get children(){const s=B7();return k(s,()=>P("Rtmp.StreamPopup.Hint")),Me(()=>be(s,gc("-text"))),s}}),null),k(e,T(Ku,{get children(){const s=D7();return Lr(s,"click",a.onStreamStart,!0),k(s,(()=>{const i=V(()=>!!a.active);return()=>i()?P("Rtmp.StreamPopup.EndLiveStream"):P("Rtmp.StreamPopup.StartStreaming")})()),Me(i=>er(s,{[gc("-button")]:!0,[gc("-button_danger")]:a.active},i)),s}}),null),Me(s=>{const i=gc("-content"),n=gc("-text");return i!==s._v$&&be(e,s._v$=i),n!==s._v$2&&be(t,s._v$2=n),s},{_v$:void 0,_v$2:void 0}),e})();Fs(["click"]);class rw{constructor(e={}){this.options=e,this.fullTexts=new Map,e.minChars??(e.minChars=0)}indexObject(e,t){if(t.trim()&&(t=this.processSearchText(t)),!t)return this.fullTexts.delete(e),!1;this.fullTexts.set(e,t)}indexObjectArray(e,t){return this.indexObject(e,t.join(" "))}_search(e,t=e.split(" ").filter(i=>i.trim()),s=this.options.minChars){const i=[],n=this.fullTexts,r=t.length;return n.forEach((o,l)=>{let c=!0,d=0;for(let u=0;u<r;++u){const h=t[u],p=o.indexOf(h),m=u===r-1;if(p===-1||this.options.fullWords&&!m&&o[p+h.length]!==" "||p!==0&&o[p-1]!==" "){c=!1;break}d+=h.length}if(c){d+=r-1;const u=o.length;(s<=d||u<=d)&&i.push({fullText:o,fullTextLength:u,what:l,foundChars:d})}}),i}search(e,t){e=this.processSearchText(e);const i=e.split("").map(o=>this._search(o,void 0,t)),n=va(i);return n.sort((o,l)=>{const c=o.fullTextLength-o.foundChars,d=l.fullTextLength-l.foundChars;return c-d||o.fullTextLength-l.fullTextLength}),new Set(n.map(o=>o.what))}processSearchText(e){return this.options?z3(e,this.options):e}}const A0=[["af","Afrikaans"],["sq","Shqip"],["am","አማርኛ"],["ar","العربية"],["hy","Հայերեն"],["az","Azərbaycan dili"],["eu","Euskara"],["be","Беларуская"],["bn","বাংলা"],["bs","Bosanski"],["bg","Български"],["ca","Català"],["ceb","Cebuano"],["zh-CN","简体中文"],["zh","中文"],["zh-TW","繁體中文"],["co","Corsu"],["hr","Hrvatski"],["cs","Čeština"],["da","Dansk"],["nl","Nederlands"],["en","English"],["eo","Esperanto"],["et","Eesti"],["fi","Suomi"],["fr","Français"],["fy","Frysk"],["gl","Galego"],["ka","ქართული"],["de","Deutsch"],["el","Ελληνικά"],["gu","ગુજરાતી"],["ht","Kreyòl ayisyen"],["ha","Hausa"],["haw","ʻŌlelo Hawaiʻi"],["he","עברית"],["iw","עברית"],["hi","हिन्दी"],["hmn","Hmoob"],["hu","Magyar"],["is","Íslenska"],["ig","Igbo"],["id","Indonesia"],["ga","Gaeilge"],["it","Italiano"],["ja","日本語"],["jv","Basa Jawa"],["kn","ಕನ್ನಡ"],["kk","Қазақ тілі"],["km","ភាសាខ្មែរ"],["rw","Kinyarwanda"],["ko","한국어"],["ku","Kurdî"],["ky","Кыргызча"],["lo","ລາວ"],["la","Latina"],["lv","Latviešu"],["lt","Lietuvių"],["lb","Lëtzebuergesch"],["mk","Македонски"],["mg","Malagasy"],["ms","Bahasa Melayu"],["ml","മലയാളം"],["mt","Malti"],["mi","Māori"],["mr","मराठी"],["mn","Монгол"],["my","ဗမာ"],["ne","नेपाली"],["no","Norsk"],["ny","Chichewa"],["or","ଓଡ଼ିଆ"],["ps","پښتو"],["fa","فارسی"],["pl","Polski"],["pt","Português"],["pa","ਪੰਜਾਬੀ"],["ro","Română"],["ru","Русский"],["sm","Gagana fa'a Samoa"],["gd","Gàidhlig"],["sr","Српски"],["st","Sesotho"],["sn","Shona"],["sd","سنڌي"],["si","සිංහල"],["sk","Slovenčina"],["sl","Slovenščina"],["so","Soomaali"],["es","Español"],["su","Basa Sunda"],["sw","Kiswahili"],["sv","Svenska"],["tl","Tagalog"],["tg","Тоҷикӣ"],["ta","தமிழ்"],["tt","Татар теле"],["te","తెలుగు"],["th","ไทย"],["tr","Türkçe"],["tk","Türkmen"],["uk","Українська"],["ur","اردو"],["ug","ئۇيغۇرچە"],["uz","O‘zbek"],["vi","Tiếng Việt"],["cy","Cymraeg"],["xh","isiXhosa"],["yi","ייִדיש"],["yo","Yorùbá"],["zu","isiZulu"]],O7=Y("<div class=pinned-translation-button>");function ow(a,e){const t=Mt(),s=new rw({ignoreCase:!0}),i=new Map;A0.forEach(([r,o])=>{const l=Ne.format(`Language.${r}`,!0);i.set(r,[o,l]),s.indexObjectArray(r,[r,o,l])});const n=ue.createPopup(Rs,{peerType:["custom"],renderResultsFunc:r=>{r.forEach(o=>{const[l,c]=i.get(o),d=new Fe({title:c,subtitle:l,clickable:!0,havePadding:a});a&&d.container.append(n.selector.checkbox(n.selector.selected.has(o))),d.container.dataset.peerId=""+o,n.selector.list.append(d.container)})},placeholder:"Search",getMoreCustom:async r=>({result:r?[...s.search(r)]:A0.map(([l])=>l),isEnd:!0}),onSelect:a?void 0:t.resolve.bind(t),onMultiSelect:a?t.resolve.bind(t):void 0,titleLangKey:a?"Telegram.LanguageViewController":void 0,checkboxSide:"left",noPlaceholder:!0});if(n.addEventListener("close",()=>{t.reject()}),e){const r=n.selector.add.bind(n.selector);n.selector.add=({key:o,scroll:l})=>r({key:o,title:P(`Language.${o}`),scroll:l,fallbackIcon:"check"}),n.selector.addInitial(e)}return t}class U7 extends Pd{constructor(e,t,s){super({topbar:e,chat:t,listenerSetter:e.listenerSetter,className:"translation",floating:!0,height:42}),this.topbar=e,this.chat=t,this.managers=s,[this.peerId,this.setPeerId]=K(Wt),this.dispose=wi(()=>this.init(),this.container)}init(){const{peerId:e}=this,t=new Ne.IntlElement({key:"DoNotTranslateLanguage"}),s=V(()=>Qc(e())),i=Ig();le(()=>{t.compareAndUpdate({args:[P(`Language.${s().peerLanguage()}`)]})}),le(()=>{this.toggle(!s().shouldShow())});const n=new $t;ze(()=>n.removeAll());const r=ki({direction:"bottom-left",buttons:[{icon:"premium_translate",text:"Chat.Translate.Menu.To",onClick:async()=>{const o=await ow(!1);s().setLanguage(o)},verify:i},{icon:"hand",textElement:t.element,onClick:()=>{const[o,l]=Ho();l("translations","doNotTranslate",c=>[...c,s().peerLanguage()])},verify:i,separatorDown:!0},{icon:"crossround",text:"Hide",onClick:()=>{this.managers.appTranslationsManager.togglePeerTranslations(e(),!0)}}],listenerSetter:n});return r.classList.add("pinned-translation-menu","primary"),[(()=>{const o=O7();return o.$$click=()=>{if(!i()){rs.show({feature:"translations"});return}const l=s();l.toggle(!l.enabled())},k(o,()=>Be("premium_translate","pinned-translation-button-icon"),null),k(o,(()=>{const l=V(()=>!!s().enabled());return()=>l()?P("ShowOriginalButton"):P("TranslateToButton",[P(`Language.${s().language()}`)])})(),null),o})(),r]}destroy(){super.destroy(),this.dispose()}}Fs(["click"]);const H7=!1;class G7{constructor(e,t,s){this.chat=e,this.appSidebarRight=t,this.managers=s,this.verifyButtons=i=>{const n=!!i||!!(this.btnMore&&this.btnMore.classList.contains("menu-open"));i&&_e(i),(async()=>{const o=this.buttonsToVerify.concat(n?this.menuButtons:[]);(await Promise.all(o.map(async c=>({result:await c.verify(),button:c})))).forEach(({button:c,result:d})=>{c.element.classList.toggle("hide",!d)})})()},this.verifyVideoChatButton=async i=>{if(!Uh||this.peerId.isUser()||this.chat.type!==we.Chat||this.chat.threadId)return!1;const n=Wa.groupCall,r=this.peerId.toChatId();if(n?.chatId===r||i&&(i==="group"&&await this.managers.appPeersManager.isBroadcast(this.peerId)||i==="broadcast"&&await this.managers.appPeersManager.isAnyGroup(this.peerId)))return!1;const o=Ae.getChat(r);if(Cr(o,"manage_call")&&i==="admin")return!o.pFlags?.call_active;if(!o.pFlags?.call_active)return!1;const l=await this.managers.appProfileManager.getChatFull(r),c=await this.managers.appGroupCallsManager.getGroupCallFull(l.call.id);return c?._!=="groupCall"?!1:!c.pFlags.rtmp_stream},this.verifyCallButton=async i=>{if(!Gh||!this.peerId.isUser()||this.chat.type!==we.Chat)return!1;const n=this.peerId.toUserId(),r=await this.managers.appProfileManager.getCachedFullUser(n);return!!r&&!!(i==="voice"?r.pFlags.phone_calls_available:r.pFlags.video_calls_available)},this.onJoinGroupCallClick=()=>{this.chat.appImManager.joinGroupCall(this.peerId)},this.onJoinClick=async i=>{const n=this.chat.bubbles.getMiddleware();i.setAttribute("disabled","true");const r=this.peerId.toChatId();let o;await this.managers.appChatsManager.isChannel(r)?o=this.managers.appChatsManager.joinChannel(r):o=this.managers.appChatsManager.addChatUser(r,I.myId),o.catch(l=>{switch(l.type){case"INVITE_REQUEST_SENT":{$e({langPackKey:"Chat.SendJoinRequest.Info"});return}}throw l}).finally(()=>{n()&&i.removeAttribute("disabled")})},this.onMuteClick=()=>{ue.createPopup(K_,this.peerId)},this.onUnmuteClick=()=>{this.managers.appMessagesManager.togglePeerMute({peerId:this.peerId,threadId:this.chat.threadId})},this.onResize=()=>{this.setUtilsWidth(!0),this.setFloating()},this.onChangeScreen=(i,n)=>{const r=n===fn.mobile||H7;this.pinnedMessage&&this.pinnedMessage.pinnedMessageContainer.container.classList.toggle("is-floating",r),this.onResize()},this.setUtilsWidth=(i=!1)=>{this.setUtilsRAF&&window.cancelAnimationFrame(this.setUtilsRAF),dn&&i&&this.chatUtils.classList.add("hide"),this.setUtilsRAF=window.requestAnimationFrame(()=>{dn&&i&&this.chatUtils.classList.remove("hide");const n=this.chatUtils.getBoundingClientRect().width;this.chat.log("utils width:",n),this.container.style.setProperty("--utils-width",n+"px"),this.setUtilsRAF=0})},this.setFloating=()=>{const i=[...this.pinnedContainers||[],this.pinnedMessage?.pinnedMessageContainer].filter(Boolean);let n=56,r=0;const o=i.reduce((l,c)=>{const d=c.isFloating();return this.container.classList.toggle(`is-pinned-${c.className}-floating`,d),c.isVisible()?(d?(r+=c.height,c.container.style.top=n+"px",n+=c.height):c.container.style.top="",l+ +d):l},0);this.container.dataset.floating=""+o,this.container.style.setProperty("--pinned-floating-height",`calc(${r}px + var(--topbar-floating-call-height)`)},this.listenerSetter=new $t,this.menuButtons=[],this.buttonsToVerify=[]}construct(){this.container=document.createElement("div"),this.container.classList.add("sidebar-header","topbar","hide"),this.container.dataset.floating="0",this.btnBack=yt("left sidebar-close-button",{noRipple:!0}),this.btnBackBadge=xo("span",20,"primary"),this.btnBackBadge.classList.add("back-unread-badge"),this.btnBack.append(this.btnBackBadge),this.chatInfoContainer=document.createElement("div"),this.chatInfoContainer.classList.add("chat-info-container"),this.chatInfo=document.createElement("div"),this.chatInfo.classList.add("chat-info");const e=this.person=document.createElement("div");e.classList.add("person");const t=document.createElement("div");t.classList.add("content");const s=document.createElement("div");s.classList.add("top"),this.title=document.createElement("div"),this.title.classList.add("user-title"),s.append(this.title);const i=document.createElement("div");i.classList.add("bottom"),this.subtitle&&i.append(this.subtitle),t.append(s,i),e.append(t),this.chatInfo.append(e),this.chatUtils=document.createElement("div"),this.chatUtils.classList.add("chat-utils"),this.chatAudio=new O6(this,this.chat,this.managers),this.chatRequests=new S7(this,this.chat,this.managers),this.chatActions=new C7(this,this.chat,this.managers),Cv&&(this.chatLive=new A7(this,this.chat,this.managers)),this.chatTranslation=new U7(this,this.chat,this.managers),this.menuButtons.length&&(this.btnMore=ki({listenerSetter:this.listenerSetter,direction:"bottom-left",buttons:this.menuButtons,onOpen:async(o,l)=>{const c=this.menuButtons[this.menuButtons.length-1];if(c?.element){const d=await this.managers.appPeersManager.getDeleteButtonText(this.peerId);c.element.lastChild.replaceWith(P(d))}}})),this.chatUtils.append(...[this.btnJoin,this.btnPinned,this.btnCall,this.btnGroupCall,this.btnGroupCallMenu,this.btnMute,this.btnSearch,this.btnMore].filter(Boolean)),this.pushButtonToVerify(this.btnCall,this.verifyCallButton.bind(this,"voice")),this.pushButtonToVerify(this.btnGroupCall,this.verifyVideoChatButton.bind(this,"nonadmin")),this.pushButtonToVerify(this.btnGroupCallMenu,this.verifyVideoChatButton.bind(this,"admin")),this.chatInfoContainer.append(this.btnBack,this.chatInfo,this.chatUtils),this.container.append(this.chatInfoContainer),this.pinnedMessage&&this.appendPinnedMessage(this.pinnedMessage);const n=this.pinnedContainers=[this.chatAudio,this.chatRequests,this.chatActions,this.chatLive,this.chatTranslation].filter(Boolean);this.container.append(...n.map(o=>o.container)),this.listenerSetter.add(window)("resize",this.onResize),this.listenerSetter.add(st)("changeScreen",this.onChangeScreen),J(this.container,o=>{if(ne(o.target,"topbar-search-container")||!o.target.isConnected||ne(o.target,"pinned-translation")||ne(o.target,"chat-search-top"))return;const l=ne(o.target,"pinned-container");if(Fa(),l){if(_e(o),ne(o.target,"progress-line")||ne(o.target,"pinned-container-wrapper-utils"))return;const c=+l.dataset.mid;if(l.classList.contains("pinned-message"))this.pinnedMessage.followPinnedMessage(c);else if(l.dataset.peerId){const d=l.dataset.peerId.toPeerId(),u=rt.getSearchContext();this.chat.appImManager.setInnerPeer({peerId:d,lastMsgId:c,type:u.isScheduled?we.Scheduled:void 0,threadId:u.threadId})}}else{const c=Wh(o.target);if(st.activeScreen===fn.medium&&document.body.classList.contains(kh))r();else if(c){if(c.classList.contains("has-stories"))return;this.appSidebarRight.toggleSidebar(!document.body.classList.contains(Lh))}else this.appSidebarRight.toggleSidebar(!0)}},{listenerSetter:this.listenerSetter});const r=o=>{if(o&&_e(o),this.chat.type===we.Search){this.chat.resetSearch();return}if(st.activeScreen===fn.medium&&document.body.classList.contains(kh))this.chat.appImManager.setPeer({peerId:this.peerId});else{const l=this.chat.appImManager.chats.indexOf(this.chat)===0;Pt.back(l?"im":"chat")}};J(this.btnBack,r,{listenerSetter:this.listenerSetter})}pushButtonToVerify(e,t){e&&this.buttonsToVerify.push({element:e,verify:t})}constructUtils(){this.menuButtons=[{icon:"search",text:"Search",onClick:()=>{this.chat.initSearch()},verify:()=>st.isMobile},{icon:"mute",text:"ChatList.Context.Mute",onClick:this.onMuteClick,verify:async()=>this.chat.type===we.Chat&&I.myId!==this.peerId&&!await this.managers.appNotificationsManager.isPeerLocalMuted({peerId:this.peerId,respectType:!1,threadId:this.chat.threadId})},{icon:"unmute",text:"ChatList.Context.Unmute",onClick:this.onUnmuteClick,verify:()=>this.chat.type===we.Chat&&I.myId!==this.peerId&&this.managers.appNotificationsManager.isPeerLocalMuted({peerId:this.peerId,respectType:!1,threadId:this.chat.threadId})},{icon:"comments",text:"ViewDiscussion",onClick:()=>{const e=this.chat.bubbles.getMiddleware();Promise.resolve(this.managers.appProfileManager.getChannelFull(this.peerId.toChatId())).then(t=>{e()&&t.linked_chat_id&&this.chat.appImManager.setInnerPeer({peerId:t.linked_chat_id.toPeerId(!0)})})},verify:async()=>{const e=await this.managers.appProfileManager.getCachedFullChat(this.peerId.toChatId());return this.chat.type===we.Chat&&!!e?.linked_chat_id}},{icon:"phone",text:"Call",onClick:this.onCallClick.bind(this,"voice"),verify:this.verifyCallButton.bind(this,"voice")},{icon:"videocamera",text:"VideoCall",onClick:this.onCallClick.bind(this,"video"),verify:this.verifyCallButton.bind(this,"video")},{icon:"videochat",text:"PeerInfo.Action.LiveStream",onClick:this.onJoinGroupCallClick,verify:this.verifyVideoChatButton.bind(this,"broadcast")},{icon:"videochat",text:"PeerInfo.Action.VoiceChat",onClick:this.onJoinGroupCallClick,verify:this.verifyVideoChatButton.bind(this,"group")},{icon:"topics",text:"TopicViewAsTopics",onClick:()=>{this.chat.appImManager.toggleViewAsMessages(this.peerId,!1)},verify:async()=>{const e=await this.managers.appMessagesManager.getDialogOnly(this.peerId);return!!(e&&e.pFlags.view_forum_as_messages)}},{icon:"topics",text:"SavedViewAsChats",onClick:()=>{this.chat.appImManager.toggleViewAsMessages(this.peerId,!1)},verify:()=>this.peerId===I.myId&&!this.chat.threadId&&!I.settings.savedAsForum},{icon:"select",text:"Chat.Menu.SelectMessages",onClick:()=>{const e=this.chat.selection;e.toggleSelection(!0,!0),Ae.getState().then(t=>{const[s,i]=Ho();if(s.chatContextMenuHintWasShown)return;const n=e.toggleByElement.bind(e);e.toggleByElement=async r=>{i("chatContextMenuHintWasShown",!0),Wi(P("Chat.Menu.Hint")),e.toggleByElement=n,e.toggleByElement(r)}})},verify:()=>!this.chat.selection.isSelecting&&!!this.chat.bubbles.getRenderedLength()},{icon:"select",text:"Chat.Menu.ClearSelection",onClick:()=>{this.chat.selection.cancelSelection()},verify:()=>this.chat.selection.isSelecting},{icon:"adduser",text:"AddContact",onClick:()=>{this.addContact()},verify:async()=>this.peerId.isUser()&&!await this.managers.appPeersManager.isContact(this.peerId)},{icon:"forward",text:"ShareContact",onClick:()=>{const e=this.peerId;Rs.createSharingPicker({onSelect:async t=>{const s=await _r.prepareStarsForPayment({messageCount:1,peerId:t});if(s===Fn)throw new Error;const i=()=>{this.managers.appMessagesManager.sendContact(t,e,s),this.chat.appImManager.setInnerPeer({peerId:t})};return s?void i():new Promise((n,r)=>{ue.createPopup(mi,"",{titleLangKey:"SendMessageTitle",descriptionLangKey:"SendContactToGroupText",descriptionLangArgs:[new Xt({peerId:t,dialog:!0}).element],buttons:[{langKey:"Send",callback:async()=>{n(),i()}},{langKey:"Cancel",callback:()=>{r()},isCancel:!0}],peerId:t,overlayClosable:!0}).show()})}})},verify:async()=>I.myId!==this.peerId&&this.peerId.isUser()&&await this.managers.appPeersManager.isContact(this.peerId)&&!!(await this.managers.appUsersManager.getUser(this.peerId.toUserId())).phone},{icon:"gift",text:"Chat.Menu.SendGift",onClick:()=>ue.createPopup(wI,this.peerId),verify:async()=>this.chat.isChannel||this.chat.peerId.isUser()&&this.managers.appUsersManager.isRegularUser(this.peerId)},{icon:"statistics",text:"Statistics",onClick:()=>{this.appSidebarRight.createTab(Wu).open(this.peerId.toChatId()),this.appSidebarRight.toggleSidebar(!0)},verify:()=>this.managers.appProfileManager.canViewStatistics(this.peerId)},{icon:"addboost",text:"Boosts",onClick:()=>{this.appSidebarRight.createTab(g3).open(this.peerId),this.appSidebarRight.toggleSidebar(!0)},verify:()=>this.chat.isBroadcast&&this.managers.appProfileManager.canViewStatistics(this.peerId)},{icon:"bots",text:"Settings",onClick:()=>{this.managers.appMessagesManager.sendText({peerId:this.peerId,text:"/settings"})},verify:async()=>{try{return!!(await this.managers.appAttachMenuBotsManager.getAttachMenuBot(this.peerId.toUserId()))?.pFlags?.has_settings}catch{return!1}}},{icon:"lock",text:"BlockUser",onClick:()=>{this.blockUser()},verify:async()=>{if(!this.peerId.isUser())return!1;const e=await this.managers.appProfileManager.getCachedFullUser(this.peerId.toUserId());return this.peerId!==I.myId&&e&&!e.pFlags?.blocked}},{icon:"lockoff",text:"Unblock",onClick:()=>{this.managers.appUsersManager.toggleBlock(this.peerId,!1).then(()=>{$e({langPackKey:"UserUnblocked"})})},verify:async()=>!!(await this.managers.appProfileManager.getCachedFullUser(this.peerId.toUserId()))?.pFlags?.blocked},{icon:"delete",danger:!0,text:"Delete",onClick:()=>{ue.createPopup(kg,this.peerId,void 0,void 0,this.chat.threadId)},verify:async()=>this.chat.type===we.Saved||this.chat.type===we.Chat&&!!await this.managers.appMessagesManager.getDialogOnly(this.peerId)}],this.btnSearch=yt("search"),this.attachClickEvent(this.btnSearch,e=>{this.chat.initSearch()},!0)}addContact(){if(!this.appSidebarRight.isTabExists(ry)){const e=this.appSidebarRight.createTab(ry);e.peerId=this.peerId,e.open(),this.appSidebarRight.toggleSidebar(!0)}}async blockUser(e,t,s){const i=this.peerId,n=[e&&{text:"DeleteReportSpam",checked:!0},t&&{text:"DeleteThisChat",checked:!0}],r=await Rt({peerId:i,titleLangKey:"BlockUser",descriptionLangKey:"AreYouSureBlockContact2",descriptionLangArgs:[new Xt({peerId:i}).element],button:{langKey:"BlockUser",isDanger:!0},checkboxes:n.filter(Boolean)}),[o,l]=Array.isArray(r)?r:[],c=Promise.all([o&&this.managers.appMessagesManager.reportSpam(i),l&&this.managers.appMessagesManager.flushHistory(i,!1,!0),this.managers.appUsersManager.toggleBlock(i,!0)]);s?.(c),await c,$e({langPackKey:"UserBlocked"})}attachClickEvent(e,t,s){J(e,i=>{_e(i),!s&&Fa(),t(i)},{listenerSetter:this.listenerSetter})}onCallClick(e){this.chat.appImManager.callUser(this.peerId.toUserId(),e)}get peerId(){return this.chat.peerId}constructPeerHelpers(){return this.subtitle=document.createElement("div"),this.subtitle.classList.add("info"),this.pinnedMessage=new Km(this,this.chat,this.managers),this.btnJoin=ot("btn-primary btn-color-primary chat-join hide"),this.btnCall=yt("phone"),this.btnGroupCall=yt("videochat"),this.btnGroupCallMenu=ki({listenerSetter:this.listenerSetter,direction:"bottom-left",buttons:[{icon:"videochat",text:"Rtmp.Topbar.StartVideoChat",onClick:this.onJoinGroupCallClick},{icon:"link",text:"Rtmp.Topbar.StreamWith",onClick:()=>{ue.createPopup(RP,{peerId:this.peerId}).show()},verify:()=>Cv}],icon:"videochat"}),this.btnPinned=yt("pinlist chat-pinlist"),this.btnMute=yt("mute"),this.attachClickEvent(this.btnCall,this.onCallClick.bind(this,"voice")),this.attachClickEvent(this.btnGroupCall,this.onJoinGroupCallClick),this.attachClickEvent(this.btnPinned,()=>{this.openPinned(!0)}),this.attachClickEvent(this.btnMute,()=>{!!+this.btnMute.dataset.muted?this.onUnmuteClick():this.onMuteClick()}),this.attachClickEvent(this.btnJoin,this.onJoinClick.bind(this,this.btnJoin)),this.listenerSetter.add(I)("folder_unread",e=>{if(e.id!==Fi)return;const t=e.unreadUnmutedPeerIds.size;Ro(this.btnBackBadge,t?""+un(t,1):"")}),this.listenerSetter.add(I)("chat_update",e=>{if(this.peerId===e.toPeerId(!0)){const t=Ae.getChat(e);if(!t.pFlags.broadcast)return;this.btnJoin.classList.toggle("hide",!t?.pFlags?.left),this.setUtilsWidth(),this.verifyButtons()}}),this.listenerSetter.add(I)("dialog_notify_settings",e=>{e.peerId===this.peerId&&this.setMutedState()}),this.listenerSetter.add(I)("peer_full_update",e=>{this.peerId===e&&this.verifyButtons()}),this.listenerSetter.add(I)("chat_requests",({chatId:e,recentRequesters:t,requestsPending:s})=>{if(this.peerId!==e.toPeerId(!0))return;const i=this.chat.bubbles.getMiddleware();this.chatRequests.set(this.peerId,t.map(n=>n.toPeerId(!1)),s).then(n=>{i()&&n()})}),this.listenerSetter.add(I)("peer_settings",async({peerId:e,settings:t})=>{if(this.peerId!==e)return;this.chatActions.set(e,t)()}),this.chat.addEventListener("setPeer",(e,t)=>{const s=this.chat.bubbles.getMiddleware();Ae.getState().then(i=>{!s()||!this.pinnedMessage||(this.pinnedMessage.hidden=!!i.hiddenPinnedMessages[this.chat.peerId],t?(this.pinnedMessage.unsetScrollDownListener(),this.pinnedMessage.testMid(e,0)):this.pinnedMessage.locked||(this.pinnedMessage.handleFollowingPinnedMessage(),this.pinnedMessage.testMid(e)))})}),this.listenerSetter.add(I)("peer_pinned_messages",({peerId:e,mids:t})=>{this.chat.type!==we.Pinned||e!==this.peerId||t&&this.setTitle()}),this}openPinned(e){this.chat.appImManager.setInnerPeer({peerId:this.peerId,lastMsgId:e?+this.pinnedMessage.pinnedMessageContainer.container.dataset.mid:0,type:we.Pinned})}destroy(){this.listenerSetter.removeAll(),this.status?.destroy(),this.titleMiddlewareHelper?.destroy(),this.avatarMiddlewareHelper?.destroy(),this.pinnedMessage?.destroy(),this.pinnedContainers?.forEach(e=>e.destroy()),delete this.pinnedMessage,delete this.chatAudio,delete this.chatRequests,delete this.chatActions,delete this.chatLive,delete this.chatTranslation}cleanup(){this.chat.peerId||this.container.classList.add("hide")}appendPinnedMessage(e){const t=e.pinnedMessageContainer.container;this.pinnedMessage&&this.pinnedMessage!==e?this.pinnedMessage.pinnedMessageContainer.container.replaceWith(t):this.chatUtils.prepend(t)}async finishPeerChange(e){const{peerId:t,threadId:s}=this.chat,{middleware:i}=e;let n,r;const o=this.chat.type===we.Saved,l=this.chat.type===we.Search;if([we.Chat].includes(this.chat.type)||o){const b=o?s:t,S=o?void 0:s,_=this.avatar;!_||_.node.dataset.peerId.toPeerId()!==b||_.node.dataset.threadId!==(S?""+S:void 0)||t===I.myId?(n=vs({middleware:(r=Ht()).get(),isDialog:!0,size:42,peerId:b,threadId:S,wrapOptions:{customEmojiSize:ii(32,32)},withStories:!0,meAsNotes:o}),n.node.classList.add("person-avatar")):n=this.avatar}this.status?.destroy();const c=this.status=this.createStatus(),d=[this.managers.appPeersManager.isBroadcast(t),this.managers.appPeersManager.isAnyChat(t),t.isAnyChat()?Ae.getChat(t.toChatId()):void 0,n?.readyThumbPromise,this.setTitleManual(),c?.prepare(!0),Ae.getState(),Fl(this.chatRequests?.setPeerId(t)),Fl(this.chatActions?.setPeerId(t))],[u,h,p,m,g,f,v,y,w]=await Promise.all(d);return!i()&&r&&r.destroy(),()=>{const b=!(this.chat.type===we.Pinned||this.chat.type===we.Scheduled);this.btnMute&&this.btnMute.classList.toggle("hide",!u||!b),this.btnJoin&&(u&&!this.chat.isRestricted&&b?(St(this.btnJoin,P(u?"Chat.Subscribe":"ChannelJoin")),this.btnJoin.classList.toggle("hide",!p?.pFlags?.left)):this.btnJoin.classList.add("hide")),this.btnSearch&&this.btnSearch.classList.toggle("hide",!b),this.btnPinned&&this.btnPinned.classList.toggle("hide",!b),this.avatar!==n&&(n&&this.person.prepend(n.node),this.avatar&&(this.avatarMiddlewareHelper.destroy(),this.avatar.node.remove()),this.avatar=n,this.avatarMiddlewareHelper=r,this.container.classList.toggle("has-avatar",!!n)),this.setUtilsWidth(),this.verifyButtons(),this.btnMore&&this.btnMore.classList.toggle("hide",!b);const S=this.chat.isPinnedMessagesNeeded();if(S||this.chat.type===we.Discussion){if(this.chat.wasAlreadyUsed||!this.pinnedMessage){const _=new Km(this,this.chat,this.managers);this.appendPinnedMessage(_),this.pinnedMessage?.destroy(),this.pinnedMessage=_}S?this.pinnedMessage.hidden=!!v.hiddenPinnedMessages[t]:this.chat.type===we.Discussion&&(this.pinnedMessage.pinnedMid=this.chat.threadId,this.pinnedMessage.count=1,this.pinnedMessage.pinnedIndex=0,this.pinnedMessage._setPinnedMessage())}else this.pinnedMessage&&(this.pinnedMessage.destroy(),this.pinnedMessage=void 0);g(),f?.(),this.subtitle.classList.toggle("hide",!f),this.setMutedState(),this.container.classList.remove("hide"),y.result instanceof Promise&&this.chatRequests.unset(t),w.result instanceof Promise&&this.chatActions.unset(t),this.chatLive?.setPeerId(t),this.chatTranslation?.setPeerId(t),en(y.result,_=>{i()&&_()}),en(w.result,_=>{i()&&_()}),this.container.classList.toggle("show-back-button",l)}}async setTitleManual(e){const{peerId:t,threadId:s}=this.chat;let i;this.titleMiddlewareHelper?.destroy();const o=(this.titleMiddlewareHelper=Ht()).get();if(this.chat.type===we.Pinned)e===void 0?i=P("Loading"):i=P("PinnedMessagesCount",[e]),e===void 0&&this.managers.appMessagesManager.getSearchCounters(t,[{_:"inputMessagesFilterPinned"}],!1).then(l=>{if(!o())return;const c=l[0].count;if(this.setTitle(c),!c){this.chat.appImManager.setPeer();const d=this.chat.appImManager.chat;d.topbar.pinnedMessage&&d.topbar.pinnedMessage.pinnedMessageContainer.toggle(!0)}});else if(this.chat.type===we.Scheduled)i=P(t===I.myId?"Reminders":"ScheduledMessages");else if(this.chat.type===we.Discussion){const l=this.messagesCounter(o,"Chat.Title.Comments",this.chat.isForum);if(e===void 0){const c=await this.chat.getHistoryStorage();if(!o())return;l.compareAndUpdate(c.count===null?{key:"Loading",args:void 0}:{args:[c.count-(this.chat.isForum?1:0)]})}i=l.element}else if(this.chat.type===we.Chat||this.chat.type===we.Saved){const l=this.chat.type===we.Saved?s:t;if([i]=await Promise.all([qe({peerId:l,dialog:!0,withIcons:!s,threadId:s,wrapOptions:{middleware:o},meAsNotes:this.chat.type===we.Saved})]),!o())return}return()=>{St(this.title,i)}}setTitle(e){this.setTitleManual(e).then(t=>t())}async setMutedState(){if(!this.btnMute)return;const e=this.peerId,t=await this.managers.appNotificationsManager.isPeerLocalMuted({peerId:e,respectType:!1,threadId:this.chat.threadId}),s=await this.managers.appPeersManager.isBroadcast(e);s&&(Wo(this.btnMute,t?"unmute":"mute"),this.btnMute.dataset.muted=""+ +t),this.btnMute.style.display=s?"":"none"}messagesCounter(e,t,s){const i=new Ne.IntlElement({key:t,args:[1]}),n=this.chat.historyStorageKey,r=({historyKey:o,count:l})=>{n===o&&i.compareAndUpdate({key:t,args:[l-(s?1:0)]})};return I.addEventListener("history_count",r),this.managers.appMessagesManager.toggleHistoryKeySubscription(n,!0),e.onDestroy(()=>{I.removeEventListener("history_count",r),this.managers.appMessagesManager.toggleHistoryKeySubscription(n,!1)}),i}createStatus(){if(!this.subtitle||this.chat.type!==we.Chat&&this.chat.type!==we.Saved)return;const e=Ht(),t=e.get(),s=new $t;let i;if(this.chat.type===we.Saved){const r=this.messagesCounter(t,"messages");i=async()=>{const o=await this.chat.getHistoryStorage();return r.compareAndUpdate({args:[o.count]}),()=>St(this.subtitle,r.element)}}else if(this.chat.threadId)i=async()=>{const r=await qe({peerId:this.peerId,dialog:!0}),o=P("TopicProfileStatus",[r]);return()=>St(this.subtitle,o)};else{const r=this.peerId;s.add(I)("peer_typings",({peerId:l})=>{r===l&&n()}),s.add(I)("user_update",l=>{r===l.toPeerId()&&n()});const o=window.setInterval(()=>n(),6e4);t.onDestroy(()=>{clearInterval(o)}),i=l=>this.chat.appImManager.setPeerStatus({peerId:r,element:this.subtitle,needClear:l,useWhitespace:!1,middleware:t})}t.onDestroy(()=>{s.removeAll()});const n=()=>{i(!1).then(r=>t()&&r?.())};return{prepare:i,destroy:()=>e.destroy()}}}class FP extends Zt{constructor(){super(...arguments),this.threadId=0,this.query=""}onOpenAfterTimeout(){this.appSearch.beginSearch(this.peerId,this.threadId,this.query)}init(e,t,s,i){this.container.id="search-private-container",this.container.classList.add("chatlist-container"),this.inputSearch=new jo({placeholder:"Search"}),this.title.replaceWith(this.inputSearch.container),this.btnPickDate=yt("calendar sidebar-header-right"),this.header.append(this.btnPickDate);const n=document.createElement("div");n.classList.add("chatlist-container"),this.scrollable.container.replaceWith(n),this.appSearch=new Zk(n,this.inputSearch,{messages:new aa("Chat.Search.PrivateSearch","messages")},this.middlewareHelper.get(),void 0,void 0,!!(e===I.myId&&t)),this.peerId?this.appSearch.beginSearch(this.peerId,this.threadId,i):(this.query=i,this.peerId=e,this.threadId=t,this.onDatePick=s,this.btnPickDate.classList.toggle("hide",!this.onDatePick),this.onDatePick&&J(this.btnPickDate,()=>{ue.createPopup(Ng,new Date,this.onDatePick).show()},{listenerSetter:this.listenerSetter}),i&&this.appSearch.searchInput.inputField.setValueSilently(i),Gs.toggleSidebar(!0))}}async function V7(a){let e,t=0,s=0,i=0;const n=I.settings,r=I.managers.appPeersManager;return!n.autoDownloadNew.pFlags.disabled&&a&&(a.isUser()?await r.isContact(a)?e="contacts":e="private":await r.isBroadcast(a)?e="channels":e="groups",n.autoDownload.photo[e]&&(t=n.autoDownloadNew.photo_size_max),n.autoDownload.video[e]&&(s=n.autoDownloadNew.video_size_max),n.autoDownload.file[e]&&(i=n.autoDownloadNew.file_size_max)),{photo:t,video:s,file:i}}function z7(a){let e;return Po(a)?e=a.peerId:Yr(a)?e=a.id:pr(a)&&(e=a.savedPeerId),e}function W7(a){if(a.inputFilter||a.savedReaction||a.query||a.isPublicHashtag)return a.isCacheableSearch?"cached":a.query||!a.peerId||a.fromPeerId?"uncached":"cached"}function BP(a){const{type:e,peerId:t,threadId:s}=a,i=K7(a);return[e,t,i,s].filter(Boolean).join("_")}function K7({inputFilter:a,savedReaction:e,query:t,hashtagType:s}){let i;return e&&(i=`tag-${e.map(o=>o.document_id||o.emoticon).join(",")}`,a??(a={_:"inputMessagesFilterEmpty"})),[a?._,s!=="this"&&s,t,i].filter(Boolean).join("_")}function DP(a){return W7(a)?"search":a.threadId?"replies":"history"}const kp="keydown",j7="active",R0=["ArrowUp","ArrowDown"],F0=["ArrowLeft","ArrowRight"],B0="nextElementSibling",D0="previousElementSibling",Tp="firstElementChild",$0="lastElementChild";function $P({list:a,type:e,onSelect:t,once:s,waitForKey:i,activeClassName:n=j7,cancelMouseDown:r,target:o}){let l=i?.length?new Set(i):void 0;const c=new Set(e==="xy"?R0.concat(F0):e==="x"?F0:R0),d=()=>o||a.querySelector("."+n)||a[Tp],u=(L,E)=>{if(o===L)return;let x=!1;o&&(x=!0,o.classList.remove(n)),o=L,o&&(o.classList.add(n),x&&f&&E&&Bu({container:f,element:o,position:"center",forceDuration:100,axis:e==="x"?"x":"y"}))},h=(L,E)=>{let x;return E?x=L[B0]||a[Tp]:x=L[D0]||a[$0],x},p=(L,E)=>{const x=E?B0:D0,R=E?Tp:$0,B=L.getBoundingClientRect();let N=L[x]||a[R];for(;N!==L;){const G=N.getBoundingClientRect();if(G.x===B.x&&G.y!==B.y)break;N=N[x]||a[R]}return N};let m;e==="xy"?m=(L,E)=>E==="ArrowUp"||E==="ArrowDown"?p(L,E==="ArrowDown"):h(L,E==="ArrowRight"):m=(L,E)=>h(L,E==="ArrowRight"||E==="ArrowDown");let g=L=>{const E=L.key;if(!c.has(E)){(E==="Enter"||e!=="xy"&&E==="Tab")&&(_e(L),w(d()));return}if(_e(L),a.childElementCount>1){let x=d();x=m(x,E),u(x,!0)}};const f=ne(a,"scrollable");a.classList.add("navigable-list");const v=L=>{const E=Mi(L.target,a);E&&u(E,!1)},y=L=>{_e(L);const E=Mi(L.target,a);E&&(u(E,!1),w(d()))},w=async L=>{const E=await t(L);(E!==void 0?!E:s)&&M()};let b=!1,S;const _=()=>{b||(b=!0,document.addEventListener(kp,g,{capture:!0,passive:!1}),a.addEventListener("mousemove",v,{passive:!0}),r&&a.addEventListener("mousedown",_e),S=J(a,y,{ignoreMove:r}))},M=()=>{b&&(b=!1,document.removeEventListener(kp,g,{capture:!0}),a.removeEventListener("mousemove",v),r&&a.removeEventListener("mousedown",_e),S(),S=void 0)},C=()=>{l||u(a[Tp],!1)};if(l){const L=g;g=E=>{l.has(E.key)&&(_e(E),document.removeEventListener(kp,g,{capture:!0}),g=L,document.addEventListener(kp,g,{capture:!0,passive:!1}),l=void 0,C())}}else o||C();return _(),{attach:_,detach:M,resetTarget:C}}function N0(a,e){return a.length>e?a.slice(0,e/2|0)+"..."+a.slice(-Math.round(e/2)):a}const ah=Y("<div>"),q7=Y("<span><b></b> "),Y7=Y("<span class=secondary>"),Q7=Y("<div><div class=chat-search-footer-left><span></span></div><div><span class=chat-search-footer-type>"),X7=Y('<div class="chat-search-results chatlist-container">'),Z7=Y("<div class=chat-search-top>"),J7=Y("<span>"),e$=Y("<div class=topbar-search-input-tools>"),t$=Y("<div class=topbar-search-left-results-empty>"),s$=Y("<div class=topbar-search-left-results-padding>"),i$=Y("<div class=topbar-search-left-delimiter>"),xp=Y("<div class=topbar-search-left-reactions-padding>"),n$=Y("<div class=topbar-search-left-search-types>"),a$=Y("<div class=topbar-search-container><div><div class=topbar-search-left-background>"),O0=Y('<div class="topbar-search-left-reactions-container topbar-search-left-collapsable"><div class=topbar-search-left-delimiter>'),r$=Y("<div class=topbar-search-right-container>"),o$=a=>{const[,e]=wa(a,["onScrolledBottom","onScrolledTop"]);let t;const s=(()=>{const n=ah(),r=t;return typeof r=="function"?Ue(r,n):t=n,so(n,e,!1,!0),k(n,()=>a.children),n})(),i=new tn(void 0,void 0,void 0,void 0,t);return i.onScrolledBottom=a.onScrolledBottom,i.onScrolledTop=a.onScrolledTop,ze(()=>{i.destroy()}),s},l$=["this","my","public"],U0=void 0,c$=({middleware:a,peerId:e,fromSavedDialog:t,messages:s,query:i,searchType:n})=>{const r=s.map(async o=>{const l=o.fromId,c=[],{dom:d}=nt.addDialogAndSetLastMessage({peerId:t?I.myId:l||e,container:!1,avatarSize:"abitbigger",meAsSaved:n==="my",message:o,query:i,wrapOptions:{middleware:a},loadPromises:c,threadId:t?o.saved_peer_id?it(o.saved_peer_id):I.myId:void 0,autonomous:!0});return await Promise.all(c),d.containerEl});return Promise.all(r)},d$=a=>{const{middleware:e,peerId:t,threadId:s,query:i,fromPeerId:n,reaction:r,searchType:o}=a,l=!!(t===I.myId&&s);let c,d=!1,u;const h=async()=>{if(d)return;d=!0;const g=c?.mid||0,f=c?.peerId||Wt,v={peerId:o==="this"||!o?t:Wt,threadId:o==="this"||!o?s:void 0,query:i,inputFilter:{_:"inputMessagesFilterEmpty"},offsetId:g,offsetPeerId:f,limit:30,fromPeerId:n,savedReaction:r?[r]:void 0,nextRate:u,isPublicHashtag:o==="public",isCacheableSearch:!!o,hashtagType:o},y=BP({type:DP(v),...v});I.managers.appMessagesManager.toggleHistoryKeySubscription(y,!0),ze(()=>{I.managers.appMessagesManager.toggleHistoryKeySubscription(y,!1)});const w=await I.managers.appMessagesManager.getHistory(v);if(!e())return;let b;w.messages?(b=w.messages,u=w.nextRate):b=w.history.map(_=>Ae.getMessageByPeer(t,_));const S=await c$({...a,fromSavedDialog:l,messages:b});e()&&(m(_=>(_.count=w.count,_.values.push(...b),c=b[b.length-1],w.isEnd.top&&(_.loadMore=void 0),_.rendered.push(...S),_)),d=!1)},[p,m]=id({loadMore:h});return p},h$=a=>{const{middleware:e,peerId:t,query:s}=a;let i=!1,n=0;const r=async()=>{if(i)return;i=!0;const c=await I.managers.appProfileManager.getParticipants({id:t.toChatId(),filter:{_:"channelParticipantsSearch",q:s},limit:30,offset:n,forMessagesSearch:!0});if(!e())return;const d=c.participants.map(Zc),u=d.map(async p=>{const m=await qe({peerId:p}),g=Ae.getPeer(p),f=ji(g)[0],v=new Fe({title:(()=>{const b=q7(),S=b.firstChild;return S.nextSibling,k(S,m),k(b,f&&(()=>{const _=Y7();return k(_,`@${f}`),_})(),null),b})(),clickable:!0});v.container.classList.add("topbar-search-left-sender");const y=40,w=vs({peerId:p,size:y,middleware:e});return v.createMedia(`${y}`).append(w.node),await w.readyThumbPromise,v.container}),h=await Promise.all(u);e()&&(l(p=>{p.count=c.count??d.length;const m=p.values.push(...d);return n=m,m>=p.count&&(p.loadMore=void 0),p.rendered.push(...h),p}),i=!1)},[o,l]=id({loadMore:r});return o};function u$(a){return(()=>{const e=Q7(),t=e.firstChild,s=t.firstChild,i=t.nextSibling,n=i.firstChild;return k(t,()=>a.pickDateBtn,s),k(t,()=>a.pickUserBtn,s),k(s,(()=>{const r=V(()=>a.count()===0);return()=>r()?P("NoResult"):(()=>{const o=V(()=>!!a.resultsShown());return()=>o()?P("messages",[a.count()]):P("Of",[a.index()+1,a.count()])})()})()),n.$$click=()=>a.onToggle(),k(n,()=>P(a.resultsShown()?"SearchAsChat":"SearchAsList")),Me(r=>{const o=Ge("chat-search-footer",a.choosingSender()&&"hide"),l=Ge("chat-search-footer-count",a.count()===void 0&&"hide"),c=Ge("chat-search-footer-right",!a.count()&&"hide");return o!==r._v$&&be(e,r._v$=o),l!==r._v$2&&be(s,r._v$2=l),c!==r._v$3&&be(i,r._v$3=c),r},{_v$:void 0,_v$2:void 0,_v$3:void 0}),e})()}function p$(a){return(()=>{const e=X7();return k(e,()=>a.scrollable),e})()}function m$(a){return(()=>{const e=Z7();return k(e,()=>a.hasSearchTypes()?a.searchTypesScrollable:a.reactionsScrollable),e})()}function g$(a){const e=(s,i)=>{const n=Cn({icon:s,className:"bubbles-corner-button chat-secondary-button chat-search-go chat-search-go-"+s}),r=J(n,i);ze(r);const o=V(()=>s==="down"?a.index()===0:a.index()===a.count()-1);return le(()=>{n.classList.toggle("is-end",o()),n.classList.toggle("hide",(a.count()||0)<2)}),n},t=[e("up",a.onArrowButtonClick.bind(null,"up")),e("down",a.onArrowButtonClick.bind(null,"down"))];a.chat.bubbles.container.after(...t),ze(()=>{t.forEach(s=>{s.remove()})})}function f$(a){const e=WE(),t=V(()=>e()===fn.mobile),[s,i]=K(!1),[n,r]=K(""),[o,l]=K(),[c,d]=K(),[u,h]=K(),[p,m]=K(),[g,f]=K(),[v,y]=K(),[w,b]=K(void 0,{equals:!1}),[S,_]=K(!1),[M,C]=K(),[L,E]=K(),[x,R]=K(void 0,{equals:!1}),[B,N]=K(),[G,O]=K(void 0,{equals:!1}),[$,H]=K(U0),[D,U]=K(!1),j=V(()=>S()&&!M()),q=V(()=>t()?D():s()),W=V(()=>q()&&o()&&u()||void 0),ee=V(()=>{if(S()||G())return;const se=n();return se.startsWith("#")?se.slice(1):void 0}),z=V(()=>ee()!==void 0),Z=V(()=>{if(z())return!1;const se=B(),ye=x();return!!(se&&ye?.length)}),de=V(()=>z()),ie=V(()=>(!t()||!M())&&S()),oe=V(()=>t()||Z()||q()),ae=Ig();a.onActive&&(le(()=>{a.onActive(oe(),Z(),t())}),ze(()=>{a.onActive(!1,!1,t())})),le(()=>{ce.onChange(ce.value=a.query()),_(!!a.filterPeerId()),C(a.filterPeerId()),O(a.reaction()),Jt(()=>{Ki(ce.input)})}),le(()=>{const{element:se}=W()||{};if(!se)return;const ye=se.firstElementChild,Te="menu-open",Pe=ye.querySelector(`.${Te}`);Pe&&Pe.classList.remove(Te);const{detach:De}=$P({list:ye,type:"y",onSelect:We=>{const Ke=!!(!S()||M());b(We),Ke&&Fa()},activeClassName:Te,cancelMouseDown:!0,target:Ot(w)});ze(()=>{De()})});const ke={type:"topbar-search",onPop:()=>{if(s()&&n())return Fa(),!1;a.onClose?.()}};Pt.pushItem(ke),ze(()=>{Pt.removeItem(ke)});const re=(se,ye=ce.inputField.isEmpty())=>{if(M()){se&&_e(se),ye&&C(void 0);return}if(S()){se&&_e(se),ye&&_(!1);return}if(ye){if(t())return;a.onClose?.()}},ce=new jo({placeholder:"Search",onChange:r,onClear:re,onFocusChange:i,onBack:()=>{a.onClose?.()},alwaysShowClear:!0,noBorder:!0,verifyDebounce:se=>se!=="#"&&!ce.container.classList.contains("show-placeholder")&&!!se.trim(),arrowBack:t()});ce.container.classList.add("topbar-search-input-container"),ce.input.classList.add("topbar-search-input");const Ie=se=>{if(se.key!=="Backspace")return;const ye=ce.inputField.isEmpty();ye&&(M()||S())&&re(void 0,ye)};Ta(ce.input)("keydown",Ie),ze(()=>{ce.remove()});const Ve=Dl("#",$h),fe=Ne.format("Search.From",!0)+" ",Xe=Dl(fe,$h),Ye=(()=>{const se=J7();return k(se,fe),Me(()=>be(se,Ge("topbar-search-input-from",ie()&&"is-visible"))),se})();ce.container.append(Ye),le(se=>{const ye=S(),Te=z();se&&(se.classList.remove("scale-in"),se.offsetWidth,se.classList.add("scale-out"),setTimeout(()=>{se.remove()},200));const Pe=L();if(Pe){Pe.classList.add("topbar-search-input-entity","scale-in");const De=J(Pe,We=>{_e(We),Te?H():C()},{cancelMouseDown:!0});ze(De),ce.container.append(Pe)}return ce.container.style.setProperty("--padding-placeholder",(ie()?Xe:0)+"px"),ce.container.style.setProperty("--padding-hashtag",(Te?Ve:0)+"px"),ce.container.style.setProperty("--padding-sender",(Pe?Pe.offsetWidth+6:0)+"px"),ce.setPlaceholder(ye&&!Pe?"Search.Member":Te?"Search.Hashtag":"Search"),Pe}),le(()=>{ce.container.classList.toggle("show-placeholder",ee()==="")});const Ze=se=>{const ye=ui().get(),Te=Ot(()=>wn.renderEntity({key:se.peerId,title:se.title,fallbackIcon:se.fallbackIcon,middleware:ye,avatarSize:30,meAsSaved:!1}));if(se.active!==void 0&&le(()=>{Te.element.classList.toggle("active",se.active())}),se.onClick){const Pe=J(Te.element,De=>{_e(De),se.onClick()},{cancelMouseDown:!0});ze(Pe)}return se.onPromises&&se.onPromises(Te.promises),Te.element},Je=se=>{const ye=se.type==="this"?a.peerId:se.type==="my"?I.myId:"public",Te=P(`Search.Types.${se.type==="this"?"ThisChat":se.type==="my"?"MyMessages":"PublicPosts"}`);return T(Ze,ni({peerId:ye,title:Te},()=>!se.notList&&{active:()=>$()===se.type,onClick:()=>H(Pe=>Pe===se.type?U0:se.type)},{get fallbackIcon(){return se.type==="public"?"newchannel_filled":void 0},get onPromises(){return se.onPromises}}))};le(async()=>{const se=M(),ye=$(),Te=ui().get();let Pe;(se||ye)&&(Pe=await new Promise(De=>{let We;const Ke=async Bt=>(await Promise.all(Bt),De(We));ye?We=Je({type:ye,notList:!0,onPromises:Ke}):We=Ze({peerId:se,onPromises:Ke})}),!Te())||E(Pe)});const tt=43,ht=271,Ee=se=>{let ye=w();if(!ye){ye=at.querySelector(".chatlist-chat"),b(ye);return}if(se==="down"?ye=ye.previousElementSibling:ye=ye.nextElementSibling,!ye||!ye.classList.contains("chatlist-chat"))return;const Te=ye.offsetTop,Pe=ht;at.scrollTop=Te-Pe/2+ye.clientHeight/2,b(ye)},ve=({direction:se})=>T(Pi,{icon:se,get class(){return Ge("input-search-part","topbar-search-input-arrow",(!o()||S()&&!M())&&"hide")},noRipple:!0,onClick:()=>{Ee(se)}}),Qe=ce.clearBtn.previousSibling;let A;(()=>{const se=e$(),ye=A;return typeof ye=="function"?Ue(ye,se):A=se,k(se,(()=>{const Te=V(()=>!t());return()=>Te()&&[T(ve,{direction:"up"}),T(ve,{direction:"down"})]})(),null),k(se,()=>ce.clearBtn,null),se})(),Qe.after(A);const F=(se,ye)=>{Ce.chat.setMessageId({query:se&&ye||void 0,isPublicHashtag:se==="public"||void 0,isCacheableSearch:!!se||void 0,inputFilter:ye&&se?{_:"inputMessagesFilterEmpty"}:void 0,type:ye&&se?we.Search:a.chatType,hashtagType:se})};le(se=>{se||(se={});const{peerId:ye,threadId:Te}=a,Pe=n(),De=M(),We=j(),Ke=ui().get(),Bt=!Pe.trim()||Pe==="#",bt=z(),ct=!We&&G(),Tt=$();if(Tt&&!Pe){H(),F(void 0,void 0);return}y(()=>{}),m(),f(),b();const ft=(We?h$:d$)({middleware:Ke,peerId:ye,threadId:Te,query:Pe,fromPeerId:De,reaction:ct,searchType:Tt}),Kt=V(()=>o()===0||bt&&o()===void 0);let es;(()=>{const ts=ah(),$n=es;return typeof $n=="function"?Ue($n,ts):es=ts,k(ts,(()=>{const Ba=V(()=>!!Kt());return()=>Ba()?(()=>{const Oi=t$();return k(Oi,()=>bt&&(o()===void 0?P("Search.HelpHashtag"):P("Search.EmptyHashtag",[je(N0(Pe,18))])),null),k(Oi,()=>!bt&&(De?P("Search.EmptyFrom",[new Xt({peerId:De}).element]):P("Search.Empty",[je(N0(Pe,18))])),null),Oi})():[(()=>{const Oi=ah();return k(Oi,()=>ft().rendered),Oi})(),V((()=>{const Oi=V(()=>!!ft().rendered);return()=>Oi()&&s$()})())]})()),Me(()=>be(ts,Ge(!Ot(t)&&"topbar-search-left-chatlist","chatlist",Kt()&&"is-empty"))),ts})();let ys=!0;const Ds=ts=>{ys&&(ce.toggleLoading(!1),h({element:es,type:We?"senders":"messages"}),at.scrollTop=0,ys=!1,Ot(t)&&!We&&b(Ot(p)&&ts))};(Tt!==se.searchType||Tt&&Pe!==se.query)&&(a.onSearchTypeChange?.(),F(Tt,Pe));const Tn={searchType:Tt,query:Pe};return!We&&!De&&!ct&&Bt?(l(),d(),Ds(),Tn):(le(Vt(()=>ft(),({rendered:ts,values:$n,count:Ba,loadMore:Oi})=>{l(ts.length),d(Ba),y(()=>Oi),We?f($n):m($n),Ds(ts[0])},{defer:!0})),ce.toggleLoading(!0),Ot(()=>ft().loadMore()),Tn)}),le(Vt(w,se=>{const ye=Bn(se);if(ye===-1)return;if(j()){const De=g()[ye];pi(()=>{C(De),ce.onChange(ce.value="")});return}const Te=se.parentElement.querySelector(".active");Te&&Te.classList.remove("active"),se.classList.add("active"),U(!1);const Pe=p()[ye];Ce.chat.setMessageId({lastMsgId:Pe.mid,lastMsgPeerId:Pe.peerId})},{defer:!0}));const Q=se=>({_:"reactionCount",count:se.count,reaction:se.reaction}),X=se=>({_:"messageReactions",pFlags:{reactions_as_tags:!0},results:se.map(Q)}),ge=({savedPeerId:se,tags:ye})=>{se===a.threadId&&R(ye)};Ta(I)("saved_tags",ge),le(se=>{const ye=x(),Te=B();if(!ye||!Te)return se;const Pe={...Te.getContext(),reactions:X(ye)},De=G();let We;if(De){const Bt=Pe.reactions.results.find(bt=>Wn(bt.reaction,De));Bt&&(We=Bt,Bt.chosen_order=0)}if(se?.remove(),Te.update(Pe),We){const Bt=Te.getSorted().find(bt=>Wn(bt.reactionCount.reaction,De));Bu({container:Us,element:Bt,position:"center",axis:"x"})}const Ke=ae();if(Te.classList.toggle("is-locked",!Ke),!Ke){const Bt="premium_lock",bt=new Qo;bt.init(la.Tag,ui().get()),bt.reactionCount={_:"reactionCount",count:1,reaction:Bt},bt.setCanRenderAvatars(!1),bt.renderCounter(void 0,P("Unlock")),bt.classList.add("reaction-tag-lock");const ct=document.createElement("div");return ct.classList.add("reaction-sticker","reaction-sticker-icon"),ct.append(Be(Bt)),bt.lastElementChild.before(ct),Te.prepend(bt),bt}}),le(()=>{if(a.peerId!==I.myId){N(),R();return}const se=ui().get(),ye=Ht();ze(()=>{setTimeout(()=>{ye.destroy()},400)});const Te=new Wg;Te.init({context:{peerId:a.peerId,mid:0,reactions:X([])},type:la.Block,middleware:ye.get(),forceCounter:!0}),Te.classList.remove("has-no-reactions"),Te.classList.add("topbar-search-left-reactions");const Pe=J(Te,We=>{const Ke=ne(We.target,"reaction-tag");if(!Ke)return;if(!ae()){rs.show({feature:"saved_tags"});return}const{reactionCount:Bt}=Ke,{reaction:bt}=Bt;O(ct=>{if(!Wn(ct,bt))return bt}),Ki(ce.input)},{cancelMouseDown:!0});ze(Pe);const De=()=>{I.managers.appReactionsManager.getSavedReactionTags(a.threadId).then(We=>{se()&&(N(Te),R(We))})};De(),I.addEventListener("saved_tags_clear",De),ze(()=>{I.removeEventListener("saved_tags_clear",De)})});let he=!0;le(Vt(G,se=>{he&&(he=!1,!se)||Ce.chat.setMessageId({savedReaction:se?[se]:void 0})})),ze(()=>{G()&&Ce.chat.setMessageId({lastMsgId:void 0,lastMsgPeerId:void 0,mediaTimestamp:void 0,savedReaction:void 0})}),ze(()=>{Ce.chat.type===we.Search&&F(void 0,void 0)}),le(()=>{if(ce.setArrowBack(t()),!t())return;const se=()=>Bn(w()),ye=u$({index:se,count:c,pickUserBtn:lt,pickDateBtn:mt,resultsShown:q,onToggle:()=>{U(Ke=>!Ke)},choosingSender:j}),Te=p$({scrollable:kt}),Pe=m$({reactionsScrollable:Ts,searchTypesScrollable:et,hasReactions:()=>!!Se(),hasSearchTypes:()=>!!xe()});g$({index:se,count:c,chat:a.chat,onArrowButtonClick:Ee});const De=(Ke=D())=>{a.chat.bubbles.container.classList.toggle("search-results-active",Ke),Te.classList.toggle("active",Ke)},We=Ke=>{Ke??(Ke=!!(Se()||xe())),a.chat.topbar.container.classList.toggle("search-top-active",Ke),Te.classList.toggle("search-top-active",Ke),Ke?te.after(Pe):Pe.remove()};le(()=>De()),le(()=>We()),le(()=>{j()?U(!0):S()||U(!1)}),ze(()=>{ye.remove(),U(!1),De(),We(!1),setTimeout(()=>{Te.remove()},400)}),a.chat.input.chatInput.before(Te,ye)});const Le=V(()=>{if(!q())return 0;const se=o();if(se===void 0&&!z())return 0;const ye=8*2;let Te;return se?u().type==="senders"?Te=1+ye+se*48:Te=1+ye+se*56:Te=tt,Math.min(ht,Te)}),Se=V(()=>oe()&&Z()?61:0),xe=V(()=>oe()&&de()?61:0),lt=a.canFilterSender&&T(Pi,{get class(){return Ge(!t()&&"topbar-search-right-filter-button")},icon:"newprivate",ref:se=>{const ye=J(se,Te=>{_e(Te),ce.onChange(ce.value=""),_(!0),Ki(ce.input,!0)},{cancelMouseDown:!0});ze(ye)}}),mt=a.onDatePick&&T(Pi,{icon:"calendar",onClick:()=>{ue.createPopup(Ng,new Date,a.onDatePick).show()}});let at;const kt=T(o$,ni({ref(se){const ye=at;typeof ye=="function"?ye(se):at=se}},()=>!t()&&{class:"topbar-search-left-results topbar-search-left-collapsable",style:Le()?{height:Le()+"px"}:void 0},{onScrolledBottom:()=>{v()?.()},get children(){return[V(()=>V(()=>!t())()&&i$()),T(Yo,{type:"cross-fade",get children(){return u()?.element}})]}}));let Us;const Ts=T(cu,{ref(se){const ye=Us;typeof ye=="function"?ye(se):Us=se},class:"topbar-search-left-reactions-scrollable",get children(){return[xp(),V(()=>B()),xp()]}});let zs;const et=T(cu,{ref(se){const ye=zs;typeof ye=="function"?ye(se):zs=se},class:"topbar-search-left-reactions-scrollable",get children(){return[xp(),(()=>{const se=n$();return k(se,()=>l$.map(ye=>T(Je,{type:ye}))),se})(),xp()]}});let te;return(()=>{const se=a$(),ye=se.firstChild;ye.firstChild;const Te=te;return typeof Te=="function"?Ue(Te,se):te=se,k(ye,()=>ce.container,null),k(ye,(()=>{const Pe=V(()=>!t());return()=>Pe()&&(()=>{const De=O0();return De.firstChild,k(De,Ts,null),Me(We=>Ii(De,Se()?{height:Se()+"px"}:void 0,We)),De})()})(),null),k(ye,(()=>{const Pe=V(()=>!t());return()=>Pe()&&(()=>{const De=O0();return De.firstChild,k(De,et,null),Me(We=>Ii(De,xe()?{height:xe()+"px"}:void 0,We)),De})()})(),null),k(ye,()=>!t()&&kt,null),k(se,(()=>{const Pe=V(()=>!t());return()=>Pe()&&(()=>{const De=r$();return k(De,lt&&(()=>{const We=ah();return k(We,lt),Me(()=>be(We,Ge("topbar-search-right-filter",(S()||z())&&"is-hidden"))),We})(),null),k(De,mt&&(()=>{const We=ah();return k(We,mt),Me(()=>be(We,Ge("topbar-search-right-filter",z()&&"is-hidden"))),We})(),null),De})()})(),null),Me(()=>be(ye,Ge("topbar-search-left-container",oe()&&"is-focused"))),se})()}Fs(["click"]);var we=(a=>(a.Chat="chat",a.Pinned="pinned",a.Discussion="discussion",a.Scheduled="scheduled",a.Stories="stories",a.Saved="saved",a.Search="search",a))(we||{});const Jf=["query","isCacheableSearch","isPublicHashtag","savedReaction","fromPeerId","inputFilter","hashtagType"];class NP extends pn{constructor(e,t,s,i={}){super(),this.appImManager=e,this.managers=t,this.isMainChat=s,this.excludeParts=i,this.log=Ni("CHAT",Rn.Log|Rn.Warn|Rn.Debug|Rn.Error),this.log.warn("constructor"),this.type="chat",this.animationGroup=`chat-${Math.round(Math.random()*65535)}`,this.middlewareHelper=Ht(),this.destroyMiddlewareHelper=Ht(),this.hadAnyBackground=!1,this.excludeParts.elements||(this.container=document.createElement("div"),this.container.classList.add("chat","tabs-tab"),this.backgroundEl=document.createElement("div"),this.backgroundEl.classList.add("chat-background"),this.container.append(this.backgroundEl)),this.peerId=Wt,this.backgroundTempId=0,this.sharedMediaTabs=[]}hasBackgroundSet(){return!!(this.theme||this.wallPaper)}async setBackground({url:e,theme:t,wallPaper:s,skipAnimation:i,manual:n,onCachedStatus:r}){this.hadAnyBackground=!0;const o=this.log.bindPrefix("setBackground");o("start");const l=!t,c=Ls.getTheme(),d=Ls.getThemeSettings(c).wallpaper,u=t??c,h=!!(u||!l||s);if(s||(s=Ls.getThemeSettings(u).wallpaper),this.wallPaper===s&&this.theme===u){o("same background"),r?.(!0);return}const p=_v(s),m=s?.slug;let g,f;const v=!!p&&!m&&!s.settings.intensity;if(v&&document.documentElement.style.cursor==="grabbing"&&this.gradientRenderer&&!this.patternRenderer){o("just changing color"),this.gradientCanvas.dataset.colors=p,this.gradientRenderer.init(this.gradientCanvas),r?.(!0);return}const y=++this.backgroundTempId;if(!e&&!v){const N=s.settings,G=kc.getBackground({slug:m,canDownload:!0,managers:this.managers,appDownloadManager:fs,blur:N&&N.pFlags.blur}),O=!(G instanceof Promise);if(o("getting background, cached",O),r?.(O),i??(i=O),O||(n=void 0),e=await G,this.backgroundTempId!==y)return}else o("global background"),r?.(!0);const w=this.gradientRenderer,b=this.patternRenderer;this.gradientCanvas;const S=this.patternCanvas;this.theme,this.wallPaper,this.gradientRenderer=this.patternRenderer=this.gradientCanvas=this.patternCanvas=this.theme=this.wallPaper=void 0,u!==c&&(this.theme=t),s!==d&&(this.wallPaper=s);const _=!!s.pFlags.pattern,M=s.settings?.intensity&&s.settings.intensity/100,C=!!M&&M<0;let L,E=g?.firstElementChild,x;if(!g)if(g=document.createElement("div"),g.classList.add("chat-background-item"),e)if(_){g.classList.add("is-pattern");const N=this.appImManager.chatsContainer.getBoundingClientRect();L=this.patternRenderer=m_.getInstance({element:this.appImManager.chatsContainer,url:e,width:N.width,height:N.height,mask:C}),E=this.patternCanvas=L.createCanvas(),E.classList.add("chat-background-item-canvas","chat-background-item-pattern-canvas"),C&&g.classList.add("is-dark")}else f=document.createElement("img"),f.classList.add("chat-background-item-image"),g.classList.add("is-image","chat-background-item-scalable"),g.append(f);else g.classList.add("is-color");let R;if(p){const{canvas:N,gradientRenderer:G}=kv.create(p);R=this.gradientRenderer=G,x=this.gradientCanvas=N,x.classList.add("chat-background-item-canvas","chat-background-item-color-canvas"),x.classList.add("chat-background-item-scalable")}if(M&&(!f||Ls.isNight())){let N;f?N=f:N=C?x:E;let G=Math.abs(M)*(C?.5:1);f?G=Math.max(.3,1-M):C&&(G=Math.max(.3,G)),N.style.setProperty("--opacity-max",""+G)}const B=new Promise(N=>{const G=()=>{if(this.backgroundTempId!==y){L?.cleanup(E),R?.cleanup();return}const H=this.backgroundEl.lastElementChild;if(H===g)return;const D=()=>{const j=performance.now();let q;f?q=KE(f):q=g_(x);const W=ib(Array.from(q));return o("getHighlightningColor",W,performance.now()-j),W},U=[x,E].filter(Boolean);U.length&&g.append(...U),this.backgroundEl.append(g),Dt({element:g,className:"is-visible",forwards:!0,duration:i?0:200,onTransitionStart:()=>{const j=performance.now();u&&Ls.applyTheme(u,this.container),h&&Ls.applyHighlightingColor({hsla:D(),element:this.container}),o("transition start time",performance.now()-j)},onTransitionEnd:H?()=>{b?.cleanup(S),w?.cleanup(),H.remove()}:null,useRafs:2})},O=()=>{o("background is ready",performance.now()-$),n?N(G):(G(),N(void 0))},$=performance.now();L?L.renderToCanvas(E).then(O):e?Ka(f,e,O,!1):O()});return n?B:this.setBackgroundPromise=Promise.race([ns(500),B]).then(()=>{I.dispatchEvent("chat_background_set")})}setBackgroundIfNotSet(e){if(!this.hasBackgroundSet())return this.setBackground(e)}_handleBackgrounds(){const e=this.log.bindPrefix("handleBackgrounds"),t=Mt();let s=!0;const i=d=>{const u=this.setBackground({manual:s,onCachedStatus:h=>{h||t.resolve(void 0)},...d});return VL(u,t),u},n=d=>{if(!d)return;const{accountThemes:u}=c;return u.themes?.find(h=>h.emoticon===d)},r=()=>{if(!this.hasBackgroundSet()&&this.hadAnyBackground){e("no background"),t.resolve(void 0);return}e("resetting background"),i(this.getResetBackgroundOptions())},o=()=>{const d=l();if(!d){r();return}let u=bl(d.wallpaper);const h=d.theme_emoticon||u&&u.settings?.emoticon,p=bl(n(h));if(!p&&!u){r();return}h&&p&&(u=void 0),e("updating",d,p,u),i({theme:p,wallPaper:u,skipAnimation:s});const m=Mg();le(Vt(m,o,{defer:!0}))},l=L_(()=>this.peerId),[c]=bg();return le(()=>{o(),s=!1}),t}handleBackgrounds(){return this.type==="stories"?Promise.resolve(as):Ft(e=>(this.middlewareHelper.get().onClean(e),this._handleBackgrounds()))}setType(e){this.type=e}init(){this.topbar=new G7(this,Gs,this.managers),this.bubbles=new F6(this,this.managers),this.input=new Zm(this,this.appImManager,this.managers,"chat-input-main"),this.contextMenu=new In(this,this.managers),this.selection=new $6(this,this.bubbles,this.input,this.managers),this.topbar.constructUtils(),this.topbar.constructPeerHelpers(),this.topbar.construct(),this.input.construct(),this.bubbles.constructPeerHelpers(),this.input.constructPeerHelpers(),pt||this.bubbles.setReactionsHoverListeners(),this.bubbles.attachContainerListeners(),this.container.append(this.topbar.container,this.bubbles.container,this.input.chatInput),this.bubbles.listenerSetter.add(I)("dialog_migrate",({migrateFrom:t,migrateTo:s})=>{this.peerId===t&&this.setPeer({peerId:s})}),this.bubbles.listenerSetter.add(I)("dialog_drop",t=>{t.peerId===this.peerId&&(Po(t)||this.threadId===z7(t))&&this.appImManager.setPeer({isDeleting:!0})}),this.bubbles.listenerSetter.add(I)("chat_update",async t=>{const{peerId:s}=this;if(s.isAnyChat()&&s.toChatId()===t){const{starsAmount:i,isAnonymousSending:n}=await bb({starsAmount:this.managers.appChatsManager.getStarsAmount(t),isAnonymousSending:this.managers.appMessagesManager.isAnonymousSending(s)});s===this.peerId&&(this.isAnonymousSending=n,this.starsAmount=i,this.input.setStarsAmount(i),au()?.setStarsAmount(i))}});const e=t=>{const s=()=>{this.bubbles.observer?.toggleObservingNew(t),Ut.toggleIntersectionGroup(this.animationGroup,t),t&&Ut.checkAnimations(t,this.animationGroup)};t?s():setTimeout(()=>{s()},400)};this.bubbles.listenerSetter.add(this.appImManager)("chat_changing",({to:t})=>{e(t!==this)}),this.bubbles.listenerSetter.add(this.appImManager)("tab_changing",t=>{e(this.appImManager.chat!==this||t!==pd.CHAT&&st.activeScreen===fn.mobile)}),this.searchSignal=fo(),Ft(t=>{this.middlewareHelper.get().onDestroy(t);const s=async(h,p)=>{const m=wt.isAvailable("animations"),g=[{opacity:0},{opacity:1}],f={fill:"forwards",duration:m?200:0,easing:"ease-in-out"};p||g.reverse();const v=this.topbar.container.querySelectorAll(".content, .chat-utils"),y=[],w=h.animate(g,f).finished;g.reverse();const b=Array.from(v).map(S=>S.animate(g,f).finished);return y.push(w,...b),Promise.all(y)},[i,n]=K(!1),[r,o]=K("",{equals:!1}),[l,c]=K(void 0,{equals:!1}),[d,u]=K(void 0,{equals:!1});le(h=>{if(!i()){if(!h)return;s(h,!1).then(()=>{h.remove()});return}return h=Ot(()=>f$({chat:this,chatType:this.type,peerId:this.peerId,threadId:this.threadId,canFilterSender:this.isAnyGroup,query:r,filterPeerId:l,reaction:d,onClose:()=>{this.searchSignal(void 0)},onDatePick:p=>{this.bubbles.onDatePick(p)},onActive:(p,m,g)=>{const f="is-search-active",v=!!(p&&(m||g));if(this.container.classList.contains(f)===v)return;const w=this.bubbles.createScrollSaver();w.save(),this.container.classList.toggle(f,!g&&v),this.topbar.container.classList.toggle("hide-pinned",g),w.restore()},onSearchTypeChange:()=>{this.ignoreSearchCleaning=!0}})),this.topbar.container.append(h),s(h,!0),h}),le(()=>{const h=this.searchSignal();o(h?.query),c(h?.filterPeerId),u(h?.reaction),n(!!h)})}),Ft(t=>{this.middlewareHelper.get().onDestroy(t),this.stars=Jl()})}beforeDestroy(){this.destroyPromise=Mt(),this.bubbles.cleanup(),this.searchSignal?.(void 0)}cleanupBackground(){++this.backgroundTempId,this.patternRenderer?.cleanup(this.patternCanvas),this.gradientRenderer?.cleanup(),this.patternRenderer=this.gradientRenderer=void 0}destroy(){this.destroyPromise?.resolve(),this.destroySharedMediaTab(),this.topbar?.destroy(),this.bubbles?.destroy(),this.input?.destroy(),this.contextMenu?.destroy(),this.selection?.attachListeners(void 0,void 0),this.destroyMiddlewareHelper.destroy(),this.cleanupBackground(),this.topbar=this.bubbles=this.input=this.contextMenu=this.selection=void 0,this.container?.remove(),this.changeHistoryStorageKey(void 0)}cleanup(e=!0){this.input?.cleanup(e),this.topbar?.cleanup(),this.selection?.cleanup(),this.ignoreSearchCleaning?this.ignoreSearchCleaning=void 0:this.searchSignal?.(void 0)}get isForumTopic(){return!!(this.isForum&&this.threadId)}async onChangePeer(e,t){const{peerId:s,threadId:i}=e;this.excludeParts.elements||Gs.getTab(FP)?.close();const n=Ae.isForum(s);i&&!n&&(e.type=e.peerId===I.myId?"saved":"discussion"),e.query&&(e.type="search");const r=e.type??"chat";this.setType(r);const[o,l,c,d,u,h,p,m,g,f,v,y,w]=await t(Promise.all([this.managers.appPeersManager.noForwards(s),this.managers.appPeersManager.isPeerRestricted(s),this._isLikeGroup(s),this.managers.appPeersManager.isAnyGroup(s),this.setAutoDownloadMedia(),this.managers.appPeersManager.isMegagroup(s),this.managers.appPeersManager.isBroadcast(s),this.managers.appPeersManager.isChannel(s),this.managers.appPeersManager.isBot(s),this.managers.appMessagesManager.isAnonymousSending(s),s.isUser()&&this.managers.appProfileManager.isCachedUserBlocked(s),this.isPremiumRequiredToContact(s),this.managers.appPeersManager.getStarsAmount(s)]));n&&i&&await t(this.managers.dialogsStorage.getForumTopicOrReload(s,i)),this.noForwards=o,this.isRestricted=l,this.isLikeGroup=c,this.isAnyGroup=d,this.isMegagroup=h,this.isBroadcast=p,this.isChannel=m,this.isBot=g,this.isForum=n,this.isAllMessagesForum=n&&!i,this.isAnonymousSending=f,this.isUserBlocked=v,this.isPremiumRequired=y,this.starsAmount=w,this.selection&&(this.selection.isScheduled=r==="scheduled"),this.messagesStorageKey=`${this.peerId}_${this.type==="scheduled"?"scheduled":"history"}`,this.excludeParts.sharedMedia||(this.sharedMediaTab=Gs.createSharedMediaTab(),this.sharedMediaTabs.push(this.sharedMediaTab),this.sharedMediaTab.setPeer(s,i)),this.input?.clearHelper(),this.selection?.cleanup()}get requestHistoryOptionsPart(){const e={peerId:this.peerId,threadId:this.threadId};return Jf.forEach(t=>{e[t]=this[t]}),this.hashtagType&&this.hashtagType!=="this"&&(e.peerId=Wt,e.threadId=void 0),e}setPeer(e){const{peerId:t,threadId:s}=e;t?this.inited||(this.init&&(this.init(),this.init=null),this.inited=!0):this.inited=void 0;const i=this.appImManager.isSamePeer(this,e);if(!i)this.appImManager.dispatchEvent("peer_changing",this),this.peerId=t||Wt,this.threadId=s,this.middlewareHelper.clean();else if(this.setPeerPromise)return;if(!t){this.peerId=0;let d;this.hasBackgroundSet()&&this===this.appImManager.chats[0]&&(d=this.setBackground(this.getResetBackgroundOptions())),en(d,()=>{Gs.toggleSidebar(!1),this.cleanup(!0),this.bubbles.setPeer({peerId:t,samePeer:!1,sameSearch:!1}),this.appImManager.dispatchEvent("peer_changed",this),this.excludeParts.sharedMedia||(Gs.replaceSharedMediaTab(),this.destroySharedMediaTab(),this.sharedMediaTab=void 0)});return}this.peerChanged=i;let n=!0;(!i||Jf.some(d=>e.hasOwnProperty(d)))&&(Jf.forEach(d=>{this[d]=e[d]}),n=!1);const{requestHistoryOptionsPart:r}=this,o=BP({type:DP(r),...r});this.changeHistoryStorageKey(o);const l=this.bubbles.setPeer({...e,samePeer:i,sameSearch:n}),c=this.setPeerPromise=l.then(d=>d.promise).catch(as).finally(()=>{this.setPeerPromise===c&&(this.setPeerPromise=null)});return l}changeHistoryStorageKey(e){this.historyStorageKey!==e&&(this.historyStorageKey&&this.managers.appMessagesManager.toggleHistoryKeySubscription(this.historyStorageKey,!1),this.historyStorageKey=e,this.historyStorageKey&&this.managers.appMessagesManager.toggleHistoryKeySubscription(this.historyStorageKey,!0))}getResetBackgroundOptions(){return{url:this.appImManager.lastBackgroundUrl,skipAnimation:!0}}destroySharedMediaTab(e=this.sharedMediaTab){e&&(Vs(this.sharedMediaTabs,e),e.destroy())}async setAutoDownloadMedia(){this.autoDownload=await V7(this.peerId)}setMessageId(e={}){return this.setPeer({peerId:this.peerId,threadId:this.threadId,...e})}async finishPeerChange(e){if(this.peerChanged)return;const t=this.peerId;this.peerChanged=!0,this.wasAlreadyUsed=!0;const{middleware:s}=e;this.cleanup(!1);const i=this.sharedMediaTab,n=[this.topbar?.finishPeerChange(e),this.bubbles?.finishPeerChange(),this.input?.finishPeerChange(e),i?.fillProfileElements(),this.handleBackgrounds()],o=await Promise.all(n);i?.loadSidebarMedia(!0),s()&&(o.forEach(l=>{l?.()}),i&&(Gs.replaceSharedMediaTab(i),this.sharedMediaTabs.filter(l=>l!==i).forEach(l=>this.destroySharedMediaTab(l))),this.container&&(this.container.dataset.type=this.type==="search"?"chat":this.type,this.container.classList.toggle("can-click-date",["chat","discussion","saved"].includes(this.type))),this.log.setPrefix("CHAT-"+t+"-"+this.type),this.isMainChat&&this.appImManager.dispatchEvent("peer_changed",this))}getMessage(e){if(typeof e=="string"){const{peerId:t,mid:s}=ti(e);return Ae.getMessageByPeer(t,s)}return Ae.getMessageFromStorage(this.messagesStorageKey,e)}getMessageByPeer(e,t){return this.query?Ae.getMessageByPeer(e,t):this.getMessage(t)}async getMidsByMid(e,t){return this.managers.appMessagesManager.getMidsByMessage(this.getMessageByPeer(e,t))}getHistoryStorage(e){return this.managers.appMessagesManager.getHistoryStorageTransferable({...this.requestHistoryOptionsPart,threadId:e?void 0:this.threadId}).then(t=>({...t,history:ed.fromJSON(t.historySerialized),searchHistory:t.searchHistorySerialized&&ed.fromJSON(t.searchHistorySerialized)}))}getDialogOrTopic(){return this.managers.dialogsStorage.getAnyDialog(this.peerId,(this.isForum||this.type==="saved")&&this.threadId)}getHistoryMaxId(){return this.getHistoryStorage().then(e=>e.maxId)}_isLikeGroup(e){return e===I.myId||e===Lo||this.type==="search"&&this.hashtagType!=="this"||this.managers.appPeersManager.isLikeGroup(e)}resetSearch(){this.searchSignal?.(void 0)}initSearch(e={}){this.peerId&&(e.query||(e.query=""),this.searchSignal(e))}canSend(e){return this.type==="saved"&&this.threadId!==this.peerId?Promise.resolve(!1):this.managers.appMessagesManager.canSendToPeer(this.peerId,this.threadId,e)}isStartButtonNeeded(){return Promise.all([this.managers.appPeersManager.isBot(this.peerId),this.managers.appMessagesManager.getDialogOnly(this.peerId),this.getHistoryStorage(!0),this.peerId.isUser()?this.managers.appProfileManager.isCachedUserBlocked(this.peerId.toUserId()):void 0]).then(([e,t,s,i])=>e?!t&&!s.history.length||i:!1)}isPremiumRequiredToContact(e=this.peerId){return e.isUser()?this.managers.appUsersManager.getRequirementToContact(e.toUserId(),!0).then(t=>t?._==="requirementToContactPremium"):Promise.resolve(!1)}getMessageSendingParams(){return{peerId:this.peerId,threadId:this.threadId,updateStickersetOrder:I.settings.stickers.dynamicPackOrder,...this.input&&{...this.input.getReplyTo()||!1,scheduleDate:this.input.scheduleDate,silent:this.input.sendSilent,sendAsPeerId:this.input.sendAsPeerId,effect:this.input.effect()},savedReaction:this.savedReaction}}isOurMessage(e){return this.isMegagroup?!!e.pFlags.out:!!(e.fromId===I.myId&&!e.pFlags.post||e.fwd_from?.pFlags?.saved_out)}isOutMessage(e){const t=e.fwd_from;return!!(this.isOurMessage(e)&&(!t||this.peerId!==I.myId||this.threadId))}isAvatarNeeded(e){return this.isLikeGroup&&!this.isOutMessage(e)}isPinnedMessagesNeeded(){return this.type==="chat"||this.isForum}isForwardOfForward(e){let t=II(e);const s=e.fwd_from;return t&&s.saved_from_id&&this.type==="saved"&&it(s.saved_from_id)===this.threadId&&(t=!1),t}getPostAuthor(e){if(this.isLikeGroup)return;const t=e.fwd_from;if(e.pFlags.post||t?.post_author&&!this.isOutMessage(e))return e.post_author||t?.post_author}async canGiftPremium(){const e=this.peerId;if(!e.isUser())return!1;const[t,s]=await Promise.all([this.managers.appProfileManager.canGiftPremium(this.peerId.toUserId()),Ae.isPremiumPurchaseBlocked()]);return e.isUser()&&t&&!s}async openWebApp(e){return Object.assign(e,this.getMessageSendingParams()),e.peerId??(e.peerId=this.peerId),this.appImManager.openWebApp(e)}async sendReaction(e){const t=e.reaction._==="reactionPaid",s=e.count??1;if(t){const n=iI(e.message);let r=vh.get(n);const o=!!r,l=(r?r.count():0)+s;if(+this.stars()<l){r&&r.abortController.abort(),ue.createPopup(ba,{itemPrice:s,onTopup:()=>{this.sendReaction(e)},purpose:"reaction",peerId:this.peerId});return}if(r)clearTimeout(r.sendTimeout);else{const[c,d]=K(0),[u,h]=K(0),p=new AbortController;p.signal.addEventListener("abort",()=>{clearTimeout(r.sendTimeout),r.setSendTime(0),vh.delete(n),p.signal.reason!==zS&&eu(m=>m-r.count()),I.dispatchEventSingle("messages_reactions",[{message:this.getMessageByPeer(e.message.peerId,e.message.mid),changedResults:[],removedResults:[]}])}),vh.set(n,r={count:c,setCount:d,sendTime:u,setSendTime:h,sendTimeout:0,abortController:p})}r.setCount(c=>c+s),r.setSendTime(Date.now()+Oh),r.sendTimeout=window.setTimeout(()=>{const c=r.count();r.abortController.abort(zS),this.managers.appReactionsManager.sendReaction({...e,count:c})},Oh),eu(c=>c+s),o||q1({titleCount:r.count,subtitleCount:r.count,sendTime:r.sendTime,onUndo:()=>void r.abortController.abort(),...n3})}const i=await this.managers.appReactionsManager.sendReaction({...e,count:t?0:s,onlyReturn:t});if(t){const{message:n}=e;n.reactions=i,I.dispatchEventSingle("messages_reactions",[{message:n,changedResults:[i.results[0]],removedResults:[]}])}}}const v$=Y("<div>"),sl="popup-delete-megagroup-messages";class y$ extends ue{constructor(e){super(sl,{body:!0,scrollable:!0,title:P("DeleteOptionsTitle",[e.messages.length]),overlayClosable:!0,buttons:Go([{langKey:"DeleteProceedBtn",isDanger:!0,callback:()=>this.onConfirmClick(),iconLeft:"delete_filled"}])}),this.messages=e.messages,this.onConfirm=e.onConfirm,this.construct()}async onConfirmClick(){const e=this.fields.reduce((r,o)=>{let l=r.get(o.peerId);return l||r.set(o.peerId,l=new Set),o.checkboxField.checked&&l.add(o.action),r},new Map),t=this.messages.map(({mid:r})=>r),s=this.messages[0].peerId,{restricting:i,managers:n}=this;for(const[r,o]of e){const l=[];if(o.has("ban")&&i){const c=this.chatPermissions.takeOut();l.push(n.appChatsManager.editBanned(s.toChatId(),r,c))}else o.has("ban")&&l.push(n.appChatsManager.kickFromChannel(s.toChatId(),r));o.has("report")&&l.push(n.appMessagesManager.reportSpamMessages(s,r,t)),o.has("delete")&&l.push(n.appMessagesManager.doFlushHistory(s,!1,!0,void 0,r))}return n.appMessagesManager.deleteMessages(s,t,!0),this.onConfirm?.(),!0}async construct(){const e=eo(this.messages.map(({fromId:g})=>g)),t=this.messages[0].peerId,s=new Zl({middleware:this.middlewareHelper.get(),avatarSize:32}),i=[];s.render(e.slice(0,3),i),s.container.classList.add(`${sl}-avatars`),this.header.prepend(s.container);const n=e.length===1,r=[{action:"report",peerIds:e,langKey:"DeleteReportSpam"},{action:"delete",peerIds:e,langKey:n?"DeleteAllFrom":"DeleteAllFromUsers",langArgs:n?[await qe({peerId:e[0],onlyFirstName:!0})]:void 0},{action:"ban",peerIds:e,langKey:n?"DeleteBan":"DeleteBanUsers",langArgs:n?[await qe({peerId:e[0],onlyFirstName:!0})]:void 0}],o="delete-fields",l=(...g)=>[o,...g].join("-"),c=g=>{const f=n?[]:g.peerIds.map(v=>{const y=l(g.action,""+v);return{action:g.action,name:y,peerId:v}});return[{action:g.action,text:g.langKey,textArgs:g.langArgs,nested:n?void 0:f,name:n?l(g.action,""+t):l(g.action),peerId:n?g.peerIds[0]:void 0},...f]},d=this.fields=va(r.map(c)),u=new $g({fields:d,listenerSetter:this.listenerSetter,round:!0,onRowCreation:(g,f)=>{if(!f.nestedTo)return;g.container.classList.add(`${sl}-row`);const v=document.createElement("div");v.classList.add(`${sl}-row-title`);const y=g.createTitle(),w=vs({peerId:f.peerId,middleware:this.middlewareHelper.get(),size:32}),b=new Xt,S=b.update({peerId:f.peerId,onlyFirstName:!0});y.append(b.element),i.push(w.readyThumbPromise,S),v.append(w.node,y),g.container.append(v)},rightButtonIcon:"group_filled",onAnyChange:()=>{m()},onExpand:()=>{const f=Date.now();No(()=>(this.scrollable.onScroll(),Math.min((Date.now()-f)/300,1)<1))}}),h=d.map(g=>u.createField(g)?.nodes).filter(Boolean),p=document.createElement("div");this.chatPermissions=new fw({appendTo:p,chatId:t.toChatId(),listenerSetter:this.listenerSetter},this.managers);let m;this.appendSolid(()=>{const[g,f]=K([]),[v,y]=K(!0),w=()=>v()?g().length===1?"DeleteToggleRestrictUser":"DeleteToggleRestrictUsers":g().length===1?"DeleteToggleBanUser":"DeleteToggleBanUsers";return m=()=>{const b=d.filter(S=>S.action==="ban"&&S.checkboxField.checked&&S.peerId).map(({peerId:S})=>S);f(b)},le(()=>{g().length||y(!0)}),le(()=>{const b=d.find(_=>_.action==="ban"&&(n?!0:!_.peerId)),S=Ne.weakMap.get(b.row.title.firstElementChild);this.restricting=!v(),S.compareAndUpdate({key:v()?n?"DeleteBan":"DeleteBanUsers":n?"DeleteRestrict":"DeleteRestrictUsers"})}),le(()=>{if(!v()){const S=Date.now(),_=this.scrollable.scrollPosition+this.scrollable.clientSize,C=712+this.scrollable.scrollSize-_;No(()=>{const L=Math.min((Date.now()-S)/300,1),E=_+C*L;return this.scrollable.scrollPosition=E,L<1})}}),[T(Ms,{name:"DeleteAdditionalActions",noShadow:!0,noDelimiter:!0,get children(){return va(h)}}),T(Ms,{class:`${sl}-permissions`,name:"UserRestrictionsCanDoUsers",get nameArgs(){return[g().length]},noShadow:!0,get style(){return{"max-height":v()?"0px":"712px"}},children:p}),T(Ms,{get classList(){return{hide:!g().length}},get children(){return T(En,{ref:b=>{b.classList.add("primary")},get title(){return(()=>{const b=v$();return k(b,()=>P(w()),null),k(b,T(hs,{icon:"down",class:`${sl}-expand-row-icon`}),null),Me(()=>be(b,Ge(`${sl}-expand-row`,!v()&&"is-expanded"))),b})()},clickable:()=>{y(b=>!b)},color:"primary"})}})]}),await Promise.all(i),this.show()}}class Md{constructor(e,t,s,i,n){this.peerId=e,this.mids=t,this.type=s,this.onConfirm=i,this.threadId=n,this.construct()}async construct(){let{peerId:e,mids:t,type:s,onConfirm:i,threadId:n}=this;t=t.slice();const r=ue.MANAGERS,o=await qe({peerId:e,threadId:n,onlyFirstName:!0}),l=await Promise.all(t.map(y=>r.appMessagesManager.getMessageByPeer(e,y))),c=await r.appPeersManager.isMegagroup(e);if(c&&!l.some(y=>y.pFlags.out)){const y=await r.appProfileManager.getParticipants({id:e.toChatId(),filter:{_:"channelParticipantsAdmins"},limit:100});if(!l.some(b=>y.participants.some(S=>Zc(S)===b.fromId))){ue.createPopup(y$,{messages:l,onConfirm:this.onConfirm});return}}const d=(y,w,b)=>{i?.(),s===we.Scheduled?r.appMessagesManager.deleteScheduledMessages(e,t):r.appMessagesManager.deleteMessages(e,t,!!w.size||b)},u=[{langKey:"Delete",isDanger:!0,callback:d}],h=[];let p,m,g,f;if(t.length===1?p="DeleteSingleMessagesTitle":(p="DeleteMessagesTitle",m=[P("messages",[t.length])]),c?g=t.length===1?"AreYouSureDeleteSingleMessageMega":"AreYouSureDeleteFewMessagesMega":g=t.length===1?"AreYouSureDeleteSingleMessage":"AreYouSureDeleteFewMessages",!(e===I.myId||s===we.Scheduled))if(e.isUser())h.push({text:"DeleteMessagesOptionAlso",textArgs:[o]});else{const y=await r.appChatsManager.getChat(e.toChatId()),w=Cr(y,"delete_messages");if(y._==="chat"){const b=w?t.slice():t.filter((S,_)=>l[_].fromId===I.myId);b.length&&(b.length===t.length?h.push({text:"DeleteForAll"}):(h.push({text:"DeleteMessagesOption"}),g="DeleteMessagesTextGroup",f=[P("messages",[b.length])]))}else{let b;l.find(S=>S&&S.media?._==="messageMediaGiveaway"&&!S.fwdFromId&&(b=S.media)),b&&b.until_date>=Qs(!0)&&(p="BoostingGiveawayDeleteMsgTitle",g="BoostingGiveawayDeleteMsgText",f=[gs(b.until_date,void 0,!0)]),u[0].callback=(S,_)=>d(S,_,!0)}}Go(u),ue.createPopup(mi,"popup-delete-chat",{peerId:e,threadId:n,titleLangKey:p,titleLangArgs:m,descriptionLangKey:g,descriptionLangArgs:f,buttons:u,checkboxes:h}).show()}}function Fc(a=window.getSelection()){if(!a?.rangeCount)return!0;const e=a.getRangeAt(0);return!!(e.collapsed||!e.START_TO_END)}function Ul(a){window.open(a,"_blank","noreferrer")}class b$ extends mi{constructor(){super("popup-sponsored",{titleLangKey:"Chat.Message.Sponsored.What",descriptionLangKey:"Chat.Message.Ad.Text",descriptionLangArgs:[P("Chat.Message.Sponsored.Link")],buttons:[{langKey:"OK",isCancel:!0},{langKey:"Chat.Message.Ad.ReadMore",callback:()=>{Ul(Ne.format("Chat.Message.Sponsored.Link",!0))},isCancel:!0}],scrollable:!0}),this.scrollable.append(this.description),this.show()}}const H0=24,w$=ii(H0,H0);async function OP({peerId:a,dialogElement:e,reaction:t,middleware:s,isMine:i,date:n,mediaSize:r=w$}){const{dom:o}=e;if(t){const l=document.createElement("div");if(l.classList.add("reacted-list-reaction-icon"),t._==="reactionEmoji"){const c=await I.managers.appReactionsManager.getReaction(t.emoticon);ai({doc:c.static_icon,div:l,width:24,height:24,middleware:s})}else t._==="reactionCustomEmoji"&&l.append(ab({docIds:[t.document_id],customEmojiSize:r,middleware:s}));o.listEl.append(l)}if(n&&i){const l=document.createElement("span");o.lastMessageSpan.style.cssText="display: flex !important; align-items: center;";const c=Be(t?"reactions":"checks","reacted-list-checks"),d=document.createDocumentFragment();l.append(gs(n,!1)),d.append(c,l),St(o.lastMessageSpan,d)}else{const l=await I.managers.appUsersManager.getUser(a.toUserId());St(o.lastMessageSpan,qo(l))}}class S$ extends ue{constructor(e){super("popup-reacted-list",{closable:!0,overlayClosable:!0,body:!0}),this.message=e,this.init()}async init(){const e=this.middlewareHelper.get(),t=await this.managers.appMessagesManager.getGroupsFirstMessage(this.message);if(!e())return;const s=await this.managers.appMessagesManager.canViewMessageReadParticipants(t);if(!e())return;const i=new Wg,n={...t,mid:0,id:0,reactions:{_:"messageReactions",results:[],...t.reactions,pFlags:{},recent_reactions:[]}};n.reactions.results=n.reactions.results.map(d=>({...d,chosen_order:void 0})),i.init({context:n,type:la.Block,middleware:this.middlewareHelper.get()}),i.render(),i.classList.add("no-stripe"),i.classList.remove("has-no-reactions"),i.append(this.btnClose),this.header.append(i);const r=document.createElement("div");r.classList.add("tabs-container"),r.dataset.animation="tabs";const o=new Map;if(n.reactions.results.length){const d=this.createFakeReaction("reactions",n.reactions.results.reduce((u,h)=>u+h.count,0));i.prepend(d),n.reactions.results.unshift(d.reactionCount)}let l=!1;if(s)try{const d=await this.managers.appMessagesManager.getMessageReadParticipants(t.peerId,t.mid);if(!e())return;if(!d.length)throw"";const u=this.createFakeReaction("checks",d.length);i.prepend(u),n.reactions.results.unshift(u.reactionCount),l=!0}catch{}i.customEmojiRenderer&&i.append(i.customEmojiRenderer),n.reactions.results.forEach(d=>{const u=new tn(void 0);u.container.classList.add("tabs-tab");const h=new Oe({noShadow:!0,noDelimiter:!0}),p=nt.createChatList({dialogSize:72});nt.setListClickListener({list:p,onFound:()=>{this.hide()},withContext:void 0,autonomous:!1,openInner:!0}),h.content.append(p),u.append(h.container);const m=d.reaction!=="checks",g=d.reaction==="checks";["checks","reactions"].includes(d.reaction)&&(d.reaction=void 0);let f;const v=new yb({scrollable:u,getPromise:async()=>{const y=await this.managers.appMessagesManager.getMessageReactionsListAndReadParticipants(t,void 0,d.reaction,f,m,g);return f=y.nextOffset,await Promise.all(y.combined.map(async({peerId:w,reaction:b,date:S})=>{const _=nt.addDialogNew({peerId:w,autonomous:!0,container:p,avatarSize:"abitbigger",rippleEnabled:!1,meAsSaved:!1,wrapOptions:{middleware:this.middlewareHelper.get()}});await OP({dialogElement:_,date:S,isMine:t.pFlags.out,middleware:e,peerId:w,reaction:b})})),!f}});o.set(u.container,v),r.append(u.container)}),this.body.append(r);const c=vd(i,r,(d,u)=>{if(d>=i.childElementCount-(i.customEmojiRenderer?2:1))return!1;const h=i.children[d],p=c.prevId();p!==-1&&i.children[p].setIsChosen(!1),h.setIsChosen(!0),o.get(u).load()},void 0,void 0,void 0,this.listenerSetter);c(0,!1),this.show()}createFakeReaction(e,t){const s=new Qo;s.init(la.Block,this.middlewareHelper.get()),s.reactionCount={_:"reactionCount",count:t,reaction:e},s.setCanRenderAvatars(!1),s.renderCounter();const i=document.createElement("div");return i.classList.add("reaction-counter","reaction-sticker-icon"),i.append(Be(e)),s.prepend(i),s}}const Rr="btn-menu-reactions",oc=Rr+"-reaction",Ap=7,my=28,C$=6,G0=my+C$*2,_$=!dn,I$=_$&&!1;class lw{constructor(e){this.render=async(i,n)=>{const r=this.middlewareHelper.get();if(await Promise.all(i),!r())return;if(n&&!this.noMoreButton){const l=yt(`${this.openSide==="bottom"?"down":"up"} ${Rr}-more`,{noRipple:!0});this.container.append(l),J(l,this.onMoreClick,{listenerSetter:this.listenerSetter})}return()=>{this.widthContainer.classList.add("is-visible")}},this.reactionToDocId=i=>{if(i._==="reactionPaid")return Iv;let n=i.document_id;return n||(n=this.availableReactions.find(o=>o.reaction===i.emoticon).select_animation.id),n},this.reactionsToDocIds=i=>i.map(this.reactionToDocId),this.loadTags=()=>[this.managers.appReactionsManager.getTagReactions().then(this.reactionsToDocIds)],this.loadEffects=()=>[this.managers.appReactionsManager.getAvailableEffects().then(n=>n.filter(r=>!!r.effect_animation_id).map(r=>r.effect_sticker_id))],this.loadReactions=()=>{const i=Promise.resolve(this.reactions).then(this.reactionsToDocIds),n=this.managers.appReactionsManager.getRecentReactions().then(this.reactionsToDocIds),r=i.then(l=>this.noPacks?l:l.slice(0,16)),o=this.noPacks?void 0:Promise.all([i,n,r]).then(([l,c,d])=>(c=c.filter(u=>!d.includes(u)),c.push(...l.slice(16)),eo(c)));return[r,o].filter(Boolean)},this.onMoreClick=i=>{_e(i);const n=this.noPacks&&this.noSearch,r=new Ua({noRegularEmoji:!0,noPacks:this.noPacks,noSearch:this.noSearch,managers:this.managers,mainSets:this.isTags?this.loadTags:this.isEffects?this.loadEffects:this.loadReactions,additionalLocalStickerSet:this.isEffects?async()=>{const c=await this.managers.appReactionsManager.getAvailableEffects();return(await this.splitAvailableEffects(c)).localStickerSet}:void 0,onClick:async c=>{if(c.docId&&c.emoji){const h=(await Ae.getAvailableReactions()).find(p=>p.select_animation?.id===c.docId);h&&(c.emoji=h.reaction,delete c.docId)}let d;c.docId===Iv?d={_:"reactionPaid"}:c.docId?d={_:"reactionCustomEmoji",document_id:c.docId}:d={_:"reactionEmoji",emoticon:c.emoji},l.resolve(d),o.hideAndDestroy()},freeCustomEmoji:this.freeCustomEmoji,onReady:()=>{const c=o.getElement();if(n){const d=c.querySelector(".emoticons-categories-container");c.style.setProperty("--height",d.offsetHeight+"px")}},searchFetcher:this.isEffects?async c=>{const d=await this.managers.appReactionsManager.searchAvailableEffects({q:c});return this.splitAvailableEffects(d)}:void 0,groupFetcher:this.isEffects?async c=>{const d=await this.managers.appReactionsManager.searchAvailableEffects({emoticon:c.emoticons});return this.splitAvailableEffects(d)}:void 0,showLocks:this.isEffects}),o=new Gl({tabsToRender:[r],customParentElement:document.body,getOpenPosition:()=>this.getOpenPosition(!this.noPacks)});n&&o.getElement().classList.add("shrink"),this.isEffects&&o.getElement().classList.add("smaller");const l=Mt();this.onFinish(l),o.addEventListener("closed",()=>{l.resolve(void 0),o.hideAndDestroy()}),o.onButtonClick()},this.onMouseMove=i=>{const n=ne(i.target,oc);if(!n)return;const r=this.reactionsMap.get(n);if(!r||!r.appear?.paused)return;const o=r.select;o&&o.paused&&(o.autoplay=!0,o.restart())},this.managers=e.managers,this.middlewareHelper=e.middleware?e.middleware.create():Ht(),this.onFinish=e.onFinish,this.listenerSetter=new $t,this.size=e.size??my,this.openSide=e.openSide??"bottom",this.getOpenPosition=e.getOpenPosition,this.noMoreButton=e.noMoreButton,this.isTags=e.isTags,this.isEffects=e.isEffects,this.middlewareHelper.get().onDestroy(()=>{this.listenerSetter.removeAll()});const t=this.widthContainer=document.createElement("div");if(t.classList.add(Rr+"-container",Rr+"-container-"+e.type,"btn-menu-transition"),this.isTags||this.isEffects){t.classList.add(Rr+"-container-tags");const i=this.isEffects?P("AddEffectMessageHint"):P(I.premium?"Reactions.Tag.Description":"Reactions.Tag.PremiumHint",[xi(()=>{Li.close(),rs.show({feature:"saved_tags"})})]);i.classList.add(Rr+"-description"),t.append(i)}const s=this.container=document.createElement("div");s.classList.add(Rr),["big"].forEach(i=>{const n=document.createElement("div");n.classList.add(Rr+"-bubble",Rr+"-bubble-"+i),t.append(n)}),this.reactionsMap=new Map,this.animationGroup=`CHAT-MENU-REACTIONS-${Date.now()}`,Ut.setOverrideIdleGroup(this.animationGroup,!0),pt||s.addEventListener("mousemove",this.onMouseMove),J(s,i=>{const n=ne(i.target,oc);if(!n)return;const r=this.reactionsMap.get(n);r&&this.onFinish(r.reaction)},{listenerSetter:this.listenerSetter}),t.append(s)}renderReactions({type:e,reactions:t},s){s&&(this.availableReactions=s,this.freeCustomEmoji=new Set(this.availableReactions.map(n=>n.select_animation.id)));const i=t.slice(0,Ap).map(n=>{const r=n._==="reactionEmoji"?s.find(o=>o.reaction===n.emoticon):void 0;return this.renderReaction(n,r)});return this.render(i,t.length>Ap)}renderEffects(e){const t=e.slice(0,Ap).map(s=>this.renderReaction({_:"reactionCustomEmoji",document_id:s.effect_sticker_id}));return this.render(t,e.length>Ap)}async prepareReactions(e){const t=this.middlewareHelper.get(),s=Ae.getAvailableReactions(),i=await this.managers.acknowledged.appReactionsManager.getAvailableReactionsByMessage(e),n=!(s instanceof Promise)&&i.cached,r=Ky([i.result,s],async([o,l])=>{if(t()&&o.type!=="chatReactionsNone")return this.reactions=o.reactions,this.noPacks=this.noSearch=o.type!=="chatReactionsAll",this.renderReactions(o,l)});return[n,r]}async prepareEffects(){const e=this.middlewareHelper.get(),t=await this.managers.acknowledged.appReactionsManager.getAvailableEffects(),{cached:s}=t,i=en(t.result,async n=>{if(e())return this.freeCustomEmoji=new Set(n.filter(r=>!r.pFlags.premium_required).map(r=>r.effect_sticker_id)),this.noPacks=!0,this.renderEffects(n)});return[s,i]}async init(e){let t,s;this.isEffects?[t,s]=await this.prepareEffects():[t,s]=await this.prepareReactions(e),t&&await s,s.then(i=>{i&&(t?i():$s(i))}),this.inited=!0}cleanup(){this.middlewareHelper.clean(),this.reactionsMap.clear(),Ut.setOverrideIdleGroup(this.animationGroup,!1),Ut.checkAnimations(!0,this.animationGroup,!0)}async splitAvailableEffects(e){const[t,s]=qc(e,r=>!r.effect_animation_id),i=t.map(r=>r.effect_sticker_id),n=await Promise.all(i.map(r=>this.managers.appDocsManager.getDoc(r)));return{emojis:s.map(r=>({emoji:"",docId:r.effect_sticker_id})),localStickerSet:{title:"StickerEffects",stickers:n}}}canUseAnimations(){return wt.isAvailable("animations")&&wt.isAvailable("stickers_chat")&&!Gi}async renderReaction(e,t){const s=document.createElement("div");s.classList.add(oc);const i=document.createElement("div");i.classList.add(oc+"-scale");const n=document.createElement("div");let r;n.classList.add(oc+"-appear"),this.canUseAnimations()&&(r=document.createElement("div"),r.classList.add(oc+"-select","hide"));const o={selectWrapper:r,appearWrapper:n,reaction:e};this.reactionsMap.set(s,o);const l=this.middlewareHelper.get(),d=my*(pt||!I$?1:1.25),u=[],h={width:d,height:d,skipRatio:1,needFadeIn:!1,withThumb:!1,group:this.animationGroup,middleware:l,loadPromises:u},p=this.canUseAnimations(),m=e._==="reactionPaid";if(this.container.append(s),m&&!p)n.append(ya());else if(m&&p){const g=Ns.loadAnimationAsAsset({container:n,loop:!1,autoplay:!0,width:d,height:d,skipRatio:1,middleware:l,group:this.animationGroup},"StarReactionAppear").then(f=>{o.appear=f;const v=Ns.loadAnimationAsAsset({container:r,loop:!1,autoplay:!1,...h},"StarReactionSelect");f.addEventListener("enterFrame",y=>{f.maxFrame===y&&v.then(w=>{n.classList.add("hide"),r.classList.remove("hide"),o.select=w},as)})});u.push(g)}else if(!p||!t){delete h.needFadeIn,delete h.withThumb;const g=()=>{ai({doc:f,div:n,liteModeKey:!1,play:t===void 0?!0:void 0,...h})};let f=t?.static_icon,v=!1;if(!f){const y=await this.managers.acknowledged.appEmojiManager.getCustomEmojiDocument(e.document_id);y.cached?f=await y.result:(delete h.loadPromises,v=!0,y.result.then(w=>(f=w,g())))}v||g()}else{let g=!0;ai({doc:t.appear_animation,div:n,play:!0,liteModeKey:!1,...h}).then(({render:v})=>v).then(v=>{o.appear=v,v.addEventListener("enterFrame",y=>{v.maxFrame===y&&f.then(w=>{n.classList.add("hide"),r.classList.remove("hide"),g&&(o.select=w,g=!1)},as)})},as);const f=ai({doc:t.select_animation,div:r,liteModeKey:!1,...h}).then(({render:v})=>v).then(v=>Ns.waitForFirstFrame(v)).catch(as)}return i.append(n),r&&i.append(r),s.append(i),Promise.all(u)}}function UP(a){return a&&!a.pFlags.is_outgoing&&!a.pFlags.noforwards&&!a.media?.extended_media}function HP(a){return{width:a.width,height:a.height,top:a.top,right:a.right,bottom:a.bottom,left:a.left}}const P$=Y("<div class=popup-toggle-read-date-title>"),M$=Y("<div class=popup-toggle-read-date-subtitle>"),L$=Y("<button>"),E$=Y("<div class=popup-toggle-read-date-sticker>");class GP extends ue{constructor(e,t){super("popup-toggle-read-date",{closable:!0,overlayClosable:!0,body:!0}),this.peerId=e,this.type=t,this.construct()}_construct(){const e=this,t=n=>{let r;return[(()=>{const o=P$();return k(o,()=>n.title),o})(),(()=>{const o=M$();return k(o,()=>n.text),o})(),(()=>{const o=L$();o.$$click=()=>{n.onClick()instanceof Promise&&os(r,!0)};const l=r;return typeof l=="function"?Ue(l,o):r=o,k(o,()=>P(n.buttonText)),Me(()=>be(o,"btn-primary btn-color-primary popup-toggle-read-date-button"+(n.isPremium?" popup-gift-premium-confirm shimmer":""))),o})()]},i={lastSeen:{title1:"PremiumLastSeenHeader1",text1:"PremiumLastSeenText1",lockedText:"PremiumLastSeenText1Locked",buttonText1:"PremiumLastSeenButton1",onClick:async()=>{await this.managers.appPrivacyManager.setPrivacy("inputPrivacyKeyStatusTimestamp",[{_:"inputPrivacyValueAllowAll"}]),this.hide(),$e({langPackKey:"PremiumLastSeenSet"})},title2:"PremiumLastSeenHeader2",text2:"PremiumLastSeenText2",buttonText2:"PremiumLastSeenButton2"},readTime:{title1:"PremiumReadHeader1",text1:"PremiumReadText1",lockedText:"PremiumReadText1Locked",buttonText1:"PremiumReadButton1",onClick:async()=>{const n=await this.managers.appPrivacyManager.getGlobalPrivacySettings();await this.managers.appPrivacyManager.setGlobalPrivacySettings({_:"globalPrivacySettings",pFlags:{...n.pFlags,hide_read_marks:void 0}}),this.hide(),$e({langPackKey:"PremiumReadSet"})},title2:"PremiumReadHeader2",text2:"PremiumReadText2",buttonText2:"PremiumReadButton2"}}[this.type];return[(()=>{const n=E$();return k(n,()=>e.stickerContainer),n})(),T(t,{get title(){return P(i.title1)},get text(){return P(e.isPremiumPurchaseBlocked?i.lockedText:i.text1,[e.titles[0]])},get buttonText(){return i.buttonText1},get onClick(){return i.onClick}}),V((()=>{const n=V(()=>!e.isPremiumPurchaseBlocked);return()=>n()&&[T(CI,{langKey:"PremiumOr"}),T(t,{get title(){return P(i.title2)},get text(){return P(i.text2,[e.titles[1]])},get buttonText(){return i.buttonText2},onClick:()=>{e.hide(),rs.show()},isPremium:!0})]})())]}async construct(){const[e,t,s]=await Promise.all([Promise.all(new Array(2).fill(0).map(()=>qe({peerId:this.peerId,onlyFirstName:!0}))),Ae.isPremiumPurchaseBlocked(),Dg({width:86,height:86,assetName:this.type==="lastSeen"?"large_lastseen":"large_readtime",middleware:this.middlewareHelper.get(),loop:!1,autoplay:wt.isAvailable("stickers_chat")}).then(async({container:i,promise:n})=>(await n,i))]);this.titles=e,this.isPremiumPurchaseBlocked=t,this.stickerContainer=s,this.appendSolid(()=>this._construct()),this.show()}}Fs(["click"]);const k$=Y("<div dir=auto>"),T$=Y("<span class=popup-translate-text-text>"),x$=Y('<span class="popup-translate-text-more primary">'),A$=Y("<div class=popup-translate-preloader>");class VP extends ue{constructor(e){super("popup-translate",{buttons:[{langKey:"OK",isCancel:!0},{langKey:"Telegram.LanguageViewController",callback:()=>(ow(!1).then(s=>{Qc(this.options.peerId).setLanguage(s)}),!1)}],scrollable:!0,body:!0,overlayClosable:!0}),this.options=e,this.header.remove();const t=wi(()=>this.d(),this.scrollable.container);this.addEventListener("closeAfterTimeout",t)}d(){const e=this,t=this;Jt(()=>{setTimeout(()=>{this.show()},0)});let s=this.options.textWithEntities;this.options.message&&(s={_:"textWithEntities",text:this.options.message.message,entities:this.options.message.totalEntities});const i={middleware:this.middlewareHelper.get(),textColor:"primary-text-color"},n=p=>{let m;const g=(()=>{const v=k$(),y=m;return typeof y=="function"?Ue(y,v):m=v,k(v,()=>p.children),Me(()=>be(v,Ge("popup-translate-text","spoilers-container",p.limited&&"is-limited"))),v})(),f=v=>{const y=m&&tp(m,v);y&&(m.removeEventListener("click",f,{capture:!0}),this.hideWithCallback(y))};return m.addEventListener("click",f,{capture:!0}),g},r=(p,m)=>{const g=this,[f,v]=K(p.text.length>m),[y,w]=K();return le(()=>{const b=jt(p.text,{...i,entities:p.entities,noTextFormat:f()});w(kl(b))}),T(n,{get limited(){return f()},get children(){return T(Js,{get when(){return f()},get fallback(){return y()},get children(){return[(()=>{const b=T$();return k(b,y),b})(),(()=>{const b=x$();return b.$$click=()=>{v(!1),setTimeout(()=>{g.scrollable.onScroll()},0)},k(b,()=>P("Show")),b})()]}})}})},o=Qc(this.options.peerId),l=Yn(void 0,!0),[c,d]=K(!0),u=[],h=T(A_,{get peerId(){return e.options.peerId},get message(){return e.options.message},get textWithEntities(){return e.options.textWithEntities},get richTextOptions(){return{...i,loadPromises:u}},enabled:!0});return Promise.all(u).then(()=>{d(!1),setTimeout(()=>{this.scrollable.onScroll()},0)}),[T(Ms,{noShadow:!0,get name(){return`Language.${t.options.detectedLanguage}`},get children(){return r(s,120)}}),T(Ms,{noShadow:!0,get name(){return`Language.${o.language()}`},fakeGradientDelimiter:!0,get children(){return T(Js,{get when(){return!c()},get fallback(){return(()=>{const p=A$();return k(p,l),p})()},get children(){return T(n,{children:h})}})}})]}}Fs(["click"]);function R$(a){const t=document.getSelection().getRangeAt(0),{startContainer:s,startOffset:i,endContainer:n,endOffset:r}=t,o=s.nodeValue,l=n.nodeValue,c="",d=ne(a,"spoilers-container"),h=[".reply"].map(M=>{const C=d.querySelector(M);if(C){const L=document.createTextNode("");return C.replaceWith(L),[L,C]}}).filter(Boolean);let p,m;o===null&&s.parentNode.insertBefore(p=document.createTextNode(c),i===0?s:s.nextSibling),l===null&&n.parentNode.insertBefore(m=document.createTextNode(c),r===0?n:n.nextSibling),s===n&&!p?s.nodeValue=o.slice(0,i)+c+o.slice(i,r)+c+o.slice(r):(m||(n.nodeValue=l.slice(0,r)+c+l.slice(r)),p||(s.nodeValue=o.slice(0,i)+c+o.slice(i)));const{value:g}=xn(d),f=g.indexOf(c),v=g.indexOf(c,f+1)-1;p?p.remove():s.nodeValue=o,m?m.remove():n.nodeValue=l;const y=new Set(["messageEntityBold","messageEntityItalic","messageEntityUnderline","messageEntityStrike","messageEntitySpoiler","messageEntityCustomEmoji","messageEntityEmoji"]),{value:w,entities:b}=xn(d,!0),S=w.slice(f,v);for(let M=0;M<b.length;++M){const C=b[M],L=C.offset;if(L+C.length<f||L>=v||!y.has(C._)){b.splice(M--,1);continue}C.offset=Math.max(L-f,0);const x=Math.max(f-L,0),R=v-f-C.offset;C.length=Math.min(C.length-x,R)}return h.forEach(([M,C])=>M.replaceWith(C)),ml(),{text:S,entities:b.length?b:void 0,offset:f}}async function zP(a){const[e]=Ho();if(!a||!e.translations.showInMenu)return;const t=await E_(a);if(!e.translations.doNotTranslate.includes(t))return t}const WP=a=>{const e=(n,r)=>{const o=a.transitions.get(n);le(l=>{const c=o();if(l||c)return c||r(),!0})},t=new Map,s=(n,r)=>{Ft(o=>{t.set(n,o),e(n,()=>{o(),r()}),ze(()=>{t.get(n)===o&&t.delete(n)})})};return ze(()=>{t.forEach(n=>n())}),Lb(yd(()=>a.children).toArray,{exitMethod:"keep-relative",onChange:({added:n,removed:r,finishRemoved:o})=>{for(const c of n)t.get(c)?.();if(a.noWait?.()||!wt.isAvailable("animations")){o(r);return}const l=[];for(const c of r){if(!a.transitions.has(c)){l.push(c);continue}s(c,()=>{o([c])})}l.length&&o(l)}})};function KP(a,e,t){return I.managers.appStickersManager.preloadAnimatedEmojiSticker(a).then(({doc:s})=>{if(s)return fs.downloadMedia({media:s}).then(async i=>{const n=st.active.emojiSticker,r=zL(a),o=Ht(),l=await Ns.loadAnimationWorker({container:void 0,animationData:i,width:n.width,height:n.height,name:"doc"+s.id,autoplay:!1,loop:!1,toneIndex:r,group:"none",middleware:o.get()});l.addEventListener("firstFrame",()=>{WL(s,l.canvas[0],r),o.destroy()},{once:!0})})})}async function Xo(a){const{emoji:e,div:t,managers:s=I.managers}=a,i=await s.appStickersManager.getAnimatedEmojiSticker(e);if(!i)throw t.classList.add("media-sticker-wrapper"),new Error("no sticker");return ai({doc:i,play:!0,loop:!1,...a})}const F$=Y("<div>"),B$=Y('<div class="popup-report-ad-tabs tabs-container">'),D$=Y('<div class="transition slide-fade"><div class=transition-item></div><div class=transition-item><div class=popup-report-ad-header-rows><div class=popup-report-ad-header-title></div><div class=popup-report-ad-header-subtitle>'),wo=class wo extends ue{constructor(e,t,s){super("popup-report-ad",{closable:!0,overlayClosable:!0,body:!0,onBackClick:()=>(this.setSections(i=>i.slice(0,-1)),!1),title:!0,scrollable:!0}),this.type=e,this.report=t,this.onAdHide=s,this.construct(),KP(wo.STICKER_EMOJI)}renderSection(e,t){const s=this,i=this,[n,r]=K(void 0,{equals:!1}),[o]=ma(()=>n()?.option,C=>this.report(C)),l=C=>{this.hide(),this.onAdHide?.(),$e({langPackKey:this.type==="ad"?C?"Ads.Reported":"AdHidden":"Reported2"})};le(()=>{const C=o();if(!C)return;const L=C._==="channels.sponsoredMessageReportResultReported"||C._==="reportResultReported",E=C._==="channels.sponsoredMessageReportResultAdsHidden";if(L||E){l(L);return}const x=this.renderSection(C,Ot(n).text),R=ui().get();x.readyPromise.then(()=>{R()&&this.setSections(B=>[...B,x])}),r()});const[c,d]=K(!1);let u;const h=C=>{if(C.target!==b)return;const L=C.type==="transitionstart";d(L),clearTimeout(u),L&&(u=window.setTimeout(()=>{d(!1)},300))};let p,m,g,f,v,y=Promise.resolve();const w=e._==="reportResultAddComment";if(w){g=document.createElement("div");const C=130;y=Xo({div:g,emoji:wo.STICKER_EMOJI,width:C,height:C,middleware:ui().get()}).then(({render:L})=>L),f=new Yt({label:"ReportHint",maxLength:512,placeholder:e.pFlags.optional?"Report2CommentOptional":"Report2Comment",required:!e.pFlags.optional}),[p,m]=K()}else p=()=>48*e.options.length;let b,S;const _=V(()=>{const C=this.activeSection(),L=C?.maxHeight();return L&&C.isComment&&!w?L-64:L}),M=w?[g,V(()=>f.container)]:T(Cs,{get each(){return e.options},children:C=>T(En,{get title(){return je(C.text)},clickable:()=>r(C),get rightContent(){return Be("next","popup-report-ad-option-arrow-icon")}})});if(T(Ms,{ref(C){const L=b;typeof L=="function"?L(C):b=C},get name(){return V(()=>"title"in e)()?je(e.title):void 0},get caption(){return s.type==="ad"?"ReportAdLearnMore":w?"ReportInfo":void 0},captionRef:C=>S=C,class:"popup-report-ad-tab tabs-tab",noShadow:!0,noDelimiter:!0,onTransitionStart:h,onTransitionEnd:h,get children(){const C=F$();return k(C,M),Me(L=>{const E=Ge("popup-report-ad-tab-options"),x=(_()||p())+"px";return E!==L._v$&&be(C,L._v$=E),x!==L._v$2&&((L._v$2=x)!=null?C.style.setProperty("height",x):C.style.removeProperty("height")),L},{_v$:void 0,_v$2:void 0}),C}}),this.transitions.set(b,c),ze(()=>this.transitions.delete(b)),w){const[C,L]=K(!1);T(Za,{ref(x){const R=v;typeof R=="function"?R(x):v=x},get disabled(){return C()},class:"btn-primary btn-color-primary popup-report-ad-send-button",text:"Report2Send",onClick:async()=>{L(!0),f.input.contentEditable="false";try{await i.report(e.option,f.value),l(!0)}catch(x){console.error(x),L(!1),f.input.contentEditable="true"}}});const E=()=>{L(!f.isValid()),m((f.value?f.container.offsetHeight:54)+142+147)};f.input.addEventListener("input",E),E(),S.classList.add("popup-report-ad-comment-caption"),S.after(v)}return{container:b,transition:c,maxHeight:p,prevText:t,readyPromise:y,isComment:w}}_construct(){const e=this,[t,s]=K([]),[i,n]=K();this.sections=t,this.setSections=s,this.activeSection=i,s([this.renderSection(this.reportResult)]),le(()=>{const p=t();this.btnCloseAnimatedIcon.classList.toggle("state-back",p.length>1),l(p.length-1),h(p.length===1?0:1),Ot(i)||n(p[p.length-1])});let r;const o=(()=>{const p=B$(),m=r;return typeof m=="function"?Ue(m,p):r=p,k(p,T(WP,{get transitions(){return e.transitions},get children(){return t().map(({container:g})=>g)}})),p})(),l=Sr({content:r,type:"tabs",transitionTime:150,animateFirst:!1,onTransitionStartAfter:()=>{n(t()[t().length-1])}}),c=V(p=>i()?.prevText??p),d=this.type==="ad"?"ReportAd":"ReportChat";let u;this.title.append((()=>{const p=D$(),m=p.firstChild,g=m.nextSibling,f=g.firstChild,v=f.firstChild,y=v.nextSibling,w=u;return typeof w=="function"?Ue(w,p):u=p,k(m,()=>P(d)),k(v,()=>P(d)),k(y,()=>je(c())),p})());const h=Sr({content:u,type:"slide-fade",transitionTime:400,isHeavy:!1});return o}async construct(){this.transitions=new WeakMap,this.reportResult=await this.report(new Uint8Array),this.appendSolid(()=>this._construct()),this.show()}static createAdReport(e,t){ue.createPopup(wo,"ad",s=>I.managers.appMessagesManager.reportSponsoredMessage(e.random_id,s),t)}static createMessageReport(e,t){ue.createPopup(wo,"message",(s,i)=>I.managers.appMessagesManager.reportMessages(e,t,s,i))}static createStoryReport(e,t,s){ue.createPopup(wo,"story",(i,n)=>I.managers.appStoriesManager.report(e,t,i,n),s)}};ro(wo,"STICKER_EMOJI","👮♀️");let lu=wo;function $$(a,e){return e*Math.sqrt(1- --a*a)}const ev=300;class jP{constructor(e){Nt(this,e),this.middlewareHelper=Ht(),this.listenerSetter=new $t,this.construct()}construct(){this.container=document.createElement("div"),this.container.classList.add("new-message-send-as-container"),this.closeBtn=document.createElement("div"),this.closeBtn.classList.add("new-message-send-as-close","new-message-send-as-avatar"),this.closeBtn.append(Be("close"));const e=[{text:this.forPaidReaction?"SendReactionAsTitle":"SendMessageAsTitle",onClick:void 0}];this.buttons=[];let t;const s=i=>{if(this.forPaidReaction)return;i&&(t=this.avatar);const n=this.avatar!==t,r=!i&&n?2:0;Dt({element:this.closeBtn,className:"is-visible",forwards:i,duration:ev,useRafs:r}),n||Dt({element:t.node,className:"is-visible",forwards:!i,duration:ev,useRafs:r})};ki({buttonOptions:{noRipple:!0},listenerSetter:this.listenerSetter,container:this.menuContainer??this.container,direction:this.forPaidReaction?"bottom-center":"top-right",buttons:e,onOpenBefore:()=>{s(!0)},onOpen:(i,n)=>{e[0].element.classList.add("btn-menu-item-header"),this.btnMenu=n,this.btnMenu.classList.add("scrollable","scrollable-y"),this.btnMenu.append(...this.buttons.map(r=>r.element))},onClose:()=>{s(!1)},onCloseAfter:()=>{this.btnMenu=void 0}}),this.container.append(this.closeBtn)}async updateButtons(e){const t=e.map(async(i,n)=>{const r=document.createElement("div"),{peerId:o,needPremium:l}=i,c=document.createElement("div");c.classList.add("btn-menu-item-subtitle"),o.isUser()?c.append(P("Chat.SendAs.PersonalAccount")):o===this.peerId&&Ae.getPeer(this.peerId).pFlags.megagroup?c.append(P("VoiceChat.DiscussionGroup")):c.append(await ja(o.toChatId()));const d=document.createElement("div");return d.append(new Xt({peerId:o}).element),l&&d.append(Be("premium_lock","new-message-send-as-lock")),r.append(d,c),{onClick:n?async()=>{if(i.needPremium&&!I.premium){rs.show();return}const u=this.peerId;this.changeSendAsPeerId(o);const h=this.middlewareHelper.get(),p=()=>{if(this.sendAsPeerId!==o||!h())return;const m=this.sendAsPeers.slice(),g=m.findIndex(f=>f.peerId===o);g!==-1&&m.splice(g,1),m.unshift(i),this.updateButtons(m)};wt.isAvailable("animations")?setTimeout(p,250):p(),this.forPaidReaction||this.managers.appMessagesManager.saveDefaultSendAs(u,o)}:void 0,textElement:r}}),s=await Promise.all(t);xa({buttons:s}),s.forEach((i,n)=>{const{peerId:r}=e[n],o=vs({middleware:this.middlewareHelper.get(),size:26,peerId:r});o.node.classList.add("btn-menu-item-icon","btn-menu-item-avatar"),n||o.node.classList.add("active"),i.element.prepend(o.node)}),this.buttons=s,this.btnMenu?.append(...this.buttons.map(i=>i.element))}async updateAvatar(e,t){const s=this.avatar;if(s&&s.node.dataset.peerId.toPeerId()===e)return;s||(t=!0);const i=t?0:2,n=t?0:ev,r=this.avatar=vs({middleware:this.middlewareHelper.get(),size:30,isDialog:!1,peerId:e});r.node.classList.add("new-message-send-as-avatar"),await r.readyThumbPromise,Dt({element:r.node,className:"is-visible",forwards:!0,duration:n,useRafs:i}),s&&Dt({element:s.node,className:"is-visible",forwards:!1,duration:n,onTransitionEnd:()=>{s.node.remove()},useRafs:i}),this.container.append(r.node)}changeSendAsPeerId(e,t){return this.sendAsPeerId=e,this.onChange(e),this.updateAvatar(e,t)}getDefaultSendAs(){return this.forPaidReaction?Promise.resolve({cached:!0,result:Promise.resolve(this.defaultPeerId)}):this.managers.acknowledged.appProfileManager.getChannelFull(this.peerId.toChatId()).then(e=>({cached:e.cached,result:e.result.then(t=>t.default_send_as?it(t.default_send_as):void 0)}))}async updateManual(e){const t=this.peerId;if(this.updatingPromise||!await this.managers.appPeersManager.isChannel(t))return;const s=this.middlewareHelper.get(()=>!this.updatingPromise||this.updatingPromise===c),{container:i}=this,n=t.toChatId(),r=(await Fl(this.getDefaultSendAs())).result,o=e;r instanceof Promise&&(e=void 0);const l=o&&!e,c=this.updatingPromise=en(r,async d=>{if(!s()||d===void 0||(await this.changeSendAsPeerId(d,e),!s()))return;Promise.all([this.managers.appChatsManager.getSendAs(n,this.forPaidReaction),Ae.isPremiumFeaturesHidden()]).then(([h,p])=>{if(!s())return;p&&(h=h.filter(f=>!f.pFlags.premium_required));const m=h.map(f=>({peerId:it(f.peer),needPremium:f.pFlags.premium_required}));this.sendAsPeers=m.slice();const g=m.findIndex(f=>f.peerId===d);if(g!==-1){const f=m.splice(g,1)[0];m.unshift(f)}else m.unshift({peerId:d});this.updateButtons(m)});const u=()=>{this.onReady(i,e),this.addedListener||(this.listenerSetter.add(I)("peer_full_update",h=>{this.peerId===h&&this.update()}),this.addedListener=!0)};if(l){u();return}return u});if(c.finally(()=>{this.updatingPromise===c&&(this.updatingPromise=void 0)}),!l)return c}update(e){return this.updateManual(e).then(t=>t?.())}setPeerId(e){this.middlewareHelper.clean(),this.updatingPromise=void 0,this.peerId=e}getSendAsPeerId(){return this.sendAsPeerId}destroy(){this.container.remove(),this.setPeerId(),this.listenerSetter.removeAll()}}const N$=Y("<div><div class=popup-star-reaction-senders-avatar-wrap><div class=popup-star-reaction-senders-amount>"),O$=Y("<div class=popup-star-reaction-senders-item-anonymous><img src=assets/img/anon_paid_reaction.png alt=Anonymous>"),U$=Y("<div class=peer-title>"),H$=Y("<div class=popup-stars-slider><div class=popup-stars-slider-hint-tail-container><div class=popup-stars-slider-hint-tail></div></div><div class=popup-stars-slider-hint>"),G$=Y("<div class=popup-stars-title>"),V$=Y("<div class=popup-stars-subtitle>"),z$=Y("<div class=popup-star-reaction-senders><div class=popup-star-reaction-senders-delimiter><div class=popup-star-reaction-senders-line></div><span class=popup-star-reaction-senders-text></span><div class=popup-star-reaction-senders-line></div></div><div class=popup-star-reaction-senders-list>"),W$=Y("<div class=popup-star-reaction-checkbox>");class V0 extends ue{constructor(e,t,s){super("popup-stars popup-star-reaction",{closable:!0,overlayClosable:!0,body:!0,scrollable:!0,footer:!0,withConfirm:!0}),this.peerId=e,this.mid=t,this.chat=s,this.footer.classList.add("abitlarger"),vh.forEach(i=>i.abortController.abort()),this.construct()}_construct(e){const{defaultSendAs:t,peerTitle:s,message:i}=e;this.footer.append(this.btnConfirm),this.body.after(this.footer);const n=new Ne.IntlElement({key:"PaidReaction.Send"});this.btnConfirm.append(n.element),Wo(this.btnConfirm,"star");const r=document.createElement("div");r.classList.add("popup-stars-send-as"),this.header.append(r),this.header.append(Vg());const[o]=bg(),l=o.appConfig.stars_paid_reaction_amount_max,[c,d]=K(.1),[u,h]=K(!t||t._==="paidReactionPrivacyDefault"?I.myId:t._==="paidReactionPrivacyAnonymous"?pp:it(t.peer)),p=()=>i.reactions?.top_reactors?.slice()??[];let m;const g=p().find(G=>G.pFlags.my);g?m=it(g.peer_id):m=I.myId;const f=()=>{const G=c(),O=$$(1-G,1);return Math.max(1,Math.round((1-O)*l))};J(this.btnConfirm,()=>{this.chat.sendReaction({sendAsPeerId:u(),message:i,reaction:{_:"reactionPaid"},count:f()}),this.destroy()},{listenerSetter:this.listenerSetter});const v=new Xl({step:1e-4,min:0,max:1,useProperty:!0,offsetAxisValue:30},c());v.setListeners(),v.setHandlers({onScrub:d});const y=new _t({text:"StarsReactionShowMeInTopSenders",checked:g?!g.pFlags.anonymous:t?._!=="paidReactionPrivacyAnonymous"});y.input.addEventListener("change",()=>{const G=y.checked?b.getSendAsPeerId():pp;h(G)});const w=new ad({reverse:!0,duration:50,calculateWidth:!0});w.setCount(f());const b=new jP({managers:this.managers,menuContainer:r,onReady:G=>{r.replaceChildren(G,Be("down"))},onChange:G=>{u()!==pp&&h(G)},forPaidReaction:!0,defaultPeerId:m});b.setPeerId(i.peerId),b.update(!0),g&&le(Vt(u,G=>{this.managers.appReactionsManager.togglePaidReactionPrivacy(i.peerId,i.mid,G)},{defer:!0}));let S,_,M;function C(){const G=S.getBoundingClientRect().width,O=S.parentElement.getBoundingClientRect().width,$=c(),D=(ht=>ht*O+30*(1-ht)-15)($),U=D-G/2,j=8,q=j,W=O-G-j,ee=zt(U,q,W);S.style.setProperty("--left",ee+"px");const z=46,Z=z/2,de=15,ie=de/2,oe=D-Z;let ae=oe;const ke=-de,re=O-z+de;re-oe<de&&(ae+=js(0,de,1-(re-oe)/de)),oe<ie&&(ae-=js(0,de,1- -(-ie-oe)/de));const ce=zt(ae,ke,re),Ie=re-ae>de?0:(1-Math.max(re-ae,0)/de*.633)*50,Ve=ae>de?0:(1-Math.max(-(-de-ae),0)/de*.595)*50;M.style.setProperty("--tail-left",ce+"px"),M.style.clipPath=`inset(0 ${Ie}% 0 ${Ve}%)`,_.style.setProperty("--tail-left-relative",String(zt((D-ee)/G,0,1)));const fe=24,Xe=ae<16?Math.max(0,7+ae)/fe:1,Ye=O-ae-z,Ze=Ye<16?Math.max(0,8+Ye)/fe:1,Je=Xe===1?fe:js(0,fe,Xe),tt=Ze===1?fe:js(0,fe,Ze);S.style.setProperty("--border-radius",`${fe}px ${fe}px ${tt}px ${Je}px`)}const L=$i(w.setCount.bind(w),10,!0,!0);le(()=>{n.compareAndUpdate({args:[f()]}),$s(C),L(f())}),Jt(()=>{E.observe(S),$s(C)});const E=new ResizeObserver(C),x=V(()=>{const G=p().find(U=>U.pFlags.my),O=u(),$=O===pp,H=$?void 0:O===I.myId?{_:"peerUser",user_id:I.myId}:{_:"peerChannel",channel_id:O};return{_:"messageReactor",pFlags:{my:!0,anonymous:$||void 0},peer_id:H,get count(){return(G?.count||0)+f()}}}),R=V(()=>{const G=p();return tr(G,O=>O.pFlags.my),G.push(x()),G.sort((O,$)=>$.count-O.count).slice(0,3)}),B=T(Rl,{get count(){return zt(f(),20,100)},mode:"progress"});v.container.querySelector(".progress-line__filled").appendChild(B);const N=G=>{const O=this,$=it(G.peer_id),H=G.pFlags.anonymous;let D=(()=>{const U=N$(),j=U.firstChild,q=j.firstChild;return U.$$click=()=>{H||(Ce.setInnerPeer({peerId:$,stack:{peerId:O.peerId,mid:O.mid}}),O.hide())},k(j,H?O$():T(Eg,{peerId:$,size:60}),q),k(q,T(hs,{icon:"star"}),null),k(q,()=>G.count,null),k(U,H?(()=>{const W=U$();return k(W,()=>P("AuthorHiddenShort")),W})():T(Rv,{peerId:$}),null),Me(()=>be(U,Ge("popup-star-reaction-senders-item",!H&&"is-clickable"))),U})();return H||(D=T(Ku,{children:D})),D};return[(()=>{const G=H$(),O=G.firstChild,$=O.firstChild,H=O.nextSibling;k(G,()=>v.container,O);const D=M;typeof D=="function"?Ue(D,O):M=O;const U=_;typeof U=="function"?Ue(U,$):_=$;const j=S;return typeof j=="function"?Ue(j,H):S=H,k(H,T(hs,{icon:"star"}),null),k(H,()=>w.container,null),k(H,T(Rl,{mode:"button"}),null),G})(),(()=>{const G=G$();return k(G,()=>P("StarsReactionTitle")),G})(),(()=>{const G=V$();return k(G,()=>P("StarsReactionText",[s])),G})(),(()=>{const G=z$(),O=G.firstChild,$=O.firstChild,H=$.nextSibling,D=O.nextSibling;return k(H,()=>P("StarsReactionTopSenders")),k(D,T(Cs,{get each(){return R()},children:N})),G})(),(()=>{const G=W$();return k(G,T(En,{classList:{"popup-star-reaction-checkbox-row":!0},get checkboxField(){return y.label}})),G})()]}async construct(){const[e,t,s]=await Promise.all([qe({peerId:this.peerId}),I.managers.appMessagesManager.getMessageByPeer(this.peerId,this.mid),I.managers.appReactionsManager.getPaidReactionPrivacy()]);this.appendSolid(()=>this._construct({peerTitle:e,message:t,defaultSendAs:s})),this.show()}}Fs(["click"]);function K$(a){const e=[],t=n=>{if(!n)return;const r=n.filter(o=>o._==="messageEntityCustomEmoji");e.push(...r.map(o=>o.document_id))};t(a.entities);const s=a.reactions;if(s){const n=s.results.filter(r=>r.reaction._==="reactionCustomEmoji");e.push(...n.map(r=>r.reaction.document_id))}const i=a.media?.poll;return i&&i.answers.forEach(n=>{t(n.text.entities)}),eo(e)}class In{constructor(e,t){this.chat=e,this.managers=t,this.onContextMenu=s=>{let i,n,r;try{n=ne(s.target,"bubble-content-wrapper"),i=n?n.parentElement:ne(s.target,"bubble"),r=ne(s.target,"bubbles-group-avatar")||void 0}catch{}if((!i||i.classList.contains("bubble-first"))&&!r)return;let o=this.element;if((s instanceof MouseEvent||s.hasOwnProperty("preventDefault"))&&s.preventDefault(),o&&o.classList.contains("active"))return!1;(s instanceof MouseEvent||s.hasOwnProperty("cancelBubble"))&&(s.cancelBubble=!0);let l=r?0:+i.dataset.mid;if(!l&&l!==0)return;if(r&&!r.dataset.peerId){$e({langPackKey:"HidAccount"});return}if(s.target.closest(".reaction.is-paid")){ue.createPopup(V0,i.dataset.peerId.toPeerId(),l,this.chat);return}const d=ne(s.target,"reaction-tag");(async()=>{const h=this.isSponsored=l<0;if(this.isSelectable=this.chat.selection.canSelectBubble(i),this.messagePeerId=i?i.dataset.peerId.toPeerId():void 0,this.peerId=this.messagePeerId??this.chat.peerId,this.target=s.target,this.isTextSelected=!Fc(),this.isAnchorTarget=this.target.tagName==="A"&&(this.target.target==="_blank"||this.target.classList.contains("anchor-url")),this.isEmailTarget=this.isAnchorTarget&&this.target.href.startsWith("mailto:"),this.isUsernameTarget=this.target.tagName==="A"&&this.target.classList.contains("mention"),this.isTag=!!d,this.reactionElement=d,this.isTag&&!I.premium){rs.show({feature:"saved_tags"});return}if(this.isTextSelected){const M=document.getSelection().getRangeAt(0);this.isTextFromMultipleMessagesSelected=ne(M.startContainer.parentElement,"spoilers-container")!==ne(M.endContainer.parentElement,"spoilers-container")}else this.isTextFromMultipleMessagesSelected=!1;this.sponsoredMessage=h?i.message.sponsoredMessage:void 0;const p=r?[]:await this.chat.getMidsByMid(this.messagePeerId,l);if(this.chat.selection.isSelecting&&!n&&l){if(h)return;if(p.length>1){const M=this.chat.selection.isMidSelected(this.messagePeerId,l)?l:p.find(C=>this.chat.selection.isMidSelected(this.messagePeerId,C));M&&(l=M)}}this.isOverBubble=!!n,this.avatarPeerId=r&&r.dataset.peerId.toPeerId();const m=ne(this.target,"grouped-item");this.isTargetAGroupedItem=!!m,m?this.mid=+m.dataset.mid:this.mid=l,this.isLegacy=this.messagePeerId&&this.messagePeerId!==this.peerId,this.isSelected=this.chat.selection.isMidSelected(this.messagePeerId,this.mid),this.message=r?void 0:i.message||this.chat.getMessageByPeer(this.messagePeerId,this.mid),this.groupedMessages=this.message?.grouped_id?await this.managers.appMessagesManager.getMessagesByGroupedId(this.message.grouped_id):void 0,!m&&this.groupedMessages&&(this.message=xm(this.groupedMessages)),this.mainMessage=this.groupedMessages?xm(this.groupedMessages):this.message,this.selectedMessages=this.chat.selection.isSelecting&&!r?await this.chat.selection.getSelectedMessages():void 0,this.noForwards=this.message&&!h&&!(await Promise.all((this.selectedMessages||[this.message]).map(M=>this.managers.appMessagesManager.canForward(M)))).every(Boolean),this.viewerPeerId=void 0,this.canOpenReactedList=void 0,this.linkToMessage=await this.getUrlToMessage(),this.selectedMessagesText=await this.getSelectedMessagesText(),this.messageLanguage=this.selectedMessages||!this.message?void 0:await zP(this.message.message);const g=await this.init();if(!g)return;o=g.element;const{cleanup:f,destroy:v,menuPadding:y,reactionsMenu:w,reactionsMenuPosition:b}=g,S=w&&In.appendReactionsMenu({element:o,reactionsMenu:w,reactionsMenuPosition:b}),_=!i||i.classList.contains("is-in")?"left":"right";Ql(s.touches?s.touches[0]:s,o,_,y),Li.openBtnMenu(o,()=>{S?.onClose(),this.mid=0,this.peerId=void 0,this.target=null,this.viewerPeerId=void 0,this.canOpenReactedList=void 0,f(),setTimeout(()=>{v()},300)}),S?.onAfterInit()})()},this.onSendScheduledClick=async()=>{this.chat.selection.isSelecting?Xs(this.chat.selection.selectionSendNowBtn):ue.createPopup(hP,this.peerId,await this.chat.getMidsByMid(this.messagePeerId,this.mid))},this.onReplyClick=async()=>{const{mid:s,peerId:i}=this,n={replyToMsgId:s};if(!await this.chat.canSend()){n.replyToPeerId=i,this.chat.input.createReplyPicker(n);return}this.chat.input.initMessageReply(n)},this.onFaveStickerClick=s=>{const i=this.message.media.document,n=i.id;i.type==="gif"?this.managers.appGifsManager.saveGif(n,s):this.managers.appStickersManager.faveSticker(n,s)},this.onEditClick=()=>{const s=this.getMessageWithText();this.chat.input.initMessageEditing(this.isTargetAGroupedItem?this.mid:s.mid)},this.onEditFactCheckClick=async()=>{const{mainMessage:s}=this,i=s.factcheck,n=new Ne.IntlElement({key:"Done"}),r={text:n.element},o=new Yt({placeholder:"FactCheckPlaceholder",withLinebreaks:!0,onRawInput:i?u=>{n.compareAndUpdate({key:u?"Done":"Remove"}),r.element&&(r.element.classList.toggle("primary",!!u),r.element.classList.toggle("danger",!u))}:void 0,canHaveFormatting:["bold","italic","link"]});i&&o.setValueSilently(ug(i.text.text,{entities:i.text.entities}));try{await Rt({titleLangKey:"FactCheckDialog",inputField:o,button:r,confirmShortcutIsSendShortcut:!0})}catch{return}const{value:l,entities:c}=xn(o.input,!0,!1),d=l?{_:"textWithEntities",text:l,entities:c}:void 0;i&&Pn(i.text,d)||this.managers.appMessagesManager.updateFactCheck(s.peerId,s.mid,d).then(()=>{$e({langPackKey:l?"FactCheckEdited":"FactCheckDeleted"})})},this.onCopyClick=async()=>{if(Fc()){const{text:s,html:i}=this.selectedMessagesText;si(s,i)}else document.execCommand("copy")},this.onCopyAnchorLinkClick=()=>{let s=this.target.href;s=s.replace(/^mailto:/,""),si(s)},this.onCopyLinkClick=()=>{const{url:s,isPrivate:i}=this.linkToMessage,n=i?"LinkCopiedPrivateInfo":"LinkCopied";Wi(Ne.format(n,!0)),si(s)},this.onPinClick=()=>{ue.createPopup(ru,this.messagePeerId,this.mid)},this.onUnpinClick=()=>{ue.createPopup(ru,this.messagePeerId,this.mid,!0)},this.onRetractVote=()=>{this.managers.appPollsManager.sendVote(this.message,[])},this.onStopPoll=()=>{this.managers.appPollsManager.stopPoll(this.message)},this.onForwardClick=async()=>{if(this.chat.selection.isSelecting)Xs(this.chat.selection.selectionForwardBtn);else{const s=this.messagePeerId,i=this.isTargetAGroupedItem?[this.mid]:await this.chat.getMidsByMid(s,this.mid);kr.create({[s]:i})}},this.onSelectClick=()=>{this.chat.selection.toggleByElement(ne(this.target,"grouped-item")||ne(this.target,"bubble"))},this.onClearSelectionClick=()=>{this.chat.selection.cancelSelection()},this.onDeleteClick=async()=>{if(this.chat.selection.isSelecting){Xs(this.chat.selection.selectionDeleteBtn);return}const{message:s}=this,{peerId:i,mid:n}=s;ue.createPopup(Md,i,this.isTargetAGroupedItem?[n]:await this.chat.getMidsByMid(i,n),this.chat.type)},this.onQuoteClick=async()=>{const s=this.getMessageWithText(),{peerId:i,mid:n}=s;let{text:r,entities:o=[],offset:l}=this.getQuotedText(),d=(await this.managers.apiManager.getAppConfig()).quote_length_max??1024;const u=r.length-r.trimEnd().length;u&&(d=Math.min(r.length-u,d)),r.length>d&&(r=r.slice(0,d),o=o.filter(m=>m.offset<d).map(m=>(m.offset+m.length>d&&(m.length=d-m.offset),m)));const h={text:r,entities:o.length?o:void 0,offset:l},p={replyToMsgId:n,replyToQuote:h};if(!await this.chat.canSend()){p.replyToPeerId=i,this.chat.input.createReplyPicker(p);return}this.chat.input.initMessageReply(p)},this.onStatisticsClick=()=>{this.chat.topbar.appSidebarRight.createTab(Wu).open(this.messagePeerId.toChatId(),this.mid),this.chat.topbar.appSidebarRight.toggleSidebar(!0)},this.listenerSetter=new $t,this.attachListenerSetter=new $t,this.middleware=Ht()}attachTo(e){this.attachListenerSetter.removeAll(),pt?J(e,t=>{if(this.chat.selection.isSelecting)return;this.chat.log("touchend",t);const s=[".name",".peer-title",".reply",".document","audio-element","a",".bubble-beside-button","replies-element","[data-saved-from]:not(.bubble)","poll-element",".attachment",".reply-markup-button",".bubble-view-button",".webpage",".bubbles-group-avatar",".bubble-service-button"];!t.target.closest(s.join(", "))&&(_e(t),this.onContextMenu(t))},{listenerSetter:this.attachListenerSetter}):Er({element:e,callback:this.onContextMenu,listenerSetter:this.attachListenerSetter})}cleanup(){this.listenerSetter.removeAll(),this.reactionsMenu&&this.reactionsMenu.cleanup(),this.middleware.clean()}destroy(){this.cleanup(),this.attachListenerSetter.removeAll()}async filterButtons(e){return zn(e,async t=>{let s;return this.isSponsored&&!t.isSponsored||!this.isSponsored&&t.isSponsored?!1:(this.chat.selection.isSelecting&&!t.withSelection?s=!1:s=(this.isOverBubble||pt,await t.verify()),!!s)})}setButtons(){if(this.isTag){const s=this.reactionElement.findTitle(),i=this.reactionElement.reactionCount,n=s?"SavedTagRenameTag":"SavedTagLabelTag";this.buttons=[{icon:"tag_filter",text:"SavedTagFilterByTag",onClick:()=>{this.chat.initSearch({reaction:i.reaction})},verify:()=>!0},{icon:"tag_name",text:n,onClick:async()=>{const r=new Yt({maxLength:12,label:"SavedTagLabelPlaceholder"});s&&r.setOriginalValue(s),await Rt({titleLangKey:n,descriptionLangKey:"SavedTagLabelTagText",button:{langKey:"Save"},inputField:r}),this.managers.appReactionsManager.updateSavedReactionTag(i.reaction,r.value)},verify:()=>!0},{icon:"tag_crossed",text:"SavedTagRemoveTag",onClick:()=>{this.chat.sendReaction({message:this.message,reaction:i.reaction})},verify:()=>!0,danger:!0},{text:"Loading",onClick:()=>{this.emojiInputsPromise.then(r=>{ue.createPopup(ga,r,!0,this.chat.input).show()})},verify:()=>i.reaction._==="reactionCustomEmoji",localName:"emojis"}];return}if(this.avatarPeerId!==void 0){const s=()=>{this.chat.appImManager.setInnerPeer({peerId:this.avatarPeerId,stack:this.chat.appImManager.getStackFromElement(this.target)})};this.buttons=[{icon:"message",text:"SendMessage",onClick:s,verify:()=>this.chat.peerId!==this.avatarPeerId&&this.avatarPeerId.isUser()},{icon:"newgroup",text:"OpenGroup2",onClick:s,verify:()=>this.chat.peerId!==this.avatarPeerId&&this.managers.appPeersManager.isAnyGroup(this.avatarPeerId)},{icon:"newchannel",text:"OpenChannel2",onClick:s,verify:()=>this.chat.peerId!==this.avatarPeerId&&this.managers.appPeersManager.isBroadcast(this.avatarPeerId)},{icon:"mention",text:"Mention",onClick:()=>{this.chat.input.mentionUser(this.avatarPeerId,!1)},verify:()=>this.chat.canSend("send_plain")},{icon:"search",text:"Search",onClick:()=>{this.chat.initSearch({filterPeerId:this.avatarPeerId})},verify:()=>this.chat.isAnyGroup}];return}const e=this.message.media?.document?.type==="gif",t=async s=>{const i=this.message.media?.document;if(!i?.sticker&&!e)return!1;const n=await(e?this.managers.acknowledged.appGifsManager.getGifs():this.managers.acknowledged.appStickersManager.getFavedStickersStickers());if(!n.cached)return!1;const r=(await n.result).some(o=>o.id===i.id);return s?!r:r};this.buttons=[{onClick:()=>{this.canViewReadTime===!1&&ue.createPopup(GP,this.peerId,"readTime")},verify:()=>this.peerId.isUser()&&this.managers.appMessagesManager.canViewMessageReadParticipants(this.message),notDirect:()=>!0,localName:"views",checkForClose:()=>this.canViewReadTime!==void 0},{icon:"send2",text:"MessageScheduleSend",onClick:this.onSendScheduledClick,verify:()=>this.chat.type===we.Scheduled&&!this.message.pFlags.is_outgoing},{icon:"send2",text:"Message.Context.Selection.SendNow",onClick:this.onSendScheduledClick,verify:()=>this.chat.type===we.Scheduled&&this.isSelected&&!this.chat.selection.selectionSendNowBtn.hasAttribute("disabled"),notDirect:()=>!0,withSelection:!0},{icon:"schedule",text:"MessageScheduleEditTime",onClick:()=>{this.chat.input.scheduleSending(()=>{this.message,this.managers.appMessagesManager.editMessage(this.message,this.message.message,{scheduleDate:this.chat.input.scheduleDate,entities:this.message.entities}),this.chat.input.onMessageSent(!1,!1)},new Date(this.message.date*1e3))},verify:()=>this.chat.type===we.Scheduled},{icon:"message_quote",text:"Quote",onClick:this.onQuoteClick,verify:async()=>!this.message.pFlags.is_outgoing&&!!this.chat.input.messageInput&&!!this.message.message&&this.isTextSelected&&!this.isTextFromMultipleMessagesSelected&&(!Qc(this.peerId).enabled()||this.message.pFlags.out)&&(this.chat.bubbles.canForward(this.message)||this.chat.canSend())},{icon:"reply",text:"Reply",onClick:this.onReplyClick,verify:async()=>!this.isLegacy&&!this.message.pFlags.is_outgoing&&!!this.chat.input.messageInput&&this.chat.type!==we.Scheduled&&(this.chat.bubbles.canForward(this.message)||this.chat.canSend())},{icon:"bubblereply",text:"ViewReplies",textArgs:[this.message?.replies?.replies],onClick:()=>{this.chat.appImManager.openThread({peerId:this.message.peerId,threadId:this.message.mid,lastMsgId:0})},verify:()=>{if(this.chat.threadId)return!1;const s=this.message?.replies;return!!(s&&!s.pFlags.comments&&s.replies)}},{icon:e?"gifs":"favourites",text:e?"SaveToGIFs":"AddToFavorites",onClick:this.onFaveStickerClick.bind(this,!1),verify:()=>t(!0)},{icon:e?"crossgif":"crossstar",text:e?"Message.Context.RemoveGif":"DeleteFromFavorites",onClick:this.onFaveStickerClick.bind(this,!0),verify:()=>t(!1)},{icon:"edit",text:"Edit",onClick:this.onEditClick,verify:async()=>await this.managers.appMessagesManager.canEditMessage(this.message,"text")&&!!this.chat.input.messageInput},{icon:"factcheck",text:this.mainMessage?.factcheck?"EditFactCheck":"AddFactCheck",onClick:this.onEditFactCheckClick,verify:()=>this.mainMessage&&this.managers.appMessagesManager.canUpdateFactCheck(this.mainMessage.peerId,this.mainMessage.mid)},{icon:"copy",text:"Copy",onClick:this.onCopyClick,verify:()=>!this.noForwards&&!!this.message.message&&!this.isTextSelected&&(!this.isAnchorTarget||this.message.message!==this.target.innerText)},{icon:"copy",text:"Chat.CopySelectedText",onClick:this.onCopyClick,verify:()=>!this.noForwards&&!!this.message.message&&this.isTextSelected},{icon:"search",text:"Chat.SearchSelected",onClick:()=>{const s=document.getSelection();this.chat.initSearch({query:s.toString()})},verify:()=>!!this.message.message&&this.isTextSelected},{icon:"copy",text:"Message.Context.Selection.Copy",onClick:this.onCopyClick,verify:async()=>{if(!this.isSelected||this.noForwards)return!1;for(const[s,i]of this.chat.selection.selectedMids){const n=`${s}_${this.chat.type===we.Scheduled?"scheduled":"history"}`;for(const r of i)if((await this.managers.appMessagesManager.getMessageFromStorage(n,r)).message)return!0}return!1},notDirect:()=>!0,withSelection:!0},{icon:"copy",text:this.isEmailTarget?"Text.Context.Copy.Email":"CopyLink",onClick:this.onCopyAnchorLinkClick,verify:()=>this.isAnchorTarget,withSelection:!0},{icon:"copy",text:"Text.Context.Copy.Username",onClick:()=>{si(this.target.textContent)},verify:()=>this.isUsernameTarget,withSelection:!0},{icon:"copy",text:"Text.Context.Copy.Hashtag",onClick:()=>{si(this.target.textContent)},verify:()=>this.target.classList.contains("anchor-hashtag"),withSelection:!0},{icon:"premium_translate",text:"TranslateMessage",onClick:()=>{if(!I.premium)rs.show({feature:"translations"});else{let s;if(this.isTextSelected){const{text:i,entities:n}=this.getQuotedText();s={_:"textWithEntities",text:i,entities:n}}ue.createPopup(VP,{peerId:s?this.peerId:this.message.peerId,textWithEntities:s,message:s?void 0:this.message,detectedLanguage:this.messageLanguage})}},verify:()=>!!this.messageLanguage},{icon:"link",text:"MessageContext.CopyMessageLink1",onClick:this.onCopyLinkClick,verify:async()=>!this.isLegacy&&await this.managers.appPeersManager.isChannel(this.peerId)&&!this.message.pFlags.is_outgoing},{icon:"pin",text:"Message.Context.Pin",onClick:this.onPinClick,verify:async()=>!this.isLegacy&&!this.message.pFlags.is_outgoing&&this.message._!=="messageService"&&!this.message.pFlags.pinned&&await this.managers.appPeersManager.canPinMessage(this.message.peerId)&&this.chat.type!==we.Scheduled},{icon:"unpin",text:"Message.Context.Unpin",onClick:this.onUnpinClick,verify:()=>this.message.pFlags.pinned&&this.managers.appPeersManager.canPinMessage(this.message.peerId)},{icon:"download",text:"MediaViewer.Context.Download",onClick:()=>In.onDownloadClick(this.message,this.noForwards),verify:()=>In.canDownload(this.message,this.target,this.noForwards)},{icon:"checkretract",text:"Chat.Poll.Unvote",onClick:this.onRetractVote,verify:()=>{const s=this.message.media?.poll;return s&&s.chosenIndexes.length&&!s.pFlags.closed&&!s.pFlags.quiz}},{icon:"stop",text:"Chat.Poll.Stop",onClick:this.onStopPoll,verify:async()=>{const s=this.message.media?.poll;return await this.managers.appMessagesManager.canEditMessage(this.message,"poll")&&s&&!s.pFlags.closed&&!this.message.pFlags.is_outgoing}},{icon:"statistics",text:"ViewStatistics",onClick:this.onStatisticsClick,verify:async()=>await this.managers.appPeersManager.isBroadcast(this.messagePeerId)&&await this.managers.appProfileManager.canViewStatistics(this.messagePeerId)&&!this.message.pFlags.is_outgoing},{icon:"forward",text:"Forward",onClick:this.onForwardClick,verify:()=>!this.noForwards&&this.chat.type!==we.Scheduled&&(!this.message.pFlags.is_outgoing||this.message.fromId===ku)&&this.message._!=="messageService"},{icon:"forward",text:"Message.Context.Selection.Forward",onClick:this.onForwardClick,verify:()=>this.chat.selection.selectionForwardBtn&&this.isSelected&&!this.chat.selection.selectionForwardBtn.hasAttribute("disabled"),notDirect:()=>!0,withSelection:!0},{icon:"download",text:"Message.Context.Selection.Download",onClick:()=>In.onDownloadClick(this.selectedMessages,this.noForwards),verify:()=>this.selectedMessages&&In.canDownload(this.selectedMessages,void 0,this.noForwards),withSelection:!0},{icon:"flag",text:"ReportChat",onClick:()=>{lu.createMessageReport(this.messagePeerId,[this.mid])},verify:()=>!this.message.pFlags.out&&this.message._==="message"&&!this.message.pFlags.is_outgoing&&this.managers.appPeersManager.isChannel(this.messagePeerId),notDirect:()=>!0,withSelection:!0},{icon:"select",text:"Message.Context.Select",onClick:this.onSelectClick,verify:()=>!this.message.action&&!this.isSelected&&this.isSelectable,notDirect:()=>!0,withSelection:!0},{icon:"select",text:"Message.Context.Selection.Clear",onClick:this.onClearSelectionClick,verify:()=>this.isSelected,notDirect:()=>!0,withSelection:!0},{onClick:()=>{if(this.viewerPeerId,this.canOpenReactedList)ue.createPopup(S$,this.message);else return!1},verify:()=>!this.peerId.isUser()&&(!!this.message.reactions?.recent_reactions?.length||this.managers.appMessagesManager.canViewMessageReadParticipants(this.message)),notDirect:()=>!0,localName:"views"},{icon:"delete",className:"danger",text:"Delete",onClick:this.onDeleteClick,verify:async()=>this.managers.appMessagesManager.canDeleteMessage(this.message)},{icon:"delete",className:"danger",text:"Message.Context.Selection.Delete",onClick:this.onDeleteClick,verify:()=>this.isSelected&&!this.chat.selection.selectionDeleteBtn.hasAttribute("disabled"),notDirect:()=>!0,withSelection:!0},{icon:"info",text:"Chat.Message.Sponsored.What",onClick:()=>{ue.createPopup(b$)},verify:()=>this.isSponsored&&!this.sponsoredMessage.pFlags.can_report,isSponsored:!0},{icon:"info",text:"AboutRevenueSharingAds",onClick:()=>{ue.createPopup(MI)},verify:()=>this.isSponsored&&!!this.sponsoredMessage.pFlags.can_report,isSponsored:!0},{icon:"hand",text:"HideAd",onClick:()=>{rs.show({feature:"no_ads"})},verify:()=>this.isSponsored&&!this.sponsoredMessage.pFlags.can_report,isSponsored:!0},{icon:"hand",text:"ReportAd",onClick:()=>{const{peerId:s,mid:i}=this.message;lu.createAdReport(this.sponsoredMessage,()=>{this.chat.bubbles.deleteMessagesByIds([ps(s,i)],!0)})},verify:()=>this.isSponsored&&!!this.sponsoredMessage.pFlags.can_report,isSponsored:!0},{icon:"crossround",text:"RemoveAds",onClick:()=>{rs.show({feature:"no_ads"})},verify:()=>this.isSponsored&&!!this.sponsoredMessage.pFlags.can_report,isSponsored:!0},{icon:"copy",text:"Copy",onClick:this.onCopyClick,verify:()=>this.isSponsored,isSponsored:!0},{text:"Loading",onClick:()=>{this.emojiInputsPromise.then(s=>{ue.createPopup(ga,s,!0,this.chat.input).show()})},verify:()=>!!this.getUniqueCustomEmojisFromMessage().length,notDirect:()=>!0,localName:"emojis"},{regularText:this.sponsoredMessage?.sponsor_info?je(this.sponsoredMessage.sponsor_info):void 0,separator:!0,secondary:!0,onClick:()=>si(this.sponsoredMessage.sponsor_info),verify:()=>!!this.sponsoredMessage.sponsor_info,isSponsored:!0},{regularText:this.sponsoredMessage?.additional_info?je(this.sponsoredMessage.additional_info):void 0,separator:!0,secondary:!0,onClick:()=>si(this.sponsoredMessage.additional_info),verify:()=>!!this.sponsoredMessage.additional_info,isSponsored:!0}]}static canDownload(e,t,s){if(Array.isArray(e))return e.some(o=>In.canDownload(o,t,s));if(!UP(e)||s)return!1;const i=!!e.media?.photo;let n=!1;if(i)n=!0;else{if(!e.media?.document)return!1;n=!0}let r=!t||!!pt;return n&&t&&(r||(r=!!(ne(t,"document")||ne(t,"audio")||ne(t,"media-sticker-wrapper")||ne(t,"media-photo")||ne(t,"media-video")))),n&&r}getMessageWithText(){return this.groupedMessages&&aI(this.groupedMessages)||this.message}getUniqueCustomEmojisFromMessage(){return K$(this.getMessageWithText())}async init(){this.cleanup(),this.setButtons();const e=await this.filterButtons(this.buttons);if(!e.length)return;const t=this.element=await Kh({buttons:e,listenerSetter:this.listenerSetter});t.id="bubble-contextmenu",t.classList.add("contextmenu");const s=e.find(l=>l.localName==="views");if(s&&this.peerId.isUser()){s.element.prepend(Be("checks","btn-menu-item-icon"));const l=document.createElement("div");l.classList.add("btn-menu-item-loader","shimmer"),s.textElement.append(l),s.element.after(document.createElement("hr"));const c=s.element.nextElementSibling,d=this.middleware.get();this.managers.appMessagesManager.getOutboxReadDate(this.message.peerId,this.message.mid).then(u=>{d()&&(this.canViewReadTime=!0,l.replaceWith(gs(u.date,!0,!1)))},u=>{if(!d())return;if(u.type!=="YOUR_PRIVACY_RESTRICTED"){c.remove(),s.element.remove();return}this.canViewReadTime=!1;const h=P("PmReadShowWhen");h.classList.add("show-when"),l.replaceWith(P("Chat.ContextMenu.Read")," ",h)})}else if(s){const l=this.message.reactions,c=l?.recent_reactions,d=!!c?.length,u=await this.managers.appMessagesManager.canViewMessageReadParticipants(this.message)?(await this.managers.appPeersManager.getPeer(this.peerId)).participants_count:void 0,h=l?l.results.reduce((w,b)=>w+b.count,0):void 0;s.element.prepend(Be(d?"reactions":"checks","btn-menu-item-icon"));const p=new Ne.IntlElement({key:d?u===void 0?"Chat.Context.ReactedFast":"Chat.Context.Reacted":"NobodyViewed",args:d?u===void 0?[h]:[u,u]:void 0,element:s.textElement});let m;d?u===void 0?m=P("Chat.Context.ReactedFast",[h]):m=P(c.length===u?"Chat.Context.ReactedFast":"Chat.Context.Reacted",[c.length,u]):m=P("Loading"),m.classList.add("btn-menu-item-text-fake"),s.element.append(m);const g=22,f=3,v=1.125;p.element.style.visibility="hidden",p.element.style.paddingRight=d?v*Math.min(f,c.length)+"rem":"1rem";const y=this.middleware.get();this.managers.appMessagesManager.getMessageReactionsListAndReadParticipants(this.message).then(w=>{if(!y())return;m?.remove();const b=w.combined,S=u===void 0?w.reactionsCount:d?b.filter(M=>M.reaction).length:b.length;let _;if(b.length===1)_=new Xt({peerId:b[0].peerId,onlyFirstName:!0,dialog:!1}).element,(!d||w.readParticipantDates.length<=1)&&(this.viewerPeerId=b[0].peerId);else if(d){const M=S===b.length||u===void 0;_=P(M?"Chat.Context.ReactedFast":"Chat.Context.Reacted",M?[S]:[S,b.length])}else b.length?_=P("MessageSeen",[b.length]):p.element.style.visibility="";if(_&&(_.style.paddingRight=v*Math.min(f,S)+"rem",_.classList.add("btn-menu-item-text-fake"),s.element.append(_)),b.length){const M=new Zl({avatarSize:g,middleware:y});M.render(c?c.map(C=>it(C.peer_id)):b.map(C=>C.peerId)),s.element.append(M.container),this.canOpenReactedList=!0}})}let i,n,r;if(this.message?._==="message"&&!this.chat.selection.isSelecting&&!this.message.pFlags.is_outgoing&&!this.message.pFlags.is_scheduled&&!this.message.pFlags.local&&!this.reactionElement){const l=this.message.reactions,c=this.message.peerId===I.myId&&(!l||l.pFlags.reactions_as_tags),d=await this.managers.appMessagesManager.getGroupsFirstMessage(this.message);r=($o||pt,"horizontal"),n=this.reactionsMenu=new lw({managers:this.managers,type:r,middleware:this.middleware.get(),onFinish:async u=>{if(Li.close(),u=await u,!!u){if(u._==="reactionPaid"){ue.createPopup(V0,d.peerId,d.mid,this.chat);return}if(!I.premium&&c){rs.show({feature:"saved_tags"});return}this.chat.sendReaction({message:d,reaction:u})}},getOpenPosition:u=>In.getReactionsOpenPosition(n,u),isTags:c}),await n.init(d),i=In.getReactionsMenuPadding(r)}const o=e.find(l=>l.localName==="emojis");if(o){o.element.classList.add("is-multiline"),o.element.parentElement.insertBefore(document.createElement("hr"),o.element);const l=()=>{i??(i={}),i.bottom=24},c=this.reactionElement?[this.reactionElement.reactionCount.reaction.document_id]:this.getUniqueCustomEmojisFromMessage(),d=this.emojiInputsPromise=Mt();await this.managers.appEmojiManager.getCachedCustomEmojiDocuments(c).then(async u=>{const h=async p=>{const m=new Map;p.forEach(f=>{!f||m.has(f.stickerSetInput.id)||m.set(f.stickerSetInput.id,f.stickerSetInput)});const g=[...m.values()];if(d.resolve(g),m.size===1){const f=await this.managers.acknowledged.appStickersManager.getStickerSet(g[0]),v=f.result.then(y=>{const w=P(this.isTag?"Reaction.Tag.From":this.reactionElement?"MessageContainsReactionPack":"MessageContainsEmojiPack",[je(y.set.title)]);St(o.textElement,w)});return f.cached?v:(l(),void 0)}St(o.textElement,P("MessageContainsEmojiPacks",[m.size]))};if(u.some(p=>!p))l(),this.managers.appEmojiManager.getCustomEmojiDocuments(c).then(h);else return h(u)})}return this.chat.container.append(t),{element:t,cleanup:()=>{this.cleanup(),n&&n.cleanup()},destroy:()=>{t.remove(),n&&n.widthContainer.remove()},menuPadding:i,reactionsMenu:n,reactionsMenuPosition:r}}async getUrlToMessage(){if(!this.message||this.messagePeerId.isUser())return;let e;const{peerId:t,mid:s}=this.message,i=this.chat.threadId;this.chat.type===we.Discussion&&(e=await this.managers.appMessagesManager.getMessageByPeer(t,i));const n=await this.managers.appPeersManager.getPeerUsername(e?e.fromId:t),r=An(s);let o="https://t.me/";return n?(o+=n,e?o+=`/${An(e.fwd_from.channel_post)}?comment=${r}`:i?o+=`/${An(i)}/${r}`:o+="/"+r):(o+="c/"+t.toChatId(),e?o+=`/${r}?thread=${An(e.mid)}`:i?o+=`/${An(i)}/${r}`:o+="/"+r),{url:o,isPrivate:!n}}async getSelectedMessagesText(){if(this.avatarPeerId||!Fc())return;let e;if(this.chat.selection.isSelecting){const r=[...this.chat.selection.selectedMids.entries()].map(([o,l])=>[...l].map(c=>ps(o,c)));e=va(r)}else{const n=this.getMessageWithText();if(!n)return;e=[ps(n.peerId,n.mid)]}let t;this.isSponsored?t=[this.sponsoredMessage]:t=e.map(n=>this.chat.getMessage(n));const s=t.map(n=>{if(!n?.message)return;const r=jt(n.message,{entities:n.totalEntities||n.entities,wrappingDraft:!0});return KL(r)});return{text:t.map(n=>n?.message).filter(Boolean).join(`
- `),html:s.filter(Boolean).join(`
- `)}}getQuotedText(){return R$(this.target)}static onDownloadClick(e,t){if(Array.isArray(e))return e.map(s=>this.onDownloadClick(s));if(this.canDownload(e,void 0,t))return fs.downloadToDisc({media:Vi(e,!0)})}static getReactionsMenuPadding(e){let n=56;const r=40;pt&&(n+=32);let o;return e==="vertical"?o={top:n,left:44}:o={top:44,right:r,left:n},o}static getReactionsOpenPosition(e,t){const s=e.container.getBoundingClientRect(),i=HP(s);return i.left-=21/2,i.top-=121/2,t||(i.top+=37),i}static appendReactionsMenu({element:e,reactionsMenu:t,reactionsMenuPosition:s}){let i=!1;if(t){const n="is-visible";if(i=t.container.classList.contains(n),i&&t.container.classList.remove(n),s==="horizontal"){const r=e.offsetWidth,c=(r-8)/G0%1,d=.65;if(c<d){const u=r+(d-c)*G0|0;e.style.minWidth=u+"px"}}}if(t){const n=t.widthContainer;if(Gi)e.prepend(n);else{const r=document.createElement("div");r.classList.add("btn-menu-items","btn-menu-transition"),r.append(...Array.from(e.childNodes)),e.classList.add("has-items-wrapper"),e.append(n,r)}n.style.setProperty("--height",n.offsetHeight+"px")}return{onAfterInit:()=>{i&&t.container.classList.add("is-visible")},onClose:()=>{t&&t.container.classList.remove("is-visible")}}}}class cw{constructor(e){this.options=e,this.middlewareHelper=e.middleware.create(),this.createMenu()}setPeerParams(e){this.type=e.peerId===I.myId?"reminder":"schedule",this.isPaid=e.isPaid}createButtons(){return[{icon:"mute",text:"Chat.Send.WithoutSound",onClick:this.options.onSilentClick,verify:()=>this.type==="schedule"},{icon:"schedule",text:"Chat.Send.ScheduledMessage",onClick:this.options.onScheduleClick,verify:()=>this.type==="schedule"&&!this.isPaid},{icon:"schedule",text:"Chat.Send.SetReminder",onClick:this.options.onScheduleClick,verify:()=>this.type==="reminder"},{icon:"online",text:"Schedule.SendWhenOnline",onClick:this.options.onSendWhenOnlineClick,verify:()=>this.type==="schedule"&&this.options.canSendWhenOnline?.()&&!this.isPaid},{icon:"crossround",text:"Effect.Remove",danger:!0,onClick:()=>this.options.onEffect(void 0),verify:()=>!!this.options.effect?.()}]}createMenu(){this.middlewareHelper.clean();const e=this.middlewareHelper.get(),t=new $t;e.onClean(()=>{t.removeAll()}),this.createButtons();const s=this.createButtons(),i=xa({buttons:s,listenerSetter:t});i.classList.add("menu-send",this.options.openSide),this.options.onRef(i),Er({element:this.options.onContextElement,callback:async n=>{if(this.options.onOpen&&!this.options.onOpen())return;_e(n),await Promise.all(s.map(async u=>{const h=await u.verify();u.element.classList.toggle("hide",!h)}));const r=Ht(),o=r.get(),l="horizontal";let c;this.options.withEffects?.()&&(c=new lw({managers:I.managers,type:l,middleware:o,onFinish:async u=>{if(Li.close(),u=await u,!u)return;const h=u.document_id;if(!I.premium&&!c.freeCustomEmoji.has(h)){rs.show({feature:"premium_stickers"});return}const m=(await I.managers.appReactionsManager.getAvailableEffects()).find(g=>g.effect_sticker_id===h);this.options.onEffect(m.id)},getOpenPosition:u=>In.getReactionsOpenPosition(c,u),isEffects:!0}),await c.init());const d=c&&In.appendReactionsMenu({element:i,reactionsMenu:c,reactionsMenuPosition:l});Li.openBtnMenu(i,()=>{d?.onClose(),r.destroy(),this.createMenu(),setTimeout(()=>{i.remove()},400)}),d?.onAfterInit()},listenerSetter:t})}}const z0=255,W0=100,K0=200;class j$ extends ue{constructor(e){super("popup-create-poll popup-new-media",{closable:!0,overlayClosable:!0,withConfirm:"Create",body:!0,title:"NewPoll",isConfirmationNeededOnClose:()=>{if(!(!this.getFilledAnswers().length||this.sent))return Rt({titleLangKey:"CancelPollAlertTitle",descriptionLangKey:"CancelPollAlertText",button:{langKey:"Discard",isDanger:!0}})}}),this.chat=e,this.tempId=0,this.onSubmitClick=()=>{this.send()},this.onInput=t=>{const s=t.target,i=Mn(s,"LABEL"),n=Pv(s);n||(s.parentElement.classList.add("is-filled"),i.classList.remove("hidden-widget"),i.firstElementChild.removeAttribute("disabled")),!i.nextElementSibling&&!n&&this.questions.childElementCount<10&&this.appendMoreField(),this.handleChange()},this.onDeleteClick=t=>{const s=t.target,i=Mn(s,"LABEL"),n=Bn(i);this.correctAnswers&&this.correctAnswers[0][0]===n&&(this.correctAnswers=void 0),i.remove(),this.optionInputFields.splice(n,1),this.optionInputFields.forEach((r,o)=>{r.options.labelOptions.length=0,r.options.labelOptions.push(o+1),Ne.weakMap.get(r.label.firstElementChild).update()}),this.handleChange()},this.construct()}async construct(){this.questionInputField=new Yt({placeholder:"AskAQuestion",label:"AskAQuestion",name:"question",maxLength:z0}),this.listenerSetter.add(this.questionInputField.input)("input",()=>{this.handleChange()}),this.optionInputFields=[],this.chat.type!==we.Scheduled&&new cw({onSilentClick:()=>{this.chat.input.sendSilent=!0,this.send()},onScheduleClick:()=>{this.chat.input.scheduleSending(()=>{this.send()})},openSide:"bottom-left",onContextElement:this.btnConfirm,middleware:this.middlewareHelper.get(),onRef:u=>{this.header.append(u)}})?.setPeerParams({peerId:this.chat.peerId,isPaid:!!this.chat.starsAmount}),this.header.append(this.questionInputField.container);const e=document.createElement("hr"),t=document.createElement("div");t.classList.add("caption"),ks(t,"PollOptions"),this.questions=document.createElement("form"),this.questions.classList.add("poll-create-questions");const s=document.createElement("div");s.classList.add("poll-create-settings");const i=document.createElement("div");i.classList.add("caption"),ks(i,"Settings"),await this.chat.managers.appPeersManager.isBroadcast(this.chat.peerId)||(this.anonymousCheckboxField=new _t({text:"NewPoll.Anonymous",name:"anonymous"}),this.anonymousCheckboxField.input.checked=!0,s.append(this.anonymousCheckboxField.label)),this.multipleCheckboxField=new _t({text:"NewPoll.MultipleChoice",name:"multiple"}),this.quizCheckboxField=new _t({text:"NewPoll.Quiz",name:"quiz"}),this.listenerSetter.add(this.multipleCheckboxField.input)("change",()=>{const d=this.multipleCheckboxField.checked;this.quizCheckboxField.input.toggleAttribute("disabled",d)}),this.listenerSetter.add(this.quizCheckboxField.input)("change",()=>{const d=this.quizCheckboxField.checked;Array.from(this.questions.children).map(u=>{u.classList.toggle("radio-field",d)}),d||(this.correctAnswers=void 0,this.quizSolutionField.setValueSilently("")),n.forEach(u=>u.classList.toggle("hide",!d)),this.multipleCheckboxField.input.toggleAttribute("disabled",d),this.handleChange()}),s.append(this.multipleCheckboxField.label,this.quizCheckboxField.label);const n=[],r=document.createElement("div");r.classList.add("caption"),ks(r,"AccDescrQuizExplanation");const o=document.createElement("hr"),l=document.createElement("div");l.classList.add("poll-create-questions"),this.quizSolutionField=new Yt({placeholder:"NewPoll.Explanation.Placeholder",label:"NewPoll.Explanation.Placeholder",name:"solution",maxLength:K0}),this.listenerSetter.add(this.questionInputField.input)("input",()=>{this.handleChange()});const c=document.createElement("div");c.classList.add("subtitle"),ks(c,"AddAnExplanationInfo"),l.append(this.quizSolutionField.container,c),n.push(o,r,l),n.forEach(d=>d.classList.add("hide")),this.body.parentElement.insertBefore(e,this.body),this.body.append(t,this.questions,document.createElement("hr"),i,s,...n),J(this.btnConfirm,this.onSubmitClick,{listenerSetter:this.listenerSetter}),this.scrollable=new tn(this.body),this.appendMoreField(),this.handleChange()}getFilledAnswers(){return Array.from(this.questions.children).map((t,s)=>{const i=t.querySelector(".input-field-input");return i instanceof HTMLInputElement?i.value:xn(i,!1,!1).value}).filter(t=>!!t.trim())}validate(){const e=this.questionInputField.value;if(!e||e.length>z0||this.quizCheckboxField.checked&&!this.correctAnswers?.length)return!1;const t=this.getFilledAnswers();if(t.length<2||t.find(n=>n.length>W0))return!1;const{value:i}=xn(this.quizSolutionField.input,!1,!1);return!(i.length>K0)}handleChange(){const e=this.validate();this.btnConfirm.toggleAttribute("disabled",!e)}async send(e=!1){const t=this.questionInputField.value,s=this.getFilledAnswers(),{value:i,entities:n}=xn(this.quizSolutionField.input,!0,!1);if(this.chat.type===we.Scheduled&&!e){this.chat.input.scheduleSending(()=>{this.send(!0)});return}this.sent=!0;const r={};this.anonymousCheckboxField&&!this.anonymousCheckboxField.checked&&(r.public_voters=!0),this.multipleCheckboxField.checked&&(r.multiple_choice=!0),this.quizCheckboxField.checked&&(r.quiz=!0);const o={_:"poll",pFlags:r,question:{_:"textWithEntities",text:t,entities:[]},answers:s.map((u,h)=>({_:"pollAnswer",text:{_:"textWithEntities",text:u,entities:[]},option:new Uint8Array([h])})),id:void 0},l=await this.chat.managers.appPollsManager.getInputMediaPoll(o,this.correctAnswers,i,n),c=this.chat.getMessageSendingParams(),d=await this.chat.input.paidMessageInterceptor.prepareStarsForPayment(1);d!==Fn&&(c.confirmedPaymentResult=d,this.hide(),this.chat.managers.appMessagesManager.sendOther({...c,inputMedia:l}),this.chat.input.helperType==="reply"&&this.chat.input.clearHelper(),this.chat.input.onMessageSent(!1,!1))}appendMoreField(){const e=this.tempId++,t=this.questions.childElementCount+1,s=new Yt({placeholder:"NewPoll.OptionsAddOption",label:"NewPoll.OptionLabel",labelOptions:[t],name:"question-"+e,maxLength:W0});this.listenerSetter.add(s.input)("input",this.onInput);const i=new rn({text:"",name:"question"});i.main.append(s.container),J(s.input,_e,{listenerSetter:this.listenerSetter}),i.label.classList.add("hidden-widget"),i.input.disabled=!0,this.quizCheckboxField.checked||i.label.classList.remove("radio-field"),this.listenerSetter.add(i.input)("change",()=>{if(i.input.checked){const o=Bn(i.label);this.correctAnswers=[new Uint8Array([o])],this.handleChange()}});const n=yt("close");s.container.append(n),J(n,this.onDeleteClick,{listenerSetter:this.listenerSetter,once:!0}),this.questions.append(i.label),this.scrollable.scrollIntoViewNew({element:this.questions.lastElementChild,position:"center"}),this.optionInputFields.push(s)}}class sf extends pn{constructor(e){super(!1),this.hidden=!0,this.onVisible=()=>{this.detach?.();const t=this.list,{attach:s,detach:i,resetTarget:n}=$P({list:this.getNavigationList?.()||t,type:this.listType,onSelect:this.onSelect,once:!0,waitForKey:this.waitForKey});this.attach=s,this.detach=i,this.resetTarget=n,!Gi&&!this.navigationItem&&(this.navigationItem={type:"autocomplete-helper",onPop:()=>{this.navigationItem=void 0,this.toggle(!0)},noBlurOnPop:!0},Pt.pushItem(this.navigationItem)),this.addEventListener("hidden",()=>{this.resetTarget=void 0,this.attach=void 0,this.detach=void 0,t.replaceChildren(),i(),this.navigationItem&&(Pt.removeItem(this.navigationItem),this.navigationItem=void 0)},{once:!0})},Nt(this,e),this.container=document.createElement("div"),this.container.classList.add("autocomplete-helper","z-depth-1"),e.appendTo.append(this.container),this.attachNavigation(),this.controller?.addHelper(this)}toggleListNavigation(e){e?this.attach?.():this.detach?.()}attachNavigation(){this.addEventListener("visible",this.onVisible)}toggle(e,t=!1,s){if(this.init)return;if(e===void 0&&(e=this.container.classList.contains("is-visible")&&!this.container.classList.contains("backwards")),this.hidden===e){e||this.dispatchEvent("visible");return}this.hidden=e,e?(this.navigationItem&&(Pt.removeItem(this.navigationItem),this.navigationItem=void 0),!t&&this.controller&&this.controller.hideOtherHelpers(),this.detach?.()):(this.controller&&this.controller.hideOtherHelpers(this),this.dispatchEvent("visible"));const i=this.controller||e?0:2;e&&this.dispatchEvent("hiding"),Dt({element:this.container,className:"is-visible",forwards:!e,duration:wt.isAvailable("animations")&&!s?300:0,onTransitionEnd:()=>{this.hidden&&this.dispatchEvent("hidden")},useRafs:i})}}class q$ extends sf{constructor(e,t,s,i){super({appendTo:e,controller:t,listType:"xy",onSelect:async n=>!await this.chat.input.emoticonsDropdown.onMediaClick({target:n},!0),waitForKey:["ArrowUp","ArrowDown"]}),this.chat=s,this.managers=i,this.container.classList.add("stickers-helper"),this.addEventListener("visible",()=>{setTimeout(()=>{this.scrollable.scrollPosition=0},0),I.dispatchEvent("choosing_sticker",!0)}),this.addEventListener("hidden",()=>{this.onChangeScreen&&(st.removeEventListener("changeScreen",this.onChangeScreen),this.onChangeScreen=void 0,this.listenerSetter.removeAll(),this.listenerSetter=void 0),I.dispatchEvent("choosing_sticker",!1)})}checkEmoticon(e){const t=this.controller.getMiddleware();KP(e),this.managers.appStickersManager.getStickersByEmoticon({emoticon:e,includeOurStickers:!0,includeServerStickers:I.settings.stickers.suggest==="all"}).then(s=>{if(!t())return;this.init&&(this.init(),this.init=null);const i=this.list.cloneNode();let n;if(s.length){const r=new sr,o=new Id({regularLazyLoadQueue:r,group:this.chat.animationGroup,managers:this.managers});n=new Promise(l=>{const c=[];s.forEach(d=>{i.append(o.renderSticker(d,void 0,c))}),Promise.all(c).finally(l)}),t.onClean(()=>{r.clear(),setTimeout(()=>o.destroy(),500)})}else n=Promise.resolve();n.then(()=>{this.list.replaceWith(i),this.list=i,this.onChangeScreen||(this.onChangeScreen=()=>{const r=this.list.childElementCount*st.active.esgSticker.width+(this.list.childElementCount-1);this.list.style.width=r+"px"},st.addEventListener("changeScreen",this.onChangeScreen),this.listenerSetter=new $t,_d({listenTo:this.container,listenerSetter:this.listenerSetter})),this.onChangeScreen(),this.toggle(!s.length),this.scrollable.scrollPosition=0})})}init(){this.list=document.createElement("div"),this.list.classList.add("stickers-helper-stickers","super-stickers"),this.container.append(this.list),this.scrollable=new tn(this.container)}}class Y$ extends sf{constructor(e,t,s,i){super({appendTo:e,controller:t,listType:"x",onSelect:n=>{s.onEmojiSelected(Jm(n),!0)},getNavigationList:()=>this.innerList}),this.chatInput=s,this.managers=i,this.container.classList.add("emoji-helper")}init(){this.list=document.createElement("div"),this.list.classList.add("emoji-helper-emojis","super-emojis"),this.container.append(this.list),this.scrollable=new io(this.container),this.addEventListener("visible",()=>{setTimeout(()=>{this.scrollable.scrollPosition=0},0)})}async renderEmojis(e,t){const s=this.list.cloneNode(),i=new Map,n=this.innerList=document.createElement("span");if(s.append(n),I.premium||(e=e.filter(r=>this.chatInput.emoticonsDropdown.canUseEmoji(r,!1))),e.forEach(r=>{const o=oM(r,!0);if(n.append(o),r.docId){const l=o.firstElementChild;i.set(l.docId,new Set([l]))}}),i.size){const r=Ht();t.create().get().onClean(()=>{setTimeout(()=>r.destroy(),500)});const o=jy.create({animationGroup:"INLINE-HELPER",customEmojiSize:st.active.esgCustomEmoji,textColor:"primary-text-color",observeResizeElement:!1,middleware:r.get()});s.prepend(o),o.setDimensionsFromRect({width:e.length*42+8,height:42});const l=new $t;t.onClean(()=>{l.removeAll(),this.innerList===n&&(this.innerList=void 0)}),_d({listenTo:this.container,listenerSetter:l}),await o.add({addCustomEmojis:i})}return s}async render(e,t,s){if(this.init){if(!e.length)return;this.init(),this.init=null}if(!e.length){this.toggle(!0);return}e=e.slice(0,80);const i=await this.renderEmojis(e,s);s()&&(this.list.replaceWith(i),this.list=i,this.waitForKey=t?["ArrowUp","ArrowDown"]:void 0,this.toggle(!1),this.scrollable.scrollPosition=0)}checkQuery(e,t){const s=this.controller.getMiddleware(),i=e.replace(/^:/,"");this.managers.appEmojiManager.prepareAndSearchEmojis({q:i,addCustom:!0}).then(async n=>{s()&&this.render(n,t!==":",s)})}}const Dr=class Dr extends sf{constructor(e,t,s,i){super({appendTo:e,controller:t,listType:"y",onSelect:i}),this.className=s,this.container.classList.add(Dr.BASE_CLASS,s)}init(){this.list=document.createElement("div"),this.list.classList.add(Dr.BASE_CLASS+"-list",this.className+"-list"),this.container.append(this.list),this.scrollable=new tn(this.container),this.addEventListener("visible",()=>{setTimeout(()=>{this.scrollable.scrollPosition=0},0)})}render(e,t,s){if(this.init){if(!e.length)return;this.init(),this.init=null}e.length&&(this.list.replaceChildren(),e.forEach(i=>{const n=Dr.listElement({className:this.className,peerId:i.peerId,name:i.name,description:i.description,middleware:t});this.list.append(n)})),s||this.toggle(!e.length)}static listElement(e){const t=Dr.BASE_CLASS_LIST_ELEMENT;e.className+="-list-element";const s=document.createElement("div");s.classList.add(t,e.className),s.dataset.peerId=""+e.peerId;const{node:i}=vs({middleware:e.middleware,isBig:!1,size:30,peerId:e.peerId});i.classList.add(t+"-avatar",e.className+"-avatar");const n=document.createElement("div");if(n.classList.add(t+"-name",e.className+"-name"),e.name?Qt(n,je(e.name)):n.append(new Xt({peerId:e.peerId,dialog:!1,onlyFirstName:!1,plainText:!1}).element),s.append(i,n),e.description){const r=document.createElement("div");r.classList.add(t+"-description",e.className+"-description"),Qt(r,je(e.description)),s.append(r)}return s}};Dr.BASE_CLASS="autocomplete-peer-helper",Dr.BASE_CLASS_LIST_ELEMENT=Dr.BASE_CLASS+"-list-element";let Hl=Dr;function qP(a,e,t){const s=[].concat(e.bot_info);let i;t!==void 0&&(i=new rw({ignoreCase:!0}));const n=new Map;s.forEach(o=>{o.commands&&o.commands.forEach(({command:l,description:c},d)=>{const u="/"+l;n.set(l,{peerId:o.user_id?o.user_id.toPeerId(!1):a,command:l,name:u,description:c,index:d}),i&&i.indexObject(l,u)})});let r;if(!i)r=[...n.values()];else{const o=i.search(t);r=Array.from(o).map(l=>n.get(l))}return r=r.sort((o,l)=>n.get(o.command).index-n.get(l.command).index),r}class Q$ extends Hl{constructor(e,t,s,i){super(e,t,"commands-helper",n=>{const r=n.querySelector(`.${Hl.BASE_CLASS_LIST_ELEMENT}-name`).innerHTML;return s.getReadyToSend(()=>{s.messageInput.innerHTML=r,s.sendMessage(!0)})}),this.managers=i}async checkQuery(e,t){if(!await this.managers.appUsersManager.isBot(t))return!1;const s=this.controller.getMiddleware();return this.managers.appProfileManager.getProfileByPeerId(t).then(i=>{if(!s())return;const n=qP(t,i,e);this.render(n,s)}),!0}}class X${constructor(){this.helpers=new Set,this.middleware=Ht()}toggleListNavigation(e){for(const t of this.helpers)t.toggleListNavigation(e)}getMiddleware(){return this.middleware.clean(),this.middleware.get()}addHelper(e){this.helpers.add(e)}hideOtherHelpers(e){this.helpers.forEach(t=>{t!==e&&t.toggle(!0,!0)}),e||this.middleware.clean()}}class Z$ extends Hl{constructor(e,t,s,i){super(e,t,"mentions-helper",n=>{const r=n.dataset.peerId.toPeerId();s.mentionUser(r,!0)}),this.managers=i}checkQuery(e,t,s,i){const n=e.trim();if(e.length!==n.length)return!1;const r=this.controller.getMiddleware();return this.managers.appProfileManager.getMentions(t&&t.toChatId(),n,s,i).then(async o=>{if(!r())return;o=o.filter(d=>d!==I.myId);const l=o.map(async d=>{const u=await this.managers.appUsersManager.getUser(d),h=ji(u);return{peerId:d,description:h[0]?"@"+h[0]:void 0}}),c=(await Promise.all(l)).filter(Boolean);r()&&this.render(c,r)}),!0}}const j0=200,J$=200;class Ph extends pn{constructor(e){super(!1),this.onButtonClick=(t,s)=>{const i="click",n=!this.ignoreMouseOut.has(i);n&&!this.ignoreMouseOut.size&&(t&&this.ignoreButtons.add(t),setTimeout(()=>{this.detachClickEvent=J(window,this.onClickOut,{capture:!0})},0)),this.setIgnoreMouseOut(i,n),this.toggle(n)},this.onClickOut=t=>{const s=t.target;t.isTrusted&&!Mi(s,this.element)&&!Array.from(this.ignoreButtons).some(i=>Mi(s,i)||s===i)&&this.ignoreMouseOut.size<=1&&(!this.ignoreOutClickClassName||!ne(s,this.ignoreOutClickClassName))&&this.toggle(!1)},this.onMouseOut=t=>{if(!this.isActive()||(this.clearTimeout("toggle"),this.ignoreMouseOut.size))return;const s=t.toElement;s&&Mi(s,this.element)||this.setTimeout("toggle",()=>{this.toggle(!1)},j0)},this.toggle=async t=>{const s=!!this.element.style.display&&t===void 0||t;if(this.init)if(s)this.init(),this.init=null;else return;if(s===this.isActive())return;const i=pt||!wt.isAvailable("animations")?0:J$;if(this.element.style.display&&t===void 0||t){const n=this.dispatchResultableEvent("open");await Promise.all(n),this.element.style.display="",this.element.offsetLeft,this.element.classList.add("active"),this.dispatchEvent("openAfterLayout"),Pt.pushItem(this.navigationItem={type:"dropdown",onPop:()=>{this.toggle(!1)}}),this.clearTimeout("toggle"),this.setTimeout("done",()=>{this.forceClose=!1,this.dispatchEvent("opened")},i)}else this.dispatchEvent("close"),this.ignoreMouseOut.clear(),this.ignoreButtons.clear(),this.element.classList.remove("active"),Pt.removeItem(this.navigationItem),this.detachClickEvent?.(),this.detachClickEvent=void 0,this.clearTimeout("toggle"),this.setTimeout("done",()=>{this.element.style.display="none",this.forceClose=!1,this.dispatchEvent("closed")},i)},Nt(this,e),this.forceClose=!1,this.inited=!1,this.ignoreMouseOut=new Set,this.ignoreButtons=new Set,this.timeouts={}}attachButtonListener(e,t){let s=!0;pt?J(e,()=>{s?(s=!1,this.toggle(!0)):this.toggle()},{listenerSetter:t}):(t.add(e)("mouseover",i=>{s&&(t.add(e)("mouseout",n=>{this.clearTimeout("toggle"),this.onMouseOut(n)}),s=!1),this.setTimeout("toggle",()=>{this.toggle(!0)},j0)}),J(e,this.onButtonClick.bind(this,e),{listenerSetter:t}))}clearTimeout(e){this.timeouts[e]!==void 0&&(clearTimeout(this.timeouts[e]),delete this.timeouts[e])}setTimeout(e,t,s){this.clearTimeout(e),this.timeouts[e]=window.setTimeout(()=>{this.clearTimeout(e),t()},s)}init(){pt||(this.element.onmouseout=this.onMouseOut,this.element.onmouseover=e=>{this.forceClose||this.clearTimeout("toggle")})}isActive(){return this.element.classList.contains("active")}setIgnoreMouseOut(e,t){t?this.ignoreMouseOut.add(e):this.ignoreMouseOut.delete(e)}}const Pc=class Pc extends Ph{constructor(e){super({element:document.createElement("div")}),this.onBodyTouchStart=t=>{const s=t.touches[0].target;!Mi(s,this.element)&&s!==this.btnHover&&(_e(t),this.toggle(!1))},Nt(this,e),this.element.classList.add(Pc.BASE_CLASS),this.element.style.display="none",this.onClickMap=new Map,this.scrollable=new tn,this.element.append(this.scrollable.container),this.attachButtonListener(this.btnHover,this.listenerSetter),this.listenerSetter.add(I)("history_reply_markup",async({peerId:t})=>{this.peerId===t&&(this.checkAvailability()&&this.isActive()&&await this.render(),vi().then(()=>{this.checkForceReply()}))})}init(){return this.appendTo.append(this.element),this.listenerSetter.add(this)("open",async()=>{await this.render(),pt&&(this.touchListener=this.listenerSetter.add(document.body)("touchstart",this.onBodyTouchStart,{passive:!1,capture:!0}),this.listenerSetter.add(this)("close",()=>{this.listenerSetter.remove(this.touchListener)},{once:!0}))}),J(this.element,e=>{const t=ne(e.target,"btn");if(!t)return;this.onClickMap.get(t)?.(e),this.toggle(!1)},{listenerSetter:this.listenerSetter}),super.init()}async checkForceReply(){const e=await this.getReplyMarkup();e._==="replyKeyboardForceReply"&&!e.pFlags.hidden&&!e.pFlags.used&&(e.pFlags.used=!0,this.chatInput.initMessageReply({replyToMsgId:e.mid}))}async getReplyMarkup(){return(await this.managers.appMessagesManager.getHistoryStorageTransferable({peerId:this.peerId})).replyMarkup??{_:"replyKeyboardHide",pFlags:{}}}async render(e){e===void 0&&(e=await this.getReplyMarkup()),this.onClickMap.clear(),this.scrollable.replaceChildren();for(const t of e.rows){const s=document.createElement("div");s.classList.add(Pc.BASE_CLASS+"-row");for(const i of t.buttons){const{buttonEl:n,onClick:r}=EI({button:i,chat:this.chatInput.chat,replyMarkup:e});this.onClickMap.set(n,r),n.classList.add(Pc.BASE_CLASS+"-button","btn"),s.append(n)}this.scrollable.append(s)}}async checkAvailability(e){e===void 0&&(e=await this.getReplyMarkup());const t=e._==="replyKeyboardHide"||!e.rows?.length;return this.btnHover.classList.toggle("hide",t),t&&this.toggle(!1),!t}setPeer(e){this.peerId=e,this.checkAvailability(),this.checkForceReply()}};Pc.BASE_CLASS="reply-keyboard";let gy=Pc;class e9 extends XC{constructor(e,t){super(e),this.onVisibilityChange=t,this.intersector=new vg(s=>{const{target:i,visible:n}=s,r=a_(this.queue,o=>o.div===i);n&&r.length&&r.forEach(o=>{this.queue.unshift(o)}),this.onVisibilityChange&&this.onVisibilityChange(s),this.setProcessQueueTimeout()})}observe(e){super.observe(e)}}class dw{constructor(e,t,s,i=!0){this.element=e,this.group=t,this.scrollable=s,this.scrollPromise=Promise.resolve(),this.timeout=0,this.onScroll=()=>{this.timeout?clearTimeout(this.timeout):this.scrollPromise=Mt(),this.timeout=window.setTimeout(()=>{this.timeout=0,this.scrollPromise.resolve()},150)},this.processInvisibleDiv=n=>this.scrollPromise.then(async()=>{if(this.lazyLoadQueue.intersector.isVisible(n))return;const r=n.querySelector("img, canvas");r&&(r.classList.remove("hide"),await hi()),!this.lazyLoadQueue.intersector.isVisible(n)&&n.middlewareHelper.clean()}),this.managers=I.managers,this.middlewareHelper=Ht(),this.map=new Map,this.lazyLoadQueue=new e9(void 0,({target:n,visible:r})=>{r?this.processVisibleDiv(n):this.processInvisibleDiv(n)}),i&&this.attach()}attach(){this.scrollable.container.addEventListener("scroll",this.onScroll)}detach(){this.clear(),this.scrollable.container.removeEventListener("scroll",this.onScroll),this.middlewareHelper.destroy()}clear(){this.lazyLoadQueue.clear()}processVisibleDiv(e){if(e.querySelector("video"))return;const s=()=>{const i=e.dataset.docId;return Promise.all([this.managers.appDocsManager.getDoc(i),this.scrollPromise]).then(async([r])=>{if(!this.lazyLoadQueue.intersector.isVisible(e)){this.processInvisibleDiv(e);return}e.middlewareHelper.clean();const o=e.middlewareHelper.get().create().get(),l=await Xa({doc:r,container:e,lazyLoadQueue:null,group:this.group,noInfo:!0,noPreview:!0,middleware:o}),c=l.loadPromise;return c.finally(()=>{if(o.onDestroy(()=>{l.video?.remove()}),!o()||!this.lazyLoadQueue.intersector.isVisible(e)){this.processInvisibleDiv(e);return}const d=e.querySelector("img, canvas");d&&d.classList.add("hide")}),c})};this.lazyLoadQueue.push({div:e,load:s})}addBatch(e){e.forEach(t=>this.add(t))}update(e){for(const[t]of this.map)e.some(s=>s.id===t)||this.delete(t);this.addBatch(e);for(let t=0,s=e.length;t<s;++t){const i=this.map.get(e[t].id);di(i,this.element,t)}}add(e,t=this.element){if(this.map.has(e.id))return;const s=document.createElement("div");s.classList.add("gif","grid-item"),s.dataset.docId=""+e.id,s.middlewareHelper=this.middlewareHelper.get().create(),this.map.set(e.id,s),t.append(s),this.lazyLoadQueue.observe({div:s,load:as}),Xa({doc:e,container:s,lazyLoadQueue:null,noInfo:!0,onlyPreview:!0,middleware:s.middlewareHelper.get()})}delete(e){const t=this.map.get(e);t&&(t.remove(),t.middlewareHelper.destroy(),this.map.delete(e))}}function t9(a,e){return a+"_"+e}const q0="INLINE-HELPER";class s9 extends sf{constructor(e,t,s,i){super({appendTo:e,controller:t,listType:"xy",waitForKey:["ArrowUp","ArrowDown"],onSelect:n=>{if(!n)return!1;const{peerId:r,botId:o,queryId:l}=this.list.dataset;return this.chat.input.getReadyToSend(()=>{const c=t9(l,n.dataset.resultId);this.managers.appInlineBotsManager.sendInlineResult(r.toPeerId(),o,c,{...this.chat.getMessageSendingParams(),clearDraft:!0}),this.chat.input.onMessageSent(!0,!0)})}}),this.chat=s,this.managers=i,this._checkQuery=async(n,r,o,l)=>{const c=this.controller.getMiddleware(),d=await this.managers.appUsersManager.resolveUsername(r);if(!c())throw"PEER_CHANGED";if(d._!=="user"||!d.pFlags.bot)throw"NOT_A_BOT";if(!l)throw c()?(this.init&&(this.init(),this.init=null),this.container.classList.add("cant-send"),this.toggle(!1),"NO_INLINES"):"PEER_CHANGED";const u=d.id,h=this.managers.appInlineBotsManager.getInlineResults(n,u,o).then(p=>{if(!c())throw"PEER_CHANGED";this.init&&(this.init(),this.init=null);const m=this.list.cloneNode();m.dataset.peerId=""+n,m.dataset.botId=""+u,m.dataset.queryId=""+p.query_id;const g=new dw(null,q0,this.scrollable,!1);this.lazyLoadQueue.clear(),this.superStickerRenderer.clear();const f=[],v=!!p.pFlags.gallery;for(const y of p.results){const w=document.createElement("div");w.classList.add("inline-helper-result"),w.dataset.resultId=y.id;const b=v?void 0:document.createElement("div");if(b&&(b.classList.add("inline-helper-result-preview"),w.append(b)),m.append(w),v)w.classList.add("grid-item");else{b.classList.add("empty"),Qt(b,je([...y.title.trim()][0]));const S=document.createElement("div");S.classList.add("inline-helper-result-title"),Qt(S,je(y.title));const _=document.createElement("div");_.classList.add("inline-helper-result-description"),Qt(_,jt(y.description,{noCommands:!0,noLinks:!0})),w.append(S,_);const M=document.createElement("div");M.classList.add("inline-helper-separator"),m.append(M)}if(y._==="botInlineResult"){if(y.thumb&&y.thumb.mime_type.indexOf("image/")===0){let S;b?(S=document.createElement("div"),b.append(S)):S=w,S.classList.add("media-container"),v&&S.classList.add("no-border-radius"),this.lazyLoadQueue.push({div:w,load:()=>fs.download({dcId:4,location:{_:"inputWebFileLocation",access_hash:y.thumb.access_hash,url:y.thumb.url},size:y.thumb.size,mimeType:y.thumb.mime_type}).then(_=>{const M=new Image;M.classList.add("media-photo"),GE(_).then(C=>{N_({container:S,media:M,url:C,needFadeIn:wt.isAvailable("animations")})})})})}}else{const S=y.document||y.photo;if(["sticker","gif"].includes(S?.type)&&v)S.type==="gif"?g.add(S,w):S.type==="sticker"&&(w.classList.add("super-sticker"),this.superStickerRenderer.renderSticker(S,w,f),S.animated&&this.superStickerRenderer.observeAnimated(w));else if(S){const _=v?48:void 0;v&&w.classList.add("no-border-radius"),Bi({photo:S,container:v?w:b,boxWidth:_,boxHeight:_,middleware:c,lazyLoadQueue:this.lazyLoadQueue,loadPromises:f})}}}return Promise.all(f).then(()=>{if(!c()){g.clear();return}m.classList.toggle("is-gallery",v),m.classList.toggle("super-stickers",v),this.container.classList.toggle("is-gallery",v);const y=this.list.parentElement;y.textContent="";const w=p.switch_pm||p.switch_webview;if(w){const b=ot("btn-primary btn-secondary btn-primary-transparent primary");Qt(b,je(w.text)),J(b,async S=>{w._==="inlineBotSwitchPM"?(await this.chat.appImManager.setInnerPeer({peerId:n}),this.managers.appInlineBotsManager.switchToPM(n,u,w.start_param)):this.chat.openWebApp({botId:u,url:w.url,isSimpleWebView:!0,buttonText:w.text,fromSwitchWebView:!0})}),y.append(b)}y.append(this.list=m),this.container.classList.remove("cant-send"),this.gifsMasonry?.detach(),this.gifsMasonry=g,g.attach(),this.onChangeScreen||(this.onChangeScreen=()=>{if(this.list.classList.contains("is-gallery")){const b=this.list.childElementCount*st.active.popupSticker.width+(this.list.childElementCount-1);this.list.style.width=b+"px"}else this.list.style.width=""},st.addEventListener("changeScreen",this.onChangeScreen)),this.onChangeScreen(),this.toggle(!p.results.length&&!w),this.scrollable.scrollPosition=0})});return{user:d,renderPromise:h}},this.container.classList.add("inline-helper"),this.addEventListener("visible",()=>{setTimeout(()=>{this.scrollable.scrollPosition=0},0)}),this.checkQuery=$i(this._checkQuery,200,!0,!0),this.addEventListener("hidden",()=>{this.onChangeScreen&&(st.removeEventListener("changeScreen",this.onChangeScreen),this.onChangeScreen=void 0)})}init(){this.list=document.createElement("div"),this.list.classList.add("inline-helper-results"),this.container.append(this.list),this.scrollable=new tn(this.container),this.lazyLoadQueue=new sr,this.superStickerRenderer=new Id({regularLazyLoadQueue:this.lazyLoadQueue,group:q0,managers:this.managers});const e=P(gl.send_inline);e.classList.add("inline-helper-cant-send"),this.container.append(e)}}const i9="bot-commands";class n9 extends Hl{constructor(e,t,s){super(e,void 0,i9,i=>{const n=i.querySelector(`.${Hl.BASE_CLASS_LIST_ELEMENT}-name`).innerHTML;return t.getReadyToSend(()=>{t.messageInput.innerHTML=n,t.sendMessage(!0),this.toggle(!0)})}),this.managers=s}setUserId(e,t){if(this.userId===e&&this.list?.childElementCount){this.toggle(!1);return}return this.userId=e,en(this.managers.appProfileManager.getProfile(e),s=>{if(!t())return;const i=qP(e.toPeerId(!1),s),o=i.length*50+8+24;this.container.style.setProperty("--height",o+"px"),this.render(i,t)})}}function Y0(a,e=[],t){const s=[];let i=!1;const n=d=>YL(e,d)?i=!1:(s.push(d),i=!0),r=[];let o=0,l;for(;l=a.match(jL);){const d=o+l.index,u=l.index+l[0].length,h=l.index>0&&a.slice(0,l.index);h&&r.push(h);const p=l[3]||l[8]||l[11]||l[13];let m;if(i=!1,p.match(/^`*$/))r.push(l[0]);else if(l[3]){let f=l[3].match(/(.*?)\n/);f?.[1]||(f=void 0);let v=f?l[3].slice(f[1].length):l[3];const y=v[0]===`
- `?1:0,w=v[v.length-1]===`
- `?-1:void 0;if(v=v.slice(y,w),m={_:"messageEntityPre",language:f?.[1]||"",offset:d+l[1].length,length:v.length},n(m)){w&&(o-=1),f&&(o-=f[0].length);let b="";if(l[1])b=l[1];else{const S=r[r.length-1];S&&!/\s/.test(S[S.length-1])&&(b=`
- `)}r.push(b,v,l[5]),o-=l[2].length+l[4].length}}else if(l[7]){const f=l[6]==="";m={_:r_[l[7]],offset:d+(f?0:l[6].length),length:p.length},n(m)&&(f?r.push(p):r.push(l[6]+p+l[9]),o-=l[7].length*2+(f?2:0))}else l[11]?(m={_:"messageEntityMentionName",user_id:l[10].toUserId(),offset:d,length:p.length},n(m)&&(r.push(p),o-=l[0].length-p.length)):l[12]&&(m={_:"messageEntityTextUrl",url:l[14],offset:d,length:p.length},n(m)&&(r.push(p),o-=l[12].length-p.length));i||r.push(l[0]),a=a.substr(l.index+l[0].length),o+=l.index+l[0].length;const g=o-u;g&&e.forEach(f=>{f.offset>=d&&(f.offset+=g)})}a&&r.push(a);let c=r.join("");return c.replace(/\s+/g,"").length||(c=a,s.splice(0,s.length)),e=El(e,s),qL(e),c.length,[c,e]}function a9(a,e){return Pn(a,e)}function Q0(a,e){return Pn(a,e,["date","reply_to"])&&a9(a?.reply_to,e?.reply_to)}function hw(a){if(a)return a.icons.find(e=>e.name===QL)}function Xm(a){return a?a.match(XL):null}function fy(a,e){const t={};a.forEach(d=>t[d]={elements:[],active:!1});const s=window.getSelection();if(s.isCollapsed)return t;const i=s.getRangeAt(0),n=i.commonAncestorContainer,o=(n.nodeType===n.ELEMENT_NODE?n:n.parentElement).closest('[contenteditable="true"]');if(!o)return t;const l=document.createTreeWalker(o,NodeFilter.SHOW_ELEMENT|NodeFilter.SHOW_TEXT,{acceptNode:d=>i.intersectsNode(d)?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_REJECT});let c;for(;c=l.nextNode();)for(const d of a){const u=ZL[d],h=c.nodeType===c.ELEMENT_NODE?c:c.parentElement;h.closest(u.match)&&t[d].elements.push(h)}for(const d of a)t[d].active=t[d].elements.length>=1;return t}class Ld{constructor(){this.buttons={},this.addedListener=!1,this.waitingForMouseUp=!1,this.mouseUpCounter=0,this.onMouseUpSingle=e=>{if(this.waitingForMouseUp=!1,pt)if(e&&_e(e),this.mouseUpCounter++===0)this.resetSelection(this.savedRange);else{this.hide();return}this.show()}}static getInstance(){return this.INSTANCE||(this.INSTANCE=new Ld)}init(){this.container=document.createElement("div"),this.container.classList.add("markup-tooltip","z-depth-1","hide"),this.wrapper=document.createElement("div"),this.wrapper.classList.add("markup-tooltip-wrapper");const e=document.createElement("div"),t=document.createElement("div");e.classList.add("markup-tooltip-tools","markup-tooltip-tools-regular"),t.classList.add("markup-tooltip-tools","markup-tooltip-tools-link"),["bold","italic","underline","strikethrough","monospace","spoiler",["quote","quote_outline"],"link"].forEach(l=>{const c=typeof l=="string"?l:l[0],d=typeof l=="string"?l:l[1],u=yt(d,{noRipple:!0});e.append(this.buttons[c]=u),l!=="link"?u.addEventListener("mousedown",h=>{_e(h),vy(this.input,c),this.cancelClosening()}):J(u,h=>{_e(h),this.showLinkEditor(),this.cancelClosening()})}),this.linkBackButton=yt("left",{noRipple:!0}),this.linkInput=document.createElement("input"),ks(this.linkInput,"MarkupTooltip.LinkPlaceholder",void 0,"placeholder"),this.linkInput.classList.add("input-clear"),this.linkInput.addEventListener("keydown",l=>{const c=!this.linkInput.value.length||!!Xm(this.linkInput.value);l.key==="Enter"&&(c?this.applyLink(l):(this.linkInput.classList.contains("error")&&(this.linkInput.classList.remove("error"),this.linkInput.offsetLeft),this.linkInput.classList.add("error")))}),this.linkInput.addEventListener("input",l=>{const c=this.isLinkValid();this.linkInput.classList.toggle("is-valid",c),this.linkInput.classList.remove("error")}),this.linkBackButton.addEventListener("mousedown",l=>{_e(l),this.container.classList.remove("is-link"),this.resetSelection(),this.setTooltipPosition(),this.cancelClosening()}),this.linkApplyButton=yt("check markup-tooltip-link-apply",{noRipple:!0}),this.linkApplyButton.addEventListener("mousedown",l=>{this.applyLink(l)});const i=document.createElement("div");i.classList.add("markup-tooltip-link-apply-container");const n=document.createElement("span"),r=document.createElement("span"),o=document.createElement("span");n.classList.add("markup-tooltip-delimiter"),r.classList.add("markup-tooltip-delimiter"),o.classList.add("markup-tooltip-delimiter"),e.insertBefore(n,this.buttons.link),i.append(o,this.linkApplyButton),t.append(this.linkBackButton,r,this.linkInput,i),this.wrapper.append(e,t),this.container.append(this.wrapper),document.body.append(this.container),window.addEventListener("resize",()=>{this.hide()})}showLinkEditor(){(!this.container||!this.container.classList.contains("is-visible"))&&this.show();const e=this.buttons.link;this.container.classList.add("is-link");const t=document.getSelection();this.savedRange=t.getRangeAt(0);const i=fy(["link"]).link.elements.find(n=>n.tagName==="A");e.classList.contains("active")?this.linkInput.value=i.href:this.linkInput.value="",this.setTooltipPosition(!0),setTimeout(()=>{this.linkInput.focus()},200),this.linkInput.classList.toggle("is-valid",this.isLinkValid())}applyLink(e){_e(e),this.resetSelection();let t=this.linkInput.value;t&&!JL(t)&&(t="https://"+t),vy(this.input,"link",t),setTimeout(()=>{this.hide()},0)}isLinkValid(){return!this.linkInput.value.length||!!Xm(this.linkInput.value)}resetSelection(e=this.savedRange){const t=window.getSelection();t.removeAllRanges(),t.addRange(e),this.input.focus()}hide(){this.init||(this.input=void 0,this.container.classList.remove("is-visible"),document.removeEventListener("mouseup",this.onMouseUpSingle),this.waitingForMouseUp=!1,Pt.removeByType("markup"),this.hideTimeout&&clearTimeout(this.hideTimeout),this.hideTimeout=window.setTimeout(()=>{this.hideTimeout=void 0,this.container.classList.add("hide"),this.container.classList.remove("is-link")},200))}getActiveMarkupButton(){const e=new Set,t=Object.keys(this.buttons),s=fy(t);return t.forEach(i=>{s[i].active&&e.add(this.buttons[i])}),[...e]}setActiveMarkupButton(){const e=this.getActiveMarkupButton();for(const t in this.buttons){const s=this.buttons[t];s.classList.toggle("active",e.includes(s))}}setTooltipPosition(e=!1){const s=document.getSelection().getRangeAt(0),i=ne(this.input,"rows-wrapper")||ne(this.input,"input-message-container")||ne(this.input,"input-field"),n=this.container.classList.contains("is-link")?this.wrapper.lastElementChild:this.wrapper.firstElementChild,r=document.body.getBoundingClientRect(),o=s.getBoundingClientRect(),l=i.getBoundingClientRect(),c=n.getBoundingClientRect();this.container.style.maxWidth=l.width+"px";const d=Ko(void 0,this.input,!1,o),{newHeight:u=0,oldHeight:h=u}=this.input;if(!d)return;const m=(d?d.rect.top:l.top)+r.top*-1-c.height-8+(h-u),g=l.left,f=l.left+l.width-Math.min(l.width,c.width);let v;if(e){const y=this.container.getBoundingClientRect();v=zt(y.left,g,f)}else{const y=o.left+(o.width-c.width)/2;v=zt(y,g,f)}this.container.style.transform=`translate3d(${v}px, ${m}px, 0)`}show(){if(this.init&&(this.init(),this.init=null),Fc()){this.hide();return}if(this.hideTimeout!==void 0&&clearTimeout(this.hideTimeout),this.container.classList.contains("is-visible"))return;this.container.classList.toggle("night",vn.isDarkOverlayActive),this.setActiveMarkupButton(),this.container.classList.remove("is-link");const e=this.container.classList.contains("hide");e&&(this.container.classList.remove("hide"),this.container.classList.add("no-transition")),this.setTooltipPosition(),e&&(this.container.offsetLeft,this.container.classList.remove("no-transition")),this.container.classList.add("is-visible"),Gi||Pt.pushItem({type:"markup",onPop:()=>{this.hide()}})}setMouseUpEvent(){this.waitingForMouseUp||(this.waitingForMouseUp=!0,document.addEventListener("mouseup",this.onMouseUpSingle,{once:!0}))}cancelClosening(){pt&&!$o&&(document.removeEventListener("mouseup",this.onMouseUpSingle),document.addEventListener("mouseup",e=>{_e(e),this.mouseUpCounter=1,this.waitingForMouseUp=!1,this.setMouseUpEvent()},{once:!0}))}canFormatInput(e){return e.classList.contains("input-message-input")||e.getAttribute("can-format")}handleSelection(){this.addedListener||(this.addedListener=!0,document.addEventListener("selectionchange",e=>{if(document.activeElement===this.linkInput)return;const t=document.activeElement;if(this.input?t!==this.input:!this.canFormatInput(t)){this.hide();return}const s=document.getSelection();if(Fc(s)){this.hide();return}if(this.input=t,pt)if($o)this.show(),this.setTooltipPosition();else{if(this.mouseUpCounter===2){this.mouseUpCounter=0;return}this.savedRange=s.getRangeAt(0),this.setMouseUpEvent()}else this.container&&this.container.classList.contains("is-visible")?(this.setActiveMarkupButton(),this.setTooltipPosition()):this.input.matches(":active")?this.setMouseUpEvent():this.show()}),document.addEventListener("beforeinput",e=>{(e.inputType==="historyRedo"||e.inputType==="historyUndo")&&e.target.addEventListener("input",()=>this.setActiveMarkupButton(),{once:!0})}))}}function r9(a){const e=document.createRange();if(a.endContainer.nodeType===Node.TEXT_NODE&&a.endOffset<a.endContainer.nodeValue.length)return e.setStart(a.endContainer,a.endOffset),e.setEnd(a.endContainer,a.endOffset+1),e.toString();const t=o9(a.endContainer);if(t)return e.setStart(t,0),e.setEnd(t,Math.min(t.nodeValue.length,1)),e.toString()}function o9(a){for(;a&&!a.nextSibling;)a=a.parentNode;if(a&&a.nextSibling)return YP(a.nextSibling)}function YP(a){if(a.nodeType===Node.TEXT_NODE)return a;for(let e=0;e<a.childNodes.length;e++){const t=a.childNodes[e],s=YP(t);if(s)return s}}const QP=new WeakMap;function l9(a){const e=QP.get(a);e&&(e.canRedoFromHTML="",e.undoHistory.length=0,e.executedHistory.length=0,e.canUndoFromHTML="")}function c9(a){const e=QP.get(a);e&&e.canRedoFromHTML&&!e.lockRedo&&a.innerHTML!==e.canRedoFromHTML&&(e.canRedoFromHTML="",e.undoHistory.length=0)}function vy(a,e,t){const s={link:t?()=>document.execCommand("createLink",!1,t):()=>document.execCommand("unlink",!1,null)},i=h=>{s[h]=()=>{const p=(n.includes(h)?n:[h]).filter(g=>u[g]?.active);if(Vs(p,h)||p.push(h),h==="quote"){const g=document.getSelection();g.rangeCount&&r9(g.getRangeAt(0))===`
- `&&g.modify(g.isCollapsed?"move":"extend","forward","character")}let m;return p.length?m=document.execCommand("fontName",!1,"markup-"+p.join("-")):m=h9(),XP(a),m}},n=["bold","italic","underline","strikethrough","spoiler","quote"];if(n.forEach(h=>{i(h)}),i("monospace"),!s[e])return!1;const r=s[e],o=[],c=Jy.getInstance().prepareApplyingMarkdown(),d={capture:!0,passive:!1};a.addEventListener("input",_e,d),o.push(document.execCommand("styleWithCSS",!1,"true"));const u=fy(Object.keys(s));return u.monospace?.active&&e==="link"&&o.push(d9()),o.push(typeof r=="function"?r():document.execCommand(r,!1,null)),o.push(document.execCommand("styleWithCSS",!1,"false")),c(),Ld.getInstance().setActiveMarkupButton(),a.removeEventListener("input",_e,d),md(a,"input"),!0}function XP(a){a.querySelectorAll('[style*="font-family"]').forEach(e=>{if(e.style.caretColor){e.style.cssText="";return}const t=e.style.fontFamily;t!==Mv&&(e.classList.add("is-markup"),e.dataset.markup=t,Xr(e),t.includes("quote")&&e.classList.add("quote-like","quote-like-icon","quote-like-border"))}),a.querySelectorAll(".is-markup").forEach(e=>{const t=e.style.fontFamily;t&&t!==Mv||(t.includes("quote")||e.classList.remove("quote-like","quote-like-icon","quote-like-border"),e.classList.remove("is-markup"),delete e.dataset.markup)})}function d9(){return document.execCommand("removeFormat",!1,null)}function h9(){return document.execCommand("fontName",!1,Mv)}function u9(a,e){const t={KeyB:"bold",KeyI:"italic",KeyU:"underline",KeyS:"strikethrough",KeyM:"monospace",KeyP:"spoiler"};t.KeyK="link";const s=e.code,i=t[s],n=document.getSelection();!Fc(n)&&i&&(s==="KeyK"?Ld.getInstance().showLinkEditor():vy(a,i),_e(e))}function yy(a,e){if(a.length<e)return[a];let t=0,s=0,i=0;const n=" ",r=[],o=c=>{let d=a.slice(s,c);const u=i++;if(d.length>e){const h=d.slice(e);yy(h,e).forEach(m=>{r[i++]=m}),d=d.slice(0,e)}s=c,t=0,r[u]=(r[u]||"")+d};let l=0;do{let c=a.indexOf(n,l);if(c===-1){l!==a.length-1&&o();break}c+=n.length;const d=c-l;t+d>e&&o(t),l=c,t+=d}while(!0);return r}const p9=500,m9=!1,gl={send_voices:"GlobalAttachVoiceRestricted",send_stickers:"GlobalAttachStickersRestricted",send_gifs:"GlobalAttachGifRestricted",send_media:"GlobalAttachMediaRestricted",send_plain:"GlobalSendMessageRestricted",send_polls:"ErrorSendRestrictedPollsAll",send_inline:"GlobalAttachInlineRestricted"},Rp="chat-input",lc=new Set([we.Scheduled,we.Stories,we.Saved]),Ah=class Ah{constructor(e,t,s,i){this.chat=e,this.appImManager=t,this.managers=s,this.className=i,this.lastUrl="",this.lastTimeType=0,this.replyElements={},this.willSendWebPage=null,this.webPageOptions={},this.recording=!1,this.recordCanceled=!1,this.recordStartTime=0,this.onAttachClick=async(n,r,o)=>{if(await this.showSlowModeTooltipIfNeeded({element:this.attachMenu}))return;const l=this.fileSelectionPromise=Mt();this.fileInput.value="",l.finally(()=>{qr.removeEventListener("change",c),this.fileSelectionPromise});const c=d=>{if(l!==this.fileSelectionPromise){l.reject();return}d||setTimeout(()=>{l.reject()},1e3)};if(qr.addEventListener("change",c),n)this.fileInput.removeAttribute("accept"),this.willAttachType="document";else{const d=[...r?um:[],...o?Hp:[]].join(", ");this.fileInput.setAttribute("accept",d||"*/*"),this.willAttachType="media"}this.fileInput.click(),this.onFileSelection?.(this.fileSelectionPromise)},this.unblockUser=()=>{const n=this.toggleControlButtonDisability=os([this.unblockBtn],!0),r=this.chat.peerId,o=this.getMiddleware(()=>this.chat.peerId===r&&this.toggleControlButtonDisability===n);this.managers.appUsersManager.toggleBlock(r,!1).then(()=>{o()&&(n(),this.toggleControlButtonDisability=void 0)})},this.startBot=()=>{const{startParam:n}=this,r=this.toggleControlButtonDisability=os([this.botStartBtn],!0),o=this.chat.peerId,l=this.getMiddleware(()=>this.chat.peerId===o&&this.startParam===n&&this.toggleControlButtonDisability===r);this.managers.appMessagesManager.startBot(o.toUserId(),void 0,n).then(()=>{l()&&(r(),this.toggleControlButtonDisability=void 0,this.setStartParam())})},this.onCancelRecordClick=n=>{n&&_e(n),this.recordCanceled=!0,this.recorder.stop(),mp.setKeepAlive(!1)},this.onEmoticonsToggle=n=>{this.btnToggleEmoticons&&(pt?Wo(this.btnToggleEmoticons,n?"keyboard":"smile"):this.btnToggleEmoticons.classList.toggle("active",n))},this.onEmoticonsOpen=()=>{this.onEmoticonsToggle(!0)},this.onEmoticonsClose=()=>{this.onEmoticonsToggle(!1)},this.canSendWhenOnline=async()=>{const n=this.chat.peerId;return I.myId===n||!n.isUser()||!await this.managers.appUsersManager.isUserOnlineVisible(n)?!1:(await this.managers.appUsersManager.getUser(n)).status?._!=="userStatusOnline"},this.scheduleSending=async(n=this.sendMessage.bind(this,!0),r=new Date)=>{const o=this.getMiddleware(),l=await this.canSendWhenOnline();o()&&ue.createPopup(Fb,{initDate:r,onPick:c=>{o()&&this.setScheduleTimestamp(c,n)},canSendWhenOnline:l}).show()},this.onMessageInput=n=>{const{value:r,entities:o,caretPos:l}=xn(this.messageInputField.input),[c,d]=Y0(r,o),u=El(d,Lc(c));if(this.throttledSetMessageCountToBadgeState(r),c9(this.messageInput),this.processWebPage(r,u),!r.trim())this.lastTimeType&&this.managers.appMessagesManager.setTyping(this.chat.peerId,{_:"sendMessageCancelAction"},void 0,this.chat.threadId),Ld.getInstance().hide(),document.activeElement===this.messageInput&&!Gi&&setTimeout(()=>{document.activeElement===this.messageInput&&(this.messageInput.textContent="1",Ki(this.messageInput),this.messageInput.textContent="")},0);else{const p=Date.now();p-this.lastTimeType>=6e3&&n?.isTrusted&&(this.lastTimeType=p,this.managers.appMessagesManager.setTyping(this.chat.peerId,{_:"sendMessageTypingAction"},void 0,this.chat.threadId)),this.botCommands?.toggle(!0)}this.botCommands&&this.updateBotCommandsToggle(),!this.editMsgId&&!this.processingDraftMessage&&this.saveDraftDebounced(),this.checkAutocomplete(r,l,u),XP(this.messageInput),this.updateSendBtn()},this.onEmojiSelected=(n,r)=>{const o=n.docId?{_:"messageEntityCustomEmoji",document_id:n.docId,length:n.emoji.length,offset:0}:HC(n.emoji);return this.insertAtCaret(n.emoji,o,r),!0},this.onBtnSendClick=async n=>{_e(n);const r=this.isInputEmpty();if(this.chat.type===we.Stories&&r&&!this.freezedFocused&&this.canForwardStory){this.forwardStoryCallback?.(n);return}else if(!this.recorder||this.recording||!r||this.forwarding||this.editMsgId)this.recording?Date.now()-this.recordStartTime<p9?this.onCancelRecordClick():this.recorder.stop():this.sendMessage();else{const o=this.chat.peerId.isAnyChat(),l="send_voices";if(o&&!await this.chat.canSend(l)){$e({langPackKey:gl[l]});return}if(await this.showSlowModeTooltipIfNeeded())return;this.chatInput.classList.add("is-locked"),Fa();let c=!1;if(o||(await this.managers.appProfileManager.getProfile(this.chat.peerId.toUserId()))?.pFlags.voice_messages_forbidden&&($e({langPackKey:"Chat.SendVoice.PrivacyError",langPackArguments:[await qe({peerId:this.chat.peerId})]}),c=!0),c){this.chatInput.classList.remove("is-locked");return}this.recorder.start().then(()=>{this.releaseMediaPlayback=rt.setSingleMedia(),this.recordCanceled=!1,this.setRecording(!0),mp.setKeepAlive(!0);const d=()=>{ue.createPopup(mi,"popup-cancel-record",{titleLangKey:"DiscardVoiceMessageTitle",descriptionLangKey:"DiscardVoiceMessageDescription",buttons:[{langKey:"DiscardVoiceMessageAction",callback:()=>{Xs(this.btnCancelRecord)}},{langKey:"Continue",isCancel:!0}]}).show()};this.recordingOverlayListener=this.listenerSetter.add(document.body)("mousedown",y=>{!ne(y.target,Rp)&&!ne(y.target,"popup-cancel-record")&&(_e(y),d())},{capture:!0,passive:!1}),Pt.pushItem(this.recordingNavigationItem={type:"voice",onPop:()=>(setTimeout(()=>{d()},0),!1)}),this.recordStartTime=Date.now();const u=this.recorder.sourceNode,p=u.context.createAnalyser();u.connect(p),p.fftSize=32;const m=new Uint8Array(p.frequencyBinCount),g=m.length*255,f=54/150,v=()=>{if(!this.recording)return;p.getByteFrequencyData(m);let y=0;m.forEach(M=>{y+=M});const w=Math.min(1,y/g+f);this.recordRippleEl.style.transform=`scale(${w})`;const b=Date.now()-this.recordStartTime,S=b%1e3,_=bn(b/1e3)+","+("00"+Math.round(S/10)).slice(-2);this.recordTimeEl.textContent=_,$s(v)};v()}).catch(d=>{switch(d.name){case"NotAllowedError":{Wi("Please allow access to your microphone");break}case"NotReadableError":{Wi(d.message);break}default:console.error("Recorder start error:",d,d.name,d.message),Wi(d.message);break}this.setRecording(!1),this.chatInput.classList.remove("is-locked")})}},this.onHelperCancel=async(n,r)=>{if(n&&_e(n),this.willSendWebPage){const o=this.lastUrl;let l=!1;if(this.helperType&&(await this.helperFunc(),l=!0),this.lastUrl=o,this.noWebPage=!0,this.willSendWebPage=null,l)return}if(this.helperType==="edit"&&!r){const o=this.editMessage,l=this.getCurrentInputAsDraft(!0);l&&delete l.pFlags.no_webpage;const c=o.reply_to?._==="messageReplyHeader"?o.reply_to:void 0,d=o?.media?._==="messageMediaWebPage"?o.media:void 0,u=d?.webpage?.pFlags?.has_large_media,h={_:"draftMessage",date:l?.date,message:o.message,entities:o.entities,pFlags:{invert_media:o.pFlags.invert_media},media:d&&{_:"inputMediaWebPage",pFlags:{force_large_media:u&&d.pFlags.force_large_media||void 0,force_small_media:u&&d.pFlags.force_small_media||void 0,optional:!0},url:d.webpage.url},reply_to:c&&{_:"inputReplyToMessage",reply_to_msg_id:c.reply_to_msg_id}};if(h.entities?.length||l?.entities?.length){const p=new Set(Object.values(r_));p.add("messageEntityCustomEmoji"),h?.entities&&(h.entities=h.entities.slice()),[h,l].forEach(m=>{m?.entities&&(hn(m.entities,(g,f,v)=>{p.has(g._)||v.splice(f,1)}),m.entities.length||delete m.entities)})}if(!Q0(l,h)){ue.createPopup(mi,"discard-editing",{buttons:[{langKey:"Alert.Confirm.Discard",callback:()=>{this.onHelperCancel(void 0,!0)}}],descriptionLangKey:"Chat.Edit.Cancel.Text"}).show();return}}else this.helperType==="reply"&&this.saveDraftDebounced();this.clearHelper(),this.updateSendBtn()},this.onHelperClick=n=>{if(n&&_e(n),n&&!ne(n.target,"reply"))return;let r;this.helperType==="forward"?r=this.forwardElements?.container:this.helperType==="reply"?(this.chat.setMessageId({lastMsgId:this.replyToMsgId}),r=this.replyElements?.menuContainer):this.helperType==="edit"?this.chat.setMessageId({lastMsgId:this.editMsgId}):this.helperType||(r=this.webPageElements?.container),pt&&r&&!r.classList.contains("active")&&Li.openBtnMenu(r)},this.constructStarsState=()=>Ft(n=>{this.getMiddleware().onDestroy(()=>void n());const[o,l]=Qr({inited:!1,inputStarsCountEl:null,hasSendButton:!1,isRecording:!1,messageCount:0,forwarding:0,starsAmount:0}),c=V(()=>o.hasSendButton&&!!o.starsAmount),d=V(()=>!!o.messageCount||!!o.forwarding||o.isRecording),u=V(()=>c()&&d()),h=V(()=>o.starsAmount*Math.max(1,o.forwarding+o.messageCount)),p=V(()=>o.starsAmount);return le(()=>{o.inited&&this.starsBadge.classList.toggle("btn-send-stars-badge--active",u())}),le(()=>{o.inited&&(this.starsBadgeStars.innerText=Jr(h()))}),le(()=>{!o.inited||!o.inputStarsCountEl||!p()||(o.inputStarsCountEl.textContent=Jr(p()))}),{store:o,set:l}}),this.throttledSetMessageCountToBadgeState=eE(async n=>{if(!n?.trim()){this.starsState.set({messageCount:0});return}const r=await this.managers.apiManager.getConfig(),o=yy(n,r.message_length_max);this.starsState.set({messageCount:o.length})},120),this.listenerSetter=new $t,this.hoverListenerSetter=new $t,this.excludeParts={},this.isFocused=!1,this.emoticonsDropdown=Gn}construct(){const e=this.className;this.chatInput=document.createElement("div"),this.chatInput.classList.add(Rp,e,"hide"),this.inputContainer=document.createElement("div"),this.inputContainer.classList.add(`${Rp}-container`,`${e}-container`),this.rowsWrapperWrapper=document.createElement("div"),this.rowsWrapperWrapper.classList.add("rows-wrapper-wrapper"),this.rowsWrapper=document.createElement("div"),this.rowsWrapper.classList.add(...["rows-wrapper",`${Rp}-wrapper`,`${e}-wrapper`,this.chat.type!==we.Stories&&"chat-rows-wrapper"].filter(Boolean)),this.rowsWrapperWrapper.append(this.rowsWrapper);const t=dP(!this.chat.isMainChat);this.rowsWrapper.append(t);const s=this.fakeRowsWrapper=document.createElement("div");s.classList.add("fake-wrapper","fake-rows-wrapper");const i=this.fakeSelectionWrapper=document.createElement("div");i.classList.add("fake-wrapper","fake-selection-wrapper"),this.inputContainer.append(this.rowsWrapperWrapper,s,i),this.chatInput.append(this.inputContainer),this.excludeParts.downButton||this.constructGoDownButton();const n=this.controlContainer=document.createElement("div");n.classList.add("chat-input-control","chat-input-wrapper"),this.inputContainer.append(n),this.paidMessageInterceptor=new _r(this.chat,this.managers),this.getMiddleware().onDestroy(()=>{this.paidMessageInterceptor.dispose()}),this.starsState=this.constructStarsState()}freezeFocused(e){this.freezedFocused!==e&&(this.freezedFocused=e,this.updateSendBtn())}createButtonIcon(...e){this.noRipple&&(e[1]??(e[1]={}),e[1].noRipple=!0);const t=yt(...e);return t.tabIndex=-1,t}constructGoDownButton(){this.goDownBtn=Cn({icon:"arrow_down",className:"bubbles-corner-button chat-secondary-button bubbles-go-down hide"}),this.inputContainer.append(this.goDownBtn),J(this.goDownBtn,e=>{_e(e),this.chat.bubbles.onGoDownClick()},{listenerSetter:this.listenerSetter})}constructReplyElements(){this.replyElements.container=document.createElement("div"),this.replyElements.container.classList.add("reply-wrapper","rows-wrapper-row"),this.replyElements.iconBtn=this.createButtonIcon(""),this.replyElements.cancelBtn=this.createButtonIcon("close reply-cancel",{noRipple:!0}),this.replyElements.container.append(this.replyElements.iconBtn,this.replyElements.cancelBtn),J(this.replyElements.cancelBtn,this.onHelperCancel,{listenerSetter:this.listenerSetter}),J(this.replyElements.container,this.onHelperClick,{listenerSetter:this.listenerSetter});const e=[{icon:"message_jump",text:"ShowMessage",onClick:()=>{this.onHelperClick(),this.replyHover.toggle(!1)}},this.replyElements.replyInAnother={icon:"replace",text:"ReplyToAnotherChat",onClick:()=>this.changeReplyRecipient()},this.replyElements.doNotReply={icon:"delete",text:"DoNotReply",onClick:this.onHelperCancel,danger:!0},this.replyElements.doNotQuote={icon:"delete",text:"DoNotQuote",onClick:this.onHelperCancel,danger:!0}],t=this.replyElements.menuContainer=xa({buttons:e,listenerSetter:this.listenerSetter});pt||(this.replyHover=new Ph({element:t})),this.replyElements.container.append(t)}constructForwardElements(){const e=()=>{i=!0},t=()=>{i=!1},s=this.forwardElements={};let i=!1;const n=[s.showSender={text:"Chat.Alert.Forward.Action.Show1",onClick:e,checkForClose:()=>this.canToggleHideAuthor(),radioGroup:"author"},s.hideSender={text:"Chat.Alert.Forward.Action.Hide1",onClick:e,checkForClose:()=>this.canToggleHideAuthor(),radioGroup:"author"},s.showCaption={text:"Chat.Alert.Forward.Action.ShowCaption",onClick:t,radioGroup:"caption"},s.hideCaption={text:"Chat.Alert.Forward.Action.HideCaption",onClick:t,radioGroup:"caption"},s.changePeer={text:"Chat.Alert.Forward.Action.Another",onClick:()=>{this.changeForwardRecipient()},icon:"replace"},{icon:"delete",text:"DoNotForward",onClick:this.onHelperCancel,danger:!0}],r=s.container=xa({buttons:n,radioGroups:[{name:"author",onChange:o=>{const l=!!+o;i&&(this.forwardWasDroppingAuthor=!l);const c=this.replyElements.container.querySelector(".reply-title");if(c){const d=c.firstElementChild,u=Ne.weakMap.get(d),h=s.showSender.checkboxField.checked?"Chat.Accessory.Forward":"Chat.Accessory.Hidden";u.key=h,u.update()}},checked:0},{name:"caption",onChange:o=>{const l=!!+o;let c;l&&this.forwardWasDroppingAuthor!==void 0?c=this.forwardWasDroppingAuthor?s.hideSender:s.showSender:c=l?s.showSender:s.hideSender,c.checkboxField.checked=!0},checked:0}],listenerSetter:this.listenerSetter});pt||(this.forwardHover=new Ph({element:r})),s.modifyArgs=n.slice(0,-2),this.replyElements.container.append(r)}constructWebPageElements(){this.webPageElements={};const e=[this.webPageElements.above={text:"AboveMessage",onClick:()=>{},radioGroup:"position"},this.webPageElements.below={text:"BelowMessage",onClick:()=>{},radioGroup:"position"},this.webPageElements.larger={text:"LargerMedia",onClick:()=>{},radioGroup:"size"},this.webPageElements.smaller={text:"SmallerMedia",onClick:()=>{},radioGroup:"size"},{text:"WebPage.RemovePreview",onClick:()=>{this.onHelperCancel()},icon:"delete",danger:!0}],t=this.webPageElements.container=xa({buttons:e,radioGroups:[{name:"position",onChange:s=>{this.invertMedia=!!+s,this.saveDraftDebounced?.()},checked:0},{name:"size",onChange:s=>{this.webPageOptions.largeMedia=!!+s,this.webPageOptions.smallMedia=!+s,this.saveDraftDebounced?.()},checked:0}],listenerSetter:this.listenerSetter});pt||(this.webPageHover=new Ph({element:t})),this.replyElements.container.append(t)}constructMentionButton(e){const t=Cn({icon:e?"reactions":"mention",className:"bubbles-corner-button chat-secondary-button bubbles-go-mention bubbles-go-reaction"}),s=xo("span",24,"primary");t.append(s),this.inputContainer.append(t),J(t,i=>{_e(i);const n=this.getMiddleware();this.managers.appMessagesManager.goToNextMention({peerId:this.chat.peerId,threadId:this.chat.threadId,isReaction:e}).then(r=>{n()&&r&&this.chat.setMessageId({lastMsgId:r})})},{listenerSetter:this.listenerSetter}),Dn({buttons:[{icon:"readchats",text:e?"ReadAllReactions":"ReadAllMentions",onClick:()=>{this.managers.appMessagesManager.readMentions(this.chat.peerId,this.chat.threadId,e)}}],listenTo:t,listenerSetter:this.listenerSetter}),e?(this.goReactionUnreadBadge=s,this.goReactionBtn=t):(this.goMentionUnreadBadge=s,this.goMentionBtn=t)}constructScheduledButton(){this.btnScheduled=this.createButtonIcon("scheduled btn-scheduled float hide",{noRipple:!0}),J(this.btnScheduled,e=>{this.appImManager.openScheduled(this.chat.peerId)},{listenerSetter:this.listenerSetter}),this.listenerSetter.add(I)("scheduled_new",({peerId:e})=>{this.chat.peerId===e&&this.btnScheduled.classList.remove("hide")}),this.listenerSetter.add(I)("scheduled_delete",({peerId:e})=>{this.chat.peerId===e&&this.managers.appMessagesManager.getScheduledMessages(this.chat.peerId).then(t=>{this.btnScheduled.classList.toggle("hide",!t.length)})})}constructReplyMarkup(){this.btnToggleReplyMarkup=this.createButtonIcon("botcom toggle-reply-markup float hide",{noRipple:!0}),this.replyKeyboard=new gy({appendTo:this.rowsWrapper,listenerSetter:this.listenerSetter,managers:this.managers,btnHover:this.btnToggleReplyMarkup,chatInput:this}),this.listenerSetter.add(this.replyKeyboard)("open",()=>this.btnToggleReplyMarkup.classList.add("active")),this.listenerSetter.add(this.replyKeyboard)("close",()=>this.btnToggleReplyMarkup.classList.remove("active"))}constructBotCommands(){this.botCommands=new n9(this.rowsWrapper,this,this.managers),this.botCommandsToggle=document.createElement("div"),this.botCommandsToggle.classList.add("new-message-bot-commands"),this.botCommandsToggle.append(Be("webview","new-message-bot-commands-view-icon"));const e=document.createElement("div");e.classList.add("new-message-bot-commands-icon-scale");const t=this.botCommandsIcon=document.createElement("div");t.classList.add("animated-menu-icon","animated-menu-close-icon"),e.append(t),this.botCommandsView=document.createElement("div"),this.botCommandsView.classList.add("new-message-bot-commands-view"),this.botCommandsToggle.append(e,this.botCommandsView);let s=0,i=!1;J(this.botCommandsToggle,n=>{_e(n);const r=this.chat.peerId.toUserId(),{botMenuButton:o}=this;if(o){if(i)return;const d=++s;i=!0,Promise.resolve().then(()=>{if(s===d)return this.chat.openWebApp({botId:r,url:o.url,buttonText:o.text,fromBotMenu:!0})}).finally(()=>{s===d&&(i=!1)});return}const l=this.getMiddleware();t.classList.contains("state-back")?this.botCommands.toggle(!0):this.botCommands.setUserId(r,l)},{listenerSetter:this.listenerSetter}),this.botCommands.addEventListener("visible",()=>{t.classList.add("state-back")}),this.botCommands.addEventListener("hiding",()=>{t.classList.remove("state-back")})}constructRecorder(){const e=window.Recorder;if(e)try{this.recorder=new e({encoderSampleRate:48e3,monitorGain:0,numberOfChannels:1,recordingGain:1,reuseWorker:!0})}catch(t){console.error("Recorder constructor error:",t)}this.recorder&&(J(this.btnCancelRecord,this.onCancelRecordClick,{listenerSetter:this.listenerSetter}),this.recorder.onstop=()=>{this.setRecording(!1),this.chatInput.classList.remove("is-locked"),this.recordRippleEl.style.transform=""},this.recorder.ondataavailable=async t=>{if(this.releaseMediaPlayback&&(this.releaseMediaPlayback(),this.releaseMediaPlayback=void 0),this.recordingOverlayListener&&(this.listenerSetter.remove(this.recordingOverlayListener),this.recordingOverlayListener=void 0),this.recordingNavigationItem&&(Pt.removeItem(this.recordingNavigationItem),this.recordingNavigationItem=void 0),this.recordCanceled)return;const s=this.chat.getMessageSendingParams(),i=await this.paidMessageInterceptor.prepareStarsForPayment(1);if(i===Fn)return;s.confirmedPaymentResult=i;const n=(Date.now()-this.recordStartTime)/1e3|0,r=new Blob([t],{type:"audio/ogg"});mp.decode(t,!0).then(o=>{mp.setKeepAlive(!1),this.managers.appMessagesManager.sendFile({...s,file:r,isVoiceMessage:!0,isMedia:!0,duration:n,waveform:o.waveform,objectURL:o.url,clearDraft:!0}),this.onMessageSent(!1,!0)})})}constructPeerHelpers(){this.excludeParts.reply||(this.constructReplyElements(),this.excludeParts.forwardOptions||(this.constructForwardElements(),this.constructWebPageElements())),this.newMessageWrapper=document.createElement("div"),this.newMessageWrapper.classList.add("new-message-wrapper","rows-wrapper-row"),this.excludeParts.emoticons||(this.btnToggleEmoticons=this.createButtonIcon("smile toggle-emoticons",{noRipple:!0})),this.inputMessageContainer=document.createElement("div"),this.inputMessageContainer.classList.add("input-message-container"),this.goDownBtn&&(this.goDownUnreadBadge=xo("span",24,"primary"),this.goDownBtn.append(this.goDownUnreadBadge)),this.excludeParts.mentionButton||(this.constructMentionButton(),this.constructMentionButton(!0)),this.excludeParts.scheduled||this.constructScheduledButton(),this.excludeParts.replyMarkup||this.constructReplyMarkup(),this.excludeParts.botCommands||this.constructBotCommands(),this.attachMenuButtons=[{icon:"image",text:"Chat.Input.Attach.PhotoOrVideo",onClick:()=>this.onAttachClick(!1,!0,!0)},{icon:"document",text:"Chat.Input.Attach.Document",onClick:()=>this.onAttachClick(!0)},{icon:"gift",text:"GiftPremium",onClick:()=>this.chat.appImManager.giftPremium(this.chat.peerId),verify:()=>this.chat&&Promise.all([this.chat.canGiftPremium(),this.managers.apiManager.getAppConfig()]).then(([i,{premium_gift_attach_menu_icon:n}])=>i&&n)},{icon:"poll",text:"Poll",onClick:async()=>{const i="send_polls";if(!await this.chat.canSend(i)){$e({langPackKey:gl[i]});return}ue.createPopup(j$,this.chat).show()},verify:()=>this.chat.peerId.isAnyChat()||this.chat.isBot}];const e=this.attachMenuButtons.slice();this.attachMenu=ki({buttonOptions:{noRipple:!0},listenerSetter:this.listenerSetter,direction:"top-left",buttons:this.attachMenuButtons,onOpenBefore:this.excludeParts.attachMenu?void 0:async()=>{const i=await this.managers.appAttachMenuBotsManager.getAttachMenuBots(),n=e.slice(),r=i.filter(o=>o.pFlags.show_in_attach_menu).map(o=>{const l=hw(o);return{regularText:je(o.short_name),onClick:()=>{this.chat.openWebApp({attachMenuBot:o,fromAttachMenu:!0})},iconDoc:l?.icon,verify:async()=>{let d=!1;const u={attachMenuPeerTypeSameBotPM:()=>this.chat.peerId.toUserId()===o.bot_id,attachMenuPeerTypeBotPM:()=>this.chat.isBot,attachMenuPeerTypePM:()=>this.chat.peerId.isUser(),attachMenuPeerTypeChat:()=>this.chat.isAnyGroup,attachMenuPeerTypeBroadcast:()=>this.chat.isBroadcast};for(const h of o.peer_types){const p=u[h._];if(d=await p(),d)break}return d}}});n.splice(n.length,0,...r),this.attachMenuButtons.splice(0,this.attachMenuButtons.length,...n)},onOpen:()=>{this.emoticonsDropdown?.toggle(!1),this.onMenuToggle?.(!0)},onClose:()=>{this.onMenuToggle?.(!1)}}),this.attachMenu.classList.add("attach-file"),this.attachMenu.firstElementChild.replaceWith(Be("attach")),this.recordTimeEl=document.createElement("div"),this.recordTimeEl.classList.add("record-time"),this.fileInput=document.createElement("input"),this.fileInput.type="file",this.fileInput.multiple=!0,this.fileInput.style.display="none",this.newMessageWrapper.append(...[this.botCommandsToggle,this.btnToggleEmoticons,this.inputMessageContainer,this.btnScheduled,this.btnToggleReplyMarkup,this.attachMenu,this.recordTimeEl,this.fileInput].filter(Boolean)),this.replyElements?.container&&this.rowsWrapper.append(this.replyElements.container),this.autocompleteHelperController=new X$,this.stickersHelper=new q$(this.rowsWrapper,this.autocompleteHelperController,this.chat,this.managers),this.emojiHelper=new Y$(this.rowsWrapper,this.autocompleteHelperController,this,this.managers),this.excludeParts.commandsHelper||(this.commandsHelper=new Q$(this.rowsWrapper,this.autocompleteHelperController,this,this.managers)),this.mentionsHelper=new Z$(this.rowsWrapper,this.autocompleteHelperController,this,this.managers),this.inlineHelper=new s9(this.rowsWrapper,this.autocompleteHelperController,this.chat,this.managers),this.rowsWrapper.append(this.newMessageWrapper),this.btnCancelRecord=this.createButtonIcon("binfilled btn-circle btn-record-cancel chat-input-secondary-button chat-secondary-button"),this.btnSendContainer=document.createElement("div"),this.btnSendContainer.classList.add("btn-send-container"),this.recordRippleEl=document.createElement("div"),this.recordRippleEl.classList.add("record-ripple"),this.btnSend=this.createButtonIcon(),this.btnSend.classList.add("btn-circle","btn-send","animated-button-icon");const t=[["send","send"],["schedule","schedule"],["check","edit"],["microphone_filled","record"],["forward_filled","forward"]];this.btnSend.append(...t.map(([i,n])=>Be(i,"animated-button-icon-icon","btn-send-icon-"+n))),this.addStarsBadge(),this.btnSendContainer.append(this.recordRippleEl,this.btnSend),Ft(i=>{this.chat.destroyMiddlewareHelper.onDestroy(i);const[n,r]=K();this.effect=n,this.setEffect=r,this.btnSendContainer.append(AI({effect:this.effect}))}),this.sendMenu=new cw({onSilentClick:()=>{this.sendSilent=!0,this.sendMessage()},onScheduleClick:()=>{this.scheduleSending(void 0)},onSendWhenOnlineClick:()=>{this.setScheduleTimestamp(Nh,this.sendMessage.bind(this,!0))},middleware:this.chat.destroyMiddlewareHelper.get(),openSide:"top-left",onContextElement:this.btnSend,onOpen:()=>{const i=this.chat.type!==we.Scheduled&&(!this.isInputEmpty()||!!Object.keys(this.forwarding).length)&&!this.editMsgId;return i&&this.emoticonsDropdown?.toggle(!1),i},canSendWhenOnline:this.canSendWhenOnline,onRef:i=>{this.btnSendContainer.append(i)},withEffects:()=>this.chat.peerId.isUser()&&this.chat.peerId!==I.myId,effect:this.effect,onEffect:this.setEffect}),this.inputContainer.append(...[this.btnReaction,this.btnCancelRecord,this.btnSendContainer].filter(Boolean)),this.btnToggleEmoticons&&(this.emoticonsDropdown.attachButtonListener(this.btnToggleEmoticons,this.listenerSetter),this.listenerSetter.add(this.emoticonsDropdown)("open",this.onEmoticonsOpen),this.listenerSetter.add(this.emoticonsDropdown)("close",this.onEmoticonsClose),Gn===this.emoticonsDropdown&&Ft(i=>{this.chat.destroyMiddlewareHelper.onDestroy(i),le(()=>{const n=It.height>=570&&It.width>600;this.emoticonsDropdown.getElement().classList.toggle("is-under",!n)})})),this.attachMessageInputField(),this.listenerSetter.add(I)("settings_updated",()=>{(this.stickersHelper||this.emojiHelper)&&(this.previousQuery="",this.checkAutocomplete()),this.messageInputField?.onFakeInput()}),this.chat&&this.setChatListeners(),this.constructRecorder(),this.updateSendBtn(),this.listenerSetter.add(this.fileInput)("change",i=>{const n=i.target.files,r=Array.from(n).slice();if(this.fileSelectionPromise.resolve(r),!r.length)return;const o=au();o?o.addFiles(r):ue.createPopup(Ao,this.chat,r,this.willAttachType),this.fileInput.value=""},!1),J(this.btnSend,this.onBtnSendClick,{listenerSetter:this.listenerSetter,touchMouseDown:!0}),this.saveDraftDebounced=$i(()=>this.saveDraft(),2500,!1,!0);const s=i=>{const n=ot("btn-primary btn-transparent text-bold chat-input-control-button");return n.append(i instanceof HTMLElement?i:P(i)),n};this.botStartBtn=s("BotStart"),this.unblockBtn=s("Unblock"),this.joinBtn=this.chat.topbar&&s("ChannelJoin"),this.onlyPremiumBtnText=new Ne.IntlElement({key:"Chat.Input.PremiumRequiredButton",args:[0,document.createElement("a")]}),this.onlyPremiumBtn=s(this.onlyPremiumBtnText.element),J(this.botStartBtn,this.startBot,{listenerSetter:this.listenerSetter}),J(this.unblockBtn,this.unblockUser,{listenerSetter:this.listenerSetter}),J(this.onlyPremiumBtn,()=>{rs.show()},{listenerSetter:this.listenerSetter}),this.joinBtn&&J(this.joinBtn,this.chat.topbar.onJoinClick.bind(this.chat.topbar,this.joinBtn),{listenerSetter:this.listenerSetter}),this.pinnedControlBtn=ot("btn-primary btn-transparent text-bold chat-input-control-button",{icon:"unpin"}),this.listenerSetter.add(this.pinnedControlBtn)("click",()=>{const i=this.chat.peerId;ue.createPopup(ru,i,0,!0,()=>{this.chat.appImManager.setPeer({isDeleting:!0});const n=this.chat.appImManager.chat;n.topbar.pinnedMessage&&n.topbar.pinnedMessage.pinnedMessageContainer.toggle(!0)})}),this.openChatBtn=s("OpenChat"),J(this.openChatBtn,()=>{this.chat.appImManager.setInnerPeer({peerId:this.chat.threadId})},{listenerSetter:this.listenerSetter}),this.controlContainer.append(...[this.botStartBtn,this.unblockBtn,this.joinBtn,this.onlyPremiumBtn,this.replyInTopicOverlay,this.pinnedControlBtn,this.openChatBtn].filter(Boolean))}setChatListeners(){this.listenerSetter.add(I)("draft_updated",({peerId:e,threadId:t,draft:s,force:i})=>{this.chat.threadId!==t||this.chat.peerId!==e||lc.has(this.chat.type)||this.setDraft(s,!0,i)}),this.listenerSetter.add(this.appImManager)("peer_changing",e=>{this.chat===e&&(this.chat.type===we.Chat||this.chat.type===we.Discussion)&&this.saveDraft()}),this.listenerSetter.add(this.appImManager)("chat_changing",({from:e,to:t})=>{this.chat===e?this.autocompleteHelperController.toggleListNavigation(!1):this.chat===t&&this.autocompleteHelperController.toggleListNavigation(!0)}),this.listenerSetter.add(I)("scheduled_delete",({peerId:e,mids:t})=>{this.chat.type===we.Scheduled&&this.chat.peerId===e&&t.includes(this.editMsgId)&&this.onMessageSent()}),this.listenerSetter.add(I)("history_delete",({peerId:e,msgs:t})=>{this.chat.peerId===e&&!lc.has(this.chat.type)&&(t.has(this.editMsgId)&&this.onMessageSent(),this.replyToMsgId&&t.has(this.replyToMsgId)&&this.clearHelper("reply"))}),this.listenerSetter.add(I)("dialogs_multiupdate",e=>{e.has(this.chat.peerId)&&(this.chat.type===we.Chat||this.chat.type===we.Discussion)&&(this.startParam===s_?this.setStartParam():this.center(!0))})}_center(e,t){if(!e&&!this.inputContainer.classList.contains("is-centering")||e===this.fakeWrapperTo)return;const s=e||this.fakeWrapperTo,i=!!e,n=this.fakeWrapperTo;let r="",o="",l;const c=s.getBoundingClientRect(),d=this.fakeRowsWrapper.getBoundingClientRect(),u=d.width,h=c.width;if(u!==h){const m=h/u,g=(u-h)/2;l=c.left-d.left-g,i&&(r=`translateX(${l}px) scaleX(${m})`,m<1&&(o=""+(16+16*(1-m))+"px"))}this.fakeWrapperTo=e;const p=t?200:0;return Dt({element:this.inputContainer,className:"is-centering",forwards:i,duration:p}),Dt({element:this.rowsWrapperWrapper,className:"is-centering-to-control",forwards:!!(i&&e&&e.classList.contains("chat-input-control")),duration:p}),this.rowsWrapper.style.transform=r,this.rowsWrapper.style.borderRadius=o,{transform:r,borderRadius:o,needTranslateX:n&&(e&&e.classList.contains("chat-input-control")&&n===this.fakeSelectionWrapper||n.classList.contains("chat-input-control"))?l*-.5:l,widthFrom:u,widthTo:h}}async center(e=!1){return this._center(await this.getNeededFakeContainer(),e)}setStartParam(e){this.startParam!==e&&(this.startParam=e,this.center(!0))}isReplyInTopicOverlayNeeded(){return m9}getJoinButtonType(){const{peerId:e,threadId:t}=this.chat;if(e.isUser())return;const s=Ae.getChat(e.toChatId());if(!(!s||!s.pFlags.left||s.pFlags.broadcast)){if(s.pFlags.join_request)return"request";if(s.pFlags.join_to_send||!t)return"join"}}async getNeededFakeContainer(e=this.startParam){if(this.chat.selection?.isSelecting)return this.fakeSelectionWrapper;if(this.chat.type===we.Pinned||this.chat.type===we.Saved&&this.chat.threadId!==this.chat.peerId||await this.chat.isStartButtonNeeded()||this.isReplyInTopicOverlayNeeded()||this.chat.peerId.isUser()&&(this.chat.isUserBlocked||this.chat.isPremiumRequired)||this.getJoinButtonType())return this.controlContainer}getReadyToSend(e){return this.chat.type===we.Scheduled?(this.scheduleSending(e),!0):(e(),!1)}setScheduleTimestamp(e,t){const s=this.getMiddleware(),i=(Date.now()/1e3|0)+10;e<=i&&(e=void 0),this.scheduleDate=e,t(),this.chat.type!==we.Scheduled&&this.chat.type!==we.Stories&&e&&setTimeout(()=>{if(!s())return;ue.getPopups(ga).forEach(r=>r.hide()),this.appImManager.openScheduled(this.chat.peerId)},0)}getMiddleware(...e){return this.chat.bubbles.getMiddleware(...e)}async setUnreadCount(){if(!this.goDownUnreadBadge)return;const e=await this.managers.dialogsStorage.getAnyDialog(this.chat.peerId,this.chat.type===we.Discussion?void 0:this.chat.threadId);if(pr(e))return;const t=e?.unread_count;Ro(this.goDownUnreadBadge,""+(t||""));const s=await this.managers.appNotificationsManager.isPeerLocalMuted({peerId:this.chat.peerId,respectType:!0,threadId:this.chat.threadId});if(this.goDownUnreadBadge.classList.toggle("badge-gray",s),this.goMentionUnreadBadge&&this.chat.type===we.Chat){const i=!!(e?.unread_mentions_count&&e.unread_count);Ro(this.goMentionUnreadBadge,i?""+e.unread_mentions_count:""),this.goMentionBtn.classList.toggle("is-visible",i)}if(this.goReactionUnreadBadge&&this.chat.type===we.Chat){const i=!!e?.unread_reactions_count;Ro(this.goReactionUnreadBadge,i?""+e.unread_reactions_count:""),this.goReactionBtn.classList.toggle("is-visible",i)}}getCurrentInputAsDraft(e){const{value:t,entities:s}=xn(this.messageInputField.input,!0,!1);let i;if(t.length||e||this.replyToMsgId||this.willSendWebPage){const n=this.willSendWebPage,r=this.webPageOptions,o=!!n?.pFlags?.has_large_media,l=this.getReplyTo();i={_:"draftMessage",date:Qs(!0),message:t.trim(),entities:s.length?s:void 0,pFlags:{no_webpage:this.noWebPage,invert_media:this.invertMedia||void 0},reply_to:l?{_:"inputReplyToMessage",reply_to_msg_id:l.replyToMsgId,top_msg_id:this.chat.threadId,reply_to_peer_id:l.replyToPeerId,...l.replyToQuote&&{quote_text:l.replyToQuote.text,quote_entities:l.replyToQuote.entities,quote_offset:l.replyToQuote.offset}}:void 0,media:n?{_:"inputMediaWebPage",pFlags:{force_large_media:o&&r?.largeMedia||void 0,force_small_media:o&&r?.smallMedia||void 0,optional:!0},url:n.url}:void 0,effect:this.effect()}}return i}saveDraft(){if(!this.chat.peerId||this.editMsgId||lc.has(this.chat.type))return;const e=this.getCurrentInputAsDraft();this.managers.appDraftsManager.syncDraft(this.chat.peerId,this.chat.threadId,e)}mentionUser(e,t){Promise.resolve(this.managers.appPeersManager.getPeer(e)).then(s=>{let i="",n;const r=ji(s);r[0]?i="@"+r[0]:(e.isUser()?i=s.first_name||s.last_name:i=s.title,n={_:"messageEntityMentionName",length:i.length,offset:0,user_id:s.id}),i+=" ",this.insertAtCaret(i,n,t)})}destroy(){this.listenerSetter.removeAll(),this.setCurrentHover()}cleanup(e=!0){this.chat&&!this.chat.peerId&&(this.chatInput.classList.add("hide"),this.goDownBtn.classList.add("hide")),ml(),this.lastTimeType=0,this.startParam=void 0,this.toggleControlButtonDisability&&(this.toggleControlButtonDisability(),this.toggleControlButtonDisability=void 0),this.messageInput&&(this.clearInput(),e&&this.clearHelper())}async setDraft(e,t=!0,s=!1){if(!s&&!Pv(this.messageInput)||lc.has(this.chat.type))return!1;if(!e&&(e=await this.managers.appDraftsManager.getDraft(this.chat.peerId,this.chat.threadId),!e))return s&&(this.chat.container.classList.contains("is-helper-active")&&this.t(),this.messageInputField.inputFake.textContent="",this.messageInputField.onFakeInput(!1),(this.chat.bubbles.messagesQueuePromise||Promise.resolve()).then(()=>{$s(()=>{this.onMessageSent()})})),!1;const i=xI(e,{wrappingForPeerId:this.chat.peerId}),n=this.getCurrentInputAsDraft(),r=e.reply_to,o=r?.reply_to_msg_id;return Q0(e,n)?!1:(t&&this.clearHelper(),this.noWebPage=e.pFlags.no_webpage,o&&this.initMessageReply({replyToMsgId:o,replyToPeerId:r.reply_to_peer_id&&it(r.reply_to_peer_id),replyToQuote:r.quote_text&&{text:r.quote_text,entities:r.quote_entities,offset:r.quote_offset}}),this.setInputValue(i,t,t,e),!0)}createSendAs(){if(this.sendAsPeerId=void 0,this.chat&&(this.chat.type===we.Chat||this.chat.type===we.Discussion)){let e=!0;this.sendAs=new jP({managers:this.managers,onReady:(t,s)=>{let i=0;t.parentElement||(this.newMessageWrapper.prepend(t),i=2),this.updateOffset("as",!0,s,i)},onChange:t=>{if(this.sendAsPeerId=t,e){e=!1;return}this.getPlaceholderParams().then(s=>{this.updateMessageInputPlaceholder(s)})}})}else this.sendAs=void 0;return this.sendAs}async finishPeerChange(e){const{peerId:t,startParam:s,middleware:i}=e,{forwardElements:n,btnScheduled:r,replyKeyboard:o,sendMenu:l,goDownBtn:c,chatInput:d,botCommandsToggle:u,attachMenu:h}=this,p=this.sendAs,m=this.createSendAs(),g=this.filterAttachMenuButtons(),[f,v,y,w,b,S,_,M,C,L,E]=await Promise.all([this.managers.appPeersManager.isBroadcast(t),this.managers.appPeersManager.canPinMessage(t),this.managers.appPeersManager.isBot(t),this.chat?.canSend("send_messages")||!0,this.chat?.canSend("send_plain")||!0,this.getNeededFakeContainer(s),Fl(this.managers.acknowledged.appProfileManager.getProfileByPeerId(t)),r?Fl(this.managers.acknowledged.appMessagesManager.getScheduledMessages(t)):void 0,m?(m.setPeerId(t),m.updateManual(!0)):void 0,qe({peerId:t,onlyFirstName:!0}),this.chat.isPremiumRequiredToContact()]),x=this.messageInput?await this.getPlaceholderParams(b):void 0;return()=>{if(d.classList.remove("hide"),c&&(c.classList.toggle("is-broadcast",f),c.classList.remove("hide")),this.goDownUnreadBadge&&this.setUnreadCount(),this.chat?.type===we.Pinned&&d.classList.toggle("can-pin",v),n&&(this.forwardWasDroppingAuthor=!1,n.showCaption.checkboxField.setValueSilently(!0),n.showSender.checkboxField.setValueSilently(!0)),r&&M&&(r.classList.add("hide"),en(M.result,B=>{!i()||!B||r.classList.toggle("hide",!B.length)})),this.newMessageWrapper&&this.updateOffset(null,!1,!0),u&&(this.hasBotCommands=void 0,this.botMenuButton=void 0,this.botCommands.toggle(!0,void 0,!0),this.updateBotCommandsToggle(!0),u.remove(),y)){const B=_.result;en(B,N=>{i()&&this.updateBotCommands(N,!(B instanceof Promise))})}p?.destroy(),C?.(),o?.setPeer(t),l?.setPeerParams({peerId:t,isPaid:!!this.chat.starsAmount});let R=!1;if(this.chat&&this.joinBtn){const B=this.getJoinButtonType(),N=!R&&!!B;R||(R=N),this.joinBtn.classList.toggle("hide",!N),this.joinBtn.replaceChildren(P(B==="request"?"ChannelJoinRequest":"ChannelJoin"))}if(this.chat&&this.pinnedControlBtn){const B=!R&&this.chat.type===we.Pinned;R||(R=B),this.pinnedControlBtn.classList.toggle("hide",!B),this.pinnedControlBtn.replaceChildren(P(v?"Chat.Input.UnpinAll":"Chat.Pinned.DontShow"))}if(this.chat&&this.openChatBtn){const B=!R&&this.chat.type===we.Saved;if(R||(R=B),B){const N=this.chat.threadId,G=Ae.getPeer(N),O=G.pFlags.broadcast?"OpenChannel2":N.isUser()?G.pFlags.bot?"BotWebViewOpenBot":"OpenChat":"OpenGroup2",$=P(O);this.openChatBtn.querySelector(".i18n").replaceWith($)}this.openChatBtn.classList.toggle("hide",!B)}if(this.chat&&this.onlyPremiumBtn){const B=!R&&!y&&t.isUser()&&E;R||(R=B),this.onlyPremiumBtnText.compareAndUpdate({args:[L,this.onlyPremiumBtnText.args[1]]}),this.onlyPremiumBtn.classList.toggle("hide",!B)}if(this.chat){const B=!R&&!y&&t.isUser();R||(R=B),this.unblockBtn.classList.toggle("hide",!B)}this.botStartBtn.classList.toggle("hide",R),this.messageInput&&(this.updateMessageInput(w||R,b,x,t.isUser()?e.text:void 0,t.isUser()?e.entities:void 0),this.messageInput.dataset.peerId=""+t,g&&h&&g.then(B=>{i()&&(h.toggleAttribute("disabled",!B.length),h.classList.toggle("btn-disabled",!B.length))})),this.messageInputField?.onFakeInput(void 0,!0),this.startParam=s,this._center(S,!1),this.setStarsAmount(this.chat.starsAmount)}}updateOffset(e,t,s,i,n){const r=this.hasOffset,o={type:e,forwards:t};Pn(r,o)&&!n||(this.hasOffset=o,e?this.newMessageWrapper.dataset.offset=e:delete this.newMessageWrapper.dataset.offset,!(r?.forwards===o.forwards&&!n)&&Dt({element:this.newMessageWrapper,className:"has-offset",forwards:t,duration:s?0:300,useRafs:i}))}updateBotCommands(e,t){const s=e.bot_info,i=s?.menu_button;this.hasBotCommands=!!s?.commands?.length,this.botMenuButton=i?._==="botMenuButton"?i:void 0,St(this.botCommandsView,this.botMenuButton?je(this.botMenuButton.text):""),this.botCommandsIcon.classList.toggle("hide",!!this.botMenuButton),this.botCommandsView.classList.toggle("hide",!this.botMenuButton),this.botCommandsToggle.classList.toggle("is-view",!!this.botMenuButton),this.updateBotCommandsToggle(t)}updateBotCommandsToggle(e){const{botCommandsToggle:t,hasBotCommands:s,botMenuButton:i}=this,n=!!(s||i),r=this.isInputEmpty(),o=n&&(r||!!i);if(!n){if(!t.parentElement)return;t.remove()}const l=o,c=t.parentElement?0:2;if(i&&r){const d=Dl(i.text,$h)+22+20+6;this.newMessageWrapper.style.setProperty("--commands-size",`${Math.ceil(d)}px`)}else this.newMessageWrapper.style.removeProperty("--commands-size");t.parentElement||this.newMessageWrapper.prepend(t),this.updateOffset("commands",l,e,c,!0)}async getPlaceholderParams(e){e??(e=await this.chat.canSend("send_plain"));const{peerId:t,threadId:s,isForum:i,type:n}=this.chat;let r,o,l;if(!e)r="Channel.Persmission.MessageBlock";else if(s&&!i&&!t.isUser())r="Comment";else if(await this.managers.appPeersManager.isBroadcast(t))r="ChannelBroadcast";else if(this.sendAsPeerId!==void 0&&this.sendAsPeerId!==I.myId||await this.managers.appMessagesManager.isAnonymousSending(t))r="SendAnonymously";else if(n===we.Stories)r="Story.ReplyPlaceholder";else if(i&&n===we.Chat&&!s){const c=await this.managers.dialogsStorage.getForumTopic(t,Tu);c?(r="TypeMessageIn",o=[je(c.title)]):r="Message"}else if(this.chat.starsAmount){r="PaidMessages.MessageForStars";const c=document.createElement("span"),d=l=document.createElement("span");c.append(Be("star","input-message-placeholder-stars"),d),o=[c]}else r="Message";return{key:r,args:o,inputStarsCountEl:l}}updateMessageInputPlaceholder({key:e,args:t=[],inputStarsCountEl:s}){const i=Ne.weakMap.get(this.messageInputField.placeholder);if(!i)return;const n=i.key,r=i.args;return i.compareAndUpdateBool({key:e,args:t})&&this.starsState.set({inputStarsCountEl:s}),{oldKey:n,oldArgs:r}}filterAttachMenuButtons(){if(this.attachMenuButtons)return zn(this.attachMenuButtons,e=>e.verify?e.verify():!0)}updateMessageInput(e,t,s,i,n){const{chatInput:r,messageInput:o}=this;r.classList.contains("is-hidden")!==!e&&(r.classList.add("no-transition"),r.classList.toggle("is-hidden",!e),r.offsetLeft,r.classList.remove("no-transition"));const d=e&&!t&&this.restoreInputLock;!d&&this.updateMessageInputPlaceholder(s),d?this.restoreInputLock=()=>{this.updateMessageInputPlaceholder(s),this.messageInput.contentEditable="false"}:!e||!t?(o.contentEditable="false",t||this.messageInputField.onFakeInput(void 0,!0)):(this.restoreInputLock=void 0,o.contentEditable="true",i&&this.managers.appDraftsManager.setDraft(this.chat.peerId,void 0,i,n),this.setDraft(void 0,!1),o.innerHTML||this.messageInputField.onFakeInput(void 0,!0)),this.updateSendBtn()}attachMessageInputField(){const e=this.messageInputField;this.messageInputField=new m1({placeholder:"Message",name:"message",withLinebreaks:!0}),this.messageInputField.input.tabIndex=-1,this.messageInputField.input.classList.replace("input-field-input","input-message-input"),this.messageInputField.inputFake.classList.replace("input-field-input","input-message-input"),this.messageInput=this.messageInputField.input,this.attachMessageInputListeners(),this.messageInput,tE&&sE(this.messageInput),e?(e.input.replaceWith(this.messageInputField.input),e.placeholder.replaceWith(this.messageInputField.placeholder),e.inputFake.replaceWith(this.messageInputField.inputFake)):this.inputMessageContainer.append(this.messageInputField.input,this.messageInputField.placeholder,this.messageInputField.inputFake)}attachMessageInputListeners(){this.listenerSetter.add(this.messageInput)("keydown",e=>{const t=e.key;if(e.isTrusted&&iE(e))_e(e),this.sendMessage();else if(e.ctrlKey||e.metaKey)u9(this.messageInput,e);else if((t==="PageUp"||t==="PageDown")&&!e.shiftKey)if(e.preventDefault(),t==="PageUp"){const s=document.createRange(),i=window.getSelection();s.setStart(this.messageInput.childNodes[0]||this.messageInput,0),s.collapse(!0),i.removeAllRanges(),i.addRange(s)}else Ki(this.messageInput)}),J(this.messageInput,e=>{if(!this.canSendPlain()){$e({langPackKey:gl.send_plain});return}const t=(i,n)=>{const r=n.getBoundingClientRect(),o=i.clientX,l=i.clientY;return o>r.right-20&&o<r.right&&l>r.top&&l<r.top+20},s=ne(e.target,"can-send-collapsed");if(s&&t(e,s)){s.dataset.collapsed?delete s.dataset.collapsed:s.dataset.collapsed="1",$e({langPackKey:s.dataset.collapsed?"Input.Quote.Collapsed":"Input.Quote.Expanded"});return}},{listenerSetter:this.listenerSetter}),pt&&J(this.messageInput,e=>{if(this.emoticonsDropdown.isActive()){this.emoticonsDropdown.toggle(!1),Fa(),_e(e);return}this.chat.isStandalone||this.appImManager.selectTab(pd.CHAT)},{listenerSetter:this.listenerSetter}),this.listenerSetter.add(this.messageInput)("input",this.onMessageInput),this.listenerSetter.add(this.messageInput)("keyup",()=>{this.checkAutocomplete()}),this.listenerSetter.add(this.messageInput)("focusin",()=>{this.isFocused=!0,(this.chat.type===we.Chat||this.chat.type===we.Discussion)&&this.chat.bubbles.scrollable.loadedAll.bottom&&this.managers.appMessagesManager.readAllHistory(this.chat.peerId,this.chat.threadId),this.onFocusChange?.(!0)}),this.listenerSetter.add(this.messageInput)("focusout",()=>{this.isFocused=!1,this.onFocusChange?.(!1)})}canSendPlain(){return this.messageInput.isContentEditable&&!this.chatInput.classList.contains("is-hidden")}processWebPage(e,t,s=this.processingDraftMessage||this.editMessage){const i=s?.media,n=s?.pFlags?.invert_media,r=i?._==="inputMediaWebPage"?i.url:i?.webpage?.url,o=(!i||r)&&t.filter(u=>u._==="messageEntityUrl"||u._==="messageEntityTextUrl");if(!o?.length){this.lastUrl&&(this.lastUrl="",delete this.noWebPage,this.willSendWebPage=null,this.helperType?this.helperFunc():this.clearHelper());return}let l=r;if(!l)for(const u of o){let h;if(u._==="messageEntityTextUrl")h=u.url;else if(h=e.slice(u.offset,u.offset+u.length),!(h.includes("http://")||h.includes("https://")))continue;l=h;break}if(this.lastUrl===l)return;if(!l){this.willSendWebPage&&this.onHelperCancel();return}this.lastUrl=l;const c=r,d=this.getWebPagePromise=Promise.all([this.managers.appWebPagesManager.getWebPage(l),this.chat.canSend("embed_links")]).then(([u,h])=>{if(this.getWebPagePromise===d&&(this.getWebPagePromise=void 0),this.lastUrl===l)if(u?._==="webPage"&&h){const p=this.setTopInfo({type:"webpage",callerFunc:()=>{},title:u.site_name||u.title||"Webpage",subtitle:u.description||u.url||""});if(this.setCurrentHover(this.webPageHover,p),delete this.noWebPage,this.willSendWebPage=u,this.webPageElements){const m=c&&n?this.webPageElements.above:this.webPageElements.below;m.checkboxField.checked=!0;const g=c&&i.pFlags.force_small_media?this.webPageElements.smaller:this.webPageElements.larger;g.checkboxField.checked=!0,g.element.parentElement.classList.toggle("hide",!u.pFlags.has_large_media)}this.webPageOptions={optional:!0,...c?{smallMedia:c&&i.pFlags.force_small_media||void 0,largeMedia:c&&i.pFlags.force_large_media||void 0}:{}}}else this.willSendWebPage&&this.onHelperCancel()})}insertAtCaret(e,t,s=!0){if(!this.canSendPlain()){$e({langPackKey:gl.send_plain});return}Jy.getInstance().makeFocused(this.messageInput);const{value:i,caretPos:n,entities:r}=xn(this.messageInput),o=n>=0?n:i.length,l=i.substr(0,o);i.substr(o);const c=s?l.match(Ah.AUTO_COMPLETE_REG_EXP):null,d=c?c.index+(c[0].length-c[2].length):l.length;if(l.slice(0,d),s&&n!==-1){const u=c?c[2]:i,h=document.getSelection();let p=0;for(;h.toString()!==u;){if(++p>=1e4)throw new Error("lolwhat");h.modify("extend","backward","character")}}nE(this.messageInput,e,t?[t]:void 0,this.chat.peerId)}async checkAutocomplete(e,t,s){const i=e!==void 0;if(!i){const l=xn(this.messageInputField.input,!0,!0);e=l.value,t=l.caretPos,s=l.entities}if(t===-1&&(t=e.length),s===void 0||!i){const[l,c]=Y0(e,s);s=El(c,Lc(l))}if(e=e.slice(0,t),this.previousQuery===e)return;this.previousQuery=e;const n=e.match(Ah.AUTO_COMPLETE_REG_EXP);let r;if(n){const l=s[0];let c=n[2];const d=c[0];if(this.stickersHelper&&I.settings.stickers.suggest!=="none"&&await this.chat.canSend("send_stickers")&&["messageEntityEmoji","messageEntityCustomEmoji"].includes(l?._)&&l.length===e.length&&!l.offset)r=this.stickersHelper,this.stickersHelper.checkEmoticon(e);else if(d==="@"){const u=this.chat.threadId?An(this.chat.threadId):void 0;this.mentionsHelper.checkQuery(c,this.chat.peerId.isUser()?Wt:this.chat.peerId,u,this.globalMentions)&&(r=this.mentionsHelper)}else!n[1]&&d==="/"?this.commandsHelper&&await this.commandsHelper.checkQuery(c,this.chat.peerId)&&(r=this.commandsHelper):I.settings.emoji.suggest&&(c=c.replace(/^\s*/,""),!e.match(/^\s*:(.+):\s*$/)&&!e.match(/:[;!@#$%^&*()-=|]/)&&c&&(r=this.emojiHelper,this.emojiHelper.checkQuery(c,d)))}let o;r||(o=await this.chat.canSend("send_inline")),r=this.checkInlineAutocomplete(e,o,r),this.autocompleteHelperController.hideOtherHelpers(r)}checkInlineAutocomplete(e,t,s){let i=!1;const n=r=>{this.btnPreloader&&(r&&!t&&(r=!1),Dt({element:this.btnPreloader,className:"show",forwards:r,duration:400}))};if(!s){const r=e.match(/^@([a-zA-Z\\d_]{3,32})\s/);if(r){const o=r[1],l=e.slice(r[0].length);i=r[0].length===e.length,s=this.inlineHelper,this.btnPreloader?n(!0):(this.btnPreloader=this.createButtonIcon("none btn-preloader float show disable-hover",{noRipple:!0}),Yn(this.btnPreloader,!0),this.inputMessageContainer.parentElement.insertBefore(this.btnPreloader,this.inputMessageContainer.nextSibling)),this.inlineHelper.checkQuery(this.chat.peerId,o,l,t).then(({user:c,renderPromise:d})=>{i&&c.bot_inline_placeholder&&(this.messageInput.dataset.inlinePlaceholder=c.bot_inline_placeholder),d.then(()=>{n(!1)})}).catch(c=>{n(!1)})}}return i||delete this.messageInput.dataset.inlinePlaceholder,s!==this.inlineHelper&&n(!1),s}setRecording(e){this.recording!==e&&(this.recording=e,this.starsState.set({isRecording:e}),this.setShrinking(this.recording,["is-recording"]),this.updateSendBtn(),this.onRecording?.(e))}setShrinking(e,t){e||(e=this.recording),Dt({element:this.chatInput,className:"is-shrinking"+(t?" "+t.join(" "):""),forwards:e,duration:200})}setCanForwardStory(e){this.canForwardStory=e||!0,this.updateSendBtn()}async showSlowModeTooltipIfNeeded({container:e,element:t,sendingFew:s,textOverflow:i}={}){const{peerId:n}=this.chat;if(n.isUser())return!1;const r=n.toChatId();if(!Ae.getChat(r).pFlags.slowmode_enabled)return!1;let l,c;if(i)l=P("SlowmodeSendErrorTooLong");else if(s)l=P("SlowmodeSendError");else if(await this.managers.appMessagesManager.hasOutgoingMessage(n))l=P("SlowmodeSendError");else{const u=await this.managers.appProfileManager.getChatFull(r),h=()=>Math.max(0,(u.slowmode_next_send_date||0)-Qs(!0));if(!h())return!1;const p=document.createElement("span");c=j1(()=>{const m=h();p.replaceChildren(S_(m)),m||d()},!0),l=P("SlowModeHint",[p])}const{close:d}=Ra({element:t||this.btnSendContainer,vertical:"top",container:e||this.btnSendContainer.parentElement,textElement:l,onClose:()=>{c?.(),this.emoticonsDropdown.setIgnoreMouseOut("tooltip",!1)},auto:!0});return this.emoticonsDropdown.setIgnoreMouseOut("tooltip",!0),!0}changeForwardRecipient(){if(this.helperWaitingForward||!this.helperFunc)return;this.helperWaitingForward=!0;const e=kn(this.forwarding),t=this.helperFunc;this.clearHelper(),this.updateSendBtn();let s=!1;ue.createPopup(kr,e,()=>{s=!0}).addEventListener("close",()=>{this.helperWaitingForward=!1,s||t()})}async changeReplyRecipient(){if(this.helperWaitingReply)return;this.helperWaitingReply=!0;const e=this.getReplyTo();e.replyToPeerId??(e.replyToPeerId=this.chat.peerId);const t=this.helperFunc;this.clearHelper(),this.updateSendBtn();try{await this.createReplyPicker(e)}catch{t()}this.helperWaitingReply=!1}async createReplyPicker(e){const t=await Rs.createReplyPicker();this.appImManager.setInnerPeer({peerId:t}).then(()=>{this.appImManager.chat.input.initMessageReply(e)})}getReplyTo(){if(!this.replyToMsgId&&!this.replyToStoryId)return;const{replyToMsgId:e,replyToStoryId:t,replyToQuote:s,replyToPeerId:i}=this;return{replyToMsgId:e,replyToStoryId:t,replyToQuote:s,replyToPeerId:i}}async clearInput(e=!0,t=!0,s=""){if(document.activeElement===this.messageInput&&wr){const n=document.createElement("input");document.body.append(n),qw(n),this.messageInputField.setValueSilently(s),qw(this.messageInput),n.remove()}else this.messageInputField.setValueSilently(s);pt||l9(this.messageInput),this.setEffect();let i=!1;e&&(i=await this.setDraft(void 0,!1)),!i&&t&&this.onMessageInput()}isInputEmpty(){return Pv(this.messageInput)}updateSendBtn(){let e;const t=this.isInputEmpty();this.chat.type===we.Stories&&t&&!this.freezedFocused&&this.canForwardStory?e="forward":this.editMsgId?e="edit":!this.recorder||this.recording||!t||this.forwarding?e=this.chat.type===we.Scheduled?"schedule":"send":e="record",["send","record","edit","schedule","forward"].forEach(s=>{this.btnSend.classList.toggle(s,e===s)}),this.starsState.set({hasSendButton:e==="send",forwarding:Uo(Object.values(this.forwarding||{}).map(s=>s.length),0)}),this.btnScheduled&&this.btnScheduled.classList.toggle("show",t&&this.chat.type!==we.Scheduled),this.btnToggleReplyMarkup&&this.btnToggleReplyMarkup.classList.toggle("show",t&&this.chat.type!==we.Scheduled),this.onUpdateSendBtn?.(e)}async addStarsBadge(){const e=this.starsBadge=document.createElement("span");e.classList.add("btn-send-stars-badge","stars-badge-base");const t=this.starsBadgeStars=document.createElement("span");e.append(Be("star","stars-badge-base__icon"),t),this.btnSendContainer.append(e),this.starsState.set({inited:!0})}async setStarsAmount(e){this.starsState.set({starsAmount:e});const t=await this.getPlaceholderParams(await this.chat?.canSend("send_plain")||!0);this.updateMessageInputPlaceholder(t)}getValueAndEntities(e){const{entities:t,value:s}=xn(e,!0,!1),i=Lc(s),n=El(t,i);return{value:s,totalEntities:n}}onMessageSent(e=!0,t){lc.has(this.chat.type)||this.managers.appMessagesManager.readAllHistory(this.chat.peerId,this.chat.threadId,!0),this.scheduleDate=void 0,this.sendSilent=void 0;const{totalEntities:s}=this.getValueAndEntities(this.messageInput);let i=0;s.filter(r=>{if(r._==="messageEntityEmoji"||r._==="messageEntityCustomEmoji"){const o=r.offset+r.length;return o<=i?!1:(i=o,!0)}return!1}).forEach(r=>{const o=r._==="messageEntityEmoji"?{emoji:eb(r.unicode)}:{docId:r.document_id,emoji:""};this.managers.appEmojiManager.pushRecentEmoji(o)}),e&&(this.lastUrl="",delete this.noWebPage,this.willSendWebPage=null,this.clearInput()),(t||e)&&this.clearHelper(),this.updateSendBtn(),this.onMessageSent2?.()}async sendMessage(e=!1){const{editMsgId:t,chat:s}=this;if(s.type===we.Scheduled&&!e&&!t){this.scheduleSending();return}const{peerId:i}=s,{noWebPage:n}=this,r=this.chat.getMessageSendingParams(),{value:o,entities:l}=xn(this.messageInputField.input,!0,!1),c=o.trim();let d=0;if(s.type!==we.Scheduled&&!t){if(this.forwarding)for(const g in this.forwarding)d+=this.forwarding[g].length;const p=(await this.managers.apiManager.getConfig()).message_length_max,m=o.length>p;if(d+=c?yy(o,p).length:0,await this.showSlowModeTooltipIfNeeded({sendingFew:d>1,textOverflow:m}))return}const u=!t&&d?await this.paidMessageInterceptor.prepareStarsForPayment(d):void 0;if(u!==Fn){if(r.confirmedPaymentResult=u,t){const h=this.editMessage;if(c||h.media)this.managers.appMessagesManager.editMessage(h,o,{entities:l,noWebPage:n,webPage:this.getWebPagePromise?void 0:this.willSendWebPage,webPageOptions:this.webPageOptions,invertMedia:this.willSendWebPage?this.invertMedia:void 0}),this.onMessageSent();else{ue.createPopup(Md,i,[t],s.type);return}}else c&&(this.managers.appMessagesManager.sendText({...r,text:o,entities:l,noWebPage:n,webPage:this.getWebPagePromise?void 0:this.willSendWebPage,webPageOptions:this.webPageOptions,invertMedia:this.willSendWebPage?this.invertMedia:void 0,clearDraft:!0}),lc.has(this.chat.type)?this.onMessageSent(!0):this.onMessageSent(!1,!1));if(this.forwarding){const h=kn(this.forwarding);for(const p in h)this.managers.appMessagesManager.forwardMessages({...r,fromPeerId:p.toPeerId(),mids:h[p],dropAuthor:this.forwardElements&&this.forwardElements.hideSender.checkboxField.checked,dropCaptions:this.isDroppingCaptions()}).catch(async m=>{m.type==="VOICE_MESSAGES_FORBIDDEN"&&$e({langPackKey:"Chat.SendVoice.PrivacyError",langPackArguments:[await qe({peerId:i})]})});o||this.onMessageSent()}}}async sendMessageWithDocument({document:e,force:t=!1,clearDraft:s=!1,silent:i=!1,target:n,ignoreNoPremium:r}){e=await this.managers.appDocsManager.getDoc(e);const o=e.type==="sticker"?"send_stickers":e.type==="gif"?"send_gifs":"send_media";if(this.chat.peerId.isAnyChat()&&!await this.chat.canSend(o))return $e({langPackKey:gl[o]}),!1;if(this.chat.type===we.Scheduled&&!t)return this.scheduleSending(()=>this.sendMessageWithDocument({document:e,force:!0,clearDraft:s,silent:i,target:n})),!1;if(!e)return!1;if(e.sticker&&ql(e)&&!I.premium&&!r)return rs.show({feature:"premium_stickers"}),!1;if(await this.showSlowModeTooltipIfNeeded({element:n}))return!1;const l=this.chat.getMessageSendingParams(),c=await this.paidMessageInterceptor.prepareStarsForPayment(1);if(c!==Fn)return l.confirmedPaymentResult=c,this.managers.appMessagesManager.sendFile({...l,file:e,isMedia:!0,clearDraft:s,silent:i}),this.onMessageSent(s,!0),e.type==="sticker"&&this.managers.appStickersManager.saveRecentSticker(e.id),!0}canToggleHideAuthor(){const{forwardElements:e}=this;if(!e)return!1;const t=e.hideCaption.checkboxField;return!t.checked||Mn(t.label,"FORM").classList.contains("hide")}isDroppingCaptions(){return!this.canToggleHideAuthor()}initMessageEditing(e){const t=this.chat.getMessage(e);let s=ug(t.message,{entities:t.totalEntities,wrappingForPeerId:this.chat.peerId});const i=async()=>{let n;if(!this.messageInput.isContentEditable){const o=await this.getPlaceholderParams(!0),{contentEditable:l}=this.messageInput;this.messageInput.contentEditable="true";const{oldKey:c,oldArgs:d}=this.updateMessageInputPlaceholder(o);n=()=>{this.messageInput.contentEditable=l,this.updateMessageInputPlaceholder({key:c,args:d})}}const r=await To({message:t,usingMids:[t.mid]});this.setTopInfo({type:"edit",callerFunc:i,title:P("AccDescrEditing"),subtitle:r,input:s,message:t}),this.editMsgId=e,this.editMessage=t,s=void 0,this.restoreInputLock=n};i()}initMessagesForward(e){const t=async()=>{const s=Object.keys(e).map(S=>S.toPeerId()),i=new Set;let n=0,r=0;const o=s.map(async S=>{const _=e[S],M=_.map(async C=>{const L=await this.managers.appMessagesManager.getMessageByPeer(S,C);Aa(L.fwd_from)&&!L.fromId&&!L.fwdFromId?i.add("N"+Aa(L.fwd_from)):i.add("P"+L.fromId),L.media&&!["messageMediaWebPage"].includes(L.media._)&&L.message&&++r});await Promise.all(M),n+=_.length});await Promise.all(o);const l=i.size>2,c=[...i].map(S=>{const _=S[0];if(S=S.slice(1),_==="P"){const M=S.toPeerId();return M===I.myId?P("Chat.Accessory.Forward.You"):new Xt({peerId:M,dialog:!1,onlyFirstName:l}).element}else return l?S.split(" ")[0]:S}),{forwardElements:d}=this;Mn(d.showCaption.checkboxField.label,"FORM").classList.toggle("hide",!r);const h=d.hideCaption.checkboxField.checked;r&&h?d.hideSender.checkboxField.setValueSilently(!0):this.forwardWasDroppingAuthor!==void 0&&(this.forwardWasDroppingAuthor?d.hideSender:d.showSender).checkboxField.setValueSilently(!0);const p=d.showSender.checkboxField.checked?"Chat.Accessory.Forward":"Chat.Accessory.Hidden",m=P(p,[n]),g=document.createDocumentFragment();c.length<3?g.append(...Yi(c,!1)):g.append(c[0],P("AndOther",[c.length-1]));let f,v;if(s.length===1){const S=s[0],_=e[S];if(f=await this.managers.appMessagesManager.getMessageByPeer(S,_[0]),v=!!f.grouped_id,v){const M=await this.managers.appMessagesManager.getMidsByMessage(f);(M.length!==n||M.find(C=>!_.includes(C)))&&(v=!1)}}const y=document.createDocumentFragment(),w=": ";if(v||n===1){const S=e[s[0]],_=await To({message:f,usingMids:S});y.append(g,w,_)}else y.append(P("Chat.Accessory.Forward.From"),w,g);const b=this.setTopInfo({type:"forward",callerFunc:t,title:m,subtitle:y});d.modifyArgs.forEach((S,_)=>{const M=S.textElement,C=Ne.weakMap.get(M);C.args=[_<2?s.length:r],C.update()}),this.setCurrentHover(this.forwardHover,b),this.forwarding=e};t()}async initMessageReply(e){if(Pn(this.getReplyTo(),e))return;let{replyToMsgId:t,replyToQuote:s,replyToPeerId:i}=e;i??(i=this.chat.peerId);let n=await(i?this.managers.appMessagesManager.getMessageByPeer(i,t):this.chat.getMessage(t));const r=()=>{let o,l;if(!n)o=P("Loading"),this.managers.appMessagesManager.reloadMessages(i,t).then(d=>{Pn(this.getReplyTo(),e)&&(n=d,n?r():this.clearHelper("reply"))});else{const d=n.fromId;o=new Xt({peerId:n.fromId,dialog:!1,fromName:d?void 0:Aa(n.fwd_from)}).element,o=P(s?"ReplyToQuote":"ReplyTo",[o])}const c=this.setTopInfo({type:"reply",callerFunc:r,title:o,subtitle:l,message:n,setColorPeerId:n?.fromId,quote:n?s:void 0});this.setReplyTo(e),this.replyElements.replyInAnother.element.classList.toggle("hide",!this.chat.bubbles.canForward(n)),this.replyElements.doNotReply.element.classList.toggle("hide",!!s),this.replyElements.doNotQuote.element.classList.toggle("hide",!s),this.setCurrentHover(this.replyHover,c)};r()}setCurrentHover(e,t){this.currentHover&&this.currentHover.toggle(!1),this.hoverListenerSetter.removeAll(),this.currentHover=e,e?.attachButtonListener(t,this.listenerSetter)}setReplyTo(e){const{replyToMsgId:t,replyToQuote:s,replyToPeerId:i,replyToStoryId:n}=e||{};this.replyToMsgId=t,this.replyToStoryId=n,this.replyToQuote=s,this.replyToPeerId=i,this.center(!0)}clearHelper(e){this.helperType==="edit"&&e!=="edit"&&this.clearInput(),e&&(this.lastUrl="",delete this.noWebPage,this.willSendWebPage=null),e!=="reply"&&(this.setReplyTo(void 0),this.forwarding=void 0),this.editMsgId=this.editMessage=void 0,this.helperType=this.helperFunc=void 0,this.setCurrentHover(),this.saveDraftDebounced(),this.restoreInputLock&&(this.restoreInputLock(),this.restoreInputLock=void 0),this.chat.container&&this.chat.container.classList.contains("is-helper-active")&&(Pt.removeByType("input-helper"),this.chat.container.classList.remove("is-helper-active"),this.t())}t(){const e="is-toggling-helper";Dt({element:this.chat.container,className:e,forwards:!0,duration:150,onTransitionEnd:()=>{this.chat.container.classList.remove(e)}})}setInputValue(e,t=!0,s=!0,i){e||(e=""),t?this.clearInput(!1,!1,e):this.messageInputField.setValueSilently(e),$s(()=>{s&&Ki(this.messageInput),this.processingDraftMessage=i,this.setEffect(i.effect),this.onMessageInput(),this.processingDraftMessage=void 0,this.messageInput.scrollTop=this.messageInput.scrollHeight})}setTopInfo({type:e,callerFunc:t,title:s,subtitle:i,setColorPeerId:n,input:r,message:o,quote:l}){if(this.willSendWebPage&&e==="reply")return;e!=="webpage"&&(this.clearHelper(e),this.helperType=e,this.helperFunc=t);const c=this.replyElements.container,d=c.lastElementChild.previousElementSibling,u=d.classList.contains("reply");this.replyElements.iconBtn.replaceWith(this.replyElements.iconBtn=this.createButtonIcon((e==="webpage"?"link":e)+" reply-icon",{noRipple:!0}));const{container:h}=Hu({title:s,subtitle:i,setColorPeerId:n,animationGroup:this.chat.animationGroup,message:o,textColor:"secondary-text-color",quote:l});return this.appImManager.setPeerColorToElement({peerId:n,element:c}),u?d.replaceWith(h):c.lastElementChild.before(h),this.chat.container.classList.contains("is-helper-active")||(this.chat.container.classList.add("is-helper-active"),this.t()),Gi||Pt.pushItem({type:"input-helper",onPop:()=>{this.onHelperCancel()}}),r!==void 0&&this.setInputValue(r),setTimeout(()=>{this.updateSendBtn()},0),h}};Ah.AUTO_COMPLETE_REG_EXP=/(\s|^)((?:(?:@|^\/)\S*)|(?::|^[^:@\/])(?!.*[:@\/]).*)$/;let Zm=Ah;function g9(a){let e;return a.pFlags.close_friends?e="close":a.pFlags.public?e="public":a.pFlags.selected_contacts?e="selected":a.pFlags.contacts?e="contacts":a.privacy&&(a.privacy.some(t=>t._==="privacyValueAllowContacts")?e="contacts":e="selected"),e}var Il=(a=>(a.Stories="stories",a.Pinned="pinnedStories",a.Archive="archiveStories",a))(Il||{});function X0(a,e,t,s,i){const n=e;return s===Il.Pinned?Tl(a,n,r=>{const o=r.id,l=r.pinnedIndex;return l!==void 0?4294967295-l:o}):s===Il.Archive?Tl(a,n,r=>r.id):Tl(a,n,r=>4294967295-r.id)}function ZP(a){for(const e in a){const t=a[e];a[e]=(...s)=>Ot(()=>t(...s))}return a}const JP=(a=new Map)=>({positions:a,onPosition:({peerId:t,position:s})=>{s?a.set(t,s):a.delete(t)}}),{positions:f9,onPosition:v9}=JP();I.addEventListener("stories_position",v9);const y9=a=>{const e=(D,U,j=n.index,q=n.peers[j])=>{const W=D?1:-1,ee=q.index+W,z=D?ee>=q.stories.length:ee<0,Z=D?j>=n.peers.length-1:j<=0;if(z)if(Z){if(U){const de=n.peers[D?0:n.peers.length-1];return{peer:de,index:de.index}}}else{const de=n.peers[j+W];return{peer:de,index:de.index}}else return{peer:q,index:ee}},t={index:a.index||0,paused:!0,ended:!1,muted:!0,loop:!1,buffering:!1,hideInterface:!1,playAfterGesture:!1,ready:!!a.peers,hasViewer:!1,startTime:0,get elapsedTime(){return n.elapsedTimeOnPause||Date.now()-n.startTime},elapsedTimeOnPause:0,changeTimeout:0,storyDuration:0,width:0,height:0,pinned:a.pinned,archive:a.archive,peers:a.peers||[],get peer(){return n.peers[n.index]},freezedSorting:new Set,getNearestStory:e};let s,i;const[n,r]=Qr(t),o=a.peerId||a.peers&&a.peers[0].peerId,l=a.archive?"archive":"stories",{positions:c,onPosition:d}=JP(new Map(f9)),u=[],h=D=>{const U=D.maxReadId||0,j=D.stories.findIndex(q=>q.id>U);return Math.max(0,j)},p=(D,U,j)=>{let q;const W=[];for(let ee=0;ee<U&&(q=n.getNearestStory(D,j,q?.peer?n.peers.indexOf(q.peer):void 0),!!q);++ee)W.push(q);return W},m=()=>{[...p(!0,3,!1),...p(!1,3,!1)].forEach(D=>{const U=D.peer.stories[D.index];U?._==="storyItemSkipped"&&I.managers.appStoriesManager.getStoryById(D.peer.peerId,U.id)})},g=()=>{const{peerId:D,pinned:U,archive:j}=a;if(D){if(U||j){const{peer:q}=n,W=q?q.stories[q.stories.length-1].id:0,ee=30;let z;return U?z=I.managers.appStoriesManager.getPinnedStories(D,ee,W):z=I.managers.appStoriesManager.getStoriesArchive(D,ee,W),z.then(({count:Z,stories:de,pinnedToTop:ie})=>(W?(r("peers",0,"stories",oe=>[...oe,...de]),r("peers",0,"count",Z)):(L([{index:0,peerId:D,stories:de,count:Z}]),r({ready:!0})),i=de.length<ee))}return I.managers.appStoriesManager.getPeerStories(D).then(q=>(x([q]),i=!0))}return I.managers.appStoriesManager.getAllStories(s?!0:void 0,s,j).then(q=>(s=q.state,i=!q.pFlags.has_more,x(q.peer_stories),i||g(),i))},f={set:D=>{if(!D){r({ended:!0});return}const U=n.peers.indexOf(D.peer);D.index!==void 0&&r("peers",U,"index",D.index),f.stop(),n.peer!==D.peer&&r({index:U}),m()},pause:D=>{r({paused:!0,playAfterGesture:D&&!n.paused}),f.toggleInterface(D)},play:(D=n.storyDuration)=>{n.buffering||!n.hasViewer||(r({paused:!1,storyDuration:D}),f.toggleInterface(!1))},stop:()=>{f.pause(),r({startTime:0,elapsedTimeOnPause:0})},restart:()=>{r({buffering:!1}),f.stop(),f.play()},toggle:(D=n.paused)=>{D?f.play():f.pause()},previous:()=>f.goToNearestStory(!1),next:()=>f.goToNearestStory(!0),goToNearestStorySafe:D=>{if(D){f.next();return}const U=n.getNearestStory(D);!U||n.storyDuration!==tM&&n.elapsedTime/n.storyDuration>.5?f.restart():f.set(U)},goToNearestStory:D=>{const U=n.getNearestStory(D);f.set(U)},viewerReady:D=>{r({hasViewer:D,ended:!1})},resetIndexes:()=>{r("peers",{},D=>({index:h(D)}))},toggleMute:()=>{r({muted:!n.muted})},toggleInterface:D=>{r({hideInterface:D})},toggleSorting:(D,U)=>{U?n.freezedSorting.add(D):(n.freezedSorting.delete(D),n.freezedSorting.size?D==="viewer"&&hn(u,(j,q)=>{j.position&&j.position.type!==l&&(u.splice(q,1),H(j,!0))}):u.splice(0,1/0).forEach(j=>H(j,!0)))},load:g,setBuffering:D=>{r({buffering:D})},setLoop:D=>{r({loop:D})}};ZP(f);const v=()=>{clearTimeout(n.changeTimeout),r({startTime:Date.now()-n.elapsedTimeOnPause,changeTimeout:window.setTimeout(()=>{n.loop?f.restart():f.next()},n.storyDuration-n.elapsedTimeOnPause)})};le(Vt(V(()=>n.paused||n.buffering),D=>{D?(clearTimeout(n.changeTimeout),r({elapsedTimeOnPause:Date.now()-n.startTime})):v()},{defer:!0}));const y=sM(),w=()=>It.height-48-8-8*2-8,b=(D=w())=>Math.min(It.width,D*.5625),S=()=>{const D=w();return{width:b(D),height:D}};le(()=>{r(S())});const M=(D,U=n.peers)=>U.findIndex(j=>j.peerId===D),C=D=>{const U={peerId:it(D.peer),stories:D.stories,maxReadId:D.max_read_id,count:D.stories.length};return U.index=h(U),U},L=D=>{const U=[];let j=n.index;const q=n.peers.slice(),W=new Map(q.map((Z,de)=>[Z.peerId,de])),ee=n.peer?.peerId,z=W.get(ee)??-1;for(const Z of D){const de=W.get(Z.peerId)??-1,ie=q[de],oe=zt(ie?.index||h(Z),0,Z.stories.length-1);Z.index!==oe&&U.push({peerId:Z.peerId,index:oe}),de!==-1&&(q[de]=Z),Tl(q,Z,ae=>c.get(ae.peerId)?.index??0,de)}if(z!==-1){const Z=M(ee,q);Z!==z&&(j=Z)}pi(()=>{r("peers",Ec(q,{key:"peerId",merge:!0})),r({index:j});for(const{peerId:Z,index:de}of U){const ie=M(Z,q);r("peers",ie,"index",de)}})},E=D=>{if(o)return o===D;const U=c.get(D);return U?U.type===l:!1},x=D=>{const U=D.map(C);L(U),r({ready:!0})},R=(D,U=M(D))=>{if(U===-1)return;const j=n.index===U;pi(()=>{const q=n.peers.slice();q.splice(U,1);const W=n.index>U?n.index-1:n.index;r({peers:q,...q.length?{}:{ended:!0},...W<q.length?{index:W}:{ended:!0}}),j&&f.restart()})},B=({peerId:D,story:U,modifiedPinned:j,modifiedArchive:q,modifiedPinnedToTop:W})=>{const ee=M(D);if(ee===-1)return;const z=n.peers[ee],Z=z.stories.findIndex(de=>de.id===U.id);if(a.pinned&&j){U.pFlags.pinned?G({peerId:D,story:U,cacheType:Il.Pinned,maxReadId:z.maxReadId}):O({peerId:D,id:U.id});return}if(a.pinned&&W){if(U.pinnedIndex===void 0&&U.id<z.stories[z.stories.length-1].id&&!i){O({peerId:D,id:U.id});return}Z===-1?G({peerId:D,story:U,cacheType:Il.Pinned,maxReadId:z.maxReadId}):r("peers",ee,"stories",Ec((ie=>(ie=ie.slice(),ie.splice(Z,1),X0(ie,U,!1,Il.Pinned),ie))(z.stories),{key:"id",merge:!0}));return}if(Z===-1){a.archive&&o&&q&&G({peerId:D,story:U,cacheType:Il.Archive,maxReadId:z.maxReadId});return}r("peers",ee,"stories",Z,Ec(U))},N=D=>{const U=it(D.peer);E(U)&&x([D])},G=({peerId:D,story:U,cacheType:j,maxReadId:q})=>{if(!E(D)||a.pinned&&!U.pFlags?.pinned)return;const W=M(D);if(W===-1){const de={peerId:D,stories:[U],maxReadId:q,count:1};de.index=h(de),L([de]);return}const Z=n.peers[W].stories.findIndex(de=>de.id===U.id);if(Z!==-1){r("peers",W,"stories",Z,U);return}pi(()=>{const de=n.peer.index;let ie;r("peers",W,"stories",oe=>(oe=oe.slice(),ie=X0(oe,U,!1,j),oe)),r("peers",W,"count",oe=>oe+1),ie<=de&&r("peers",W,"index",oe=>oe+1)})},O=({peerId:D,id:U})=>{const j=M(D);if(j===-1)return;const q=n.peers[j],W=q.stories,ee=W.findIndex(z=>z.id===U);if(ee!==-1){if(W.length===1){R(D,j);return}pi(()=>{n.peer===q&&q.index===ee&&f.next(),r("peers",j,"stories",z=>(z=z.slice(),z.splice(ee,1),z)),r("peers",j,"count",z=>z-1),q.index>=ee&&r("peers",j,"index",q.index-1)})}},$=({peerId:D,maxReadId:U})=>{const j=M(D);j!==-1&&r("peers",j,"maxReadId",U)},H=(D,U)=>{const{peerId:j,position:q}=D;if(n.freezedSorting.size&&!U){const ee=c.get(j);if(ee?.type===q?.type||n.hasViewer&&ee&&q){tr(u,z=>z.peerId===j),u.push(D);return}}if(d(D),!E(j)){R(j);return}const W=n.peers.find(ee=>ee.peerId===j);W&&L([W])};return y.add(I)("story_update",B),y.add(I)("story_deleted",O),!a.archive&&!a.pinned&&y.add(I)("story_expired",O),a.singleStory||y.add(I)("story_new",G),o||(y.add(I)("stories_stories",N),y.add(I)("stories_read",$),y.add(I)("stories_position",H)),a.onLoadCallback?a.onLoadCallback(f.load):n.ready?n.peer.index===void 0&&f.resetIndexes():f.load(),[n,f]},eM=fd(),uw=a=>(wa(a,["peers","index","peerId","pinned","archive"]),T(eM.Provider,{get value(){return y9(a)},get children(){return a.children}})),ec=()=>us(eM);function b9(a){return!!a&&a.tagName==="INPUT"&&!["checkbox","radio"].includes(a.type)||a.isContentEditable}function Z0(a){const e=a.fwd_from;let t;if(!(!e&&(t=(a.media_areas||[]).find(s=>s._==="mediaAreaChannelPost"),!t)))return{fwdFrom:e,mediaAreaChannelPost:t}}const Va=Y("<div>"),w9=Y("<a>"),S9=Y("<div><div></div><div>"),Vd=Y("<span>"),C9=Y("<div><div><div dir=auto>"),J0=Y("<div><span>"),_9=Y("<div><div><div></div><div><div></div><div></div><div><div><div><div></div><div></div></div></div><div>"),I9=Y("<div><div>"),tM=5e3,by=32,rh=.33,wy=2,P9=2,M9="storyrepost";let dl=ku;I.addEventListener("app_config",a=>{const e=a.stories_changelog_user_id;dl=e?e.toPeerId(!1):ku});const eC=new Tg(void 0,!0);function sM(){const a=new $t;return ze(()=>a.removeAll()),a}const L9=a=>{let e,t;if(a.splitByDays){const i=r=>{const o=r.date,l=new Date(o*1e3);return l.setHours(0,0,0),l.getTime()},n=V(()=>{const r=a.state.stories,o={};return r.forEach(l=>{const c=i(l);(o[c]??(o[c]=[])).push(l)}),o});t=V(()=>{const r=n(),o=a.currentStory(),l=i(o);return r[l]}),e=V(()=>{const r=a.currentStory();return t().indexOf(r)})}else t=()=>a.state.stories,e=()=>a.state.index;return T(Cs,{get each(){return t()},children:(i,n)=>T(E9,ni(()=>ni(a,{slideIndex:n,storyIndex:e})))})},E9=a=>{const[e,t]=K(0),[s]=ec(),i=()=>{const d=(Date.now()-s.startTime)/s.storyDuration;t(d)},n=()=>s.peer!==a.state||a.storyIndex()!==a.slideIndex()||s.paused?(r(),!1):(i(),!0),r=()=>{Zy(l)},o=()=>{Wl(n,l)};le(()=>{if(s.peer!==a.state){r();return}le(Vt(()=>[a.storyIndex(),a.slideIndex()],([c,d])=>{c===d?(t(void 0),le(()=>{s.paused||s.buffering?r():o()})):(r(),t(c>d?1:void 0))}))});const l=(()=>{const c=Va();return Me(d=>{const u=He.ViewerStorySlidesSlide,h=e()!==void 0?{"--progress":Math.min(100,e()*100)+"%"}:{};return u!==d._v$&&be(c,d._v$=u),d._v$2=Ii(c,h,d._v$2),d},{_v$:void 0,_v$2:void 0}),c})();return l},pw="❤",k9=a=>a?.emoticon===pw,T9=a=>{const[e,t]=ec(),[s,i]=a.focusedSignal,[n,r]=a.inputEmptySignal,[o,l]=a.inputMenuOpenSignal,[c,d]=K(!1),u=ui(),h=u.get(),p=new NP(Ce,I.managers,!1,{elements:!0,sharedMedia:!0});p.setType(we.Stories),p.isStandalone=!0;const m=async()=>{const L=!a.currentStory().sent_reaction?{_:"reactionEmoji",emoticon:pw}:void 0;a.sendReaction({reaction:L,target:g})};let g;T(Pi,{ref(M){const C=g;typeof C=="function"?C(M):g=M},onClick:m,tabIndex:-1,class:"btn-circle btn-reaction chat-input-secondary-button chat-secondary-button",noRipple:!0,get children(){return a.reaction()}});const f=p.input=new Zm(p,Ce,I.managers,"stories-input");f.noRipple=!0,f.btnReaction=g,f.excludeParts={replyMarkup:!0,scheduled:!0,downButton:!0,reply:!0,forwardOptions:!0,mentionButton:!0,attachMenu:!0,commandsHelper:!0,botCommands:!0,emoticons:Gi},f.globalMentions=!0,f.getMiddleware=(...M)=>h.create().get(...M);const v=M=>{const C=M.target;!ne(C,He.ViewerStoryReactions)&&(ne(C,He.ViewerStory)||C.classList.contains(He.Viewer))&&(_e(M),i(!1))};ze(()=>{y&&(Pt.removeItem(y),y=void 0)});let y;le(Vt(()=>s(),M=>{M?(w=Ot(()=>!e.paused),document.addEventListener("click",v,{capture:!0}),Pt.pushItem(y={type:"stories-focus",onPop:()=>{i(!1)}})):(document.removeEventListener("click",v,{capture:!0}),Pt.removeItem(y),y=void 0),t.toggle(M?!1:w),f.freezeFocused(M),f.chatInput.classList.toggle("is-focused",M)},{defer:!0}));let w=!1;f.onFocusChange=M=>{f.emoticonsDropdown.isActive()||M&&i(M)};let b=!1;const S=M=>{M&&(b=!e.paused),t.toggle(M?!1:b),l(M)};f.onMenuToggle=S,f.construct(),f.constructPeerHelpers(),f.messageInput.dataset.textColor="white",le(()=>{if(a.isActive()){const M=()=>(S(!0),void 0),C=()=>(S(!1),void 0);Gn.addEventListener("open",M),Gn.addEventListener("close",C),Gn.chatInput=f,ze(()=>{Gn.removeEventListener("open",M),Gn.removeEventListener("close",C)})}}),le(()=>{f.chatInput.classList.toggle("is-private",!a.isPublic()),f.setCanForwardStory(a.isPublic())}),le(()=>{const[M,C,L]=[s(),c(),a.isPublic()],B=Math.min(2,[!M,M?!0:L,C].reduce((D,U)=>D+ +U,0)),N=48,G=8,O=a.isFull()?8:0,$=a.isFull()?0:135,H=e.width-(N+G)*B+(M?$:0)-O*2;f.rowsWrapper.style.setProperty("width",H+"px","important"),f.chatInput.classList.toggle("is-focused",M)});const _=Sg();return p.peerId=a.state.peerId,p.onChangePeer({peerId:p.peerId,type:we.Stories},Bl(h)).then(()=>{if(h())return p.finishPeerChange({peerId:p.peerId,middleware:h})}).then(()=>{h()&&(a.setInputReady(!0),Vh(_,()=>{le(()=>{f.setReplyTo({replyToStoryId:a.currentStory().id})})}))}),ze(()=>{f.onFocusChange=f.onFileSelection=f.onMenuToggle=f.onRecording=f.onUpdateSendBtn=f.onMessageSent2=f.forwardStoryCallback=void 0,u.destroy(),p.destroy()}),f.onFileSelection=M=>{S(!0),M.finally(()=>{S(!1)})},f.onUpdateSendBtn=M=>{r(M==="record"||M==="forward")},f.onMessageSent2=()=>{Fa(),i(!1),a.onMessageSent()},f.forwardStoryCallback=M=>{a.onShareButtonClick(M,f.btnSendContainer)},f.onRecording=M=>{d(M)},f.chatInput},tC=" • ",iM=async a=>{let e;const{reaction:t,div:s,size:i,textColor:n,play:r,uReaction:o}=a,l=t._==="reactionCustomEmoji",c=ui().get();o(null);let d;if(l){const h=await I.managers.acknowledged.appEmojiManager.getCustomEmojiDocument(t.document_id);if(!c())return;h.cached||o(),e=await h.result,d=Ae.getReaction(e.stickerEmojiRaw)}else{const h=Ae.getAvailableReactions();h instanceof Promise&&o();const p=await h;if(!c())return;d=p.find(m=>Wn(t,m)),e=r?d.select_animation:d.static_icon}d&&en(d,h=>{h?.around_animation&&fs.downloadMedia({media:h.around_animation})});const u=[];await ai({div:s,doc:e,width:i,height:i,play:r,textColor:n,middleware:c,loadPromises:u,loop:r||void 0}),await Promise.all(u),c()&&o(s)},x9=a=>{const[e,t]=ec(),{x:s,y:i,w:n,h:r,rotation:o}=a.mediaArea.coordinates,l=V(C=>C||a.isActive()&&e.startTime),[c,d]=K(),u=V(()=>a.mediaArea._==="mediaAreaGeoPoint"||a.mediaArea._==="mediaAreaVenue"),h=V(()=>a.mediaArea._==="mediaAreaSuggestedReaction"),p=V(()=>a.mediaArea._==="mediaAreaChannelPost"),m=V(()=>a.mediaArea._==="mediaAreaUrl"),g=async()=>{const C=a.mediaArea.geo,L=Nb(C),E=async O=>{if(R){R=!1;return}B=!0,_e(O);try{await Rt({descriptionLangKey:"Popup.OpenInGoogleMaps",button:{langKey:"Open"}})}catch{N&&t.play();return}R=!0,x.click()};let x,R=!1,B;(()=>{const O=w9();O.$$click=E;const $=x;return typeof $=="function"?Ue($,O):x=O,Es(O,"href",L),k(O,()=>P("StoryViewLocation")),O})(),jl(x);const N=!e.paused;t.pause();const{close:G}=Ra({element:M,vertical:"top",textElement:x,centerVertically:!!o,onClose:()=>{if(B){B=!1;return}N&&t.play()}});a.setTooltipCloseCallback(()=>G)},f=()=>{const C=a.mediaArea,L=e.width*n/100;a.sendReaction({reaction:C.reaction,target:M,sizes:{genericEffect:L*.375,genericEffectSize:L*1.5,size:L,effectSize:L*2.6875},textColor:C.pFlags.dark?"white":void 0,fireSame:!0})},v=C=>{const L=xi(()=>{x(),C.callback()});L.append(C.text);const E=!e.paused;t.pause();const{close:x}=Ra({element:M,vertical:"top",textElement:L,centerVertically:!1,onClose:()=>{E&&t.play()}});a.setTooltipCloseCallback(()=>x)},y=()=>{v({callback:()=>{a.close(()=>{const L=a.mediaArea;Ce.setInnerPeer({peerId:L.channel_id.toPeerId(!0),lastMsgId:L.msg_id})})},text:P("Story.ViewPost")})},w=()=>{v({callback:()=>{const C=a.mediaArea.url;Bo(C).onclick?a.close(()=>{Ce.openUrl(C)}):Ul(C)},text:P("OpenUrlTitle")})},b=C=>{a.isActive()&&(_e(C),_(C))},S=C=>{const L=C.reaction,[E,x]=K(0),R=fo(),B=e.width*n/100*.72;let N;(()=>{const G=Va(),O=N;return typeof O=="function"?Ue(O,G):N=G,Me(()=>be(G,Ge(He.ViewerStoryMediaAreaReactionInner,E()&&He.hasCount))),G})(),iM({reaction:L,uReaction:R,div:N,size:B,textColor:C.pFlags.dark?"white":void 0,play:!0}),Me(()=>{const $=a.story.views?.reactions?.find(H=>Wn(H.reaction,L));x($?.count??0)}),le(()=>{const G=R();G!==null&&(d([(()=>{const O=S9(),$=O.firstChild,H=$.nextSibling;return Me(D=>{const U=Ge(He.ViewerStoryMediaAreaReactionBubbles,C.pFlags.dark&&He.dark,E()&&He.hasCount),j=He.ViewerStoryMediaAreaReactionBubble,q=Ge(He.ViewerStoryMediaAreaReactionBubble,He.small);return U!==D._v$3&&be(O,D._v$3=U),j!==D._v$4&&be($,D._v$4=j),q!==D._v$5&&be(H,D._v$5=q),D},{_v$3:void 0,_v$4:void 0,_v$5:void 0}),O})(),G,(()=>{const O=Va();return`calc(var(--stories-width) * ${n/100*.72*.275})`!=null?O.style.setProperty("font-size",`calc(var(--stories-width) * ${n/100*.72*.275})`):O.style.removeProperty("font-size"),k(O,(()=>{const $=V(()=>!!E());return()=>$()?un(E(),1):""})()),Me(()=>be(O,Ge(He.ViewerStoryMediaAreaReactionCount,C.pFlags.dark&&He.dark,E()&&He.hasCount))),O})()]),a.setReady(!0))})};let _;h()?(_=f,S(a.mediaArea)):u()?(_=g,a.setReady(!0)):p()?(_=y,a.setReady(!0)):(m()&&(_=w),a.setReady(!0));let M;return(()=>{const C=Va();C.$$click=b;const L=M;return typeof L=="function"?Ue(L,C):M=C,k(C,c),Me(E=>{const x=Ge(He.ViewerStoryMediaArea,...u()?[l()&&"shimmer","shimmer-bright","shimmer-once"]:[],...h()?[He.ViewerStoryMediaAreaReaction]:[]),R=`left: ${s}%; top: ${i}%; width: ${n}%; height: ${r}%; --rotate: ${o}deg`;return x!==E._v$6&&be(C,E._v$6=x),E._v$7=Ii(C,R,E._v$7),E},{_v$6:void 0,_v$7:void 0}),C})()},A9=a=>{const e=jn({size:by,peerId:a.state.peerId,isDialog:!1});e.node.classList.add(He.ViewerStoryHeaderAvatar);const t=I.myId===a.state.peerId,s=!t&&new Xt;let i;s?(s.update({peerId:a.state.peerId,dialog:!1}),i=s.element):i=P("YourStory"),i.classList.add(He.ViewerStoryHeaderName);const n=(me=!u.paused)=>()=>r(me),r=me=>{me&&h.play()},o=(me=!u.paused)=>{h.pause(),Rs.createSharingPicker({onSelect:async dt=>{const vt=a.state.peerId,At=await _r.prepareStarsForPayment({messageCount:1,peerId:dt});if(At===Fn)throw new Error;const Lt=await I.managers.appPeersManager.getInputPeerById(vt);I.managers.appMessagesManager.sendOther({peerId:dt,inputMedia:{_:"inputMediaStory",id:ve().id,peer:Lt},confirmedPaymentResult:At}),Fw(P(dt===I.myId?"StorySharedToSavedMessages":"StorySharedTo",[await qe({peerId:dt})]))},chatRightsActions:["send_media"]}).addEventListener("closeAfterTimeout",n(me))},l=(me,Re)=>{if(ve().pFlags.noforwards){const{open:vt}=Dn({buttons:[{icon:"link",text:"CopyLink",onClick:Tt}],listenTo:Re,...ft});vt(me)}else o()},c=jn({size:162,peerId:a.state.peerId,isDialog:!1,withStories:!0,storyColors:{read:"rgba(255, 255, 255, .3)"}});c.node.classList.add(He.ViewerStoryInfoAvatar);let d;if(t)d=P("MyStory");else{const me=new Xt;me.update({peerId:a.state.peerId,dialog:!1,onlyFirstName:!0}),d=me.element}d.classList.add(He.ViewerStoryInfoName);const[u,h]=ec(),[p,m]=K(),[g,f]=K(),[v,y]=K(),[w,b]=K(),[S,_]=K(),[M,C]=K(0),[L,E]=K(!1),[x,R]=K(),[B,N]=K(!1),[G,O]=K(),$=K(!1),H=K(),D=K(!0),U=K(!1),j=K(!1),[q,W]=$,[ee,z]=H,[Z]=D,[de]=U,[ie,oe]=j,[ae,ke]=K(!1),[re,ce]=a.transitionSignal,[Ie,Ve]=K(),[fe,Xe]=K(),[Ye,Ze]=K(),[Je,tt]=K(),[ht,Ee]=K(),ve=V(()=>a.state.stories[a.state.index]),Qe=V(()=>{const Re=ve().expire_date;return Re?Re<=Qs(!0):!1}),A=V(()=>u.peer===a.state),[F,Q]=K(!1,{equals:!1});let X;le(()=>{ve(),X=ui().get()});const ge=(me,Re=Ot(()=>ee()))=>{if(!Re||Re.target===Ad)return;const dt=Re.sizes??{genericEffect:26,genericEffectSize:100,size:40,effectSize:80};Qo.fireAroundAnimation({middleware:Re.fireSame?X:ui().get(),reaction:me,sizes:dt,stickerContainer:Re.target,cache:Re.fireSame?{}:Re.target,textColor:Re.textColor})};le(()=>{const me=ve().sent_reaction;me&&(me?.document_id,F(),ge(me))});const he=async me=>{let{reaction:Re}=me;const dt=a.state.peerId,vt=ve(),At=vt.id,Lt=vt.sent_reaction;if(Re instanceof Promise&&(Re=await Re,!Re))return;const bs=!Wn(Lt,Re);!bs&&!me.fireSame&&(Re=void 0),W(!1),z(me),!bs&&me.fireSame&&Q(!0),await I.managers.acknowledged.appStoriesManager.sendReaction(dt,At,bl(Re)),z()},Le=()=>{const[me,Re]=K(!1),dt=ui().get(),vt=new lw({managers:I.managers,type:"horizontal",middleware:dt,onFinish:Lt=>he({reaction:Lt,target:Ad}),size:36,openSide:"top",getOpenPosition:()=>{},noMoreButton:!0});vt.widthContainer.classList.add(He.ViewerStoryReactions),vt.init().finally(()=>{Re(!0)});let At;le(()=>{if(!me())return;const Lt=Se();vt.widthContainer.classList.toggle("is-visible",Lt),Lt?clearTimeout(At):At=window.setTimeout(()=>{Ee(),vt.cleanup()},wt.isAvailable("animations")?200:0)}),Ee(vt)},Se=()=>q()&&Z()&&!de(),xe=V(()=>ht()?!0:Se());le(()=>{xe()&&Le()});const lt=me=>{let Re=!1;ze(()=>{Re=!0,me.pause(),me.removeEventListener("waiting",vt),me.removeEventListener("canplay",dt)});const dt=()=>{N(!1),A()&&h.setBuffering(!1)},vt=()=>{const Si=me.networkState===me.NETWORK_LOADING,Ti=me.readyState<me.HAVE_FUTURE_DATA;Si&&Ti&&(N(!0),A()&&h.setBuffering(!0),me.addEventListener("canplay",dt,{once:!0}))},At=()=>{me.currentTime&&on(me,0)};me.addEventListener("waiting",vt),ze(()=>{u.buffering&&h.setBuffering(!1)}),le(()=>{u.paused||!A()?me.pause():me.play()});const Lt=()=>{le(Vt(()=>[A()],([Si])=>{Si||At()})),le(()=>{me.muted=u.muted})};A()?Lt():Or(Lt)(()=>A());const bs=Ot(()=>ve());le(()=>{A()&&!u.startTime&&ve()===bs&&At()}),Ot(ae)||Ae.getState().then(Si=>{const[Ti,Ws]=Ho();!Re&&!Ti.seenTooltips.storySound&&(Vh(ws,()=>{const _s=V(Hs=>Hs||A()&&u.startTime);le(()=>{if(_s()){const{close:Hs}=Ra({...Uw,textElement:P("Story.SoundTooltip")});tt(()=>Hs)}})}),Ws("seenTooltips","storySound",!0))});const ws=Sg()},mt=me=>{let Re=g9(me);Re==="public"&&(Re=void 0);const vt=bl(me.media)?.document,At=vt&&vt.attributes.find(Hs=>Hs._==="documentAttributeVideo"),Lt=At?!!At.pFlags.nosound:!1,bs=At?.duration,ws=me.date,Si=me.pFlags.edited,Ti=!!me.pFlags.public,Ws=Ae.getPeer(a.state.peerId),_s=ji(Ws);Ve(Re),R({timestamp:ws,edited:Si}),ke(Lt),f(bs&&bs*1e3),oe(Ti),O(Ti&&(!me.pFlags.noforwards||!!_s[0]))},at=async me=>{if(N(!0),me._!=="storyItem"){Ze(),m(),y(),_(),Xe(),b(),mt(me),I.managers.appStoriesManager.getStoryById(a.state.peerId,me.id),a.onReady?.();return}const Re=ui().get(),dt=t?fo():void 0,vt=fo(),At=fo(),Lt=fo(),bs=fo(),ws=fo(),Si=t?V(Ws=>{const Hs=me.views?.recent_viewers;return Ws?.join()===Hs?.join()?Ws:Hs}):void 0,Ti=(Ws,_s,Hs)=>({entities:_s,middleware:Re,textColor:"white",loadPromises:Hs,passMaskedLinks:dl===Ws});t&&le(async()=>{let Ws;const _s=Si();if(_s?.length){Ws=new Zl({avatarSize:30,middleware:Re});const Hs=_s.map(sn=>sn.toPeerId(!1));if(dt(null),await Ws.render(Hs),!Re())return}dt(Ws)}),le(async()=>{let Ws;const{caption:_s,entities:Hs}=me;if(_s?.trim()){const sn=[],{message:Zn,totalEntities:Et}=xv(_s,Hs?.slice()),Is=jt(Zn,Ti(a.state.peerId,Et,sn));if(vt(null),await Promise.all(sn),!Re())return;Ws=kl(Is)}vt(Ws)}),le(()=>{if(!Ot(()=>Vi(me)).id){At();return}At(null);const Hs=zu({peerId:a.state.peerId,storyItem:bl(me),forViewer:!0,containerProps:{class:He.ViewerStoryContentMediaContainer},childrenClassName:He.ViewerStoryContentMedia,useBlur:40}),sn=()=>{At(Hs.container)},Zn=()=>{Re()&&(N(!1),Ot(()=>se()))},Et=()=>{const Is=Hs.media();Is instanceof HTMLVideoElement?(lt(Is),ua(Is).then(Zn)):Zn()};Or(sn)(()=>Hs.ready()),Or(Et)(()=>Hs.media())}),le(()=>{let Ws;const _s=me.sent_reaction,Hs=k9(_s);if(!_s||Hs)Ws=Be("reactions_filled",...["btn-reaction-icon",Hs&&"btn-reaction-default"].filter(Boolean)),Lt(Ws);else{const sn=document.createElement("div");sn.classList.add("btn-reaction-sticker","night"),iM({reaction:_s,uReaction:Lt,div:sn,size:26,textColor:"white",play:!1})}}),le(()=>{if(!me.media_areas?.length){bs();return}bs(null);const[Ws,_s]=K(!1),[Hs,sn]=K(0),Zn=T(Cs,{get each(){return me.media_areas},children:Et=>{const[Is,Xi]=K(!1);return Or(()=>{sn(gi=>gi+1),Hs()===me.media_areas.length&&_s(!0)})(Is),T(x9,{story:me,mediaArea:Et,isActive:A,setTooltipCloseCallback:tt,setReady:Xi,sendReaction:he,get close(){return a.close}})}});Or(()=>{bs(Zn)})(Ws)}),le(async()=>{const Ws=Z0(me);if(!Ws){ws();return}const{fwdFrom:_s,mediaAreaChannelPost:Hs}=Ws;ws(null);const[sn,Zn]=K(),[Et,Is]=K(),Xi={header:(()=>{const Nn=Vd();return k(Nn,sn),Me(()=>be(Nn,He.ViewerStoryHeaderRepost)),Nn})()};let gi,Jn,Tr;_s?(gi=_s.from&&it(_s.from),Jn=_s.from_name,Tr=_s.story_id):gi=Hs.channel_id.toPeerId(!0);const Rd={peerId:gi,fromName:Jn},{node:rp,readyThumbPromise:op}=vs({peerId:gi,peerTitle:Jn,size:16,middleware:Re}),lp=(()=>{const Nn=Vd();return k(Nn,Et),Nn})(),cp=async(Nn,ao)=>{const Dd=await Nn;if(!Re())return;if(ao&&!Dd.caption){Is(P("Story"));return}const up=[],{message:Zo,totalEntities:uf}=xv(Dd.caption,Dd.entities?.slice()),aL=jt(Zo,Ti(gi,uf,up));await Promise.all(up),Re()&&Is(kl(aL))},dp=Tr&&I.managers.acknowledged.appStoriesManager.getStoryById(gi,Tr).then(async Nn=>{const ao=cp(Nn.result,Nn.cached);if(!Nn.cached){Is(P("Story"));return}return ao}),[Fd,Bd,hp]=await Promise.all([qe(Rd).then(async Nn=>{const ao=document.createDocumentFragment();if(gi){const Zo=await I.managers.appPeersManager.isBroadcast(gi),uf=Be(Zo?"newchannel_filled":gi.isUser()?"newprivate_filled":"group_filled","inline-icon","reply-title-icon","with-margin");ao.append(uf)}if(ao.append(Nn),Jn||Hs){const Zo=document.createElement("div");return Zo.classList.add(He.ViewerStoryRepostSmall),Zo.append(ao),Zo}const{container:Dd,fillPromise:up}=Hu({title:ao,subtitle:lp,useHighlightingColor:!0,setColorPeerId:gi});return await up,Dd}),qe(Rd),op.then(()=>rp),dp]);Re()&&(Bd.classList.add(He.ViewerStoryHeaderRepostTitle),Fd.classList.add(He.ViewerStoryRepost),Xi.reply=Fd,Zn([Be(M9,He.ViewerStoryHeaderRepostIcon),hp,Bd]),ws(Xi))}),le(Vt(()=>[WM(),dt?.(),vt(),At(),Lt?.(),bs(),ws()],([Ws,..._s])=>{if(!Ws||_s.some(gi=>gi===null))return;const[Hs,sn,Zn,Et,Is,Xi]=_s;Ze(Hs),y(sn),m(Zn),_(Et),Xe(Is),b(Xi),a.onReady?.(),le(()=>{mt(me)})},{defer:!0}))};le(()=>{const me=ve();C(0),E(!1),le(()=>{at(me)})});const kt=()=>{if(!Us.size)return;const me=Array.from(Us);Us.clear(),I.managers.appStoriesManager.getStoriesById(a.state.peerId,me,!0)},Us=new Set;let Ts;le(()=>{A()?(Ts=window.setInterval(kt,6e4),le(()=>{Us.add(ve().id)})):clearInterval(Ts)});const zs=me=>{et.size&&(I.managers.appStoriesManager.incrementStoryViews(a.state.peerId,Array.from(et)),et.clear()),I.managers.appStoriesManager.readStories(a.state.peerId,me)},et=new Set,te=$i(zs,5e3,!0,!0);le(()=>{if(!A())return;let me;le(()=>{const Re=ve();a.pinned&&Ot(()=>Qe())&&et.add(Re.id),te(me=Re.id)}),ze(()=>{te.isDebounced()&&(te.clearTimeout(),zs(me))})});const se=()=>{!u.hasViewer||Ot(()=>!A())||De()};le(se);const ye=T(L9,ni(()=>ni(a,{currentStory:ve})));let Te=!0;const Pe=()=>{let me=np();if(!me)return"0px";hf()&&u.hasViewer&&Ow()&&Te&&(me>0?++me:--me);const Re=u.width,dt=40,vt=me>0?1:-1,At=Re*rh;let Lt=Re*vt;const bs=(Re-At)/2-dt;if(Lt=(Re-bs)*vt,Math.abs(me)!==1){const ws=me-1*vt;Lt+=ws*At+dt*ws}return Lt+"px"},De=()=>{if(Ot(()=>B()))return;const me=Ot(()=>g()),Re=me?me+.001:tM;h.play(Re)},We=me=>{me&&me.target!==xd||ce(!0)},Ke=me=>{me&&me.target!==xd||(Te=!0,ce(!1),A()&&De())},Bt=me=>{if(ae()){const{close:Re}=Ra({...Uw,textElement:P("Story.NoSound")});tt(()=>Re);return}h.toggleMute()};let bt;const ct=T(Pi,{ref(me){const Re=bt;typeof Re=="function"?Re(me):bt=me},get classList(){return{[He.noSound]:ae()}},get icon(){return u.muted||ae()?"speakerofffilled":"speakerfilled"},onClick:Bt}),Tt=()=>{si(`https://t.me/${ji(of)[0]}/s/${ve().id}`),$e({langPackKey:"LinkCopied"})},ft={onOpenBefore:async()=>{of=await I.managers.appStoriesManager.getPeer(a.state.peerId),Xn=ve(),ir=a.state.peerId},onOpen:()=>{kd=!u.paused,h.pause()},onCloseAfter:()=>{kd&&!Td&&h.play(),Td=!1}},Kt=.2;le(()=>{A()&&h.setLoop(g()!==void 0&&L())});let es;const ys=me=>{const Re=Math.min(1,me/100),dt=Re>=Kt;C(Re),E(dt),g()===void 0&&(dt?es===void 0&&(es=!u.paused,h.pause()):es&&(es=void 0,h.play()))};let Ds,Tn,ts=!1;const $n=()=>{if(ts)return;const me=Ds.scrollTop;ys(me)},Ba=me=>{const Re=Math.max(0,me),dt=Date.now();ts=!0;const vt=ve();Wl(()=>{if(ve()!==vt)return!1;const At=Math.min(1,(Date.now()-dt)/300),Lt=l2(At,1),bs=me*(1-Lt),ws=Math.round(Re-bs);return Ds.scrollTop=ws,ys(ws),At<1},Ds).finally(()=>{ts=!1})},Oi=me=>{if(Ds.scrollHeight<=Ds.clientHeight||Ds.scrollTop)return;_e(me);const dt=Math.min(Tn.scrollHeight-56,Ds.clientHeight-60);Ba(dt)},qt=(()=>{const me=C9(),Re=me.firstChild,dt=Re.firstChild;me.addEventListener("scroll",$n);const vt=Ds;typeof vt=="function"?Ue(vt,me):Ds=me,Re.$$click=Oi;const At=Tn;return typeof At=="function"?Ue(At,Re):Tn=Re,k(dt,()=>w()?.reply,null),k(dt,v,null),Me(Lt=>{const bs=Ge("scrollable","scrollable-y","no-scrollbar",He.ViewerStoryCaption,w()&&v()&&He.hasReply),ws=Ge("spoilers-container",He.ViewerStoryCaptionText),Si=He.ViewerStoryCaptionTextCell;return bs!==Lt._v$8&&be(me,Lt._v$8=bs),ws!==Lt._v$9&&be(Re,Lt._v$9=ws),Si!==Lt._v$10&&be(dt,Lt._v$10=Si),Lt},{_v$8:void 0,_v$9:void 0,_v$10:void 0}),me})(),ri=(()=>{const me=Va();return k(me,p),Me(Re=>{const dt=He.ViewerStoryContentItem,vt=M()&&{opacity:1-M()*.5};return dt!==Re._v$11&&be(me,Re._v$11=dt),Re._v$12=Ii(me,vt,Re._v$12),Re},{_v$11:void 0,_v$12:void 0}),me})(),sc=()=>{const{timestamp:me,edited:Re}=x()||{};if(!me)return;const dt=Qs(!0)-me,vt=Yl(dt),At={[Hn.Seconds]:"StoryJustNow",[Hn.Minutes]:"MinutesShortAgo",[Hn.Hours]:"HoursShortAgo"},Lt=vt[0],bs=At[Lt.type],ws=[];bs?Lt.type===Hn.Days&&Lt.duration!==1?ws.push(Au(new Date(me*1e3))):ws.push(P(bs,[Lt.duration])):ws.push((()=>{const Ti=Vd();return k(Ti,()=>kl(gs(me))),Ti})()),Re&&ws.push(P("EditedMessage")),w()&&ws.unshift(w().header);let Si=Kl(ws,tC);return w()&&(Si=[Si[0],(()=>{const Ti=Vd();return k(Ti,()=>Si.slice(1)),Me(()=>be(Ti,He.ViewerStoryHeaderSecondary)),Ti})()]),Si},Fw=(me,Re)=>{let dt;Re&&(dt=document.createElement("a"),dt.href="#",dt.addEventListener("click",vt=>{_e(vt),a.close(()=>{Ce.setInnerPeer({peerId:Re})})},{capture:!0,passive:!1}),dt.append(P("ViewInChat"))),Gu({textElement:me,textRight:dt,appendTo:Ad,from:"bottom",duration:3e3,icon:"checkround_filled"})},Bw=a.state.peerId!==dl&&a.state.peerId!==I.myId&&a.state.peerId.isUser(),[WM,KM]=K(!Bw),jM=Bw&&T(T9,ni(()=>ni(a,{currentStory:ve,isActive:A,focusedSignal:$,inputEmptySignal:D,inputMenuOpenSignal:U,sendReaction:he,isPublic:ie,shareStory:o,reaction:S,onShareButtonClick:l,onMessageSent:()=>{Fw(P("Story.Tooltip.MessageSent"),a.state.peerId)},setInputReady:KM}))),Dw=async me=>{const Re=a.state.peerId;if(Re===I.myId||Re===dl)return!1;const[dt,vt]=await Promise.all([I.managers.appStoriesManager.getPeer(Re),I.managers.appStoriesManager.isSubcribedToPeer(Re)]),At=!!dt.pFlags.stories_hidden;return(me?!At:At)&&vt},$w=async me=>{const Re=a.state.peerId;I.managers.appStoriesManager.toggleStoriesHidden(Re,me),$e({langPackKey:me?"StoriesMovedToContacts":"StoriesMovedToDialogs",langPackArguments:[await qe({peerId:Re})]})},ip=async me=>{const Re=a.state.peerId;I.managers.appStoriesManager.togglePinned(Re,ve().id,me).then(()=>{$e({langPackKey:me?Re.isUser()?"StoryPinnedToProfile":"StoryPinnedToPosts":Re.isUser()?"StoryArchivedFromProfile":"StoryUnpinnedFromPosts"})})};let kd=!1,of,ir,Xn,Td=!1;const Nw=ki({buttons:[{icon:"plusround",text:"Story.AddToProfile",onClick:()=>ip(!0),verify:()=>ir===I.myId&&!Xn.pFlags?.pinned},{icon:"crossround",text:"Story.RemoveFromProfile",onClick:()=>ip(!1),verify:()=>ir===I.myId&&!!Xn.pFlags?.pinned},{icon:"plusround",text:"SaveToPosts",onClick:()=>ip(!0),verify:()=>!ir.isUser()&&!Xn.pFlags?.pinned&&I.managers.appStoriesManager.hasRights(ir,Xn.id,"pin")},{icon:"crossround",text:"RemoveFromPosts",onClick:()=>ip(!1),verify:()=>!ir.isUser()&&!!Xn.pFlags?.pinned&&I.managers.appStoriesManager.hasRights(ir,Xn.id,"pin")},{icon:"forward",text:"ShareFile",onClick:()=>{Td=!0,o(kd)},verify:()=>!!Xn?.pFlags?.public&&!Xn.pFlags.noforwards},{icon:"link",text:"CopyLink",onClick:Tt,verify:()=>Xn._!=="storyItem"?!1:Xn.pFlags.public&&!!ji(of)[0]},{icon:"download",text:"MediaViewer.Context.Download",onClick:()=>{const me=ve(),Re=Vi(me,!0);Re&&fs.downloadToDisc({media:bl(Re)})},verify:()=>{if(a.state.peerId===I.myId)return!0;const me=ve();return!!(me?._==="storyItem"&&!me.pFlags.noforwards&&I.premium)}},{icon:"archive",text:"ArchivePeerStories",onClick:()=>$w(!0),verify:()=>Dw(!0)},{icon:"unarchive",text:"UnarchiveStories",onClick:()=>$w(!1),verify:()=>Dw(!1)},{icon:"statistics",text:"ViewStatistics",onClick:()=>{const me=ve().id;a.close(()=>{setTimeout(()=>{Gs.createTab(Wu).open(ir.toChatId(),void 0,me),Gs.toggleSidebar(!0)},0)})},verify:()=>I.managers.appProfileManager.canViewStatistics(ir)},{icon:"delete danger",text:"Delete",onClick:async()=>{const me=ve().id,Re=a.state.peerId;Td=!0;const dt=n(kd);try{await Rt({titleLangKey:"DeleteStoryTitle",descriptionLangKey:"DeleteStorySubtitle",button:{langKey:"Delete",isDanger:!0}})}catch{dt();return}I.managers.appStoriesManager.deleteStories(Re,[me])},verify:()=>I.managers.appStoriesManager.hasRights(ir,Xn.id,"delete")},{icon:"flag",className:"danger",text:"ReportChat",onClick:()=>{Td=!0;const me=n(kd);lu.createStoryReport(a.state.peerId,[ve().id],me)},verify:()=>!Xn.pFlags?.out&&a.state.peerId!==dl}],direction:"bottom-left",...ft});Nw.classList.add("night");const qM={close:"star_filled",contacts:"newprivate_filled",public:"newchannel_filled",selected:"newgroup_filled"},YM=async()=>{const me=Ie(),Re=await qe({peerId:a.state.peerId,onlyFirstName:!0}),{close:dt}=Ra({container:ap,element:lf,vertical:"bottom",textElement:P(me==="close"?"StoryCloseFriendsHint":me==="selected"?"StorySelectedContactsHint":"StoryContactsHint",[Re]),paddingX:13});tt(()=>dt)};le(()=>{const me=Je();me&&(ze(me),le(Vt(()=>[A(),ve()],()=>{me(),tt()},{defer:!0})))});let lf;const QM=(()=>{const me=Va();me.$$click=()=>YM();const Re=lf;return typeof Re=="function"?Ue(Re,me):lf=me,k(me,()=>Be(qM[Ie()])),Me(()=>be(me,Ge(He.ViewerStoryPrivacy,"privacy-bg",`privacy-bg-${Ie()}`))),me})(),XM=t&&(()=>{const me=ve();if(me._!=="storyItem")return;const Re=me.views?.views_count??0;return Re?P("Views",[Re]):me.expire_date<=Qs(!0)?P("NobodyViewsArchived"):P("NobodyViews")}),ZM=t&&(()=>{let me;const Re=new Map,dt=ue.createPopup(Rs,{peerType:["custom"],getMoreCustom:vt=>I.managers.appStoriesManager.getStoryViewsList(a.state.peerId,ve().id,50,me,vt).then(({nextOffset:Lt,views:bs})=>(me=Lt,{result:bs.map(ws=>{const Si=ws.user_id.toPeerId(!1);return Re.set(Si,ws),Si}),isEnd:!me})),processElementAfter:(vt,At)=>{const Lt=Re.get(vt);return OP({dialogElement:At,peerId:vt,date:Lt.date,isMine:!0,middleware:dt.selector.middlewareHelperLoader.get(),reaction:Lt.reaction})},onSelect:vt=>{a.close(()=>{Ce.setInnerPeer({peerId:vt})})},placeholder:"SearchPlaceholder",exceptSelf:!0,meAsSaved:!1})}),JM=t&&(async()=>{const me=a.state.peerId,Re=ve().id;await Rt({titleLangKey:"DeleteStoryTitle",descriptionLangKey:"DeleteStorySubtitle",button:{isDanger:!0,langKey:"Delete"}}),I.managers.appStoriesManager.deleteStories(me,[Re])});if(t){const me=new Set,Re=2;let dt;const vt=async()=>{if(dt)return;const bs=ve(),ws=a.state.stories.indexOf(bs);a.state.stories.slice(Math.max(0,ws-Re),ws+Re).forEach(Ws=>{me.add(Ws.id)});const Ti=Array.from(me);me.clear(),dt=I.managers.appStoriesManager.getStoriesViews(a.state.peerId,Ti).then(()=>{dt=void 0}),Lt&&clearInterval(At)},At=setInterval(vt,1e4);le(()=>{const bs=ve();me.add(bs.id)});let Lt=!1;ze(()=>{Lt=!0}),Jt(()=>{vt()})}let cf;const eL=(t||dl===a.state.peerId||!a.state.peerId.isUser())&&(()=>{const me=Va();return k(me,()=>t?[(()=>{const Re=Va();return Lr(Re,"click",ZM,!0),k(Re,(()=>{const dt=V(()=>!!Ye());return()=>dt()&&Ye().container})(),null),k(Re,XM,null),Me(()=>be(Re,He.ViewerStoryFooterLeft)),Re})(),(()=>{const Re=Va();return k(Re,T(Pi,{icon:"delete",onClick:JM})),Me(()=>be(Re,He.ViewerStoryFooterRight)),Re})()]:a.state.peerId.isUser()?P("StoryCantReply"):[(()=>{const Re=J0(),dt=Re.firstChild;return k(dt,()=>Be("eye1",He.ViewerStoryFooterIconIcon),null),k(dt,()=>un(ve().views?.views_count||1,1),null),Me(vt=>{const At=He.ViewerStoryFooterLeft,Lt=He.ViewerStoryFooterIcon;return At!==vt._v$13&&be(Re,vt._v$13=At),Lt!==vt._v$14&&be(dt,vt._v$14=Lt),vt},{_v$13:void 0,_v$14:void 0}),Re})(),(()=>{const Re=J0(),dt=Re.firstChild;k(Re,(()=>{const At=V(()=>!!G());return()=>At()&&T(Pi,{icon:"forward",onClick:Lt=>{l(Lt,Lt.target)}})})(),dt),dt.$$click=At=>he({reaction:{_:"reactionEmoji",emoticon:pw},target:cf.firstElementChild});const vt=cf;return typeof vt=="function"?Ue(vt,dt):cf=dt,k(dt,T(hs,{get icon(){return ve().sent_reaction?"reactions_filled":"reactions"},get class(){return He.ViewerStoryFooterIconIcon}}),null),k(dt,()=>ve().views?.reactions_count||0,null),Me(At=>{const Lt=He.ViewerStoryFooterRight,bs=Ge(He.ViewerStoryFooterIcon,He.ViewerStoryFooterReaction,ve().sent_reaction&&He.isReacted);return Lt!==At._v$15&&be(Re,At._v$15=Lt),bs!==At._v$16&&be(dt,At._v$16=bs),At},{_v$15:void 0,_v$16:void 0}),Re})()]),Me(()=>be(me,Ge(He.ViewerStoryFooter,He.hideOnSmall,I.myId===a.state.peerId&&He.isMe,dl===a.state.peerId&&He.isChangelog))),me})();le(Vt(()=>[A(),ve()],()=>{wt.isAvailable("animations")||Ot(()=>{We(),Ke()})}));const tL=()=>{const me=a.state.peerId;a.close(()=>{Ce.setInnerPeer({peerId:me})})},np=V(()=>a.index()-a.peers.indexOf(u.peer)),sL=V(me=>re()?me:np()<0),iL=V(me=>re()?me:np()>0),[Ow,df]=K(!1),hf=V(()=>{const me=Math.abs(np());let Re;return u.hasViewer?Re=me<=wy:(Re=me===0,!a.isFull()&&me<=wy&&(Te=!1)),Re});le(me=>{if(hf()){if(me)return df(!0),hi().then(()=>{df(!1)}),!0}else return df(!0),!0});let xd,Ad,ap;const nL=(()=>{const me=_9(),Re=me.firstChild,dt=Re.firstChild,vt=dt.nextSibling,At=vt.firstChild,Lt=At.nextSibling,bs=Lt.nextSibling,ws=bs.firstChild,Si=ws.firstChild,Ti=Si.firstChild,Ws=Ti.nextSibling,_s=ws.nextSibling;me.addEventListener("transitionend",Ke),me.addEventListener("transitionstart",We),me.$$click=Et=>{if(!A())h.set({peer:a.state,index:a.state.index});else if(ne(Et.target,He.ViewerStoryRepost)){const Is=ve(),Xi=Z0(Is);if(!Xi){$e({langPackKey:"HidAccount"});return}const{fwdFrom:gi,mediaAreaChannelPost:Jn}=Xi;(gi?.from||Jn)&&a.close(()=>{const Tr=gi?it(gi.from):Jn.channel_id.toPeerId(!0);gi?.story_id?Fo({peerId:Tr,id:gi.story_id}):Ce.setInnerPeer({peerId:Tr,lastMsgId:Jn?.msg_id})})}else if(Ds.scrollTop&&!Mi(Et.target,Tn)&&!ne(Et.target,He.ViewerStoryHeader))Ba(-Ds.scrollTop);else if(!u.paused&&!u.hideInterface&&!Mi(Et.target,Tn)&&!ne(Et.target,He.ViewerStoryHeader)&&!ne(Et.target,"stories-input")&&!ne(Et.target,He.ViewerStoryReactions)&&ne(Et.target,He.ViewerStory)){const Is=xd.getBoundingClientRect(),Xi=Et.clientX>Is.left+Is.width/3;h.goToNearestStorySafe(Xi)}};const Hs=xd;typeof Hs=="function"?Ue(Hs,me):xd=me;const sn=Ad;typeof sn=="function"?Ue(sn,Re):Ad=Re,k(dt,ri),k(Lt,ye);const Zn=ap;return typeof Zn=="function"?Ue(Zn,bs):ap=bs,ws.$$click=tL,k(ws,()=>e.element,Si),k(Ti,i,null),k(Ti,(()=>{const Et=V(()=>!!a.splitByDays);return()=>Et()&&(()=>{const Is=Vd();return k(Is,()=>`${tC}${a.state.index+1}/${a.state.stories.length}`),Me(()=>be(Is,He.ViewerStoryHeaderSecondary)),Is})()})(),null),k(Ws,sc),k(_s,()=>Ie()&&QM,null),k(_s,T(Pi,{get icon(){return u.paused&&!u.playAfterGesture?"play":"pause"},onClick:()=>h.toggle()}),null),k(_s,()=>g()&&ct,null),k(_s,Nw,null),k(_s,(()=>{const Et=V(()=>!!a.isFull());return()=>Et()&&T(Pi,{icon:"close",onClick:()=>a.close()})})(),null),k(vt,()=>(v()||w())&&qt,null),k(vt,(()=>{const Et=V(()=>!!fe());return()=>Et()&&(()=>{const Is=Va();return k(Is,fe),Me(Xi=>{const gi=He.ViewerStoryMediaAreas,Jn=M()&&{opacity:1-M()*.5,"z-index":0};return gi!==Xi._v$31&&be(Is,Xi._v$31=gi),Xi._v$32=Ii(Is,Jn,Xi._v$32),Xi},{_v$31:void 0,_v$32:void 0}),Is})()})(),null),k(vt,()=>ht()?.widthContainer,null),k(Re,(()=>{const Et=V(()=>!a.isFull());return()=>Et()&&(()=>{const Is=Va();return k(Is,()=>c.node,null),k(Is,d,null),Me(()=>be(Is,He.ViewerStoryInfo)),Is})()})(),null),k(me,jM||eL,null),Me(Et=>{const Is=He.ViewerStoryContainer,Xi={...a.isFull()?{[He.fromLeft]:sL(),[He.current]:A(),[He.fromRight]:iL()}:{[He.small]:!A()},[He.hold]:u.hideInterface&&A(),[He.focused]:q(),[He.fadeIn]:Ow()},gi=!a.isFull()&&{"--translateX":Pe()},Jn=Ge(He.ViewerStory,B()&&A()&&"shimmer"),Tr=He.ViewerStoryContent,Rd=He.hideOnSmall,rp=Ge(He.ViewerStoryShadow,v()&&He.hasCaption),op=He.ViewerStorySlides,lp=Ge(He.ViewerStoryHeader,"night"),cp=He.ViewerStoryHeaderLeft,dp=He.ViewerStoryHeaderInfo,Fd=He.ViewerStoryHeaderRow,Bd=Ge(w()?He.hasRepost:He.ViewerStoryHeaderSecondary,He.ViewerStoryHeaderTime),hp=He.ViewerStoryHeaderRight;return Is!==Et._v$17&&be(me,Et._v$17=Is),Et._v$18=er(me,Xi,Et._v$18),Et._v$19=Ii(me,gi,Et._v$19),Jn!==Et._v$20&&be(Re,Et._v$20=Jn),Tr!==Et._v$21&&be(dt,Et._v$21=Tr),Rd!==Et._v$22&&be(vt,Et._v$22=Rd),rp!==Et._v$23&&be(At,Et._v$23=rp),op!==Et._v$24&&be(Lt,Et._v$24=op),lp!==Et._v$25&&be(bs,Et._v$25=lp),cp!==Et._v$26&&be(ws,Et._v$26=cp),dp!==Et._v$27&&be(Si,Et._v$27=dp),Fd!==Et._v$28&&be(Ti,Et._v$28=Fd),Bd!==Et._v$29&&be(Ws,Et._v$29=Bd),hp!==Et._v$30&&be(_s,Et._v$30=hp),Et},{_v$17:void 0,_v$18:void 0,_v$19:void 0,_v$20:void 0,_v$21:void 0,_v$22:void 0,_v$23:void 0,_v$24:void 0,_v$25:void 0,_v$26:void 0,_v$27:void 0,_v$28:void 0,_v$29:void 0,_v$30:void 0}),me})(),Uw={container:ap,element:bt,vertical:"bottom",paddingX:13};return T(Js,{get when(){return hf()},children:nL})};function R9(a){const[e,t]=ec(),[s,i]=K(!1),n=V(()=>It.height>It.width||It.width<e.width+135+8*2||e.width===It.width),r=V(O=>O||s());t.viewerReady(!1);const o=new Set(["ArrowRight","ArrowLeft","ArrowDown","Space"]),l=O=>{if(b9(document.activeElement)){c.clear();return}const $=M();if(G||$.querySelector(".is-recording")){c.clear(),_e(O);return}if(o.has(O.key)||o.has(O.code))_e(O);else{const H=$.querySelector(".input-message-input");H&&!pt&&H.isContentEditable&&vn.overlaysActive===L&&f_(H,O)}if(O.key==="ArrowDown"){c.clear(),d();return}c(O)},c=fa(O=>{O.key==="ArrowRight"?t.goToNearestStorySafe(!0):O.key==="ArrowLeft"?t.goToNearestStorySafe(!1):O.code==="Space"&&t.toggle()},200,!0);Gn.getElement().classList.add("night"),Gn.setTextColor("white"),ze(()=>{document.body.removeEventListener("keydown",l),E(!1),v.removeListeners(),Pt.removeItem(_),Gn.getElement().classList.remove("night"),Gn.setTextColor(),Gn.chatInput=void 0});const d=O=>{O&&Vh(S,()=>{ze(()=>{O()})}),t.viewerReady(!1),m&&(N=Mt(),Al(N,1e3),m(),m=void 0),t.pause(),c.clear(),i(!1),u.removeEventListener("click",b,{capture:!0})};let u,h,p,m;const g=Ft(O=>{m=O,le(()=>{e.ended&&d()});const $=new Set,H=new Set;performance.now();let D=!1;const U=()=>{clearTimeout(j),D=!0,Vh(S,()=>{Jt(()=>{w()})})},j=setTimeout(()=>{console.error("stories timeout"),e.peers.filter(ie=>H.has(ie.peerId)&&!$.has(ie.peerId)).forEach(ie=>{console.error("stories not ready",ie)}),U()},250),q=(ie,oe)=>{const ae=()=>{$.add(ie.peerId),!D&&$.size===H.size&&U()};H.add(ie.peerId);const ke=K(!1),re=T(A9,{state:ie,index:oe,get splitByDays(){return a.splitByDays},get pinned(){return a.pinned},onReady:ae,close:d,get peers(){return z()},isFull:n,transitionSignal:ke}),ce=sb(()=>re);return le(()=>{const Ie=ce();Ie&&(de.set(Ie,ke[0]),ze(()=>{de.delete(Ie)}))}),re},W=wy+P9,ee=ie=>e.peers.slice(Math.max(ie-W,0),Math.min(ie+W+1,e.peers.length)),z=V(()=>ee(e.index)),Z=T(Pi,{ref(ie){const oe=p;typeof oe=="function"?oe(ie):p=ie},icon:"close",get class(){return He.ViewerClose},onClick:()=>d()}),de=new WeakMap;return(()=>{const ie=I9(),oe=ie.firstChild;ie.$$click=re=>{if(G){_e(re);return}re.target===u&&d()};const ae=u;typeof ae=="function"?Ue(ae,ie):u=ie;const ke=h;return typeof ke=="function"?Ue(ke,oe):h=oe,k(ie,()=>!n()&&Z,null),k(ie,T(WP,{noWait:()=>n(),transitions:de,get children(){return T(Cs,{get each(){return z()},children:q})}}),null),Me(re=>{const ce=Ge(He.Viewer,!s()&&He.isInvisible,n()&&He.isFull,e.hasViewer&&He.isReady),Ie=e.width+"px",Ve=e.height+"px",fe=He.ViewerBackground;return ce!==re._v$33&&be(ie,re._v$33=ce),Ie!==re._v$34&&((re._v$34=Ie)!=null?ie.style.setProperty("--stories-width",Ie):ie.style.removeProperty("--stories-width")),Ve!==re._v$35&&((re._v$35=Ve)!=null?ie.style.setProperty("--stories-height",Ve):ie.style.removeProperty("--stories-height")),fe!==re._v$36&&be(oe,re._v$36=fe),re},{_v$33:void 0,_v$34:void 0,_v$35:void 0,_v$36:void 0}),ie})()});let f;const v=new Qn({element:u,onSwipe:(O,$,H)=>{if(!(H instanceof TouchEvent))return;const D=Math.min(125,It.width/3),U=Math.min(125,It.height*.2);if($>U)return d(),!0;if(Math.abs(O)<D)return!1;const q=e.peers.indexOf(e.peer)+(O<0?1:-1),W=e.peers[q];return W?t.set({peer:W}):d(),!0},verifyTouchTarget:O=>!ne(O.target,"btn-icon")&&!ne(O.target,"btn-corner")&&!ne(O.target,He.ViewerStoryRepost)&&!ne(O.target,He.ViewerStoryMediaArea)&&!ne(O.target,He.ViewerStoryPrivacy)&&!ne(O.target,He.ViewerStoryCaptionText)&&!ne(O.target,He.ViewerStoryReactions)&&!!ne(O.target,He.ViewerStory)&&!ne(O.target,He.small)&&!ne(O.target,He.focused),onStart:()=>{f=window.setTimeout(()=>{t.pause(!0)},200)},onReset:O=>{if(window.clearTimeout(f),!O||!e.paused||ne(O.target,"btn-icon")||ne(O.target,He.ViewerStoryPrivacy)||ne(O.target,"btn-corner")||ne(O.target,He.ViewerStoryReactions))return;const $=ne(O.target,He.ViewerStory);if($?.querySelector("."+He.ViewerStoryCaption)?.scrollTop)return;$&&e.hideInterface&&document.addEventListener("click",_e,{capture:!0,once:!0});const D=e.playAfterGesture||!e.hideInterface;t.toggleInterface(!1),D&&t.play()}});let y;const w=()=>{const O=a.target?.();if(!O||!O.classList.contains("avatar")){i(!0);return}y=jn({size:by,isDialog:!1,useCache:!1}),y.node.style.cssText="position: absolute; visibility: hidden; z-index: 1000; transform-origin: top left;",document.body.append(y.node),Ot(()=>s())||le(()=>{y.ready()&&i(!0)}),le(()=>{const $=e.peer?.peerId;!$||!y||Ot(()=>{y.render({peerId:$})})}),ze(()=>{y&&y.node.remove()})},b=O=>{G&&_e(O);const H=ne(O.target,He.ViewerStory)?.querySelector("."+He.ViewerStoryCaptionText),D=H&&tp(H,O);if(D)return d(D),!1};u.addEventListener("click",b,{capture:!0});const S=Sg(),_={type:"stories",onPop:()=>{if(G)return!1;d()}};Pt.pushItem(_);const M=(O=u)=>O.querySelector(`.${He.ViewerStoryContainer}:not(.${He.small})`),C=(O,$,H)=>{const D=M(O);if(!wt.isAvailable("animations")||!D){H();return}const U=Array.from(O.querySelectorAll(`.${He.ViewerStoryContainer}`));let j;const q=Ot(()=>{const Je=a.target?.();if(!Je)return;const tt=ne(Je,"scrollable");if(!tt)return Je;const ht=Ko(Je,tt);if(!ht){y&&(y.node.remove(),y=void 0);return}return y&&(ht.overflow.horizontal||ht.overflow.vertical)&&(j=!0),Je}),W=q&&(q.querySelector(".avatar")||q).getBoundingClientRect(),ee=D.getBoundingClientRect(),z=y?"50%":window.getComputedStyle(D).borderRadius,Z=Je=>($||Je.reverse(),Je),de={duration:250,easing:"cubic-bezier(0.4, 0.0, 0.6, 1)"};let ie,oe;if(y){oe=D.querySelector(`.${He.ViewerStoryHeaderAvatar}`),oe.style.visibility="hidden";const Je=oe.getBoundingClientRect();y.node.style.top=`${W.top}px`,y.node.style.left=`${W.left}px`,y.node.style.visibility="",y.node.parentElement||document.body.append(y.node);const tt=Je.left-W.left,ht=Je.top-W.top,Ee=Z([{transform:`translate(0, 0) scale(${W.width/by})`},{transform:`translate(${tt}px, ${ht}px) scale(1)`}]);j&&(Ee[0].opacity=0,Ee[1].opacity=1),ie=y.node.animate(Ee,de)}const ae=W&&W.left-It.width/2+W.width/2,ke=W&&W.top-It.height/2+W.height/2,re=W&&D.animate(Z([{borderRadius:z,transform:`translate3d(${ae}px, ${ke}px, 0) scale3d(${W.width/ee.width}, ${W.height/ee.height}, 1)`,opacity:0},{opacity:1,offset:.3},{borderRadius:"0%",transform:"translate3d(0, 0, 0) scale3d(1, 1, 1)"}]),de),ce=(re?[h,!n()&&p].filter(Boolean):[D,O]).map(Je=>Je.animate(Z([{opacity:0},{opacity:1}]),de)),Ie=U.indexOf(D);U.splice(Ie,1);const Ve=U.slice(0,Ie),fe=U.slice(Ie),Xe=(Je,tt)=>W?Je.map((ht,Ee,ve)=>{const Qe=(tt?Ee+1:ve.length-Ee)*60*(tt?-1:1);return ht.animate(Z([{transform:`translate3d(calc(var(--translateX) + ${Qe}px), 0, 0) scale3d(${rh/2}, ${rh/2}, 1)`,opacity:.001},{opacity:.001,offset:.5},{transform:`translate3d(var(--translateX), 0, 0) scale3d(${rh}, ${rh}, 1)`,opacity:1}]),de)}):Je.map(ht=>ht.animate(Z([{opacity:0},{opacity:1}]),de)),Ze=[...ce,re,ie,...Xe(Ve,!1),...Xe(fe,!0)].map(Je=>Je?.finished);return Promise.all(Ze).then(()=>{y&&(y.node.remove(),oe.style.visibility=""),H()})};let L;const E=O=>{t.toggleSorting("viewer",O),vn.isDarkOverlayActive=O,Ut.checkAnimations2(O),O&&(L=vn.overlaysActive)},x=sM();let R;x.add(qr)("change",O=>{if(O){R=!e.paused,t.pause(),eC.open();return}const $=()=>{clearTimeout(H)};document.body.addEventListener("mousedown",$,{once:!0});const H=setTimeout(()=>{document.body.removeEventListener("mousedown",$),eC.close()},100);R&&t.play()});let B;x.add(vn)("change",()=>{const O=vn.overlaysActive;O>L?(B=!e.paused,t.pause()):O===L&&B&&t.play()});let N=Mt(),G=!0;return T(Js,{get when(){return r()},fallback:g,get children(){return T(Du,{onEnter:(O,$)=>{Al(N,1e3),document.body.addEventListener("keydown",l),E(!0),C(O,!0,$)},onAfterEnter:()=>{G=!1,t.viewerReady(!0),N.resolve()},onExit:(O,$)=>{G=!0,t.viewerReady(!1),C(O,!1,$)},onAfterExit:()=>{G=!1,a.onExit?.(),stop(),N.resolve()},appear:!0,get children(){return s()&&g}})}})}const Ju=a=>a.peers&&!a.onExit?Ft(e=>(a.onExit=()=>e(),T(uw,{get peers(){return a.peers},get index(){return a.index},get children(){return Ju(a)}}))):T(gd,{get mount(){return document.getElementById("stories-viewer")},get children(){return T(R9,a)}}),F9=a=>{const[,e]=wa(a,["peerId","storyItem"]);return Ju({...e,peers:[{peerId:a.peerId,stories:[a.storyItem],index:0,count:1}],index:0})},Fo=async a=>{const[,e]=wa(a,["peerId","id"]),t=await I.managers.appStoriesManager.getPeerStories(a.peerId),s=a.id?t.stories.findIndex(i=>i.id===a.id):void 0;if(a.id){const i=await I.managers.appStoriesManager.getStoryById(a.peerId,a.id);if(!i){$e({langPackKey:"Story.ExpiredToast"});return}F9({...e,peerId:a.peerId,storyItem:i,singleStory:!0});return}Ju({...e,peers:[{peerId:a.peerId,stories:t.stories,maxReadId:t.max_read_id,index:s,count:t.stories.length}],index:0})};Fs(["click"]);const B9="_List_pejiw_41",D9="_ListItem_pejiw_56",$9="_ListItemName_pejiw_71",N9="_isRead_pejiw_83",O9="_isMasked_pejiw_86",U9="_ListContainer_pejiw_115",H9="_skipAnimation_pejiw_123",uo={List:B9,"space-evenly":"_space-evenly_pejiw_45",ListItem:D9,ListItemName:$9,isRead:N9,isMasked:O9,ListContainer:U9,skipAnimation:H9};class dd extends Zt{static getInitArgs(){return{animationData:Ns.loadAnimationFromURLManually("UtyanStories")}}init(e=dd.getInitArgs()){this.header.classList.add("with-border"),this.container.classList.add("chat-folders-container",`${this.isArchive?"archive":"my"}-stories-container`),this.setTitle(this.isArchive?"MyStories.Archive":"MyStories.Title");const t=()=>{const c=this.slider.createTab(dd);c.isArchive=!0,c.open()};let s,i;if(this.isArchive)i=new Oe({caption:"ProfileStoriesArchiveHint"}),i.innerContainer.remove();else{s=document.createElement("div"),s.classList.add("my-stories-placeholder","hide"),this.stickerContainer=document.createElement("div"),this.stickerContainer.classList.add("sticker-container");const c=document.createElement("div");c.classList.add("caption"),Rh({element:c,key:"MyStories.Subtitle"}),this.showArchiveBtn=ot("btn-primary btn-color-primary btn-control",{text:"MyStories.ShowArchive"}),J(this.showArchiveBtn,t,{listenerSetter:this.listenerSetter}),s.append(this.stickerContainer,c,this.showArchiveBtn)}const n=ki({listenerSetter:this.listenerSetter,direction:"bottom-left",buttons:[{icon:"archive",text:"MyStories.ShowArchive",onClick:t,verify:()=>!this.isArchive},{icon:"select",text:"Message.Context.Select",onClick:()=>{o.selection.toggleSelection(!0,!0)},verify:()=>!!(r&&!o.selection.isSelecting)},{icon:"select",text:"Message.Context.Selection.Clear",onClick:()=>{o.selection.cancelSelection()},verify:()=>o.selection.isSelecting}]});this.header.append(n);let r;const o=this.searchSuper=new ww({mediaTabs:[{inputFilter:"inputMessagesFilterEmpty",name:"Stories",type:"stories"}],scrollable:this.scrollable,hideEmptyTabs:!0,managers:this.managers,storiesArchive:this.isArchive});o.onStoriesLengthChange=c=>{r=c,s&&s.classList.toggle("hide",c>0)},o.setQuery({peerId:I.myId}),o.selectTab(0),this.middlewareHelper.onDestroy(()=>{o.destroy()}),this.scrollable.append(...[i?.container,o.container,s].filter(Boolean));const l=this.middlewareHelper.get();return Promise.all([this.loadAnimationPromise=!this.isArchive&&e.animationData.then(async c=>{const d=await c({container:this.stickerContainer,loop:!1,autoplay:!1,width:100,height:100,middleware:l});return this.animation=d,Ns.waitForFirstFrame(d)}),o.load(!0)])}}const zd=1,cc=0;function nM(a){const[e,t]=K(zd),[s,i]=K(!1),n=V(()=>e()===zd),r=(v,y)=>{wt.isAvailable("animations")&&!y&&i(!0),t(v)},o=(v,y)=>{const w=Date.now(),b=c=Wl(()=>{const S=zt((Date.now()-w)/125,0,1);let _=v;return(v>.5||y===!1)&&y!==!0?(_+=(1-v)*S,d=!1):(d=!0,_-=v*S),r(_),S<1},a.container()).finally(()=>{b===c&&(c=void 0)})},l=()=>{Zy(a.container())};let c,d;const h=$i(()=>{},75,!1,!0),p=(v,y)=>{const w=a.scrollable().scrollTop,b=y instanceof WheelEvent;{const M=v<0?cc:zd;if(w&&e()!==cc||h.isDebounced()){h();return}if(e()===M)return;y&&_e(y),r(M);return}const S=e();if(a.container().classList.add(a.skipAnimationClassName),v>0&&c&&d){h.clearTimeout(),o(S,!1);return}if(c||S>=zd&&v>0||S<=cc&&v<=0)return;let _=v/600;_=zt(S+_,0,1),r(_),_>=1||_<=0?h.clearTimeout():(y&&_e(y),h())},m=v=>{if(a.shouldIgnore?.())return;const w=-v.wheelDeltaY;p(w,v)};if(Ta(a.listenWheelOn)("wheel",m,{passive:!1}),pt){const v=new Qn({element:a.listenWheelOn,onSwipe:(y,w,b)=>{const S=-w;p(S,b)},cancelEvent:!1,cursor:"",verifyTouchTarget:y=>y instanceof TouchEvent&&!a.shouldIgnore?.()&&!ne(y.target,"folders-tabs-scrollable")});ze(()=>{v.removeListeners()})}const g=v=>{e()!==cc&&(l(),r(cc),v&&_e(v))},f=()=>{o(e(),!1)};return le(()=>{const v=a.container();v&&(v.classList.toggle("disable-hover",(a.disableHoverWhenFolded?n():!1)||s()),a.skipAnimationClassName&&v.classList.toggle(a.skipAnimationClassName,n()&&!s()))}),le(()=>{const v=a.container();v&&(Ta(v)("transitionstart",y=>y.target===v&&i(!0)),Ta(v)("transitionend",y=>y.target===v&&i(!1)))}),{folded:n,unfold:g,fold:f,progress:e,clearAnimation:l,isTransition:s,STATE_FOLDED:zd,STATE_UNFOLDED:cc}}const Sy=Y("<div>"),G9=Y("<div><div>"),cu=a=>{const[,e]=wa(a,["onAdditionalScroll"]);let t;const s=(()=>{const n=Sy(),r=t;return typeof r=="function"?Ue(r,n):t=n,so(n,e,!1,!0),k(n,()=>a.children),n})(),i=new io(void 0,void 0,void 0,void 0,t);return a.onAdditionalScroll&&(i.setListeners(),i.onAdditionalScroll=a.onAdditionalScroll),ze(()=>{i.destroy()}),s},V9=0,Fp=74+V9*2,z9=54,W9=3,K9=348;function j9(a){const[e,t]=ec(),[s,i]=K(),[n,r]=K(),[o,l]=K(!0),c=V(()=>n()?.width>K9?W9:1),d=V(()=>e.peers);let u,h;const p=V(()=>d().findIndex(W=>W.peerId===I.myId)),m=V(()=>{const W=n();return W&&W.width>d().length*Fp?(W.width-d().length*Fp)/(d().length+1):0}),g=new WeakMap,f=new WeakMap,v=W=>O(W);le(()=>{if(!s())return;const ee=()=>{i(void 0)},z=V(()=>g.get(e.peer)?.querySelector(".avatar"));Ju({onExit:ee,target:z})});const y=(W,ee)=>{if(D()!==U)return v(ee);t.resetIndexes(),t.set({peer:W}),i(W)},w=V(()=>Math.min(c(),d().length-(p()!==-1?1:0))),b=V(()=>({min:p()===0&&d().length>1?1:0,max:p()===0?w():w()-1})),S=(W,ee=b())=>{const{min:z,max:Z}=ee;return W<z||W>Z},_=(W,ee)=>{const z=y.bind(null,W),Z=V(()=>{const ae=n(),ke=D(),re=ee(),ce=m(),Ie=ce?0:C,Ve=b(),fe=S(re,Ve),Ye=h.left+Ie+re*Fp+ce*(re+1);if(ae.left+Ie+re*Fp+ce*(re+1)>ae.right)return;const Je={};fe?Je["z-index"]=100-re:Je["z-index"]=100+w()+1-re;const tt=u.right+(a.offsetX||0),ht=fe?0:(Ve.max-re)*16;let Ee=tt-Ye+5-ht,ve;fe?(Je["transform-origin"]="center 43.75%",Ee+=8*(re<Ve.min?1:-1),ve=.2):ve=26.67/48;const Qe=Ee*ke,A=`translateX(calc(var(--stories-additional-offset, 0px) * ${ke} + ${Qe*(Ne.isRTL?-1:1)}px))`,Q=`scale(${1-ke*(1-ve)})`;return Je.transform=`${A} ${Q}`,{isOut:fe,isLastIn:!fe&&re===Ve.max,cssProperties:Je}}),de=jn({peerId:W.peerId,size:z9,props:{onClick:z},isDialog:!1,withStories:!0,isStoryFolded:q}),ie=W.peerId===I.myId,oe=(()=>{const ae=G9(),ke=ae.firstChild;return Lr(ae,"click",z,!0),Ue(re=>(g.set(W,re),f.set(re,W)),ae),k(ae,()=>de.element,ke),k(ke,()=>ie?P("MyStory"):T(Cl,{get peerId(){return W.peerId},onlyFirstName:!0})),Me(re=>{const ce=uo.ListItem,Ie={[uo.isRead]:!ie&&W.maxReadId&&W.maxReadId>=W.stories[W.stories.length-1].id,[uo.isMasked]:(()=>{const Xe=Z();return Xe&&!Xe.isOut&&!Xe.isLastIn})()},Ve={...Z()?.cssProperties,transition:o()?void 0:"none"},fe=uo.ListItemName;return ce!==re._v$&&be(ae,re._v$=ce),re._v$2=er(ae,Ie,re._v$2),re._v$3=Ii(ae,Ve,re._v$3),fe!==re._v$4&&be(ke,re._v$4=fe),re},{_v$:void 0,_v$2:void 0,_v$3:void 0,_v$4:void 0}),ae})();return T(Js,{get when(){return Z()||!G()},children:oe})},M=-69,C=6,L=92;let E=!1;const x=()=>{const W=D(),ee=!E&&R();ee?.scrollLeft&&(E=!0,o_(ee).then(()=>{E=!1}));const Z=`translateY(${W*M}px)`;return a.setScrolledOn.style.setProperty("--stories-scrolled",W*L+"px"),{transform:Z,"--progress":W}};le(Vt(()=>d().length,W=>{W||$()},{defer:!0}));const R=()=>N.firstElementChild;le(()=>{if(G()||H()){const W=_e,ee=R();Ta(ee)("wheel",W,{capture:!0})}}),le(()=>{H()||t.toggleSorting("list",!G())});const B=()=>{u=a.foldInto.getBoundingClientRect(),h=a.foldInto.parentElement.getBoundingClientRect(),r(a.foldInto.parentElement.parentElement.getBoundingClientRect())};Ta(st)("resize",B),B(),a.resizeCallback?.(B);let N;Jt(()=>{const W=new $t;let ee;W.add(I)("resizing_left_sidebar",()=>{B(),window.clearTimeout(ee),l(!1),setTimeout(()=>{l(!0)},100)}),ze(()=>{W.removeAll()})});const{folded:G,unfold:O,fold:$,isTransition:H,progress:D,STATE_UNFOLDED:U}=nM({scrollable:a.getScrollable,container:()=>N,listenWheelOn:a.listenWheelOn,shouldIgnore:()=>!d().length,disableHoverWhenFolded:!0}),j=(()=>{const W=Sy(),ee=N;return typeof ee=="function"?Ue(ee,W):N=W,k(W,T(cu,{get children(){const z=Sy();return k(z,T(Cs,{get each(){return d()},children:_})),Me(Z=>{const de=uo.List,ie={[uo["space-evenly"]]:!!m()};return de!==Z._v$5&&be(z,Z._v$5=de),Z._v$6=er(z,ie,Z._v$6),Z},{_v$5:void 0,_v$6:void 0}),z}})),Me(z=>{const Z=uo.ListContainer,de=x();return Z!==z._v$7&&be(W,z._v$7=Z),z._v$8=Ii(W,de,z._v$8),z},{_v$7:void 0,_v$8:void 0}),W})();Jt(()=>{const W=async de=>{I.managers.appNotificationsManager.toggleStoriesMute(z.peerId,de),$e({langPackKey:de?"NotificationsStoryMutedHint":"NotificationsStoryUnmutedHint",langPackArguments:[await qe({peerId:z.peerId})]})},ee=async de=>{I.managers.appStoriesManager.toggleStoriesHidden(z.peerId,de),$e({langPackKey:de?"StoriesMovedToContacts":"StoriesMovedToDialogs",langPackArguments:[await qe({peerId:z.peerId})]})};let z,Z;Dn({buttons:[{icon:"stories",text:"SavedStories",onClick:()=>{Ri.createTab(dd).open()},verify:()=>Z},{icon:"archive",text:"ArchivedStories",onClick:()=>{const de=Ri.createTab(dd);de.isArchive=!0,de.open()},verify:()=>Z},{icon:"message",text:"SendMessage",onClick:()=>{Ce.setInnerPeer({peerId:z.peerId,type:we.Chat})},verify:()=>!Z&&z.peerId.isUser()},{icon:"channel",text:"OpenChannel2",onClick:()=>{Ce.setInnerPeer({peerId:z.peerId,type:we.Chat})},verify:()=>!z.peerId.isUser()},{icon:"mute",text:"NotificationsStoryMute2",onClick:()=>W(!0),verify:()=>!Z&&I.managers.appNotificationsManager.isPeerStoriesMuted(z.peerId).then(de=>!de),multiline:!0},{icon:"unmute",text:"NotificationsStoryUnmute2",onClick:()=>W(!1),verify:()=>!Z&&I.managers.appNotificationsManager.isPeerStoriesMuted(z.peerId),multiline:!0},{icon:"archive",text:"ArchivePeerStories",onClick:()=>ee(!0),verify:()=>!Z&&!a.archive},{icon:"unarchive",text:"UnarchiveStories",onClick:()=>ee(!1),verify:()=>!Z&&!!a.archive}],listenTo:N,middleware:ui().get(),findElement:de=>!G()&&ne(de.target,uo.ListItem),onOpen:(de,ie)=>{z=f.get(ie),Z=z.peerId===I.myId},onClose:()=>{z=void 0}})});const q=V(()=>D()!==U);return V(()=>e.ready&&j)}function aM(a){const[,e]=wa(a,["foldInto","getScrollable","listenWheelOn","setScrolledOn","offsetX","resizeCallback"]);return T(uw,ni(e,{get children(){return T(j9,a)}}))}Fs(["click"]);const q9=Y("<div class=emoticons-search-input-category><div class=emoticons-search-input-category-sticker>"),Y9=Y("<div class=emoticons-search-input-categories>");function Q9(a){const{inputSearch:e}=a,[t,s]=K([]),[i,n]=K(),[r,o]=K(!1),l=(p,m)=>{n(p),Bu({container:d,element:m.target,position:"center",axis:"x"})},c=({group:p,document:m})=>{if(a.type!=="stickers"&&p._==="emojiGroupPremium")return;let g,f;const v=(()=>{const y=q9(),w=y.firstChild;y.$$click=l,y.$$clickData=p;const b=g;typeof b=="function"?Ue(b,y):g=y;const S=f;return typeof S=="function"?Ue(S,w):f=w,Me(_=>{const M=i()===p,C=p.title;return M!==_._v$&&y.classList.toggle("active",_._v$=M),C!==_._v$2&&Es(y,"title",_._v$2=C),_},{_v$:void 0,_v$2:void 0}),y})();return ai({doc:m,div:f,width:24,height:24,group:a.animatedItemGroup,play:!0,middleware:ui().get(),textColor:a.color}),v};let d;T(cu,{ref(p){const m=d;typeof m=="function"?m(p):d=p},class:"emoticons-search-input-scrollable",get classList(){return{"is-searching":a.searching(),"is-scrolled":r()}},onClick:p=>{p.target===e.currentPlaceholder&&Ki(e.input,!0,!0)},onAdditionalScroll:()=>{o(d.scrollLeft>0)},get children(){return[V(()=>e.currentPlaceholder),(()=>{const p=Y9();return k(p,T(Cs,{get each(){return t()},children:c})),p})()]}}),e.input.after(d),e.currentPlaceholder.classList.remove("will-animate");const u=e.createButtonIcon("arrow_prev","will-animate","emoticons-search-input-arrow");e.searchIcon.classList.add("will-animate"),e.searchIcon.after(u);const h=J(u,()=>{n()});ze(h),le(()=>{u.classList.toggle("is-hiding",!i()),e.searchIcon.classList.toggle("is-hiding",!!i())}),le(()=>{a.searching()&&n()}),le(Vt(i,p=>{a.onGroup(p),p||o_(d)},{defer:!0})),I.managers.appEmojiManager.getEmojiGroups(a.type==="stickers"?"stickers":"esg").then(s)}function rM(a){const[e,t]=K(!1),[s,i]=K(!1),n=new jo({placeholder:a.placeholder||"Search",onChange:r=>{r=r.trim(),t(!!r),a.onValue(r)},onFocusChange:a.onFocusChange,onDebounce:i,noBorder:!0,noFocusEffect:!0,debounceTime:0});return n.container.classList.add("emoticons-search-input-container"),n.input.classList.add("emoticons-search-input"),ze(()=>{n.remove()}),a.loading&&le(()=>{n.toggleLoading(s()||a.loading())}),a.onGroup&&Q9({type:a.type,searching:e,inputSearch:n,onGroup:a.onGroup,animatedItemGroup:a.animatedItemGroup,color:a.categoryColor}),V(()=>n.container)}Fs(["click"]);class mw{constructor(e){this.mounted=!1,this.resizeCategories=()=>{for(const[t,s]of this.categoriesMap)s.setCategoryItemsHeight()},this.postponedEvent=t=>(...s)=>{this.emoticonsDropdown.isActive()?this.postponedEvents.push({cb:t,args:s}):t(...s)},Nt(this,e),this.categories={},this.categoriesMap=new Map,this.categoriesByMenuTabMap=new Map,this.localCategories=[],this.postponedEvents=[],this.listenerSetter=new $t,this.middlewareHelper=Ht(),this.container=document.createElement("div"),this.container.classList.add("tabs-tab","emoticons-container"),this.noMenu?this.container.classList.add("no-menu"):this.createMenu(),this.content=document.createElement("div"),this.content.classList.add("emoticons-content"),this.container.append(...[this.menuWrapper,this.content].filter(Boolean)),this.scrollable=new tn(this.content,"STICKERS"),this.categoriesContainer=document.createElement("div"),this.categoriesContainer.classList.add("emoticons-categories-container"),this.noMenu||(this.scrollable.container.classList.add("emoticons-will-move-up"),this.categoriesContainer.classList.add("emoticons-will-move-down")),e.searchFetcher?this.createSearch():this.scrollable.append(this.categoriesContainer)}createMenu(){this.menuWrapper=document.createElement("div"),this.menuWrapper.classList.add("menu-wrapper","emoticons-menu-wrapper","emoticons-will-move-up"),this.menu=document.createElement("nav"),this.menu.className="menu-horizontal-div no-stripe justify-start emoticons-menu",this.menuWrapper.append(this.menu),this.menuScroll=new io(this.menuWrapper)}createSearch(){const e=document.createElement("div");e.classList.add("emoticons-search-container"),this.noMenu||e.classList.add("emoticons-will-move-down"),this.scrollable.append(e),this.categoriesContainer.classList.add("emoticons-has-search"),this.disposeSearch=wi(()=>{const[t,s]=K(""),[i,n]=K(),[r,o]=K(!1),l=V(()=>!!t()),[c,d]=K(),[u]=ma(t,this.searchFetcher),[h]=this.groupFetcher?ma(i,this.groupFetcher):[],[p]=ma(()=>({data:c(),grouping:!!Ot(i),searching:Ot(l)}),this.processSearchResult),m=this.searchNoLoader?void 0:V(()=>l()&&p.loading),g=V(()=>r()||l()||!!i()),f=V(()=>p()||this.categoriesContainer);return gd({mount:this.scrollable.container,children:Yo({type:"cross-fade",get children(){return f()}})}),le(()=>{const v=i()?h:u;v.loading||d(()=>v())}),le(()=>{this.container.classList.toggle("is-searching",g())}),rM({type:this.searchType,placeholder:this.searchPlaceholder,loading:m,onValue:s,onFocusChange:o,onGroup:this.groupFetcher?n:void 0})},e)}getCategoryByContainer(e){return this.categoriesMap.get(e)}getCategoryByMenuTab(e){return this.categoriesByMenuTabMap.get(e)}createCategory({stickerSet:e,title:t,isLocal:s,noMenuTab:i=!e,styles:n}){this.noMenu&&(i=!0);const r=new WT({id:""+e?.id,title:t,overflowElement:this.content,getContainerSize:()=>{let l,c;if(this.getContainerSize){const d=this.getContainerSize();l=d.width,c=d.height}else{const d=this.emoticonsDropdown.getElement(),u=d.style.getPropertyValue("--width");l=u?parseInt(u):d.offsetWidth}return{width:l-n.padding,height:c}},styles:n,noMenuTab:i,middleware:this.middlewareHelper.get()});n.itemsClassName&&r.elements.items.classList.add(n.itemsClassName);const o=r.elements.container;return o.classList.add("hide"),e&&(r.set=e,this.categories[e.id]=r,this.categoriesMap.set(o,r),this.categoriesIntersector.observe(o)),i||(this.categoriesByMenuTabMap.set(r.elements.menuTab,r),this.menuOnClickResult.stickyIntersector.observeStickyHeaderChanges(o),!s&&r.elements.menuTab.classList.add("not-local")),r}positionCategory(e,t){const{menuTab:s,container:i}=e.elements,n=t?this.localCategories.filter(l=>l.mounted).length:65535;let r=!1;const o=t?this.localCategories.filter(l=>l.menuScroll&&!r?(r=!0,!0):l.mounted&&!l.menuScroll&&l.elements.menuTab).length:65535;di(i,this.categoriesContainer,n),di(s,this.menu,o)}isCategoryVisible(e){return this.categoriesIntersector.isVisible(e.elements.container)}toggleLocalCategory(e,t){if(!t)e.elements.menuTab?.remove(),e.elements.container.remove();else{const s=this.localCategories.indexOf(e),i=this.localCategories.slice(0,s);let n=0,r=0;i.forEach(c=>{c.mounted?(!c.elements.menuTab||c.menuScroll)&&++r:(++n,++r)});const o=s-n,l=s-r;e.elements.menuTab&&di(e.elements.menuTab,this.menu,l),di(e.elements.container,this.categoriesContainer,o)}e.mounted=t}createLocalCategory({id:e,title:t,icon:s,noMenuTab:i,styles:n}){this.noMenu&&(i=!0);const r=e!==void 0,o=this.createCategory({stickerSet:r?{id:e}:void 0,title:t&&P(t),isLocal:!0,noMenuTab:i,styles:n});return o.local=!0,r&&this.localCategories.push(o),o.elements.title&&o.elements.title.classList.add("disable-hover"),o.elements.menuTab&&(s&&o.elements.menuTab.append(Be(s)),o.elements.menuTabPadding.remove()),this.toggleLocalCategory(o,!1),o}onLocalCategoryUpdate(e){e.setCategoryItemsHeight(),this.toggleLocalCategory(e,!!e.items.length)}deleteCategory(e){return e?(e.elements.container.remove(),e.elements.menuTab?.remove(),this.categoriesIntersector.unobserve(e.elements.container),delete this.categories[e.id],this.categoriesMap.delete(e.elements.container),this.categoriesByMenuTabMap.delete(e.elements.menuTab),e.middlewareHelper.destroy(),!0):!1}spliceExceed(e){if(e.limit===void 0)return!1;const{items:t,limit:s}=e;return t.splice(s,t.length-s).forEach(({element:i})=>{i.remove()}),this.onLocalCategoryUpdate(e),!0}init(){this.emoticonsDropdown&&this.listenerSetter.add(this.emoticonsDropdown)("closed",()=>{this.postponedEvents.forEach(({cb:e,args:t})=>{e(...t)}),this.postponedEvents.length=0})}destroy(){this.getContainerSize=void 0,this.postponedEvents.length=0,this.categoriesIntersector?.disconnect(),this.listenerSetter.removeAll(),this.scrollable.destroy(),this.menuScroll?.destroy(),this.menuOnClickResult?.stickyIntersector?.disconnect(),this.middlewareHelper.destroy(),this.disposeSearch?.()}attachHelpers({getTextColor:e,verifyRecent:t,canHaveEmojiTimer:s,isGif:i}={}){_d({listenTo:this.content,listenerSetter:this.listenerSetter,getTextColor:e});const n="menu";o1({listenTo:this.content,chatInput:this.emoticonsDropdown.chatInput,verifyRecent:t,isEmojis:!!e,isGif:i,canHaveEmojiTimer:s,canViewPack:!0,onOpen:()=>{this.emoticonsDropdown.setIgnoreMouseOut(n,!0)},onClose:()=>{this.emoticonsDropdown.setIgnoreMouseOut(n,!1)}})}renderStickerSetThumb({set:e,menuTabPadding:t,middleware:s,textColor:i}){gw({set:e,container:t,group:za,lazyLoadQueue:this.emoticonsDropdown?.lazyLoadQueue,width:32,height:32,autoplay:!1,textColor:i,middleware:s})}createStickerRenderer(){const e=new Id({regularLazyLoadQueue:this.emoticonsDropdown.lazyLoadQueue,group:za,managers:this.managers,intersectionObserverInit:this.emoticonsDropdown.intersectionOptions}),t=e.lazyLoadQueue;return this.emoticonsDropdown.addLazyLoadQueueRepeat(t,e.processInvisible,this.middlewareHelper.get()),e}}const So=class So extends mw{constructor(e){super({managers:e,searchFetcher:async t=>t?this.managers.appStickersManager.searchStickers(t):[],groupFetcher:async t=>t?t._==="emojiGroupPremium"?this.managers.appStickersManager.getPremiumStickers():this.managers.appStickersManager.getStickersByEmoticon({emoticon:t.emoticons,includeServerStickers:!0}):[],processSearchResult:async({data:t,searching:s,grouping:i})=>{if(!t||!s&&!i)return;if(!t.length){const c=P("NoStickersFound");return c.classList.add("emoticons-not-found"),c}const n=this.categoriesContainer.cloneNode(!1),r=this.createCategory({styles:Ur.Stickers}),o=So.categoryAppendStickers(this,this.stickerRenderer,t.length,r,t);n.append(r.elements.container);let l=!1;return ze(()=>{l=!0,r.middlewareHelper.destroy(),this.clearCategoryItems(r,!0)}),await o,l||So._onCategoryVisibility(r,!0),n},searchPlaceholder:"SearchStickers",searchType:"stickers"}),this.onCategoryVisibility=({target:t,visible:s})=>{const i=this.categoriesMap.get(t);So._onCategoryVisibility(i,s)},this.setTyping=(t=!1)=>{!t&&(!this.emoticonsDropdown.isActive()||this.emoticonsDropdown.tab!==this)||I.dispatchEvent("choosing_sticker",!t)},this.container.classList.add("stickers-padding"),this.content.id="content-stickers"}setFavedLimit(e){const t=this.categories.faved;t.limit=e}init(){super.init(),this.scrollable.onAdditionalScroll=()=>{this.setTyping()};const e=this.emoticonsDropdown.intersectionOptions;this.categoriesIntersector=new vg(this.onCategoryVisibility,e),this.scrollable.container.addEventListener("click",l=>{const c=l.target;if(ne(c,"category-title")){const d=ne(c,"emoji-category"),u=this.categoriesMap.get(d);if(u.local)return;ue.createPopup(ga,{id:u.set.id,access_hash:u.set.access_hash},!1,this.emoticonsDropdown.chatInput).show();return}this.emoticonsDropdown.onMediaClick(l)}),this.menuOnClickResult=Gl.menuOnClick(this,this.menu,this.scrollable,this.menuScroll);const t=Yn(this.content,!0),s=(l,c)=>{l.limit&&(c=c.slice(0,l.limit));const d=new Set(c.map(u=>u.id));hn(l.items,u=>{d.has(u.document.id)||this.deleteSticker(l,u.document,!0)}),this.toggleLocalCategory(l,!!c.length),hn(c,(u,h)=>{this.unshiftSticker(l,u,!0,h)}),this.spliceExceed(l),l.elements.container.classList.remove("hide")},i=this.createLocalCategory({id:"faved",title:"FavoriteStickers",icon:"savedmessages",styles:Ur.Stickers}),n=this.createLocalCategory({id:"recent",title:"Stickers.Recent",icon:"recent",styles:Ur.Stickers});n.limit=20;const r=yt("close",{noRipple:!0});n.elements.title.append(r),J(r,()=>{Rt({titleLangKey:"ClearRecentStickersAlertTitle",descriptionLangKey:"ClearRecentStickersAlertMessage",button:{langKey:"Clear"}}).then(()=>{this.managers.appStickersManager.clearRecentStickers()},as)});const o=[Promise.all([this.managers.apiManager.getLimit("favedStickers"),this.managers.appStickersManager.getFavedStickersStickers()]).then(([l,c])=>{this.setFavedLimit(l),s(i,c)}),this.managers.appStickersManager.getRecentStickersStickers().then(l=>{s(n,l)}),this.managers.appStickersManager.getAllStickers().then(l=>{for(const c of l.sets)So.renderStickerSet(this,this.stickerRenderer,c,!1)})];Promise.race(o).finally(()=>{t.remove()}),Promise.all(o).finally(()=>{this.mounted=!0,this.setTyping();const l=this.categories.faved,c=this.categories.recent;this.menuOnClickResult.setActive(l.items.length?l:c),I.addEventListener("stickers_installed",d=>{this.categories[d.id]||So.renderStickerSet(this,this.stickerRenderer,d,!0)})}),this.stickerRenderer=this.createStickerRenderer(),I.addEventListener("sticker_updated",({type:l,document:c,faved:d})=>{const u=this.categories[l==="faved"?"faved":"recent"];u&&(d?this.unshiftSticker(u,c):this.deleteSticker(u,c))}),I.addEventListener("stickers_deleted",({id:l})=>{const c=this.categories[l];this.deleteCategory(c)}),I.addEventListener("stickers_top",this.postponedEvent(l=>{const c=this.categories[l];c&&(this.positionCategory(c,!0),this.emoticonsDropdown.addEventListener("openAfterLayout",()=>{this.menuOnClickResult.setActiveStatic(c)},{once:!0}))})),I.addEventListener("stickers_order",({type:l,order:c})=>{l==="stickers"&&c.forEach(d=>{const u=this.categories[d];u&&this.positionCategory(u,!1)})}),I.addEventListener("stickers_updated",({type:l,stickers:c})=>{const d=this.categories[l==="faved"?"faved":"recent"];d&&s(d,c)}),I.addEventListener("app_config",()=>{this.managers.apiManager.getLimit("favedStickers").then(l=>{this.setFavedLimit(l)})}),st.addEventListener("resize",this.resizeCategories),this.attachHelpers({verifyRecent:l=>!!Mi(l,this.categories.recent.elements.items)}),this.init=null}deleteCategory(e){const t=super.deleteCategory(e);return t&&this.clearCategoryItems(e),t}clearCategoryItems(e,t){t||e.elements.items.replaceChildren(),e.items.splice(0,1/0).forEach(({element:s})=>this.stickerRenderer.unobserveAnimated(s))}deleteSticker(e,t,s){const i=tr(e.items,n=>n.document.id===t.id);i&&(i.element.remove(),this.stickerRenderer.unobserveAnimated(i.element),s||this.onLocalCategoryUpdate(e))}unshiftSticker(e,t,s,i){if(i!==void 0){const r=e.items[i];if(r&&r.document.id===t.id)return}let n=tr(e.items,r=>r.document.id===t.id);n||(n={element:this.stickerRenderer.renderSticker(t,void 0,void 0,e.middlewareHelper.get()),document:t}),e.items.unshift(n),e.elements.items.prepend(n.element),s||this.spliceExceed(e)}unshiftRecentSticker(e){this.managers.appStickersManager.saveRecentSticker(e.id)}deleteRecentSticker(e){this.managers.appStickersManager.saveRecentSticker(e.id,!0)}onClosed(){this.setTyping(!0)}onOpened(){this.setTyping(),this.resizeCategories()}destroy(){this.stickerRenderer.destroy(),super.destroy()}static categoryAppendStickers(e,t,s,i,n){const{container:r}=i.elements;return i.setCategoryItemsHeight(s),r.classList.remove("hide"),Promise.all([n,Ae.isPremiumFeaturesHidden()]).then(([o,l])=>{const c=e.isCategoryVisible(i),d=o.map(u=>{if(l&&ql(u))return;const h=t.renderSticker(u,void 0,void 0,i.middlewareHelper.get());return i.items.push({document:u,element:h}),h}).filter(Boolean);c&&i.elements.items.append(...d)})}static async renderStickerSet(e,t,s,i){const n=e.createCategory({stickerSet:s,title:je(s.title),styles:Ur.Stickers}),{menuTabPadding:r}=n.elements,o=e.managers.appStickersManager.getStickerSet(s);this.categoryAppendStickers(e,t,s.count,n,o.then(l=>l.documents)),i!==void 0&&e.positionCategory(n,i),e.renderStickerSetThumb({set:s,menuTabPadding:r,middleware:n.middlewareHelper.get()})}};So._onCategoryVisibility=(e,t)=>{e.elements.items.replaceChildren(...t?e.items.map(({element:s})=>s):[])};let Hr=So;const sC=new Set;function oM(a,e=!1){if(a.docId){const n=Wy.create(a.docId),r=document.createElement("span");return r.classList.add("super-emoji","super-emoji-custom"),r.append(n),r}let{emoji:t}=a;const s=document.createElement("span");s.classList.add("super-emoji","super-emoji-regular");let i;if(e&&!aE?i=hT(t):(t=rb(t),i=je(t)),s.append(i),s.children.length>1){const n=s.firstElementChild;s.replaceChildren(n)}if(s.firstElementChild?.tagName==="IMG"){const n=s.firstElementChild,r=n.src;if(!sC.has(r)){n.setAttribute("loading","lazy");const o=document.createElement("span");o.classList.add("emoji-placeholder"),wt.isAvailable("animations")&&(n.style.opacity="0",o.style.opacity="1"),n.addEventListener("load",()=>{$s(()=>{wt.isAvailable("animations")&&(n.style.opacity="",o.style.opacity=""),s.classList.remove("empty"),sC.add(r)})},{once:!0}),s.append(o)}}return s}function Jm(a){const e=ne(a,"super-emoji");if(!e)return;const t=e.firstElementChild;return t&&t.classList.contains("custom-emoji")?{emoji:t.dataset.stickerEmoji,docId:t.dataset.docId}:a.nodeType===a.TEXT_NODE?{emoji:a.nodeValue}:(a.tagName==="SPAN"&&!a.classList.contains("emoji")&&a.firstElementChild&&(a=a.firstElementChild),{emoji:a.getAttribute("alt")||a.innerText})}const hl="Emoji.Recent",Cy=[hl,"recent"],or="",_y=[or,""],oh=[["Emoji.SmilesAndPeople","smile"],["Emoji.AnimalsAndNature","animals"],["Emoji.FoodAndDrink","eats"],["Emoji.TravelAndPlaces","car"],["Emoji.ActivityAndSport","sport"],["Emoji.Objects","lamp"],["Emoji.Flags","flag"],["Skin Tones",""]];let xr;function iC(){if(xr)return xr;const a=[[_y,[]],[Cy,[]]];xr=new Map(a);for(const s in Yw){const n=""+Yw[s],r=oh[+n[0]-1];if(!r)continue;let o=xr.get(r);o||(o=[],xr.set(r,o)),o[+n.slice(1)||0]=s}xr.delete(oh.pop()),oh.unshift(_y,Cy);const e=oh.map(([s])=>s),t=[...xr.entries()].sort((s,i)=>e.indexOf(s[0][0])-e.indexOf(i[0][0]));return xr=new Map(t),xr}const X9=ii(42,42),tv=32;class Ua extends mw{constructor(e){super({managers:e.managers,noMenu:e.noPacks,searchFetcher:e.noSearch?void 0:async t=>t?e.searchFetcher?e.searchFetcher(t):{emojis:await this.managers.appEmojiManager.prepareAndSearchEmojis({q:t,limit:1/0,minChars:1,addCustom:!0})}:{emojis:[]},groupFetcher:e.groupFetcher?e.groupFetcher:async t=>t?._!=="emojiGroup"?{emojis:[]}:e.groupFetcher?e.groupFetcher(t):{emojis:[...(await this.managers.appEmojiManager.searchCustomEmoji(t.emoticons.join(""))).document_id.map(n=>({docId:n,emoji:""})),...t.emoticons.map(n=>({emoji:n}))]},processSearchResult:async({data:t,searching:s,grouping:i})=>{const{emojis:n,localStickerSet:r}=t||{};if(!n||!s&&!i)return;if(!n.length&&!r){const d=P("NoEmojiFound");return d.classList.add("emoticons-not-found"),d}const o=this.categoriesContainer.cloneNode(!1),l=this.createCategory({styles:Ur.Emoji});this.createEmojiRendererForCategory(l);for(const d of n)this.addEmojiToCategory({category:l,emoji:d,batch:!0});l.setCategoryItemsHeight(n.length),l.elements.container.style.paddingTop=".5rem",l.elements.container.classList.remove("hide"),this._onCategoryVisibility(l,!0);const c=[l];if(r){const d=this.renderLocalStickerSet(r);c.push(d)}return o.append(...c.map(d=>d.elements.container)),ze(()=>{c.forEach(d=>{d.middlewareHelper.destroy()})}),o},searchNoLoader:!0,searchPlaceholder:"SearchEmoji",searchType:"emoji"}),this.onCategoryVisibility=({target:t,visible:s})=>{this._onCategoryVisibility(this.categoriesMap.get(t),s)},this.onContentClick=t=>{const{target:s}=t,i=ne(s,"emoji-category");if(!i)return;_e(t);const n=this.categoriesMap.get(i);if(!n){const o=ne(s,"super-sticker");if(o){this.onClick({emoji:"",docId:o.dataset.docId,element:o});return}}if(ne(s,"category-title")){if(n.local)return;ue.createPopup(ga,{id:n.set.id,access_hash:n.set.access_hash},!0,this.emoticonsDropdown.chatInput).show();return}const r=Jm(s);!r||!this.canUseEmoji(r,n,!0)||(this.onClick?this.onClick({...r,element:ne(s,"super-emoji").firstElementChild}):this.emoticonsDropdown.chatInput.onEmojiSelected(r,!1),pt&&Fa())},Nt(this,e),this.container.classList.add("emoji-padding"),this.content.id="content-emoji",this.activeElements=[],this.freeCustomEmoji??(this.freeCustomEmoji=new Set)}_onCategoryVisibility(e,t){const s=e.elements.renderer,i=[];if(s){i.push(s);const n=new Map;t?(i.push(...e.items.map(({docId:r,element:o})=>{if(!r)return o;const l=o.firstElementChild;return l.clear(!1),n.set(l.docId,new Set([l])),o})),s.add({addCustomEmojis:n})):(s.clearCanvas(),s.middlewareHelper.clean())}else t&&i.push(...e.items.map(({element:n})=>n));if(e.elements.items.replaceChildren(...i),s&&!t){const n=new Map;e.items.forEach(({docId:r,element:o})=>{if(!r)return;const l=o.firstElementChild;l.clear(),n.set(l.docId,new Set([l]))}),s.add({addCustomEmojis:n,onlyThumb:!0})}}destroy(){super.destroy(),this.menuInnerScroll?.destroy()}init(){super.init(),this.init=void 0;const e={root:this.isStandalone?this.content:this.emoticonsDropdown.getElement()};this.categoriesIntersector=new vg(this.onCategoryVisibility,e),this.menu&&(this.menuOnClickResult=Gl.menuOnClick(this,this.menu,this.scrollable,this.menuScroll,void 0,this.listenerSetter));const t=Yn(this.content,!0);let s;if(!this.isStandalone&&this.menu){const c=this.menuInnerScroll=new io(void 0);c.container.classList.add("menu-horizontal-inner-scroll"),s=document.createElement("div"),s.classList.add("menu-horizontal-inner"),s.append(c.container)}let i;iC(),this.noRegularEmoji?(i=new Map([[[_y[0],"recent"],[]]]),this.menu&&i.set([Cy[0],""],[])):i=iC(),i.forEach((c,[d,u])=>{const h=this.createLocalCategory({id:d,title:d,icon:u,noMenuTab:!u,styles:Ur.Emoji});h.elements.container.classList.remove("hide"),c.forEach(p=>{const m=eb(p);this.addEmojiToCategory({category:h,emoji:{emoji:m},batch:!0})})});const n=this.mainSets?.(),r=Promise.all([this.preloaderDelay?ns(this.preloaderDelay):void 0,!this.noRegularEmoji&&this.managers.appEmojiManager.getRecentEmojis("native"),!this.isStandalone&&this.managers.appEmojiManager.getRecentEmojis("custom"),!this.noPacks&&Promise.resolve(Ae.isPremiumFeaturesHidden()).then(c=>c?void 0:this.managers.appEmojiManager.getCustomEmojis()),n&&Promise.all(Array.isArray(n)?n:[n]),this.additionalSets?.(),this.additionalLocalStickerSet?.()]).then(([c,d,u,h,p,m,g])=>{t.remove();const f=S=>S.map(_=>({emoji:"",docId:_}));let v,y;p&&(y=f(p[0]),p[1]&&(v=f(p[1]))),!v&&d&&(v=d.map(S=>({emoji:S}))),!y&&u&&(y=f(u));const w=this.categories[hl],b=this.categories[or];if(this.noRegularEmoji||[w&&[w,d],b&&[b,u]].filter(Boolean).forEach(([_,M])=>{_.limit=tv,M.splice(tv,M.length-tv)}),w&&(this.createEmojiRendererForCategory(w),v?.length))for(const S of v)this.addEmojiToCategory({category:w,emoji:S,batch:!0});if(b){if(this.createEmojiRendererForCategory(b),y?.length)for(const S of y)this.addEmojiToCategory({category:b,emoji:S,batch:!0});b.elements.container.style.paddingTop=".5rem",this.noMenu&&(b.elements.container.style.paddingBottom=".5rem")}if(oh.forEach(([S])=>{const _=this.categories[S];_&&(this.toggleLocalCategory(_,!!_.items.length),S!==hl&&S!==or&&(_.menuScroll=this.menuInnerScroll,this.menuInnerScroll.append(_.elements.menuTab)))}),this.resizeCategories(),w&&s&&w.elements.menuTab&&w.elements.menuTab.after(s),va([h?.sets,m].filter(Boolean)).forEach(S=>{this.renderEmojiSet(S)}),g){const S=this.renderLocalStickerSet(g);this.categoriesContainer.append(S.elements.container)}this.continueInit()});J(this.content,this.onContentClick,{listenerSetter:this.listenerSetter});const o=this.categories[hl],l=this.categories[or];return this.attachHelpers({getTextColor:()=>this.textColor,verifyRecent:c=>!!(Mi(c,l.elements.items)||Mi(c,o.elements.items)),canHaveEmojiTimer:this.canHaveEmojiTimer}),this.initPromise=r}renderLocalStickerSet(e){this.stickerRenderer??(this.stickerRenderer=this.createStickerRenderer());const t=this.createLocalCategory({title:e.title,styles:Ur.Stickers,noMenuTab:!0});return Hr.categoryAppendStickers(this,this.stickerRenderer,e.stickers.length,t,e.stickers).then(()=>{Hr._onCategoryVisibility(t,!0)}),t.elements.container.style.paddingBottom=Ur.Stickers.padding/2+"px",t}continueInit(){this.listenerSetter.add(I)("premium_toggle",()=>{this.toggleCustomCategory()}),this.listenerSetter.add(I)("stickers_top",this.postponedEvent(s=>{const i=this.categories[s];i&&(this.positionCategory(i,!0),this.listenerSetter.add(this.emoticonsDropdown)("openAfterLayout",()=>{this.menuOnClickResult.setActiveStatic(i)},{once:!0}))}));const e=s=>{for(const i in this.categories){const r=this.categories[i].elements.renderer;r&&(r.ignoreSettingDimensions=s,s||r.setDimensionsFromRect(void 0,!0))}};!this.isStandalone&&this.listenerSetter.add(this.emoticonsDropdown)("opened",()=>{e(!1)}),!this.isStandalone&&this.listenerSetter.add(this.emoticonsDropdown)("close",()=>{e(!0)}),this.listenerSetter.add(I)("stickers_installed",s=>{!this.categories[s.id]&&s.pFlags.emojis&&this.renderEmojiSet(s,!0)}),this.listenerSetter.add(I)("stickers_deleted",s=>{const i=this.categories[s.id];if(this.deleteCategory(i)){const{renderer:n}=i.elements;n&&n.middlewareHelper.clean()}});const t=({emoji:s,deleted:i})=>{const n=this.categories[s.docId?or:hl];if(!n)return;const r=s.docId?l=>l.docId===s.docId:l=>l.emoji===s.emoji,o=tr(n.items,r);if(i){if(tr(this.postponedEvents,l=>l.cb===t&&l.args[0].deleted),!o)return;o.element.remove(),this.isCategoryVisible(n)&&this.onLocalCategoryUpdate(n)}else if(o){if(n.items.unshift(o),this.isCategoryVisible(n)){const{renderer:l}=n.elements;di(o.element,n.elements.items,l?1:0,-1),l?.forceRender()}}else this.addEmojiToCategory({category:n,emoji:s,batch:!1,prepend:!0});this.closeScrollTop===0&&this.menuOnClickResult.setActive(s.docId?this.categories[hl]:n)};!this.noRegularEmoji&&this.listenerSetter.add(I)("emoji_recent",this.postponedEvent(t)),!this.noRegularEmoji&&this.listenerSetter.add(I)("emoji_recent",t),this.toggleCustomCategory(),this.menuOnClickResult?.setActive([this.categories[hl],this.categories[or]].find(s=>!!s.elements.menuTab)),this.onReady?.()}get peerId(){return this.emoticonsDropdown?this.emoticonsDropdown.chatInput.chat.peerId:Wt}getCustomCategory(){return this.categories[or]}toggleCustomCategory(){const e=this.categories[or],t=I.premium||this.peerId===I.myId||!!this.mainSets,s=t||this.isStandalone;super.toggleLocalCategory(e,!!e.items.length&&s),this.content.classList.toggle("has-premium",t)}toggleLocalCategory(e,t){if(e.id===or){this.toggleCustomCategory();return}super.toggleLocalCategory(e,t)}setTextColor(e=du){this.categoriesMap.forEach(t=>{t.elements.renderer?.setTextColor(e)})}get textColor(){return this.emoticonsDropdown?.textColor||du}renderEmojiSet(e,t){const s=this.createCategory({stickerSet:e,title:je(e.title),styles:Ur.Emoji});this.positionCategory(s,t);const{container:i,menuTabPadding:n}=s.elements;s.elements.items.classList.add("not-local"),s.elements.container.classList.add("is-premium-set"),s.elements.title.prepend(Be("premium_lock","category-title-lock")),this.createEmojiRendererForCategory(s),s.setCategoryItemsHeight(e.count),i.classList.remove("hide"),this.managers.appStickersManager.getStickerSet(e).then(({documents:o})=>{o.forEach(l=>{this.addEmojiToCategory({category:s,emoji:{docId:l.id,emoji:l.stickerEmojiRaw},batch:!0})}),this.onCategoryVisibility({target:s.elements.container,visible:this.isCategoryVisible(s)})}),this.renderStickerSetThumb({set:e,menuTabPadding:n,middleware:s.middlewareHelper.get(),textColor:this.textColor})}createEmojiRendererForCategory(e){const t=e.middlewareHelper.get(),s=jy.create({animationGroup:za,customEmojiSize:st.active.esgCustomEmoji,textColor:this.textColor,middleware:t});e.elements.renderer=s,e.elements.items.append(s)}addEmojiToCategory(e){const{category:t,emoji:s,batch:i,prepend:n}=e;let r=e.element;if(r){const l=document.createElement("span");l.classList.add("super-emoji"),l.append(r),r=l}else r=oM(s),this.showLocks&&!this.canUseEmoji(s,t)&&r.append(Be("premium_lock","premium-sticker-lock"));const o={...s||{emoji:void 0},element:r};(e.active||this.activeEmoji&&(o.docId?this.activeEmoji.docId===o.docId:this.activeEmoji.emoji===o.emoji))&&(this.activeEmoji,this.activeElements.push(o),r.classList.add("active")),t.items[n?"unshift":"push"](o),!i&&!this.spliceExceed(t)&&this.onLocalCategoryUpdate(t)}canUseEmoji(e,t,s){if(e.docId===Iv)return!0;if(e.docId&&!I.premium&&(this.isStandalone&&t?t.id!==or:this.peerId!==I.myId)&&!this.freeCustomEmoji.has(e.docId)){if(s){const i=xi(()=>{no(),Ce.openPremiumBot()});$e({langPackKey:"CustomEmoji.PremiumAlert",langPackArguments:[i]})}return!1}return!0}setActive(e){(e===this.activeEmoji||e?.docId?e.docId===this.activeEmoji?.docId:e?.emoji===this.activeEmoji?.emoji)||(this.activeEmoji=e,this.activeElements.forEach(t=>{t.element.classList.remove("active")}),this.activeElements.length=0,this.categoriesMap.forEach(t=>{t.items.forEach(s=>{(e.docId?s.docId===e.docId:s.emoji===e.emoji)&&(s.element.classList.add("active"),this.activeElements.push(s))})}))}onClose(){this.closeScrollTop=this.scrollable.scrollPosition}}class sv extends mw{constructor(e){super({managers:e.managers,noMenu:!0,searchFetcher:async t=>t?this.managers.appGifsManager.searchGifs(this.query=t):{documents:[],nextOffset:""},groupFetcher:async t=>t?._!=="emojiGroup"?{documents:[],nextOffset:""}:this.managers.appGifsManager.searchGifs(this.query=t.emoticons.join("")),processSearchResult:async({data:{documents:t,nextOffset:s},searching:i,grouping:n})=>{if(!t||!i&&!n)return;if(!t.length){const u=P("NoGIFsFound");return u.classList.add("emoticons-not-found"),u}const r=ui().get(),o=this.categoriesContainer.cloneNode(!1),{masonry:l,container:c}=this.createMasonry(r);t.forEach(u=>l.add(u)),o.append(c);const d=this.scrollable.onAdditionalScroll;return this.scrollable.onAdditionalScroll=()=>{d?.(),s&&(this.managers.appGifsManager.searchGifs(this.query,s).then(({documents:u,nextOffset:h})=>{r()&&(u.forEach(p=>l.add(p)),s=h)}),s=void 0)},ze(()=>{this.scrollable.onAdditionalScroll=d}),o},searchNoLoader:!0,searchPlaceholder:"SearchGIFs",searchType:"gifs"}),Nt(this,e),this.container.classList.add("gifs-padding"),this.content.id="content-gifs"}createMasonry(e){const t=document.createElement("div");t.classList.add("gifs-masonry");const s=J(t,this.emoticonsDropdown.onMediaClick),i=new dw(t,za,this.scrollable);return e.onDestroy(()=>{i.clear(),s()}),this.emoticonsDropdown.addLazyLoadQueueRepeat(i.lazyLoadQueue,i.processInvisibleDiv,e),{masonry:i,container:t}}init(){const e=this.middlewareHelper.get(),{masonry:t,container:s}=this.createMasonry(e);this.categoriesContainer.append(s);const i=Yn(this.content,!0);this.managers.appGifsManager.getGifs().then(n=>{t.addBatch(n),i.remove()}),I.addEventListener("gifs_updated",n=>{t.update(n)}),this.attachHelpers({isGif:!0}),this.init=void 0}}const nC="GIFS-SEARCH";class aC extends Zt{constructor(){super(...arguments),this.nextOffset="",this.loadedAll=!1,this.onGifsClick=async e=>{const t=ne(e.target,"gif");if(!t)return;const s=t.dataset.docId;await Ce.chat.input.sendMessageWithDocument({document:s,target:t})?st.isMobile&&Gs.onCloseBtnClick():console.warn("got no doc by id:",s)}}init(){this.container.id="search-gifs-container",this.inputSearch=new jo({placeholder:"SearchGifsTitle",onChange:e=>{this.reset(),this.search(e)}}),this.title.replaceWith(this.inputSearch.container),this.gifsDiv=document.createElement("div"),this.gifsDiv.classList.add("gifs-masonry"),J(this.gifsDiv,this.onGifsClick,{listenerSetter:this.listenerSetter}),this.scrollable.append(this.gifsDiv),this.masonry=new dw(this.gifsDiv,nC,this.scrollable),Gs.toggleSidebar(!0).then(()=>{this.search("",!0),this.scrollable.onScrolledBottom=()=>{this.search(this.inputSearch.value,!1)}})}onClose(){this.scrollable.onScrolledBottom=()=>{}}onCloseAfterTimeout(){return this.reset(),this.gifsDiv.replaceChildren(),Ut.checkAnimations(void 0,nC),this.inputSearch.remove(),super.onCloseAfterTimeout()}reset(){this.searchPromise=null,this.nextOffset="",this.loadedAll=!1,this.masonry.clear()}async search(e,t=!0){if(!(this.searchPromise||this.loadedAll)){this.gifBotPeerId||(this.gifBotPeerId=(await this.managers.appUsersManager.resolveUsername("gif")).id.toPeerId(!1));try{this.searchPromise=this.managers.appInlineBotsManager.getInlineResults(Wt,this.gifBotPeerId,e,this.nextOffset);const{results:s,next_offset:i}=await this.searchPromise;if(this.inputSearch.value!==e)return;this.searchPromise=null,this.nextOffset=i,t&&this.gifsDiv.replaceChildren(),s.length?s.forEach(n=>{n._==="botInlineMediaResult"&&n.document&&this.masonry.add(n.document)}):this.loadedAll=!0,this.scrollable.onScroll()}catch(s){throw this.searchPromise=null,console.error("gifs loading error:",s),s}}}}class rC extends Zt{init(){this.container.id="stickers-container",this.container.classList.add("chatlist-container"),this.lazyLoadQueue=new sr,this.inputSearch=new jo({placeholder:"StickersTab.SearchPlaceholder",onChange:e=>{this.search(e)}}),this.title.replaceWith(this.inputSearch.container),this.setsDiv=document.createElement("div"),this.setsDiv.classList.add("sticker-sets"),this.scrollable.append(this.setsDiv),_d({listenTo:this.setsDiv,listenerSetter:this.listenerSetter}),J(this.setsDiv,e=>{const t=ne(e.target,"sticker-set-sticker");if(t){const o=t.dataset.docId;Ce.chat.input.sendMessageWithDocument({document:o,target:t});return}const s=ne(e.target,"sticker-set");if(!s)return;const i=s.dataset.stickerSet,n=s.dataset.access_hash,r=ne(e.target,"sticker-set-button");r?(e.preventDefault(),e.cancelBubble=!0,r.setAttribute("disabled","true"),this.managers.appStickersManager.getStickerSet({id:i,access_hash:n}).then(o=>{this.managers.appStickersManager.toggleStickerSet(o.set).then(l=>{l&&(r.textContent="",r.append(P(o.set.installed_date?"Stickers.SearchAdded":"Stickers.SearchAdd")),r.classList.toggle("gray",!!o.set.installed_date))}).finally(()=>{r.removeAttribute("disabled")})})):this.managers.appStickersManager.getStickerSet({id:i,access_hash:n}).then(o=>{ue.createPopup(ga,o.set).show()})},{listenerSetter:this.listenerSetter}),Gs.toggleSidebar(!0).then(()=>{this.renderFeatured()})}onCloseAfterTimeout(){return this.setsDiv.replaceChildren(),Ut.checkAnimations(void 0,"STICKERS-SEARCH"),super.onCloseAfterTimeout()}renderSet(e){const t=document.createElement("div");t.classList.add("sticker-set");const s=document.createElement("div");s.classList.add("sticker-set-header");const i=document.createElement("div");i.classList.add("sticker-set-details"),i.innerHTML='<div class="sticker-set-name"></div>',Qt(i.firstElementChild,je(e.title));const n=document.createElement("div");n.classList.add("sticker-set-count"),n.append(P("Stickers",[e.count])),i.append(n);const r=document.createElement("button");r.classList.add("btn-primary","btn-color-primary","sticker-set-button"),r.append(P(e.installed_date?"Stickers.SearchAdded":"Stickers.SearchAdd")),e.installed_date&&r.classList.add("gray"),s.append(i,r);const o=document.createElement("div");o.classList.add("sticker-set-stickers");const l=Math.min(5,e.count);for(let c=0;c<l;++c){const d=document.createElement("div");d.classList.add("sticker-set-sticker"),o.append(d)}this.managers.appStickersManager.getStickerSet(e).then(c=>{for(let d=0;d<l;++d){const u=o.children[d],h=c.documents[d];h._!=="documentEmpty"&&ai({doc:h,div:u,lazyLoadQueue:this.lazyLoadQueue,group:"STICKERS-SEARCH",play:!0,loop:!0,width:68,height:68,withLock:!0})}}),t.dataset.stickerSet=""+e.id,t.dataset.access_hash=""+e.access_hash,t.dataset.title=e.title,t.append(s,o),this.setsDiv.append(t)}renderFeatured(){return this.managers.appStickersManager.getFeaturedStickers().then(e=>{this.inputSearch.value||(e=this.filterRendered("",e),e.forEach(t=>{this.renderSet(t.set)}))})}filterRendered(e,t){t=t.slice();const s=Array.from(this.setsDiv.children);return hn(s,i=>{const n=i.dataset.stickerSet,r=t.findIndex(o=>o.set.id===n);r!==-1?t.splice(r,1):(!e||!i.dataset.title.toLowerCase().includes(e.toLowerCase()))&&i.remove()}),Ut.checkAnimations(void 0,"STICKERS-SEARCH"),t}search(e){return e?this.managers.appStickersManager.searchStickerSets(e,!1).then(t=>{this.inputSearch.value===e&&(t=this.filterRendered(e,t),t.forEach(s=>{this.renderSet(s.set)}))}):this.renderFeatured()}}const za="emoticons-dropdown",Z9=lh(.42,0,.58,1),Wd={forceDuration:150,transitionFunction:Z9,maxDistance:150},J9=()=>{const a=document.createElement("div");a.innerHTML=`<div class="emoji-dropdown" style="display: none;">
- <div class="emoji-container">
- <div class="tabs-container"></div>
- </div>
- <div class="emoji-tabs menu-horizontal-div emoticons-menu no-stripe"></div>
- </div>`;const e=[["search justify-self-start","search",-1],["emoji","smile",0],["stickers","stickers_face",1],["gifs","gifs",2],["delete justify-self-end","deleteleft",-1]],t=a.firstElementChild;return t.lastElementChild.append(...e.map(([s,i,n])=>{const r=yt(`${i} menu-horizontal-div-item emoji-tabs-${s}`,{noRipple:!0});return r.dataset.tab=""+n,r})),t},du="primary-text-color",xw=class xw extends Ph{constructor(e={}){super({element:J9(),ignoreOutClickClassName:"input-message-input"}),this.lazyLoadQueue=new sr(1),this.tabId=-1,this.tabsToRender=[],this.onSelectTabClick=t=>{if(this.tabId===t){const{tab:n}=this;this.scrollTo(n,n.scrollable.container);return}const i={...this.getTab(Hr)&&{[this.getTab(Hr).tabId]:"send_stickers"},...this.getTab(sv)&&{[this.getTab(sv).tabId]:"send_gifs"}}[t];if(i&&!this.rights[i])return $e({langPackKey:gl[i]}),!1;Ut.checkAnimations(!0,za),this.tabId=t,this.searchButton.classList.toggle("hide",this.tabId===this.getTab(Ua)?.tabId),this.deleteBtn.classList.toggle("hide",this.tabId!==this.getTab(Ua)?.tabId)},this.checkRights=async()=>{const{peerId:t,threadId:s}=this.chatInput.chat,i=Object.keys(this.rights),n=await Promise.all(i.map(l=>this.managers.appMessagesManager.canSendToPeer(t,s,l)));i.forEach((l,c)=>{this.rights[l]=n[c]});const r=this.getTab(Ua),o=this.tabsEl.querySelector(".active");o&&Bn(o)!==r?.tabId+1&&(!this.rights.send_stickers||!this.rights.send_gifs)&&this.selectTab(r.tabId,!1),r?.toggleCustomCategory()},this.onMediaClick=async(t,s=!1,i,n)=>{const r=Mn(t.target,"DIV");if(!r)return!1;const o=r.dataset.docId;return o?this.sendDocId({document:o,clearDraft:s,silent:i,target:r,ignoreNoPremium:n}):!1},Nt(this,e),this.listenerSetter=new $t,this.isStandalone=!!e?.tabsToRender,this.element.classList.toggle("is-standalone",this.isStandalone),this.rights={send_gifs:void 0,send_stickers:void 0},this.addEventListener("open",async()=>{if(pt&&Fa()&&await ns(100),e.getOpenPosition){const s=e.getOpenPosition();this.element.style.setProperty("--top",s.top+"px"),this.element.style.setProperty("--left",s.left+"px")}e.customParentElement?e.customParentElement.append(this.element):this.element.parentElement!==this.chatInput.chatInput&&this.chatInput.chatInput.append(this.element),this.savedRange=this.getGoodRange(),this.lazyLoadQueue.lock(),Ut.lockIntersectionGroup(za),this.tab.onOpen?.()}),this.addEventListener("opened",()=>{Ut.unlockIntersectionGroup(za),this.lazyLoadQueue.unlockAndRefresh(),this.tab.onOpened?.()}),this.addEventListener("openAfterLayout",()=>{e.getOpenPosition&&this.element.style.setProperty("--width",this.element.offsetWidth+"px")}),this.addEventListener("close",()=>{this.lazyLoadQueue.lock(),Ut.lockIntersectionGroup(za),Ut.checkAnimations(!0,za),this.tab.onClose?.()}),this.addEventListener("closed",()=>{Ut.unlockIntersectionGroup(za),this.lazyLoadQueue.unlock(),this.lazyLoadQueue.refresh(),this.savedRange=void 0,this.tab.onClosed?.()})}canUseEmoji(e,t){return this.init?.(),this.getTab(Ua).canUseEmoji(e,void 0,t)}get tab(){return this.tabs[this.tabId]}get chatInput(){return this._chatInput||Ce.chat.input}set chatInput(e){const t=this._chatInput!==e;this._chatInput=e,!this.init&&t&&this.chatInput!==void 0&&this.checkRights()}get intersectionOptions(){return{root:this.getElement()}}setTextColor(e=du){this.textColor=e,this.getTab(Ua)?.setTextColor(e)}getTab(e){return this.tabsToRender.find(t=>t instanceof e)}init(){this.managers=I.managers,this.tabsToRender.length||(this.tabsToRender=[new Ua({managers:this.managers,preloaderDelay:200}),new Hr(this.managers),new sv({managers:this.managers})]),this.tabs={},this.tabsToRender.forEach((r,o)=>{r.emoticonsDropdown=this,r.tabId=o,this.tabs[o]=r}),this.container=this.element.querySelector(".emoji-container .tabs-container"),this.container.prepend(...this.tabsToRender.map(r=>r.container)),this.tabsEl=this.element.querySelector(".emoji-tabs"),this.selectTab=vd(this.tabsEl,this.container,this.onSelectTabClick,()=>{const{tab:r}=this;r.init?.(),Ut.checkAnimations(!1,za)}),this.searchButton=this.element.querySelector(".emoji-tabs-search"),this.listenerSetter.add(this.searchButton)("click",()=>{this.tabId===this.getTab(Hr)?.tabId?Gs.isTabExists(rC)||Gs.createTab(rC).open():Gs.isTabExists(aC)||Gs.createTab(aC).open()}),this.deleteBtn=this.element.querySelector(".emoji-tabs-delete"),J(this.deleteBtn,r=>{_e(r);const o=this.chatInput.messageInput;let l=Jy.getInstance().getSavedRange(o);l||(l=document.createRange(),l.setStartAfter(o.lastChild));const c=l.cloneRange();if(l.collapsed){const{node:d,offset:u}=rE(o,l.endContainer,l.endOffset);let h;if(u)h=d;else{if(h=d.previousSibling,!h)return;for(;h.nodeType===h.TEXT_NODE&&!h.nodeValue&&(h=h.previousSibling););if(h.nodeType===h.ELEMENT_NODE&&!h.isContentEditable)return}if(h.nodeType===h.ELEMENT_NODE&&h.tagName==="IMG")c.selectNode(h);else{const p=[...h.textContent];let m;if(u){let f=0;m=p.find(v=>(f+=v.length,f>=u))}else m=p.pop()||"";const g=u?u-m.length:h.textContent.length-m.length;c.setStart(h,g)}}c.deleteContents(),this.chatInput.messageInputField.simulateInputEvent()},{listenerSetter:this.listenerSetter});const e=Vy&&!1,t=e?this.getTab(Hr).tabId:this.getTab(Ua).tabId;if(e&&this.tabsEl.children[1].classList.add("hide"),Xs(this.tabsEl.children[t+1]),this.tabsToRender.length<=1&&this.tabsEl.classList.add("hide"),this.tabs[t].init?.(),!pt){let r,o=!1;const l=c=>{r=c};this.listenerSetter.add(vn)("change",c=>{c?o||(this.listenerSetter.add(document.body)("mousemove",l),o=!0):o&&(this.listenerSetter.removeManual(document.body,"mousemove",l),r&&this.onMouseOut(r))})}const s=()=>{this._chatInput||this.isStandalone||this.toggle(!1)},i=()=>{this._chatInput||this.isStandalone||this.checkRights()};this.listenerSetter.add(Ce)("peer_changing",s),this.listenerSetter.add(Ce)("peer_changed",i),i();const n=super.init();return this.init=void 0,n}getElement(){return this.element}scrollTo(e,t){e.scrollable.scrollIntoViewNew({element:t,axis:"y",position:"start",getElementPosition:e.scrollable.container===t?()=>-t.scrollTop:void 0,...Wd})}async sendDocId(e){return await this.chatInput.sendMessageWithDocument(e)?(Mh.container&&(Mh.forceClose=!0,Mh.toggle(!1)),!0):(console.warn("got no doc by id:",document),!1)}addLazyLoadQueueRepeat(e,t,s){const i=new $t;i.add(this)("close",()=>{e.lock()}),i.add(this)("closed",()=>{const n=e.intersector.getVisible();for(const r of n)t(r);e.intersector.clearVisible()}),i.add(this)("opened",()=>{e.unlockAndRefresh()}),s.onClean(()=>{i.removeAll()})}getSavedRange(){return this.getGoodRange()||this.savedRange}getGoodRange(){const e=document.getSelection();if(e.rangeCount&&document.activeElement===this.chatInput.messageInput)return e.getRangeAt(0)}destroy(){this.cleanup(),this.listenerSetter.removeAll(),this.tabsToRender.forEach(e=>e.destroy?.()),this.element.remove()}hideAndDestroy(){return this.toggle(!1).then(()=>this.destroy())}};xw.menuOnClick=(e,t,s,i,n,r)=>{let o=-1;const l=(m,g)=>{const f=m.menuScroll||i;f&&f.scrollIntoViewNew({element:m.elements.menuTab,position:"center",axis:"x",getElementPosition:g?({elementPosition:v})=>v-106:void 0,...Wd})},c=(m,g=!0)=>{if(m===n)return!1;let f=!1;return n&&(n.elements.menuTab.classList.remove("active"),n.menuScroll&&n.menuScroll!==m.menuScroll&&(f=!0,n.menuScroll.container.parentElement.classList.remove("active"),n.menuScroll.scrollIntoViewNew({element:n.menuScroll.firstElementChild,forceDirection:g?void 0:hm.Static,position:"center",axis:"x",...Wd}))),m.elements.menuTab.classList.add("active"),m.menuScroll&&(m.menuScroll.container.parentElement.classList.add("active"),g&&i.scrollIntoViewNew({element:m.menuScroll.container.parentElement,position:"center",axis:"x",...Wd})),n&&l(m,f),n=m,!0},d=m=>{if(n?.local)return;e.scrollable.scrollPosition=m.elements.container.offsetTop+1;const g=e.menuScroll.container,f=m.elements.menuTab;g.scrollLeft=f.offsetLeft-g.clientWidth/2+f.offsetWidth/2,c(m,!1)};let u=!1;const h=new r1(s.container,(m,g)=>{if(u||Math.abs(o-s.scrollPosition)<=1)return;o=-1;const f=e.getCategoryByContainer(g);if(!f.elements.menuTab)return;const v=Bn(g);!m&&(v||f.menuScroll)||c(f)});J(t,m=>{_e(m);let g=ne(m.target,"menu-horizontal-div-item");if(!g){if(g=ne(m.target,"menu-horizontal-inner"),!g||g.classList.contains("active"))return;g=g.firstElementChild.firstElementChild}const f=Bn(g),v=e.getCategoryByMenuTab(g);c(v);let y=0,w=0;if(f>0||v.menuScroll){const b=v.elements.container;w=1,y=b.offsetTop+w}o=y,u=!0,s.scrollIntoViewNew({element:y?v.elements.container:s.firstElementChild,position:"start",axis:"y",getElementPosition:y?({elementPosition:b})=>b+w:void 0,startCallback:()=>{e instanceof Ua&&!e.isCategoryVisible(v)&&e._onCategoryVisibility(v,!0)},...Wd}).finally(()=>{c(v),u=!1})},{listenerSetter:r});const p=s.onAdditionalScroll?s.onAdditionalScroll.bind(s):as;return s.onAdditionalScroll=()=>{e.content.parentElement.classList.toggle("no-border-top",s.scrollPosition<=0||e.container.classList.contains("is-searching")),p()},e.content.parentElement.classList.add("no-border-top"),{stickyIntersector:h,setActive:c,setActiveStatic:d}};let Gl=xw;const Mh=new Gl;Di.emoticonsDropdown=Mh;const Gn=Mh;async function gw({set:a,lazyLoadQueue:e,container:t,group:s,autoplay:i,width:n,height:r,managers:o=I.managers,middleware:l,textColor:c}){if(a.thumbs?.length){t.classList.add("media-sticker-wrapper"),e.push({div:t,load:async()=>{const p=await o.appStickersManager.getStickerSetThumbDownloadOptions(a),m=fs.download(p);if(p.mimeType==="application/x-tgsticker")return m.then(f=>{Ns.loadAnimationWorker({container:t,loop:!0,autoplay:i,animationData:f,width:n,height:r,needUpscale:!0,name:"setThumb"+a.id,group:s,middleware:l})});{const f=a.thumbs?.some(y=>y.type==="v");let v;return f?(v=Do({middleware:l}),v.autoplay=!0,v.muted=!0,v.loop=!0):v=new Image,v.classList.add("media-sticker"),m.then(y=>{Ka(v,URL.createObjectURL(y),()=>{t.append(v),f&&Ut.addAnimation({animation:v,group:s,observeElement:v,type:"video"})})})}}});return}let d;a.thumb_document_id?d=o.appEmojiManager.getCustomEmojiDocument(a.thumb_document_id):d=o.appStickersManager.getStickerSet(a).then(p=>p.documents[0]);const u=await d;if(!u)return;const h=u.attributes.find(p=>p._==="documentAttributeCustomEmoji");ai({doc:u,div:t,group:s,lazyLoadQueue:e,managers:o,width:n,height:r,middleware:l,textColor:h?.pFlags?.text_color?c||du:void 0})}function ep(a){return T(oE.Provider,{value:{rootScope:I,appSidebarLeft:Ri,AppEditFolderTab:vr,AppChatFoldersTab:Cd,EmoticonsSearch:rM,wrapStickerSetThumb:gw,showLimitPopup:Ja,lottieLoader:Ns,themeController:Ls,appImManager:Ce,apiManagerProxy:Ae,setQuizHint:Gu,InputFieldTsx:Yy,PasswordInputField:gg,PasswordMonkey:l_,PopupPremium:rs},get children(){return a.children}})}class fw extends $g{constructor(e,t){super({listenerSetter:e.listenerSetter,fields:[],asRestrictions:!0}),this.options=e,this.managers=t,this.construct()}async construct(){const e=this.options,t=e.chatId.toPeerId(!0),s=this.chat=Ae.getChat(e.chatId),i=Ae.isForum(t),n=this.defaultBannedRights=s.default_banned_rights,r=this.rights=e.participant?nT(s,e.participant.banned_rights):n,o=[{flags:["send_photos"],text:"UserRestrictionsSendPhotos",exceptionText:"UserRestrictionsNoSendPhotos"},{flags:["send_videos"],text:"UserRestrictionsSendVideos",exceptionText:"UserRestrictionsNoSendVideos"},{flags:["send_stickers","send_gifs"],text:"UserRestrictionsSendStickers",exceptionText:"UserRestrictionsNoSendStickers"},{flags:["send_audios"],text:"UserRestrictionsSendMusic",exceptionText:"UserRestrictionsNoSendMusic"},{flags:["send_docs"],text:"UserRestrictionsSendFiles",exceptionText:"UserRestrictionsNoSendDocs"},{flags:["send_voices"],text:"UserRestrictionsSendVoices",exceptionText:"UserRestrictionsNoSendVoice"},{flags:["send_roundvideos"],text:"UserRestrictionsSendRound",exceptionText:"UserRestrictionsNoSendRound"},{flags:["embed_links"],text:"UserRestrictionsEmbedLinks",exceptionText:"UserRestrictionsNoEmbedLinks"},{flags:["send_polls"],text:"UserRestrictionsSendPolls",exceptionText:"UserRestrictionsNoSendPolls"}];let l=[{flags:["send_plain"],text:"UserRestrictionsSend",exceptionText:"UserRestrictionsNoSend"},{flags:["send_media"],text:"UserRestrictionsSendMedia",exceptionText:"UserRestrictionsNoSendMedia",nested:o},{flags:["invite_users"],text:"UserRestrictionsInviteUsers",exceptionText:"UserRestrictionsNoInviteUsers"},{flags:["pin_messages"],text:"UserRestrictionsPinMessages",exceptionText:"UserRestrictionsNoPinMessages"},i&&{flags:["manage_topics"],text:"CreateTopicsPermission",exceptionText:"UserRestrictionsNoChangeInfo"},{flags:["change_info"],text:"UserRestrictionsChangeInfo",exceptionText:"UserRestrictionsNoChangeInfo"}];l=l.filter(Boolean);const c={};l.push(...o),l.forEach(d=>{const u=d.flags[0];c[u]=d,d.checked=Cr(s,u,r)}),o.forEach(d=>d.nestedTo=c.send_media),c.send_media.toggleWith={unchecked:o,checked:o},c.embed_links.toggleWith={checked:[c.send_plain]},c.send_plain.toggleWith={unchecked:[c.embed_links]},this.fields=l;for(const d of this.fields)!e.forChat&&n.pFlags[d.flags[0]]?d.restrictionText="UserRestrictionsDisabled":ji(s)[0]&&(d.flags.includes("pin_messages")||d.flags.includes("change_info"))&&(d.restrictionText=e.participant?"UserRestrictionsDisabled":"EditCantEditPermissionsPublic");for(const d of this.fields){if(d.nestedTo)continue;const{nodes:u}=this.createField(d);e.appendTo.append(...u)}this.fields.forEach(d=>{d.checkboxField.listenerSetter.add(d.checkboxField.input)("change",()=>{this.options?.onSomethingChanged?.()})})}takeOut(){const e={_:"chatBannedRights",until_date:2147483647,pFlags:{}},t=new Set(["send_media"]);for(const s of this.fields)s.checkboxField.checked||s.flags.forEach(n=>{t.has(n)||(e.pFlags[n]=!0)});return e}}class e8 extends $g{constructor(e){super({listenerSetter:e.listenerSetter,fields:[],asRestrictions:!0}),this.options=e,this.construct()}construct(){const e=this.options,t=e.chat,s=!!t.pFlags.broadcast,i=!!t.pFlags.forum,n=this.rights=e.participant?e.participant.admin_rights:void 0,r=s&&[{flags:["post_messages"],text:"EditAdminPostMessages"},{flags:["edit_messages"],text:"EditAdminEditMessages"},{flags:["delete_messages"],text:"EditAdminDeleteMessages"}],o=s&&[{flags:["post_stories"],text:"AdminRights.PostStories"},{flags:["edit_stories"],text:"AdminRights.EditStories"},{flags:["delete_stories"],text:"AdminRights.DeleteStories"}],l="post_messages_nested",c="post_stories_nested";let d=[{flags:["change_info"],text:s?"EditAdminChangeChannelInfo":"EditAdminChangeGroupInfo"},s&&{flags:[l],text:"AdminRights.ManageMessages",nested:r},s&&{flags:[c],text:"AdminRights.ManageStories",nested:o},!s&&{flags:["delete_messages"],text:s?"EditAdminDeleteMessages":"EditAdminGroupDeleteMessages"},!s&&{flags:["ban_users"],text:"EditAdminBanUsers"},!s&&{flags:["invite_users"],text:"EditAdminAddUsersViaLink"},!s&&{flags:["pin_messages"],text:"EditAdminPinMessages"},i&&{flags:["manage_topics"],text:"ManageTopicsPermission"},{flags:["manage_call"],text:s?"StartVoipChatPermission":"Channel.EditAdmin.ManageCalls"},s&&{flags:["invite_users"],text:"Channel.EditAdmin.PermissionInviteSubscribers"},!s&&{flags:["anonymous"],text:"EditAdminSendAnonymously",checked:n?void 0:!1},{flags:["add_admins"],text:"EditAdminAddAdmins",checked:n?void 0:!1}];const u={};d=d.filter(Boolean),r&&d.push(...r),o&&d.push(...o),d.forEach(m=>{const g=m.flags[0];u[g]=m,m.checked??(m.checked=Cr(t,g,n))}),r&&(r.forEach(m=>m.nestedTo=u[l]),u[l].toggleWith={unchecked:r,checked:r}),o&&(o.forEach(m=>m.nestedTo=u[c]),u[c].toggleWith={unchecked:o,checked:o}),this.fields=d;const h=new Set(["anonymous"]),p=e.participant?._==="channelParticipantCreator";for(const m of this.fields){const g=m.flags[0];e.canEdit?(p&&!h.has(g)||!Cr(t,g))&&(m.restrictionText="EditCantEditPermissions"):m.restrictionText="EditAdminCantEdit"}for(const m of this.fields){if(m.nestedTo)continue;const{nodes:g}=this.createField(m);e.appendTo.append(...g)}}takeOut(){const e={_:"chatAdminRights",pFlags:{}};for(const t of this.fields)t.checkboxField.checked&&t.flags.forEach(s=>{e.pFlags[s]=!0});return e}}class t8 extends Bs{constructor(){super(...arguments),this.saveCallbacks=[],this.solidState=Ft(e=>{this.middlewareHelper.get().onDestroy(()=>void e());const t={},[s,i]=Qr({}),[n,r]=K(),[o,l]=K(!1),c=fa(l,200,!0);return le(()=>{c(!Pn(s,t))}),le(()=>{n()&&n().classList.toggle("appear-zoom--active",o())}),{setInitial:d=>{Object.assign(t,d),i(d)},store:s,set:i,saveIcon:n,setSaveIcon:r,hasChanges:o}}),this.isConfirmationNeededOnClose=async()=>{if(!this.solidState.hasChanges())return;const e={langKey:"Save"};try{await Rt({titleLangKey:"UnsavedChanges",descriptionLangKey:"UnsavedChangesDescription.Group",button:e,buttons:[e,{isCancel:!0,langKey:"Discard"}],rejectWithReason:!0}),this.saveChanges()}catch(t){if(t==="closed")throw new Error}}}async init(){this.container.classList.add("edit-peer-container","group-permissions-container"),this.setTitle("ChannelPermissions"),this.header.append(this.solidState.setSaveIcon(yt("check primary appear-zoom"))),this.solidState.saveIcon().addEventListener("click",()=>{this.saveChanges(),this.close()}),this.participants=new Map;let e;{const s=new Oe({name:"ChannelPermissionsHeader"});e=new fw({chatId:this.chatId,listenerSetter:this.listenerSetter,appendTo:s.content,forChat:!0,onSomethingChanged:()=>{this.solidState.set({rights:e.takeOut()})}},this.managers),this.solidState.setInitial({rights:e.takeOut()}),this.saveCallbacks.push(()=>{this.managers.appChatsManager.editChatDefaultBannedRights(this.chatId,e.takeOut())}),this.scrollable.append(s.container)}const t=Ae.getChat(this.chatId);if(t._==="channel"){const{default:s}=await zo(()=>import("./chargeForMessasgesSection-C_HrZ24y.js"),__vite__mapDeps([27,3,4,8,9,24,25,6,7,12,13,14,15,16,17,18,19,20]),import.meta.url),i=+t?.send_paid_messages_stars||0;this.solidState.setInitial({stars:i});const{element:n,dispose:r,promise:o}=s({initialStars:i,onStarsChange:l=>void this.solidState.set({stars:l})},ep);await o,this.scrollable.append(n),this.middlewareHelper.get().onDestroy(()=>void r()),this.saveCallbacks.push(()=>{const{stars:l}=this.solidState.store;i!==l&&this.managers.appChatsManager.updateChannelPaidMessagesPrice(t.id.toChatId(),l)})}{const s=new Oe({name:"Slowmode",caption:!0}),i=await this.managers.appProfileManager.getChannelFull(this.chatId);let n;const r=new wm({generateStep:d=>{let u;if(!d)u=P("SlowmodeOff");else{const h=Math.floor(d/3600),p=Math.floor(d/60)%60,m=d%60;h?u=P("SlowmodeHours",[h]):p?u=P("SlowmodeMinutes",[p]):u=P("SlowmodeSeconds",[m])}return[u,d]},onValue:d=>{n!==d&&(this.solidState.set({slowModeSeconds:d}),n=d,d?s.caption.replaceChildren(P("SlowmodeInfoSelected",[wd(Yl(d,1))])):s.caption.replaceChildren(P("SlowmodeInfoOff")))},middleware:this.middlewareHelper.get()}),o=[0,10,30,60,300,900,3600],l=r.generateSteps(o),c=i.slowmode_seconds||0;this.solidState.setInitial({slowModeSeconds:c}),r.setSteps(l,o.indexOf(c)),s.content.append(r.container),this.saveCallbacks.push(()=>{const{value:d}=r;d!==c&&this.managers.appChatsManager.toggleSlowMode(this.chatId,r.value)}),this.scrollable.append(s.container)}{const s=new Oe({name:"PrivacyExceptions"}),i=new Fe({titleLangKey:"ChannelAddException",subtitleLangKey:"Loading",icon:"adduser",clickable:()=>{ue.createPopup(Rs,{peerType:["channelParticipants"],onSelect:m=>{setTimeout(()=>{n(m)},0)},placeholder:"ExceptionModal.Search.Placeholder",peerId:-this.chatId,exceptSelf:!0})},listenerSetter:this.listenerSetter}),n=async m=>{let g=this.participants.get(m);if(!g)try{g=await this.managers.appProfileManager.getParticipant(this.chatId,m)}catch{Wi("User is no longer participant");return}const f=this.slider.createTab(Qh);f.participant=g,f.chatId=this.chatId,f.userId=m,f.open()};s.content.append(i.container);const r=s.generateContentElement();r.classList.add("chatlist-container");const o=nt.createChatList({new:!0});r.append(o),J(o,m=>{const g=Mn(m.target,tc);if(!g)return;const f=g.dataset.peerId.toPeerId();n(f)},{listenerSetter:this.listenerSetter});const l=async(m,g)=>{const f=g.banned_rights,v=(await this.managers.appChatsManager.getChat(this.chatId)).default_banned_rights,y=[];e.fields.forEach(b=>{const S=b.flags[0];f.pFlags[S]&&!v.pFlags[S]&&y.push(b.exceptionText)});const w=m.lastMessageSpan;y.length?(w.replaceChildren(...Yi(y.map(b=>P(b)),!1)),w.classList.toggle("hide",!y.length)):(w.replaceChildren(P("UserRestrictionsBy",[await qe({peerId:g.kicked_by.toPeerId(!1)})])),w.classList.remove("hide"))},c=(m,g)=>{const f=it(m.peer),v=nt.addDialogNew({peerId:f,container:o,rippleEnabled:!0,avatarSize:"abitbigger",append:g,wrapOptions:{middleware:this.middlewareHelper.get()}});this.participants.set(f,m),v.dom.listEl.dialogElement=v,l(v.dom,m)};this.listenerSetter.add(I)("chat_participant",m=>{const g=m.new_participant,f=m.prev_participant,v=m.user_id.toPeerId(!1),y=g?._==="channelParticipantBanned"&&!g.banned_rights.pFlags.view_messages;g?this.participants.set(v,g):this.participants.delete(v);const w=o.querySelector(`[data-peer-id="${v}"]`);y?(w?l(w.dialogElement.dom,g):c(g,!1),f?._!=="channelParticipantBanned"&&++u):(w&&w.dialogElement.remove(),f?._==="channelParticipantBanned"&&--u),d()});const d=()=>{const m=P(u?"Permissions.ExceptionsCount":"Permissions.NoExceptions",[u]);St(i.subtitle,m)};let u=0,h;const p=()=>(h=new yb({scrollable:this.scrollable,getPromise:()=>this.managers.appProfileManager.getChannelParticipants({id:this.chatId,filter:{_:"channelParticipantsBanned",q:""},limit:50,offset:o.childElementCount}).then(g=>{for(const f of g.participants)c(f,!0);return u=g.count,d(),g.participants.length<50||g.count===o.childElementCount})}),h.load());this.scrollable.append(s.container),await this.managers.appChatsManager.isChannel(this.chatId)?await p():(d(),this.listenerSetter.add(I)("dialog_migrate",({migrateFrom:m,migrateTo:g})=>{this.chatId===m&&(this.chatId=g,p())}))}}saveChanges(){this.saveCallbacks.forEach(e=>void e())}onOpenAfterTimeout(){this.scrollable.onScroll()}}function vw({doc:a,row:e,size:t,managers:s}){const i=e.media,n=e.createMedia("small");i&&n.classList.add("hide");const r=i?[]:void 0,o=t==="small"?32:48,l=ai({div:n,doc:a,width:o,height:o,loadPromises:r,managers:s}).then(({render:c})=>c);return r&&Promise.all(r).then(()=>{n.classList.remove("hide"),i.remove()}),l}class eg extends Bs{static getInitArgs(e){return{availableReactions:I.managers.appReactionsManager.getActiveAvailableReactions(),chatFull:I.managers.appProfileManager.getChatFull(e)}}async init({chatId:e,p:t=eg.getInitArgs(e)}){this.setTitle("Reactions"),this.chatId=e;const[s,i]=await Promise.all([t.availableReactions,t.chatFull]),n=await this.managers.appChatsManager.isBroadcast(this.chatId);let r=i.available_reactions??{_:"chatReactionsNone"},o=r,l=new Set(r._==="chatReactionsSome"?r.reactions.map(w=>w.emoticon):[]);const c=w=>w.map(b=>({_:"reactionEmoji",emoticon:b})),d=()=>n?"EnableReactionsChannelInfo":o._==="chatReactionsAll"?"EnableAllReactionsInfo":o._==="chatReactionsNone"?"DisableReactionsInfo":"EnableSomeReactionsInfo",u=new Oe({name:n?void 0:"AvailableReactions",caption:d()}),h=new Oe({name:"OnlyAllowThisReactions"}),p=()=>{const w=o.reactions??[];l=new Set(w.map(({emoticon:b})=>b)),g.forEach((b,S)=>{b.setValueSilently(l.has(S))})};let m;if(n){m=new _t({toggle:!0,checked:r._==="chatReactionsSome"});const w=new Fe({checkboxField:m,titleLangKey:"EnableReactions",listenerSetter:this.listenerSetter});u.content.append(w.container),this.listenerSetter.add(m.input)("change",()=>{let b=!0;m.checked?f.every(S=>!S.checked)?o={_:"chatReactionsSome",reactions:c(s.map(({reaction:S})=>S))}:o._!=="chatReactionsSome"?o={_:"chatReactionsSome",reactions:c(Array.from(l))}:b=!1:o={_:"chatReactionsNone"},b&&(p(),y())})}else{const w=[["chatReactionsAll","AllReactions"],["chatReactionsSome","SomeReactions"],["chatReactionsNone","NoReactions"]],b=()=>{h.container.classList.toggle("hide",o._!=="chatReactionsSome")};let S=r._;const _=vm(w.map(([M,C])=>({langPackKey:C,value:M,checked:r._===M})),M=>{S=M,S==="chatReactionsAll"?o={_:S,pFlags:{allow_custom:!0}}:S==="chatReactionsNone"?o={_:S}:o={_:S,reactions:c(["👍","👎"])},St(u.caption,P(d())),p(),y(),b()});u.content.append(_),b()}const g=new Map,f=s.map(w=>{const b=w.reaction,S=new _t({toggle:!0,checked:l.has(b)});g.set(b,S),this.listenerSetter.add(S.input)("change",()=>{S.checked?(l.add(b),m&&!m.checked&&(m.checked=!0)):(l.delete(b),m?.checked&&!l.size&&(m.checked=!1)),y()});const _=new Fe({checkboxField:S,title:w.title,havePadding:!0,listenerSetter:this.listenerSetter});return vw({row:_,doc:w.static_icon,size:"small"}),h.content.append(_.container),S}),v=async()=>{y.clearTimeout(),o._==="chatReactionsSome"&&(o.reactions=c(Array.from(l)),o.reactions.length||(o={_:"chatReactionsNone"})),this.managers.appChatsManager.setChatAvailableReactions(this.chatId,o),r=o},y=$i(v,3e3,!1,!0);this.eventListener.addEventListener("destroy",()=>{y.isDebounced()&&v()},{once:!0}),this.scrollable.append(u.container,h.container)}}function s8(a){const e=Mt();return{selector:new wn({...a,peerType:["channelParticipants"],multiSelect:!1,headerSearch:!0,placeholder:"SearchPlaceholder",meAsSaved:!1,noShadow:!1,onFirstRender:()=>{e.resolve()}}),loadPromise:e}}class tg extends Bs{static getInitArgs(e){return{chatFull:I.managers.appProfileManager.getChatFull(e),appConfig:I.managers.apiManager.getAppConfig()}}async init({chatId:e,p:t=tg.getInitArgs(e)}){const s=e.toPeerId(!0);this.container.classList.add("edit-peer-container","chat-administrators-container"),this.setTitle("PeerInfo.Administrators");const[i,n,r,o]=await Promise.all([this.managers.appChatsManager.getChat(e),this.managers.appChatsManager.isBroadcast(e),t.chatFull,t.appConfig]);this.addBtn=Cn({icon:"addmember_filled",className:"is-visible"}),this.content.append(this.addBtn),J(this.addBtn,()=>{const h=ue.createPopup(Rs,{peerType:["channelParticipants"],peerId:s,onSelect:p=>{const m=h.selector.participants.get(p);l(m)},placeholder:"SearchPlaceholder"})},{listenerSetter:this.listenerSetter});const l=async h=>{Qh.openTab(this.slider,e,h,!0)},c=!n&&i.participants_count>=o.telegram_antispam_group_size_min,{selector:d,loadPromise:u}=s8({appendTo:this.content,managers:this.managers,middleware:this.middlewareHelper.get(),peerId:s,channelParticipantsFilter:h=>({_:"channelParticipantsAdmins",q:h}),getSubtitleForElement:async h=>{const p=this.selector.participants.get(h);if(p._==="channelParticipantCreator"||p._==="chatParticipantCreator")return P("ChannelCreator");const m=p.promoted_by.toPeerId(!1);return P("EditAdminPromotedBy",[await qe({peerId:m})])},onSelect:h=>{const p=this.selector.participants.get(h);l(p)},channelParticipantsUpdateFilter:h=>["channelParticipantAdmin","channelParticipantCreator"].includes(h?._)});if(this.selector=d,c){const h=new Oe({noDelimiter:!0,caption:"ChannelAntiSpamInfo"}),p=!!r?.pFlags?.antispam,m=new Fe({titleLangKey:"ChannelAntiSpam",checkboxField:new _t({name:"agg",toggle:!0,listenerSetter:this.listenerSetter,checked:p}),listenerSetter:this.listenerSetter});this.eventListener.addEventListener("destroy",()=>{const g=m.checkboxField.checked;g!==p&&this.managers.appChatsManager.toggleAntiSpam(e,g)},{once:!0}),h.content.append(m.container),this.selector.scrollable.append(h.container,this.selector.scrollable.container.lastElementChild)}return ef({chatId:e,listenTo:this.selector.scrollable.container,participants:this.selector.participants,slider:this.slider,middleware:this.middlewareHelper.get()}),u}}class i8 extends Bs{async init(e){const t=await this.managers.appChatsManager.isBroadcast(e);this.container.classList.add("edit-peer-container","removed-users-container"),this.setTitle("ChannelBlacklist"),this.addBtn=Cn({icon:"addmember_filled",className:"is-visible"}),this.content.append(this.addBtn),J(this.addBtn,()=>{const o=ue.createPopup(Rs,{peerType:["channelParticipants"],peerId:e.toPeerId(!0),onSelect:l=>{const c=o.selector.participants.get(l);this.managers.appChatsManager.kickFromChat(e,c)},placeholder:"SearchPlaceholder"})},{listenerSetter:this.listenerSetter});const{selector:s,loadPromise:i}=TP({appendTo:this.content,managers:this.managers,middleware:this.middlewareHelper.get(),peerId:e.toPeerId(!0),channelParticipantsFilter:o=>({_:"channelParticipantsKicked",q:o}),channelParticipantsUpdateFilter:o=>o?._==="channelParticipantBanned"&&o.pFlags.left,getSubtitleForElement:async o=>{const c=this.selector.participants.get(o).kicked_by.toPeerId(!1);return P("UserRemovedBy",[await qe({peerId:c})])}});this.selector=s;const n=new Oe({noDelimiter:!0,caption:t?"NoBlockedChannel2":"NoBlockedGroup2"});return n.container.firstElementChild.remove(),this.selector.scrollable.container.querySelector(".gradient-delimiter")?.remove(),this.selector.scrollable.append(n.container,this.selector.scrollable.container.lastElementChild),ef({listenTo:this.selector.scrollable.container,slider:this.slider,chatId:e,participants:this.selector.participants,middleware:this.middlewareHelper.get()}),i}}class sg extends Bs{static getInitArgs(){return{animationData:Ns.loadAnimationFromURLManually("UtyanDiscussion"),chats:I.managers.appChatsManager.getGroupsForDiscussion()}}async setCaption(){this.caption.replaceChildren(P(this.linkedChatId?this.isBroadcast?"DiscussionChannelGroupSetHelp2":"DiscussionGroupHelp":"DiscussionChannelHelp3",this.linkedChatId?[await qe({peerId:this.linkedChatId.toPeerId(!0)})]:void 0))}async init({chatId:e,linkedChatId:t,p:s=sg.getInitArgs()}){this.chatId=e,this.linkedChatId=t;const[i]=await Promise.all([this.managers.appChatsManager.isBroadcast(this.chatId)]);this.isBroadcast=i,this.setTitle(i?"DiscussionController.Channel.Title":"DiscussionController.Group.Title"),this.container.classList.add("chat-folders-container","chat-discussion-container");const n=document.createElement("div");n.classList.add("sticker-container");const r=this.caption=document.createElement("div");r.classList.add("caption");const o=new Oe({caption:i?"DiscussionChannelHelp2":"DiscussionGroupHelp2"}),l=nt.createChatList();l.classList.add("chatlist"),J(l,async f=>{const v=ne(f.target,"chatlist-chat");if(!v)return;const y=v.dataset.peerId.toPeerId();if(this.linkedChatId){Ce.setInnerPeer({peerId:y});return}if(await this.managers.appPeersManager.isForum(y)){$e({langPackKey:"ChannelTopicsDiscussionForbidden"}),to(v);return}const w=document.createDocumentFragment();w.append(P("Discussion.Set.Modal.Text.PublicChannelPublicGroup",[await qe({peerId:y}),await qe({peerId:this.chatId.toPeerId(!0)})]));const[b,S,_]=await Promise.all([this.managers.appChatsManager.isPublic(y.toChatId()),this.managers.appChatsManager.isPublic(this.chatId),this.managers.appProfileManager.getChatFull(y.toChatId())]),M=document.createElement("br");S||w.append(M.cloneNode(),M.cloneNode(),P("Discussion.Set.PrivateChannel")),b||w.append(M.cloneNode(),M.cloneNode(),P("Discussion.Set.PrivateGroup")),(_._==="chatFull"||_.pFlags.hidden_prehistory)&&w.append(M.cloneNode(),M.cloneNode(),P("DiscussionLinkGroupAlertHistory")),await Rt({peerId:this.chatId.toPeerId(!0),description:w,button:{langKey:"DiscussionLinkGroup"}}),this.managers.appChatsManager.setDiscussionGroup(this.chatId,y.toChatId())},{listenerSetter:this.listenerSetter});let c;i&&(c=ot("btn-primary btn-transparent primary",{icon:"newgroup",text:"DiscussionCreateGroup"}),J(c,async()=>{let f=await Gr({peerId:this.chatId.toPeerId(!0),plainText:!0});f+=" Chat",this.slider.createTab(Q_).open({peerIds:[],onCreate:y=>{this.slider.removeTabFromHistory(this),this.managers.appChatsManager.setDiscussionGroup(this.chatId,y)},openAfter:!1,title:f,asChannel:!0})},{listenerSetter:this.listenerSetter}),o.content.append(c)),o.content.append(l);const d=new Oe({}),u=ot("btn-primary btn-transparent danger",{icon:"delete",text:i?"DiscussionUnlinkGroup":"DiscussionUnlinkChannel"});d.content.append(u),J(u,async()=>{const f=this.linkedChatId;await Rt({descriptionLangKey:i?"DiscussionUnlinkChannelAlert":"DiscussionUnlinkGroupAlert",descriptionLangArgs:[await qe({peerId:f.toPeerId(!0)})],button:{langKey:"DiscussionUnlink"}});const v=os([u],!0);try{await this.managers.appChatsManager.setDiscussionGroup(i?this.chatId:f,void 0)}catch{}if(!i){this.close();return}v()},{listenerSetter:this.listenerSetter}),this.scrollable.append(n,r,o.container,d.container);const h=[],p=s.animationData.then(async f=>{const v=await f({container:n,loop:!0,autoplay:!0,width:120,height:120});return Ns.waitForFirstFrame(v)}),m=(i?s.chats:Promise.resolve([await this.managers.appChatsManager.getChat(this.linkedChatId)])).then(f=>{const v=f.map(y=>{const w=[],{dom:b}=nt.addDialogNew({peerId:y.id.toPeerId(!0),container:l,rippleEnabled:!0,avatarSize:"abitbigger",loadPromises:w,wrapOptions:{middleware:this.middlewareHelper.get()}}),S=ji(y)[0];return S?b.lastMessageSpan.textContent="@"+S:b.lastMessageSpan.append(P(i?"DiscussionController.PrivateGroup":"DiscussionController.PrivateChannel")),Promise.all(w)});return Promise.all(v)}),g=async()=>{await this.setCaption(),i&&(Array.from(l.children).forEach(f=>{const v=f.dataset.peerId.toChatId();f.classList.toggle("hide",this.linkedChatId?this.linkedChatId!==v:!1)}),d.container.classList.toggle("hide",!this.linkedChatId),c.classList.toggle("hide",!!this.linkedChatId))};return this.listenerSetter.add(I)("dialog_migrate",({migrateFrom:f,migrateTo:v})=>{const y=l.querySelector(`[data-peer-id="${f}"]`);y&&(y.dataset.peerId=""+v)}),this.listenerSetter.add(I)("chat_full_update",async f=>{if(this.chatId!==f)return;const v=await this.managers.appProfileManager.getChannelFull(f);this.linkedChatId=v.linked_chat_id,g()}),h.push(p,m),Promise.all(h).then(()=>g())}}class oC extends Zt{async _init(){this.listenerSetter.removeAll(),this.container.classList.add("edit-peer-container","edit-group-container"),this.setTitle("Edit");let[e,t,s,i,n,r,o,l,c,d,u,h,p,m,g]=await Promise.all([this.managers.appProfileManager.getChatFull(this.chatId,!0),this.managers.appChatsManager.getChat(this.chatId),this.managers.appChatsManager.isBroadcast(this.chatId),this.managers.appChatsManager.isChannel(this.chatId),this.managers.appChatsManager.hasRights(this.chatId,"change_type"),this.managers.appChatsManager.hasRights(this.chatId,"change_permissions"),this.managers.appChatsManager.hasRights(this.chatId,"manage_topics"),this.managers.appChatsManager.hasRights(this.chatId,"change_permissions"),this.managers.appChatsManager.hasRights(this.chatId,"change_info"),this.managers.appChatsManager.hasRights(this.chatId,"delete_chat"),this.managers.appChatsManager.hasRights(this.chatId,"post_messages"),this.managers.appChatsManager.hasRights(this.chatId,"invite_links"),this.managers.appChatsManager.hasRights(this.chatId,"invite_users"),this.managers.apiManager.getAppConfig(),this.managers.appReactionsManager.getAvailableReactions()]);this.scrollable.replaceChildren();const f={full:[],basic:[]},v=(b,S="basic")=>{f[S].push(b)};this.listenerSetter.add(I)("chat_update",async b=>{this.chatId===b&&(t=await this.managers.appChatsManager.getChat(this.chatId),f.basic.forEach(S=>S()))}),this.listenerSetter.add(I)("chat_full_update",async b=>{this.chatId===b&&(e=await this.managers.appProfileManager.getCachedFullChat(b)||e||await this.managers.appProfileManager.getChatFull(b),f.full.forEach(S=>S()))});const y=this.chatId.toPeerId(!0),w=!!t.admin_rights;{const b=new Oe({noDelimiter:!0,caption:"PeerInfo.SetAboutDescription"}),S=[],_=document.createElement("div");_.classList.add("input-wrapper"),this.chatNameInputField=new Yt({label:s?"EnterChannelName":"CreateGroup.NameHolder",name:"chat-name",maxLength:255,required:!0,canBeEdited:c}),this.descriptionInputField=new Yt({label:"DescriptionPlaceholder",name:"chat-description",maxLength:255,withLinebreaks:!0,canBeEdited:c}),this.chatNameInputField.setOriginalValue(t.title),this.descriptionInputField.setOriginalValue(e.about),_.append(this.chatNameInputField.container,this.descriptionInputField.container),S.push(this.chatNameInputField,this.descriptionInputField),this.editPeer=new Ou({peerId:y,inputFields:S,listenerSetter:this.listenerSetter,popupOptions:{isForum:t.pFlags.forum},middleware:this.middlewareHelper.get()}),this.content.append(this.editPeer.nextBtn),c||(this.editPeer.avatarElem.node.classList.remove("avatar-placeholder"),this.editPeer.avatarEdit.container.replaceChildren(this.editPeer.avatarElem.node),this.editPeer.avatarEdit.container.classList.add("disable-hover")),b.content.append(this.editPeer.avatarEdit.container,_),this.scrollable.append(b.container)}{const b=new Oe({caption:!0});if(n){const S=new Fe({titleLangKey:s?"ChannelType":"GroupType",clickable:()=>{const M=this.slider.createTab(iT);M.chatId=this.chatId,M.chatFull=e,M.open()},icon:"lock",listenerSetter:this.listenerSetter}),_=()=>{let M;const C=ji(t)[0];s?M=C?"TypePublic":"TypePrivate":M=C?"TypePublicGroup":"TypePrivateGroup",S.subtitle.replaceChildren(P(M))};_(),v(_),b.content.append(S.container)}if(h){const S=new Fe({titleLangKey:"InviteLinks",navigationTab:{constructor:ou,slider:this.slider,getInitArgs:()=>({chatId:this.chatId,p:ou.getInitArgs(this.chatId)})},icon:"link",listenerSetter:this.listenerSetter,subtitle:!0}),_=()=>{S.subtitle.textContent="1"};_(),v(_,"full"),b.content.append(S.container)}if(p&&w){const S=new Fe({titleLangKey:s?"SubscribeRequests":"MemberRequests",navigationTab:{constructor:py,getInitArgs:()=>this.chatId,slider:this.slider},icon:"adduser",listenerSetter:this.listenerSetter,subtitle:!0}),_=()=>{const M=e.requests_pending;S.subtitle.textContent=""+M,S.container.classList.toggle("hide",!M)};_(),v(_,"full"),b.content.append(S.container)}if(c&&w){const S=new Fe({titleLangKey:"Reactions",icon:"reactions",navigationTab:{constructor:eg,slider:this.slider,getInitArgs:()=>({chatId:this.chatId,p:eg.getInitArgs(this.chatId)})},listenerSetter:this.listenerSetter}),_=g.filter(C=>!C.pFlags.inactive).length,M=()=>{const C=e.available_reactions??{_:"chatReactionsNone"};if(C._==="chatReactionsSome"){const L=C.reactions.length;L===_?St(S.subtitle,P("ReactionsAll")):S.subtitle.textContent=L+"/"+_}else St(S.subtitle,P(C._==="chatReactionsAll"?"ReactionsAll":"Checkbox.Disabled"))};M(),v(M,"full"),b.content.append(S.container)}if(r&&!s){const S=["send_stickers","send_polls","send_photos","send_videos","send_roundvideos","send_audios","send_voices","send_docs","send_plain","embed_links","invite_users","pin_messages","change_info"],_=new Fe({titleLangKey:"ChannelPermissions",clickable:()=>{const C=this.slider.createTab(t8);C.chatId=this.chatId,C.open()},icon:"permissions",listenerSetter:this.listenerSetter}),M=()=>{const C=S.reduce((E,x)=>E+ +Cr(t,x,t.default_banned_rights),0)+"/"+S.length,L=+t?.send_paid_messages_stars?Ne.format("PrivacySettingsController.Paid",!0):void 0;_.subtitle.innerHTML="",_.subtitle.append(...Yi([C,L].filter(Boolean)))};M(),v(M),b.content.append(_.container)}if(c&&w){const S=new Fe({icon:"comments",titleLangKey:s?"PeerInfo.Discussion":"LinkedChannel",subtitle:!0,navigationTab:{constructor:sg,getInitArgs:()=>({chatId:this.chatId,linkedChatId:e.linked_chat_id,p:sg.getInitArgs()}),slider:this.slider},listenerSetter:this.listenerSetter}),_=async()=>{const M=e.linked_chat_id;let C;M?C=await qe({peerId:M.toPeerId(!0)}):C=P("PeerInfo.Discussion.Add"),s||S.container.classList.toggle("hide",!M),S.subtitle.replaceChildren(C)};await _(),v(_,"full"),b.caption.replaceChildren(P("DiscussionInfo")),b.content.append(S.container)}if(o&&w&&(t.participants_count>=m.forum_upgrade_participants_min||t.pFlags.forum)&&!s){const S=new Fe({checkboxField:new _t({toggle:!0}),titleLangKey:"Topics",clickable:M=>{if(e.linked_chat_id){$e({langPackKey:"ChannelTopicsDiscussionForbidden"}),_e(M);return}},icon:"topics",listenerSetter:this.listenerSetter}),_=()=>{const M=!!t.pFlags.forum;this.editPeer.avatarElem.node.parentElement.classList.toggle("is-forum",M),S.checkboxField.setValueSilently(M)};this.listenerSetter.add(S.checkboxField.input)("change",M=>{if(!M.isTrusted)return;const C=this.managers.appChatsManager.toggleForum(this.chatId,S.checkboxField.checked);S.disableWithPromise(C)}),_(),v(_),v(_,"full"),b.caption.replaceChildren(P("ForumToggleDescription")),b.content.append(S.container)}b.caption.classList.toggle("hide",!b.caption.childElementCount),b.content.childElementCount&&this.scrollable.append(b.container),J(this.editPeer.nextBtn,()=>{this.editPeer.nextBtn.disabled=!0;const S=[],_=this.chatId;this.chatNameInputField.isValidToChange()&&S.push(this.managers.appChatsManager.editTitle(_,this.chatNameInputField.value)),this.descriptionInputField.isValidToChange()&&S.push(this.managers.appChatsManager.editAbout(_,this.descriptionInputField.value)),this.editPeer.uploadAvatar&&S.push(this.editPeer.uploadAvatar().then(M=>this.managers.appChatsManager.editPhoto(_,M))),Promise.race(S).finally(()=>{this.editPeer.nextBtn.removeAttribute("disabled"),this.close()})},{listenerSetter:this.listenerSetter})}{const b=new Oe({});if(l){const S=new Fe({titleLangKey:"PeerInfo.Administrators",subtitle:!0,icon:"admin",navigationTab:{constructor:tg,slider:this.slider,getInitArgs:()=>({chatId:this.chatId,p:tg.getInitArgs(this.chatId)})},listenerSetter:this.listenerSetter}),_=()=>{S.subtitle.textContent=""+(e.admins_count||1)};_(),v(_,"full"),b.content.append(S.container)}{const S=new Fe({titleLangKey:s?"PeerInfo.Subscribers":"GroupMembers",icon:"newgroup",clickable:()=>{this.slider.createTab(b7).open(this.chatId)},listenerSetter:this.listenerSetter,subtitle:!0}),_=()=>{const M=Z_(e);S.subtitle.textContent=ln(M)};_(),v(_,"full"),b.content.append(S.container)}if(r){const S=new Fe({titleLangKey:"ChannelBlockedUsers",subtitle:!0,icon:"deleteuser",clickable:()=>{this.slider.createTab(i8).open(this.chatId)},listenerSetter:this.listenerSetter}),_=()=>{const M=e.kicked_count||0;M?S.subtitle.textContent=ln(M):S.subtitle.replaceChildren(P("NoBlockedUsers"))};_(),v(_,"full"),b.content.append(S.container)}this.scrollable.append(b.container)}if(s&&u){const b=new Oe({caption:!0}),S=new _t({text:"ChannelSignMessages"}),_=new _t({text:"ChannelSignMessagesWithProfile"});this.listenerSetter.add(S.input)("change",()=>{const L=S.toggleDisability(!0);this.managers.appChatsManager.toggleSignatures(this.chatId,S.checked,S.checked&&_.checked).then(()=>{L()})}),this.listenerSetter.add(_.input)("change",()=>{const L=_.toggleDisability(!0);this.managers.appChatsManager.toggleSignatures(this.chatId,S.checked,_.checked).then(()=>{L()})});const M=()=>{S.setValueSilently(!!t.pFlags.signatures),_.setValueSilently(S.checked&&!!t.pFlags.signature_profiles),C.container.classList.toggle("hide",!S.checked),b.caption.replaceChildren(P(_.checked?"ChannelSignProfilesInfo":"ChannelSignMessagesInfo"))},C=jr(_);M(),v(M),b.content.append(jr(S).container,C.container),this.scrollable.append(b.container)}if(!s){const b=new Oe({});if(!s&&n){const S=new _t({text:"ChatHistory"});this.listenerSetter.add(S.input)("change",()=>{const M=S.toggleDisability(!0);this.managers.appChatsManager.togglePreHistoryHidden(this.chatId,!S.checked).then(()=>{M()})});const _=()=>{S.setValueSilently(i&&!e.pFlags.hidden_prehistory)};_(),v(_),b.content.append(jr(S).container)}b.content.childElementCount&&this.scrollable.append(b.container)}if(d){const b=new Oe({}),S=ot("btn-primary btn-transparent danger",{icon:"delete",text:s?"PeerInfo.DeleteChannel":"DeleteAndExitButton"});J(S,()=>{ue.createPopup(kg,y,void 0,_=>{const M=os([S],!0);_.then(()=>{this.close()},()=>{M()})})},{listenerSetter:this.listenerSetter}),b.content.append(S),this.scrollable.append(b.container)}i||this.listenerSetter.add(I)("dialog_migrate",({migrateFrom:b,migrateTo:S})=>{y===b&&(this.chatId=S.toChatId(),this._init())})}init(){return this._init()}}const lC="https://t.me/";function lM(a={}){const e=document.createElement("a");e.classList.add("anchor-copy");let t,s="LinkCopied";if(a.mePath){const i=lC+a.mePath;t=e.href=e.innerText=i}if(a.username){const i=lC+a.username;e.href=i,t=e.innerText="@"+a.username,s="UsernameCopied"}return J(e,i=>{_e(i),si(t??e.href),$e({langPackKey:s})}),e}class Bc{constructor(e,t){this.start=e,this.end=t}toString(){return Bc.timeToString(this.start)+" - "+Bc.timeToString(this.end)}static timeToString(e,t=!0){const s=e%60,i=(e-s)/60%24,n=new Date;n.setHours(i,s);const r=Ny(n).textContent;return e>Zi&&t?Ne.format("BusinessHoursNextDay",!0,[r]):r}}const Aw=class Aw{static adaptWeeklyOpen(e,t){const s=kn(e),i=new Array;for(let n=0;n<s.length;++n){const r=s[n];let o={...r};if(t!==0){const l=r.start_minute%Zi,c=l+(r.end_minute-r.start_minute);if(l===0&&(c===Zi||c===Zi-1)){o.start_minute=r.start_minute,o.end_minute=r.end_minute,i.push(o);continue}}o.start_minute=r.start_minute+t,o.end_minute=r.end_minute+t,i.push(o),o.start_minute<0?o.end_minute<0?(o.start_minute+=On,o.end_minute+=On):(o.start_minute=0,o={...r},o.start_minute=On+r.start_minute+t,o.end_minute=On-1,i.push(o)):o.end_minute>On&&o.start_minute>On&&(o.start_minute-=On,o.end_minute-=On)}return i.sort((n,r)=>n.start_minute-r.start_minute),i}static getDaysHours(e){const t=new Array(7);for(let s=0;s<t.length;++s)t[s]=[];for(let s=0;s<e.length;++s){const i=e[s],n=Math.floor(i.start_minute/Zi%7),r=i.start_minute%Zi,o=r+(i.end_minute-i.start_minute);t[n].push(new Bc(r,o))}for(let s=0;s<7;++s){const i=Zi*s,n=Zi*(s+1);let r=i;for(let l=0;l<e.length;++l){const c=e[l];c.start_minute<=r&&c.end_minute>=r&&(r=c.end_minute+1)}if(r>=n){const l=(7+s-1)%7;t[l].length&&t[l][t[l].length-1].end>=Zi&&(t[l][t[l].length-1].end=Zi-1),t[s].length=0,t[s].push(new Bc(0,Zi-1))}else{const l=(s+1)%7;if(t[s].length&&t[l].length){const c=t[s][t[s].length-1],d=t[l][0];c.end>Zi&&c.end-Zi+1===d.start&&(c.end=Zi-1,d.start=0)}}}return t}static is24x7(e){if(!e||!e.weekly_open.length)return!1;let t=0;for(let s=0;s<e.weekly_open.length;++s){const i=e.weekly_open[s];if(i.start_minute>t+1)return!1;t=i.end_minute}return t>=On-1}static isOpenNow(e){const t=new Date,s=(7+t.getDay()-1)%7,i=t.getHours(),n=t.getMinutes();let r=!1;const o=n+i*60+s*Zi;for(let l=0;l<e.length;++l){const c=e[l];if(o>=c.start_minute&&o<=c.end_minute||o+On>=c.start_minute&&o+On<=c.end_minute||o-On>=c.start_minute&&o-On<=c.end_minute){r=!0;break}}return{openNow:r,nowWeekday:s,nowHours:i,nowPeriodTime:o}}static isFull(e){if(!e||!e.length)return!1;let t=0;for(let s=0;s<e.length;++s){const i=e[s];if(t<i.start)return!1;t=i.end}return t===Zi-1||t===Zi}};Aw.Period=Bc;let yo=Aw;function iv(a,e){const t=a.slice(e),s=a.slice(0,e);return t.concat(s)}const n8=Y("<span>"),a8=Y("<div class=business-hours-row><div class=business-hours-row-day></div><div class=business-hours-row-time>"),r8=Y("<div class=business-hours>");function o8(a){const[e,t]=K(!1),[s,i]=K(!1),[n,r]=K(),[o,l]=K(),[c,d]=K(),[u,h]=K(),p=new $t;ze(()=>p.removeAll());const m=Sg();let g;const f=new Fe({title:!0,titleRight:(()=>{const b=n8(),S=g;return typeof S=="function"?Ue(S,b):g=b,k(b,(()=>{const _=V(()=>c()!==void 0);return()=>_()&&P(c()?"BusinessHoursProfileSwitchMy":"BusinessHoursProfileSwitchLocal")})()),Me(()=>be(b,Ge("business-hours-switch-time",c()===void 0&&"hide"))),b})(),subtitleLangKey:"BusinessHoursProfile",subtitleRight:!0,icon:"sending",clickable:b=>{if(Mi(b.target,g)){d(S=>!S),Vh(m,()=>{w()}),t(!0);return}s()||t(S=>!S)},contextMenu:{buttons:[{icon:"copy",text:"Copy",onClick:()=>{si(u()),$e({langPackKey:"BusinessHoursCopied"})}}]},listenerSetter:p});le(Vt(e,()=>{let b;e()&&!s()&&(b=f.container.querySelector(".business-hours").getBoundingClientRect().height),f.container.style.paddingBottom=b?`${10+b}px`:"",f.container.classList.toggle("is-expanded",e())},{defer:!0}));const y=()=>{const b=a.hours(),_=a.timezones()?.find(x=>x.id===b.timezone_id),C=-new Date().getTimezoneOffset(),L=_?_.utc_offset/60:0;return C-L},w=()=>{const b=a.hours();if(!b||!a.timezones())return;const S=yo.is24x7(b);i(S);const _=b.weekly_open,M=y(),C=!!M,L=C?Ot(c)??!1:!0,E=yo.adaptWeeklyOpen(_,M),{openNow:x,nowPeriodTime:R,nowWeekday:B}=yo.isOpenNow(E);d(C?L:void 0);const N=(z,Z)=>{if(yo.isFull(z))return[Ne.format("BusinessHoursProfileOpen",!0)];if(!Z&&!x&&!e()){let ie=-1;for(let oe=0;oe<E.length;++oe){const ae=E[oe];if(R<ae.start_minute){ie=ae.start_minute;break}}if(ie===-1&&E.length&&(ie=E[0].start_minute),ie===-1)return[Ne.format("BusinessHoursProfileClose",!0)];{const oe=ie<R?ie+(On-R):ie-R;return oe<60?[Ne.format("BusinessHoursProfileOpensInMinutes",!0,[oe])]:oe<Zi?[Ne.format("BusinessHoursProfileOpensInHours",!0,[Math.ceil(oe/60)])]:[Ne.format("BusinessHoursProfileOpensInDays",!0,[Math.ceil(oe/Zi)])]}}const de=z.map(ie=>ie.toString());return de.length?de:[Ne.format("BusinessHoursProfileClose",!0)]},G=z=>iv(z,B).map(N),O=yo.getDaysHours(_),$=G(O),H=yo.getDaysHours(E),D=G(H),U=L?D:$;if(f.title.replaceChildren(P(x?"BusinessHoursProfileNowOpen":"BusinessHoursProfileNowClosed")),f.title.classList.toggle("green",x),f.title.classList.toggle("danger",!x),f.subtitleRight.textContent=S?Ne.format("BusinessHoursProfileFullOpen",!0):U[0][0],S)return;const j=iv(lE(),B),q=U.map(z=>z.join("")).join("");if(Ot(n)===q)return;const W=[];r(q);const ee=U.map((z,Z)=>{const de=j[Z];let ie=de+": ";const oe=z;Z===0&&(z=z.slice(1));const ae=T(Cs,{each:z,children:(ke,re)=>(()=>{const ce=a8(),Ie=ce.firstChild,Ve=Ie.nextSibling;return k(Ie,()=>Z!==0&&re()===0?de:""),k(Ve,ke),ce})()});return ie+=oe.join(", "),W.push(ie),ae});h(iv(W,-B).join(`
- `)),l((()=>{const z=r8();return k(z,ee),z})())};return le(w),f.container.classList.add("business-hours-container"),T(gd,{get mount(){return f.container},get children(){return T(Yo,{type:"cross-fade",get children(){return o()}})}}),f}class l8 extends Ag{constructor(e){super({...e,loadMore:(t,s,i)=>{if(this.peerId.isAnyChat()||!s)return Promise.resolve({count:0,items:[]});const n=t?.photoId;return this.managers.appPhotosManager.getUserPhotos(this.peerId,n,i).then(r=>{const o=r.photos.map(l=>({element:null,photoId:l}));return{count:r.count,items:o}})}}),this.loadedAllUp=!0,this.peerId=e.peerId}}function c8(a){const e=a.split(" ");if(e.length!==4){e[0]||(e[0]="0px");for(let t=e.length;t<4;++t)e[t]=e[t%2]||e[0]||"0px"}return e}function Bp(a,e,t,s,i,n,r){return[a,",",e," ",t," ",s,",",i," ",n,",",r].join("")}function _c(a,e,t,s,i,n,r,o){const l=[];return l.push("M"+(a+t/2)+","+e),l.push("H"+(a+t-n)),n>0&&l.push("A"+Bp(n,n,0,0,1,a+t,e+n)),l.push("V"+(e+s-r)),r>0&&l.push("A"+Bp(r,r,0,0,1,a+t-r,e+s)),l.push("H"+(a+o)),o>0&&l.push("A"+Bp(o,o,0,0,1,a+0,e+s-o)),l.push("V"+(e+i)),i>0&&l.push("A"+Bp(i,i,0,0,1,a+i,e+0)),l.push("Z"),l.join(" ")}Di.generatePathData=_c;function cC(a,e,t){return a>=e&&a<=t}function cM(a){const e=`/rtmp/${encodeURIComponent(JSON.stringify(a))}`;return dn?`${e}?hls=playlist&t=${Date.now()}`:`${e}?t=${Date.now()}`}function dC(a){const e=Ae.getChat(a);if(e._!=="channel")throw new Error("Not a channel");return e.username||e.usernames?.length?`https://t.me/${e.username||e.usernames[0]}?livestream`:`https://t.me/c/${e.id}?livestream`}const d8="mtproto:",h8=1e6,u8=1280,p8=720;function m8(a){if(!a?.length)return[];const e=g8(a),t=f8(a);return Object.entries(e).map(([s,i])=>{const{w:n=u8,h:r=p8,duration:o=0,video_codec:l}=i,{size:c}=a.find(u=>u.id.toString()===s),d=(o>0?c/o*8:h8)|0;return{id:s,w:n,h:r,duration:o,bandwidth:d,url:t[s],codec:l}})}function g8(a){const e={};for(const t of a){const s=t?.attributes?.find(i=>i._==="documentAttributeVideo");s&&(e[t.id]=s)}return e}function f8(a){const e={};for(const t of a)cE(t)&&(e[y8(t)]=v8(t));return e}function v8(a){return`hls_quality_file/${a.id}`}function y8(a){const e=a.attributes?.find(s=>s._==="documentAttributeFilename");return(a.file_name||e?.file_name)?.slice(d8.length)}function b8(a,{download:e=!1,thumb:t,supportsHlsStreaming:s}={}){let i;return e?i="download":t?i="thumb":s?i="hls":a.supportsStreaming?i="stream":i="document",dE(i,hE(a,{thumb:t}))}const w8=.5,nr=1,Dp=.5,$p=4,S8=200,C8=350,_i="media-viewer";class yw extends pn{constructor(e,t,s=0){super(!1),this.listLoader=e,this.extraHeightPadding=s,this.author={},this.content={},this.buttons={},this.tempId=0,this.preloader=null,this.preloaderStreamable=null,this.isFirstOpen=!0,this.streamEnded=!1,this.downloadQualityMenuOptions=[],this.zoomElements={},this.transform={x:0,y:0,scale:nr},this.lastTransform=this.transform,this.lastZoomCenter=this.transform,this.lastDragOffset=this.transform,this.lastDragDelta=this.transform,this.videoTimestamps=[],this.onSwipeFirst=c=>{this.lastDragOffset=this.lastDragDelta={x:0,y:0},this.lastTransform={...this.transform},(c?.type!=="wheel"||!this.ctrlKeyDown)&&(this.moversContainer.classList.add("no-transition"),this.zoomElements.rangeSelector.container.classList.remove("with-transition")),this.isGesturingNow=!0,this.lastGestureTime=Date.now(),this.clampZoomDebounced.clearTimeout(),!this.lastTransform.x&&!this.lastTransform.y&&!this.isZooming&&(this.initialContentRect=this.content.media.getBoundingClientRect())},this.onSwipeReset=c=>{this.moversContainer.classList.remove("no-transition"),this.zoomElements.rangeSelector.container.classList.add("with-transition"),this.clampZoomDebounced.clearTimeout(),c?.type==="mouseup"&&this.draggingType==="mousemove"&&(this.ignoreNextClick=!0);const{draggingType:d}=this;if(this.isZoomingNow=!1,this.isGesturingNow=!1,this.draggingType=void 0,!this.closing)if(this.transform.scale>nr){const u=Math.min(this.transform.scale,$p),h=u/this.transform.scale;let p=this.transform.x*h+(this.lastZoomCenter.x-h*this.lastZoomCenter.x),m=this.transform.y*h+(this.lastZoomCenter.y-h*this.lastZoomCenter.y);if(d&&d!=="wheel"&&this.lastTransform.scale===this.transform.scale){const v=Math.max(1,Date.now()-this.lastGestureTime),y=Math.abs(this.lastDragOffset.x)/v,w=Math.abs(this.lastDragOffset.y)/v;p-=Math.abs(this.lastDragOffset.x)*y*.1*-this.lastDragDelta.x,m-=Math.abs(this.lastDragOffset.y)*w*.1*-this.lastDragDelta.y}const[g]=this.calculateOffsetBoundaries({x:p,y:m,scale:u});this.lastTransform=g,this.setTransform(g)}else this.transform.scale<nr&&this.resetZoom()},this.onZoom=({initialCenterX:c,initialCenterY:d,zoom:u,zoomAdd:h,currentCenterX:p,currentCenterY:m,dragOffsetX:g,dragOffsetY:f,zoomFactor:v})=>{c||(c=It.width/2),d||(d=It.height/2),p||(p=It.width/2),m||(m=It.height/2),this.isZoomingNow=!0;const y=$p*3,w=h!==void 0?zt(this.lastTransform.scale+h,Dp,y):u??zt(this.lastTransform.scale*v,Dp,y),b=w/this.lastTransform.scale,S=Math.abs(Math.min(this.lastTransform.x,0)),_=Math.abs(Math.min(this.lastTransform.y,0));this.lastZoomCenter={x:p,y:m};const M=S+c,C=_+d,{scaleOffsetX:L,scaleOffsetY:E}=this.calculateScaleOffset({x:M,y:C,scale:b}),[x]=this.calculateOffsetBoundaries({x:this.lastTransform.x+L+g,y:this.lastTransform.y+E+f,scale:w});this.setTransform(x)},this.calculateOffsetBoundaries=({x:c,y:d,scale:u},h=0)=>{if(!this.initialContentRect)return[{x:c,y:d,scale:u},!0,!0];let p=!0,m=!0;const{minX:g,maxX:f,minY:v,maxY:y}=this.getZoomBoundaries(u,h);return p=cC(c,f,g),c=zt(c,f,g),m=cC(d,y,v),d=zt(d,y,v),[{x:c,y:d,scale:u},p,m]},this.setZoomValue=(c=this.transform.scale)=>{this.initialContentRect??(this.initialContentRect=this.content.media.getBoundingClientRect()),c===nr&&(this.transform.x=0,this.transform.y=0),this.moversContainer.style.transform=`translate3d(${this.transform.x.toFixed(3)}px, ${this.transform.y.toFixed(3)}px, 0px) scale(${c.toFixed(3)})`,this.zoomElements.btnOut.classList.toggle("inactive",c<=Dp),this.zoomElements.btnIn.classList.toggle("inactive",c>=$p),this.toggleZoom(c!==nr)},this.onClick=c=>{const d=c.target;if(ne(d,"popup"))return;if(this.ignoreNextClick){this.ignoreNextClick=void 0;return}if(this.setMoverAnimationPromise||d.tagName==="A")return;if(ne(d,"admin-popup-container")||_e(c),pt){this.highlightSwitchersTimeout?clearTimeout(this.highlightSwitchersTimeout):this.wholeDiv.classList.add("highlight-switchers"),this.highlightSwitchersTimeout=window.setTimeout(()=>{this.wholeDiv.classList.remove("highlight-switchers"),this.highlightSwitchersTimeout=0},3e3);return}if(Hy(c))return;const u=this.isZooming&&!1,h=["admin-popup-container","ckin__player","media-viewer-buttons","media-viewer-author","media-viewer-caption","zoom-container"];u&&h.push("media-viewer-movers");const p=h.some(m=>!!ne(d,m));if(!p&&this.live&&document.pictureInPictureEnabled){this.videoPlayer.requestPictureInPicture();return}(!p||!u&&(d.tagName==="IMG"||d.tagName==="image"))&&this.close()},this.onKeyDown=c=>{if(vn.overlaysActive>1)return;const d=c.key;let u=!0;d==="ArrowRight"?!this.isZooming&&this.buttons.next.click():d==="ArrowLeft"?!this.isZooming&&this.buttons.prev.click():d==="-"||d==="="?this.ctrlKeyDown&&this.addZoomStep(d==="="):u=!1,(c.ctrlKey||c.metaKey)&&(this.ctrlKeyDown=!0),u&&_e(c)},this.onKeyUp=c=>{vn.overlaysActive>1||c.ctrlKey||c.metaKey||(this.ctrlKeyDown=!1,this.isZooming&&this.setZoomValue())},this.managers=I.managers,this.middlewareHelper=Ht(),this.log=Ni("AMV"),this.preloader=new Kn,this.preloaderStreamable=new Kn({cancelable:!1,streamable:!0}),this.preloader.construct(),this.preloaderStreamable.construct(),this.lazyLoadQueue=new c_,this.wholeDiv=document.createElement("div"),this.wholeDiv.classList.add(_i+"-whole"),this.overlaysDiv=document.createElement("div"),this.overlaysDiv.classList.add("overlays"),this.overlayActive=!1;const i=document.createElement("div");i.classList.add(_i);const n=this.topbar=document.createElement("div");n.classList.add(_i+"-topbar",_i+"-appear");const r=document.createElement("div");r.classList.add(_i+"-topbar-left"),this.buttons["mobile-close"]=yt("close",{onlyMobile:!0}),this.author.container=document.createElement("div"),this.author.container.classList.add(_i+"-author","no-select");const o=document.createElement("div");o.classList.add(_i+"-author-right"),this.author.nameEl=document.createElement("div"),this.author.nameEl.classList.add(_i+"-name"),this.author.date=document.createElement("div"),this.author.date.classList.add(_i+"-date"),o.append(this.author.nameEl,this.author.date),this.author.container.append(o);const l=document.createElement("div");l.classList.add(_i+"-buttons"),t.concat(["download","zoomin","close"]).forEach(c=>{const d=yt(c,{noRipple:!0});this.buttons[c]=d,l.append(d)}),this.zoomElements.container=document.createElement("div"),this.zoomElements.container.classList.add("zoom-container"),this.zoomElements.btnOut=yt("zoomout",{noRipple:!0}),J(this.zoomElements.btnOut,()=>this.addZoomStep(!1)),this.zoomElements.btnIn=yt("zoomin",{noRipple:!0}),J(this.zoomElements.btnIn,()=>this.addZoomStep(!0)),this.zoomElements.rangeSelector=new Xl({step:.01,min:Dp,max:$p,withTransition:!0},nr),this.zoomElements.rangeSelector.setListeners(),this.zoomElements.rangeSelector.setHandlers({onScrub:c=>{const d=c-this.transform.scale;this.addZoom(d),this.clampZoomDebounced?.clearTimeout()},onMouseDown:()=>{this.onSwipeFirst()},onMouseUp:()=>{this.onSwipeReset()}}),this.zoomElements.container.append(this.zoomElements.btnOut,this.zoomElements.rangeSelector.container,this.zoomElements.btnIn),pt||this.wholeDiv.append(this.zoomElements.container),this.content.main=document.createElement("div"),this.content.main.classList.add(_i+"-content"),this.content.container=document.createElement("div"),this.content.container.classList.add(_i+"-container"),this.content.media=document.createElement("div"),this.content.media.classList.add(_i+"-media"),this.content.container.append(this.content.media),this.content.main.append(this.content.container),i.append(this.content.main),this.overlaysDiv.append(i),r.append(this.buttons["mobile-close"],this.author.container),n.append(r,l),this.buttons.prev=document.createElement("div"),this.buttons.prev.className=`${_i}-switcher ${_i}-switcher-left`,this.buttons.prev.append(Be("previous",`${_i}-sibling-button`,`${_i}-prev-button`)),this.buttons.next=document.createElement("div"),this.buttons.next.className=`${_i}-switcher ${_i}-switcher-right`,this.buttons.next.append(Be("next",`${_i}-sibling-button`,`${_i}-next-button`)),this.moversContainer=document.createElement("div"),this.moversContainer.classList.add(_i+"-movers"),this.moversContainer.append(this.buttons.prev,this.buttons.next),this.wholeDiv.append(this.overlaysDiv,this.topbar,this.moversContainer),this.listLoader.onLoadedMore=()=>{this.buttons.prev.classList.toggle("hide",!this.listLoader.previous.length),this.buttons.next.classList.toggle("hide",!this.listLoader.next.length)},this.setNewMover()}get hasQualityOptions(){return this.downloadQualityMenuOptions.length>0}get target(){return this.listLoader.current}set target(e){this.listLoader.current=e}setListeners(){J(this.buttons.download,s=>{this.hasQualityOptions||this.onDownloadClick(s)}),this.buttons.download.classList.add("quality-download-options-button-menu"),ki({container:this.buttons.download,buttons:this.downloadQualityMenuOptions,direction:"bottom-left"}),[this.buttons.close,this.buttons["mobile-close"],this.preloaderStreamable.preloader].forEach(s=>{J(s,this.close.bind(this))}),[[-1,this.buttons.prev],[1,this.buttons.next]].forEach(([s,i])=>{i.addEventListener("click",n=>{_e(n),!this.setMoverPromise&&this.listLoader.go(s)})}),J(this.buttons.zoomin,()=>{this.isZooming?this.resetZoom():this.addZoomStep(!0)}),this.wholeDiv.addEventListener("click",this.onClick),this.listLoader.onJump=(s,i)=>{i?this.onNextClick(s):this.onPrevClick(s)};const e=(s,i)=>{const[n,r]=[s-this.lastDragOffset.x,i-this.lastDragOffset.y],[o,l,c]=this.calculateOffsetBoundaries({x:this.transform.x+n,y:this.transform.y+r,scale:this.transform.scale});return this.lastDragDelta={x:n,y:r},this.lastDragOffset={x:s,y:i},this.setTransform(o),{inBoundsX:l,inBoundsY:c}},t=$i(()=>{this.lastGestureTime=Date.now()},500,!1,!0);this.clampZoomDebounced=$i(()=>{this.onSwipeReset()},300,!1,!0),this.swipeHandler=new Qn({element:this.wholeDiv,onReset:this.onSwipeReset,onFirstSwipe:this.onSwipeFirst,onSwipe:(s,i,n,r)=>{if(pa())return;if(this.isZooming&&!this.isZoomingNow){t(),this.draggingType=n.type;const{inBoundsX:c,inBoundsY:d}=e(s,i);r?.(!c,!d);return}return this.isZoomingNow||!pt?void 0:Math.abs(s)/It.width>.2||Math.abs(s)>125?(s>0?this.buttons.prev.click():this.buttons.next.click(),!0):Math.abs(i)/It.height>.2||Math.abs(i)>125?(this.close(),!0):!1},onZoom:this.onZoom,onDoubleClick:({centerX:s,centerY:i})=>{if(this.isZooming)this.resetZoom();else{const n=nr+2;this.changeZoomByPosition(s,i,n)}},verifyTouchTarget:s=>!(pa()||Mi(s.target,this.zoomElements.container)||ne(s.target,"ckin__controls")||ne(s.target,"media-viewer-caption")||ne(s.target,"media-viewer-topbar")&&s.type!=="wheel"),cursor:""})}changeZoomByPosition(e,t,s){const{scaleOffsetX:i,scaleOffsetY:n}=this.calculateScaleOffset({x:e,y:t,scale:s}),r=this.calculateOffsetBoundaries({x:i,y:n,scale:s})[0];this.setTransform(r)}setTransform(e){this.transform=e,this.changeZoom(e.scale)}calculateScaleOffset({x:e,y:t,scale:s}){return{scaleOffsetX:e-s*e,scaleOffsetY:t-s*t}}toggleZoom(e){const t=this.isZooming,s=e===void 0;if((this.zoomElements.rangeSelector.mousedown||this.ctrlKeyDown)&&(e=!0),e??(e=!t),t!==e){if(Wo(this.buttons.zoomin,e?"zoomout":"zoomin"),this.zoomElements.container.classList.toggle("is-visible",this.isZooming=e),this.wholeDiv.classList.toggle("is-zooming",e),s||!e){const i=e?this.transform.scale:nr;this.setZoomValue(i),this.zoomElements.rangeSelector.setProgress(i)}this.videoPlayer&&this.videoPlayer.lockControls(e?!1:void 0)}}addZoomStep(e){this.addZoom(w8*(e?1:-1))}resetZoom(){this.setTransform({x:0,y:0,scale:nr})}changeZoom(e=this.transform.scale){this.transform.scale=e,this.zoomElements.rangeSelector.setProgress(e),this.setZoomValue(e)}addZoom(e){this.lastTransform=this.transform,this.onZoom({zoomAdd:e,currentCenterX:0,currentCenterY:0,initialCenterX:0,initialCenterY:0,dragOffsetX:0,dragOffsetY:0}),this.lastTransform=this.transform,this.clampZoomDebounced()}getZoomBounce(){return this.isGesturingNow&&pt?50:0}getZoomBoundaries(e=this.transform.scale,t=0){if(!this.initialContentRect)return{minX:0,maxX:0,minY:0,maxY:0};const s=(It.width-It.width*e)/2,i=(It.height-It.height*e)/2,n=Math.max(-this.initialContentRect.left*e,s),r=It.width-this.initialContentRect.right*e,o=Math.max(-this.initialContentRect.top*e+t,i),l=It.height-this.initialContentRect.bottom*e;return{minX:n,maxX:r,minY:o,maxY:l}}setBtnMenuToggle(e){const t=ki({buttonOptions:{onlyMobile:!0},direction:"bottom-left",buttons:e});this.topbar.append(t)}close(e){if(this.disposeSolid?.(),e&&_e(e),this.closing)return this.setMoverAnimationPromise;if(this.setMoverAnimationPromise)return Promise.reject();this.closing=!0,this.swipeHandler?.removeListeners(),this.navigationItem&&Pt.removeItem(this.navigationItem),this.lazyLoadQueue.clear(),this.author.avatarMiddlewareHelper?.destroy();const t=this.setMoverToTarget(this.target?.element,!0).then(({onAnimationEnd:s})=>s);return this.listLoader.reset(),this.listLoader.cleanup&&this.listLoader.cleanup(),this.setMoverPromise=null,this.tempId=-1,window.appMediaViewer===this&&(window.appMediaViewer=void 0),this.removeGlobalListeners(),t.finally(()=>{this.wholeDiv.remove(),this.toggleOverlay(!1),this.middlewareHelper.destroy()}),t}toggleOverlay(e){this.overlayActive!==e&&(this.overlayActive=e,vn.isDarkOverlayActive=e,Ut.checkAnimations2(e))}toggleGlobalListeners(e){e?this.setGlobalListeners():this.removeGlobalListeners()}removeGlobalListeners(){window.removeEventListener("keydown",this.onKeyDown),window.removeEventListener("keyup",this.onKeyUp)}setGlobalListeners(){window.addEventListener("keydown",this.onKeyDown),window.addEventListener("keyup",this.onKeyUp)}setMediaTimestamp(e){this.videoPlayer?.setTimestamp(e)}async setMoverToTarget(e,t=!1,s=0){this.dispatchEvent("setMoverBefore");const i=this.content.mover;t||i.replaceChildren();const n=this.isZooming&&t?this.transform.scale:nr;this.removeCenterFromMover(i),t&&(i.offsetLeft,await hi());const r=s!==0,o=wt.isAvailable("animations")?r?C8:S8:0;let l,c;e&&(Wh(e)||e.classList.contains("grid-item")?(l=e,c=e.getBoundingClientRect()):e instanceof SVGImageElement||e.parentElement instanceof SVGForeignObjectElement?(l=ne(e,"attachment"),c=l.getBoundingClientRect()):e.classList.contains("profile-avatars-avatar")&&(l=ne(e,"profile-avatars-container"),c=l.getBoundingClientRect(),t&&e.getBoundingClientRect().left!==c.left&&(e=l=c=void 0))),e||(e=this.content.media),c||(l=e.parentElement,c=e.getBoundingClientRect());let d=!1;if(e===this.content.media)d=!0;else if(!e.classList.contains("profile-avatars-avatar")){const L=ne(l,"scrollable"),E=Ko(l,L,!0);t&&E&&(E.overflow.vertical===2||E.overflow.horizontal===2)?(e=this.content.media,l=e.parentElement,c=e.getBoundingClientRect()):E&&(E.overflow.vertical===1||E.overflow.horizontal===1)&&(d=!0)}const u=this.content.media.getBoundingClientRect();let h="",p,m;r?(p=s===1?It.width:-u.width,m=u.top):(p=c.left,m=c.top),h+=`translate3d(${p}px,${m}px,0) `;let g;if(e instanceof HTMLImageElement||e instanceof HTMLVideoElement||e.tagName==="DIV"){if(i.firstElementChild&&i.firstElementChild.classList.contains("media-viewer-aspecter")){g=i.firstElementChild;const L=g.querySelector(".ckin__player");if(L&&!d){const E=L.querySelector("video");E&&(E.pause(),L.replaceWith(E))}g.style.cssText||(i.classList.remove("active"),this.setFullAspect(g,u,c),i.offsetLeft,i.classList.add("active"))}else g=document.createElement("div"),g.classList.add("media-viewer-aspecter"),i.prepend(g);g.style.cssText=`width: ${c.width}px; height: ${c.height}px; transform: scale3d(${u.width/c.width}, ${u.height/c.height}, 1);`}i.style.width=u.width+"px",i.style.height=u.height+"px";const f=c.width/u.width,v=c.height/u.height;r||(h+=`scale3d(${f},${v},1) `);let y=window.getComputedStyle(l).getPropertyValue("border-radius");if(y=c8(y).map(L=>parseInt(L)/f+"px").join(" "),r||(i.style.borderRadius=y),t&&n!==1){const L=c.left-(It.width*f-c.width)/2,E=c.top-(It.height*v-c.height)/2;this.moversContainer.style.transform=`matrix(${f}, 0, 0, ${v}, ${L}, ${E})`}else i.style.transform=h;d&&(i.style.opacity="0");let b;const S=e.classList.contains("is-out"),_=this.setMoverAnimationPromise=Mt(),M={onAnimationEnd:_},C=setTimeout(()=>{!_.isFulfilled&&!_.isRejected&&_.resolve()},1e3);if(_.finally(()=>{this.dispatchEvent("setMoverAfter"),this.setMoverAnimationPromise===_&&(this.setMoverAnimationPromise=null),clearTimeout(C)}),t)return e instanceof SVGSVGElement&&(b=i.querySelector("path"),b&&this.sizeTailPath(b,u,f,o,!1,S,y)),this.toggleWholeActive(!1),setTimeout(()=>{i.style.borderRadius=y,i.firstElementChild&&(i.firstElementChild.style.borderRadius=y)},o/2),setTimeout(()=>{i.replaceChildren(),i.classList.remove("moving","active","hiding"),i.style.cssText="display: none;",_.resolve()},o),i.classList.remove("opening"),M;{let L,E;const x="video, img, .canvas-thumbnail",R=e.matches(x)?e.parentElement:e,B=Array.from(R.querySelectorAll(x));if(B.length){e=B.pop();const N=document.createElement("canvas"),G=N.getContext("2d");e instanceof HTMLImageElement?(N.width=e.naturalWidth,N.height=e.naturalHeight):e instanceof HTMLVideoElement?(N.width=e.videoWidth,N.height=e.videoHeight):e instanceof HTMLCanvasElement&&(N.width=e.width,N.height=e.height),N.className="canvas-thumbnail thumbnail media-photo",G.drawImage(e,0,0),this.live&&XE(G,0,0,N.width,N.height,8,2),e=N}if(e.tagName==="DIV"||Wh(e)){const G=Array.from(e.querySelectorAll("img")).pop();if(G)L=new Image,E=G.src,i.append(L);else{const O=e.querySelector(".avatar[data-color]");if(O){const $=O.cloneNode(!0);$.textContent="",g.append($)}}}else if(e instanceof HTMLImageElement)L=new Image,E=e.src;else if(e instanceof HTMLVideoElement)L=Do({middleware:i.middlewareHelper.get()}),L.src=e.src;else if(e instanceof SVGSVGElement){const N=e.dataset.clipId,G=N+"-mv",{width:O,height:$}=u,H=document.createElementNS("http://www.w3.org/2000/svg","svg");H.setAttributeNS(null,"width",""+O),H.setAttributeNS(null,"height",""+$),H.setAttributeNS(null,"viewBox",`0 0 ${O} ${$}`),H.setAttributeNS(null,"preserveAspectRatio","xMidYMid meet"),H.insertAdjacentHTML("beforeend",e.firstElementChild.outerHTML.replace(N,G)),H.insertAdjacentHTML("beforeend",e.lastElementChild.outerHTML.replace(N,G));const D=H.firstElementChild,U=D.firstElementChild.firstElementChild;if(U instanceof SVGUseElement){let q=U.getAttributeNS(null,"transform");q=q.replace(/translate\((.+?), (.+?)\) scale\((.+?), (.+?)\)/,(z,Z,de,ie,oe)=>(Z=+Z,Z!==2?Z=O-2/f:Z=2/f,de=$,`translate(${Z}, ${de}) scale(${+ie/f}, ${+oe/v})`)),U.setAttributeNS(null,"transform",q),b=D.firstElementChild.lastElementChild;let W;const ee=y.split(" ").map(z=>parseInt(z));S?W=_c(0,0,O-9/f,$,...ee):W=_c(9/f,0,O-9/f,$,...ee),b.setAttributeNS(null,"d",W)}const j=H.lastElementChild;j.setAttributeNS(null,"width",""+u.width),j.setAttributeNS(null,"height",""+u.height),i.prepend(H)}else e instanceof HTMLCanvasElement&&(L=e);g&&(g.style.borderRadius=y,L&&g.append(L)),L=i.querySelector("video, img"),L instanceof HTMLImageElement&&(L.classList.add("thumbnail"),g||(L.style.width=u.width+"px",L.style.height=u.height+"px"),E&&await Vn(L,E)),i.style.display="",$s(()=>{i.classList.add(r?"moving":"active")})}return i.classList.add("opening"),await hi(),i.style.transform=`translate3d(${u.left}px,${u.top}px,0) scale3d(1,1,1)`,d&&(i.style.opacity=""),g&&this.setFullAspect(g,u,c),setTimeout(()=>{i.style.borderRadius="",i.firstElementChild&&(i.firstElementChild.style.borderRadius="")},0),i.dataset.timeout=""+setTimeout(()=>{i.classList.remove("moving","opening"),g&&(i.querySelector("video"),i.classList.remove("active"),g.style.cssText="",i.offsetLeft),i.classList.add("center","no-transition"),i.classList.add("active"),delete i.dataset.timeout,_.resolve()},o),b&&this.sizeTailPath(b,u,f,o,!0,S,y),M}toggleWholeActive(e){e?this.wholeDiv.classList.add("active"):(this.wholeDiv.classList.add("backwards"),setTimeout(()=>{this.wholeDiv.classList.remove("active")},0))}setFullAspect(e,t,s){const i=t.width/t.height;let{width:n,height:r}=s;i>0?n=r*i:r=n*i,e.style.cssText=`width: ${n}px; height: ${r}px; transform: scale3d(${t.width/n}, ${t.height/r}, 1);`}sizeTailPath(e,t,s,i,n,r,o){const l=Date.now(),{width:c,height:d}=t;i=i/2;const u=o.split(" ").map(p=>parseInt(p)),h=()=>{const p=Date.now()-l;let m=i?p/i:1;m>1&&(m=1),n&&(m=1-m);const g=u.map(v=>v*m);let f;r?f=_c(0,0,c-9/s*m,d,...g):f=_c(9/s*m,0,c,d,...g),e.setAttributeNS(null,"d",f),p<i&&$s(h)};h()}removeCenterFromMover(e){if(e.classList.contains("center")){const t=this.content.media.getBoundingClientRect();e.style.transform=`translate3d(${t.left}px,${t.top}px,0)`,e.classList.remove("center"),e.offsetLeft,e.classList.remove("no-transition")}}moveTheMover(e,t=!0){const s=It.width;this.removeCenterFromMover(e),e.classList.add("moving"),e.dataset.timeout&&clearTimeout(+e.dataset.timeout);const i=e.getBoundingClientRect(),n=e.style.transform.replace(/translate3d\((.+?),/,(r,o)=>{const l=t?-i.width:s;return r.replace(o,l+"px")});e.style.transform=n,setTimeout(()=>{e.middlewareHelper.destroy(),e.remove()},350)}setNewMover(){const e=document.createElement("div");return e.classList.add("media-viewer-mover"),e.style.display="none",e.middlewareHelper=this.middlewareHelper.get().create(),this.content.mover?this.content.mover.parentElement.append(e):this.moversContainer.append(e),this.content.mover=e}updateMediaSource(e,t,s){const i=e.tagName.toLowerCase()===s?e:e.querySelector(s);if(i&&!ne(e,"document")){if(ne(e,"attachment")){const n=e.parentElement.parentElement.querySelector(".preloader-container");if(n){if(s==="video"){n.classList.contains("manual")&&n.click();return}n.remove()}}i.getAttribute("src")!==t&&Ka(i,t),i.classList.contains("thumbnail")&&i.parentElement.classList.contains("media-container-aspecter")&&i.classList.remove("thumbnail")}}setAuthorInfo(e,t){const s=e.isPeerId();let i;if(s)i=qe({peerId:e,dialog:!1,onlyFirstName:!1,plainText:!1});else{const l=i=document.createElement("span");l.append(je(e)),l.classList.add("peer-title")}const n=this.author.avatarEl,r=this.author.avatarMiddlewareHelper,o=this.author.avatarEl=vs({middleware:(this.author.avatarMiddlewareHelper=this.middlewareHelper.get().create()).get(),size:44,peerId:e||Wt,peerTitle:s?void 0:""+e});return o.node.classList.add(_i+"-userpic"),Promise.all([o.readyThumbPromise,i]).then(([l,c])=>{St(this.author.date,this.live?P("Rtmp.MediaViewer.Streaming"):gs(t)),St(this.author.nameEl,c),n?.node&&n.node.parentElement?n.node.replaceWith(this.author.avatarEl.node):this.author.container.prepend(this.author.avatarEl.node),n&&(n.node.remove(),r.destroy())})}get mediaBoxSize(){const{width:e,height:t}=It;return new Lv(e,t-120-(st.isMobile||this.live?0:120)-this.extraHeightPadding)}removeQualityOptions(){this.downloadQualityMenuOptions.splice(0)}async loadQualityLevelsDownloadOptions(e){this.removeQualityOptions();const t=await this.managers.appDocsManager.getAltDocsByDocument(e.id);if(!t)return;const s=m8(t);if(!s.length)return;const n=Array.from(new Set(s.map(o=>uh(o.h)))).sort((o,l)=>l-o).map(o=>{let l;for(const c of s)uh(c.h)===o&&(!l||c.bandwidth<l.bandwidth)&&(l=c);return l});if(n.length<=1)return;const r=await Promise.all(n.map(async o=>{const l=await this.managers.appDocsManager.getDoc(o.id),c=uh(o.h);return{regularText:u1(`Hls.SaveIn${c}`,ur(l.size,1)),onClick:d=>{this.onDownloadClick(d,o.id)}}}));this.downloadQualityMenuOptions.push(...r)}async _openMedia({media:e,mediaThumbnail:t,timestamp:s,fromId:i,fromRight:n,target:r,reverse:o=!1,prevTargets:l=[],nextTargets:c=[],message:d,mediaTimestamp:u,setupPlayer:h,onCanPlay:p,onMoverSet:m,onBuffering:g,noAuthor:f}){if(this.setMoverPromise)return this.setMoverPromise;const v=f?Promise.resolve():this.setAuthorInfo(i,s),y=e._==="inputGroupCall",w=e._==="document",b=w&&e.mime_type&&(["video","gif"].includes(e.type)||e.mime_type.indexOf("video/")===0);let S;this.log("openMedia",e,i,l,c,y,w,b),this.live=y,this.isFirstOpen&&(this.isFirstOpen=!1,this.listLoader.setTargets(l,c,o),window.appMediaViewer=this),this.listLoader.next.length<10&&setTimeout(()=>{this.listLoader.load(!0)},0),this.buttons.prev.classList.toggle("hide",!this.listLoader.previous.length),this.buttons.next.classList.toggle("hide",!this.listLoader.next.length);const _=this.content.media,M=!r||r===_;M&&(r=_),this.target={element:r};const C=++this.tempId;_.firstElementChild&&_.replaceChildren();let L;e._==="document"?L=this.loadQualityLevelsDownloadOptions(e):L=Promise.resolve(this.removeQualityOptions()),n!==0?(this.moveTheMover(this.content.mover,n===1),this.setNewMover()):(this.navigationItem={type:"media",onPop:U=>{if(this.setMoverAnimationPromise)return!1;!U&&wr&&this.wholeDiv.remove(),this.close()}},Pt.pushItem(this.navigationItem),this.toggleOverlay(!0),this.setGlobalListeners(),await v,this.wholeDiv.parentElement||(document.body.append(this.wholeDiv),this.wholeDiv.offsetLeft),this.toggleWholeActive(!0));const x=this.content.mover,R=this.mediaBoxSize,B=y?new Lv(1080,608):void 0;let N=Promise.resolve();const G=Tc(y?{boxWidth:R.width,boxHeight:R.height,element:_,size:B}:{photo:e,element:_,boxWidth:R.width,boxHeight:R.height,noZoom:!st.isMobile,pushDocumentSize:!!(w&&e.w&&e.h)}).photoSize;if(M&&!y){const U=await this.managers.thumbsStorage.getCacheContext(e,G?.type);let j;if(U.downloaded)j=new Image,j.src=U.url;else{const q=zh({photo:e,cacheContext:U,useBlur:!0,onlyStripped:!0});q&&(N=q.loadPromise,j=q.image)}j&&(j.classList.add("thumbnail"),_.append(j))}if(y)if(t){const U=new Image;U.classList.add("thumbnail"),_.append(U),await Vn(U,t,!1)}else{const U=vs({middleware:this.middlewareHelper.get(),peerId:i.toPeerId(),size:"full"});U.node.classList.add("thumbnail-avatar"),_.append(U.node),await U.readyThumbPromise}const O=!!(w&&e.supportsStreaming),$=y?void 0:O?this.preloaderStreamable:this.preloader,H=(U=G?.type)=>y?{url:cM(e)}:S?{url:b8(e,{supportsHlsStreaming:!0})}:this.managers.thumbsStorage.getCacheContext(e,U);let D;if(b||y){const U=x.middlewareHelper.get(),j=d&&e.type!=="gif",q=Do({pip:j||y,middleware:U});y&&(q.ignoreLeak=!0),(this.wholeDiv.classList.contains("no-forwards")||y)&&q.addEventListener("contextmenu",_e);const W=()=>this.setMoverToTarget(r,!1,n).then(({onAnimationEnd:ee})=>{S=this.hasQualityOptions,m?.();const z=x.firstElementChild&&x.firstElementChild.classList.contains("media-viewer-aspecter")?x.firstElementChild:x;x.querySelector("video")?.remove(),q.setAttribute("playsinline","true"),q.autoplay=!0,e._==="inputGroupCall"?q.autoplay=!0:e.type==="gif"?(q.muted=!0,q.autoplay=!0,q.loop=!0):e.duration<60&&(q.loop=!0),u!==void 0&&on(q,u),z.append(q);const de=new Promise(ke=>{q.addEventListener("canplay",ke,{once:!0})}),ie=()=>{y||(this.releaseSingleMedia=rt.setSingleMedia({media:q,message:d}))},oe=async()=>{if(e.type==="gif")return;const ke=Promise.all([de,ee]);if(!y&&(await ke,this.tempId!==C))return;const re=!y,ce=this.videoPlayer=new p1({videoTimestamps:this.videoTimestamps,video:q,play:re,streamable:O,live:y,width:B?.width,height:B?.height,onPlaybackRateMenuToggle:Ie=>{this.wholeDiv.classList.toggle("hide-caption",!!Ie)},onPip:Ie=>{const Ve=window.appMediaViewer;if(!Ie&&Ve&&Ve!==this){this.releaseSingleMedia=void 0,this.close();return}this.moversContainer.lastElementChild.classList.toggle("in-pip",Ie),this.toggleWholeActive(!Ie),this.toggleOverlay(!Ie),this.toggleGlobalListeners(!Ie),this.navigationItem&&(Ie?Pt.removeItem(this.navigationItem):Pt.pushItem(this.navigationItem)),j&&(Ie?(this.releaseSingleMedia?.(!1),this.releaseSingleMedia=void 0,rt.setPictureInPicture(q)):ie())},onPipClose:()=>{this.close()},listenKeyboardEvents:"always",useGlobalVolume:"auto"});this.videoPlayer?.loadQualityLevels(),ce.addEventListener("toggleControls",Ie=>{this.wholeDiv.classList.toggle("has-video-controls",Ie)}),this.addEventListener("setMoverBefore",()=>{this.wholeDiv.classList.remove("has-video-controls"),this.videoPlayer.cleanup(),this.videoPlayer=void 0},{once:!0}),this.isZooming?this.videoPlayer.lockControls(!1):y&&this.videoPlayer.lockControls(!0),h?.(this.videoPlayer,ke)};if(O||y){let ke=!1,re=!1;const ce=Ve=>{re||(re=!0,g?.(),!Ve&&Ie(),$?.attach(x,!0),q.parentElement.classList.add("is-buffering"))};ee.then(()=>{q.readyState<q.HAVE_FUTURE_DATA&&ce(!0)});const Ie=()=>{ke||(ke=!0,q.addEventListener("canplay",()=>{ke=!1,re=!1,p?.(),$?.detach(),q.parentElement.classList.remove("is-buffering"),this.isZooming||this.videoPlayer?.lockControls(void 0)},{once:!0}))};q.addEventListener("waiting",()=>{const Ve=q.networkState===q.NETWORK_LOADING,fe=q.readyState<q.HAVE_FUTURE_DATA;Ve&&fe&&ce()}),this.wholeDiv.classList.contains("no-forwards")&&q.addEventListener("contextmenu",Ve=>{_e(Ve)}),Ie()}const ae=async()=>{const ke=O||y?Promise.resolve():fs.downloadMediaURL({media:e});return O||ee.then(async()=>{(await H()).url||$?.attach(x,!0,ke)}),Promise.all([ke,y?void 0:ee]).then(async()=>{if(this.tempId!==C){this.log.warn("media viewer changed video");return}const re=(await H()).url,ce=Ve=>{if(WC(Ve)||y)return;$e({langPackKey:Gi?"Video.Unsupported.Mobile":"Video.Unsupported.Desktop"});const fe=q.error;fe&&fe.code!==4&&this.log.error("Error "+fe.code+"; details: "+fe.message),$?.detach()},Ie=ua(q);y||mg(q,Ie).catch(ce),q.addEventListener("error",ce,{once:!0}),U.onClean(()=>{q.removeEventListener("error",ce)}),r instanceof SVGSVGElement?z.firstElementChild.lastElementChild.append(q):(Ka(q,re),this.videoPlayer?.loadQualityLevels()),j&&(ie(),this.addEventListener("setMoverBefore",()=>{this.releaseSingleMedia?.(),this.releaseSingleMedia=void 0},{once:!0})),this.updateMediaSource(r,re,"video"),y?oe():Ie.then(()=>{oe()})}),ke};this.lazyLoadQueue.unshift({load:ae})});D=Promise.all([N,L]).then(W)}else{const U=()=>this.setMoverToTarget(r,!1,n).then(({onAnimationEnd:j})=>{const q=async()=>{const W=w?fs.downloadMediaURL({media:e}):fs.downloadMediaURL({media:e,thumb:G}),ee=!w&&e.sizes.slice().filter(de=>de.w);ee&&ee.sort((de,ie)=>ie.size-de.size);const z=ee?.[0],Z=!w&&z!==G&&fs.downloadMediaURL({media:e,thumb:z});return j.then(async()=>{(await H()).url||this.preloader.attachPromise(W)}),Promise.all([j,W]).then(async()=>{if(this.tempId!==C){this.log.warn("media viewer changed photo");return}const de=(await H()).url;if(r instanceof SVGSVGElement)this.updateMediaSource(r,de,"img"),this.updateMediaSource(x,de,"img"),st.isMobile&&x.querySelectorAll("img").forEach(oe=>{oe.classList.remove("thumbnail")});else{const ie=x.firstElementChild&&x.firstElementChild.classList.contains("media-viewer-aspecter")?x.firstElementChild:x,oe=["CANVAS","IMG"].includes(ie.firstElementChild?.tagName)?ie.firstElementChild:null;if(oe?.src!==de){const ae=new Image;ae.classList.add("thumbnail"),Ka(ae,de,()=>{$s(()=>{this.updateMediaSource(r,de,"img"),oe&&$s(()=>{oe.remove()}),ie.append(ae)})},!1),Z&&Z.then(ke=>{const re=new Image;re.classList.add("thumbnail"),Ka(re,ke,()=>{$s(()=>{ae.replaceWith(re)})},!1)})}}}).catch(de=>{this.log.error(de),this.preloader.attach(x),this.preloader.setManual()}),W};this.lazyLoadQueue.unshift({load:q})});D=N.then(U)}return this.setMoverPromise=D.catch(()=>{this.setMoverAnimationPromise=null}).finally(()=>{this.setMoverPromise=null})}}class _8 extends yw{constructor(e){super(new l8({peerId:e,managers:I.managers}),[]),this.onPrevClick=t=>{this.openMedia({photoId:t.photoId,target:t.element,fromRight:-1})},this.onNextClick=t=>{this.openMedia({photoId:t.photoId,target:t.element,fromRight:1})},this.onDownloadClick=()=>{fs.downloadToDisc({media:this.target.photo,queueId:Ce.chat.bubbles.lazyLoadQueue.queueId})},this.peerId=e,this.setBtnMenuToggle([{icon:"download",text:"MediaViewer.Context.Download",onClick:this.onDownloadClick}]),this.setListeners()}async openMedia({photoId:e,target:t,fromRight:s=0,prevTargets:i,nextTargets:n}){if(this.setMoverPromise)return this.setMoverPromise;const r=await this.managers.appPhotosManager.getPhoto(e),o=super._openMedia({media:r,timestamp:r.date,fromId:this.peerId,fromRight:s,target:t,reverse:!1,prevTargets:i,nextTargets:n});return this.target.photoId=r.id,this.target.photo=r,o}}async function I8(a,e,t,s,i,n){let r=await I.managers.appProfileManager.getFullPhoto(e);if(!t()||!r)return;const o=()=>Array.from(a.querySelectorAll("img")).find(c=>!c.classList.contains("emoji"))?a:null;if(e.isAnyChat()){const l=!!s,c="inputMessagesFilterChatPhotos";if(!s&&(s=await I.managers.appMessagesManager.getHistory({peerId:e,inputFilter:{_:c},offsetId:0,limit:1}).then(d=>{const u=d.history[0];return Ae.getMessageByPeer(e,u)}),!t()))return;if(s){s.action.photo.id!==r.id&&(l||(s=await I.managers.appMessagesManager.generateFakeAvatarMessage(e,r)));const u=h=>h.map(p=>({element:p.element,mid:p.item.mid,peerId:p.item.peerId}));new zl().setSearchContext({peerId:e,inputFilter:{_:c}}).openMedia({message:s,target:o(),prevTargets:i?u(i):void 0,nextTargets:n?u(n):void 0});return}}if(r){!Fy(s)&&s&&(r=await I.managers.appPhotosManager.getPhoto(s));const l=c=>c.map(d=>({element:d.element,photoId:d.item}));new _8(e).openMedia({photoId:r.id,target:o(),prevTargets:i?l(i):void 0,nextTargets:n?l(n):void 0})}}let P8;function dM(){return P8??(P8=K())}function M8(a){const[e,t]=K(),[s,i]=K(),[n]=dM(),r=Mg(),o=Qy(()=>a);return le(()=>{const c=o()?.profile_color;if(!c){t(),i();return}const d=n()?.find(u=>u.color_id===c.color);t(r()&&d?.dark_colors?d.dark_colors:d?.colors),i(c.background_emoji_id)}),{colorSet:e,backgroundEmojiId:s}}const nv=3,hM=!0,fi=class fi{constructor(e,t,s){this.scrollable=e,this.managers=t,this.setCollapsedOn=s,this.processItem=async m=>{const g=this.middlewareHelper.get(),f=document.createElement("div");f.classList.add(fi.BASE_CLASS+"-avatar","media-container","hide");const v=this.avatars.childElementCount===0;this.avatars.append(f);let y;m&&(y=typeof m!="object"?await this.managers.appPhotosManager.getPhoto(m):m.action.photo);const w=async()=>{const b=vs({middleware:g,size:"full",isDialog:!1,isBig:!0});if(v&&b.node.classList.add("profile-avatars-avatar-first"),y){const _=ha(y,420,420,!1);await U_(b,y,420,_)}else b.render({peerId:this.peerId}),await b.readyThumbPromise;f.append(b.node),f.classList.remove("hide")};return this.avatars.childElementCount<=nv?await w():(this.intersectionObserver.observe(f),this.loadCallbacks.set(f,w)),this.addTab(),this.tabs.childElementCount===1&&f.classList.add("active"),m},this.container=document.createElement("div"),this.container.classList.add(fi.BASE_CLASS+"-container"),this.avatars=document.createElement("div"),this.avatars.classList.add(fi.BASE_CLASS+"-avatars"),this.gradient=document.createElement("div"),this.gradient.classList.add(fi.BASE_CLASS+"-gradient"),this.gradientTop=this.gradient.cloneNode(),this.gradientTop.classList.add(fi.BASE_CLASS+"-gradient-top"),this.info=document.createElement("div"),this.info.classList.add(fi.BASE_CLASS+"-info"),this.tabs=document.createElement("div"),this.tabs.classList.add(fi.BASE_CLASS+"-tabs"),this.arrowPrevious=document.createElement("div"),this.arrowPrevious.classList.add(fi.BASE_CLASS+"-arrow"),this.arrowPrevious.append(Be("avatarprevious",fi.BASE_CLASS+"-arrow-icon")),this.middlewareHelper=Ht(),this.arrowNext=document.createElement("div"),this.arrowNext.classList.add(fi.BASE_CLASS+"-arrow",fi.BASE_CLASS+"-arrow-next"),this.arrowNext.append(Be("avatarnext",fi.BASE_CLASS+"-arrow-icon")),this.container.append(this.avatars,this.gradient,this.gradientTop,this.info,this.tabs,this.arrowPrevious,this.arrowNext),this.loadCallbacks=new Map,this.listenerSetter=new $t;const i=()=>this.scrollable.scrollPosition!==0?(this.scrollable.scrollIntoViewNew({element:this.scrollable.firstElementChild,position:"start"}),!1):!0,n=1/3;let r=!1,o=!1;J(this.container,async m=>{if(o){_e(m);return}if(r){r=!1;return}if(!i()||this.hasNoPhoto)return;if(this.isCollapsed()&&this.unfold){if(ne(m.target,"avatar")&&this.container.classList.contains("has-stories")){r=!0,Xs(this.fakeAvatar.node);return}this.unfold(m);return}const g=this.container.getBoundingClientRect(),v=m.pageX,y=v-g.left;if(!this.listLoader.previous.length&&!this.listLoader.next.length||y>g.width*n&&y<g.width-g.width*n){const w=this.peerId,b=[];this.listLoader.previous.concat(this.listLoader.current,this.listLoader.next).forEach((C,L)=>{b.push({element:this.avatars.children[L],item:C})});const S=b.slice(0,this.listLoader.previous.length),_=b.slice(this.listLoader.previous.length+1),M=this.avatars.children[this.listLoader.previous.length];o=!0,I8(M,w,()=>w===this.peerId,this.listLoader.current,S,_),o=!1}else{const w=g.right-g.width/2,b=v>w;let S;this.listLoader.index===0&&!b?S=this.listLoader.count-1:this.listLoader.index===this.listLoader.count-1&&b?S=-(this.listLoader.count-1):S=b?1:-1,this.goWithoutTransition(S)}},{listenerSetter:this.listenerSetter});const l=()=>{r=!0,document.body.addEventListener(pt?"touchend":"click",m=>{r=!1},{once:!0})};let c=0,d=0,u=0,h=0;this.swipeHandler=new Qn({element:this.avatars,onSwipe:(m,g)=>{m*=-1,u=m;let f=d+m*-fi.SCALE;return f>0?f=0:f<h&&(f=h),this.avatars.style.transform=fi.TRANSLATE_TEMPLATE.replace("{x}",f+"px"),!1},verifyTouchTarget:m=>{if(i()){if(this.isCollapsed())return!1;if(this.container.classList.contains("is-single")||o)return!1}else return l(),_e(m),!1;return!0},onFirstSwipe:()=>{const m=this.avatars.getBoundingClientRect();c=m.width,h=-c*(this.tabs.childElementCount-1),d=m.left-this.container.getBoundingClientRect().left,this.avatars.style.transform=fi.TRANSLATE_TEMPLATE.replace("{x}",d+"px"),this.container.classList.add("is-swiping"),this.avatars.classList.add("no-transition"),this.avatars.offsetLeft},onReset:()=>{const m=Math.ceil(Math.abs(u)/(c/fi.SCALE))*(u>=0?1:-1);l(),this.avatars.classList.remove("no-transition"),$s(()=>{this.listLoader.go(m),this.container.classList.remove("is-swiping")})}}),this.intersectionObserver=new IntersectionObserver(m=>{m.forEach(g=>{g.isIntersecting&&this.loadNearestToTarget(g.target)})}),this.setCollapsed(!0);const p=e.onAdditionalScroll;e.onAdditionalScroll=()=>{p?.(),this.updateHeaderFilled()},this.middlewareHelper.onDestroy(()=>{e.onAdditionalScroll=p}),Ft(m=>{this.middlewareHelper.onDestroy(()=>{m(),this.unfold=void 0});const{folded:g,unfold:f,fold:v}=nM({container:()=>this.container,listenWheelOn:this.setCollapsedOn,scrollable:()=>e.container,disableHoverWhenFolded:!1});this.unfold=f,le(()=>{if(this.hasNoPhoto&&!g()){v();return}this.setCollapsed(g())})})}goWithoutTransition(e){this.avatars.classList.add("no-transition"),this.avatars.offsetLeft,this.listLoader.go(e),$s(()=>{this.avatars.classList.remove("no-transition")})}async setPeer(e){this.peerId=e,this.middlewareHelper.clean();const t=await this.managers.appPeersManager.getPeerPhoto(e);if(!t&&!hM)return;this.hasNoPhoto=!t,await this.applyAppearance(),this.fakeAvatar&&this.fakeAvatar.node.remove(),this.fakeAvatar=vs({peerId:e,isBig:!0,middleware:this.middlewareHelper.get(),size:120,withStories:!0,onStoriesStatus:i=>{this.container.classList.toggle("has-stories",i)},storyColors:{read:"rgba(255, 255, 255, .3)"}}),this.fakeAvatar.node.classList.add("profile-avatars-avatar-fake"),await this.fakeAvatar.readyThumbPromise,this.avatars.before(this.fakeAvatar.node);const s=this.listLoader=new Ag({loadCount:50,loadMore:(i,n,r)=>{if(!n)return Promise.resolve({count:void 0,items:[]});if(e.isUser()){const o=i;return this.managers.appPhotosManager.getUserPhotos(e,o,r).then(l=>({count:l.count,items:l.photos}))}else{const o=[];return s.current||o.push(this.managers.appProfileManager.getChatFull(e.toChatId())),o.push(this.managers.appMessagesManager.getHistory({peerId:e,offsetId:Number.MAX_SAFE_INTEGER,inputFilter:{_:"inputMessagesFilterChatPhotos"},limit:r,backLimit:0})),Promise.all(o).then(async l=>{const c=l.pop();let{messages:d,history:u}=c;if(d||(d=c.messages=u.map(h=>Ae.getMessageByPeer(e,h))),Y_(c),!s.current){const h=l[0],p=tr(d,m=>m.action.photo.id===h.chat_photo.id);s.current=p||await this.managers.appMessagesManager.generateFakeAvatarMessage(this.peerId,h.chat_photo)}return{count:c.count,items:d}})}},processItem:this.processItem,onJump:(i,n)=>{const r=this.listLoader.index,o=100*fi.SCALE*r;this.avatars.style.transform=fi.TRANSLATE_TEMPLATE.replace("{x}",`-${o}%`),[this.tabs,this.avatars].forEach(l=>{const c=l.querySelector(".active");c&&c.classList.remove("active"),l.children[r].classList.add("active")}),this.loadNearestToTarget(this.avatars.children[r])}});t?._==="userProfilePhoto"&&(s.current=t.photo_id),await this.processItem(s.current),s.load(!0)}_applyAppearance(){const e=this.middlewareHelper.get(),t=(o,l)=>{if(this.emojiPatternCanvas?.remove(),this.emojiPatternCanvas=void 0,!o)return;const c=393,d=258,u=this.emojiPatternCanvas=document.createElement("canvas");u.classList.add("profile-avatars-pattern");const h=u.getContext("2d"),p=window.devicePixelRatio;u.width=c*p,u.height=d*p,u.style.width=`${c}px`,u.style.height=`${d}px`,l?(()=>{const _=u.width/2,M=u.height/2,C=140*p,L=h.createRadialGradient(_,M,0,_,M,C);L.addColorStop(0,"rgba(255, 255, 255, 0.18)"),L.addColorStop(1,"rgba(255, 255, 255, 0)"),h.fillStyle=L,h.beginPath(),h.arc(_,M,C,0,2*Math.PI),h.fill()})():u.style.mixBlendMode="unset";const g=Mt(),f=18,v=20,y=24,w=.16,b=.2,S=kb({docId:o,canvasWidth:c,canvasHeight:d,emojiSize:24,middleware:e,positions:[[307,155,f,w],[68,155,f,w],[317,95,f,w],[58,95,f,w],[292,52,f,w],[83,52,f,w],[213,195,f,b],[162,195,f,b],[273,204,f,w],[102,204,f,w],[253,163,v,b],[120,163,v,b],[258,75,f,b],[117,75,f,b],[269,113,y,b],[100,113,y,b],[230,44,v,b],[143,44,v,b],[187.5,34,f,b]],color:yi.getProperty("primary-text-color"),onCacheStatus:_=>{_?S.then(g.resolve.bind(g)):g.resolve()}}).then(_=>{e()&&h.drawImage(_,0,0)});return this.container.prepend(this.emojiPatternCanvas),g},s=o=>{let l;if(o){const c=o.map(d=>uE(d));c.length===1?l=c[0]:l=`linear-gradient(180deg, ${c.join(", ")})`}this.container.style.background=l,this.hasBackgroundColor=!!l},{colorSet:i,backgroundEmojiId:n}=M8(this.peerId),r=Mt();return le(()=>{const o=i()?.bg_colors,l=n();s(o),this.setCollapsed(this.isCollapsed());const c=Mg();le(Vt(c,()=>{const d=t(l,!!o);d?d.then(r.resolve.bind(r)):r.resolve()}))}),r}applyAppearance(){const e=this.middlewareHelper.get();return Ft(t=>(e.onDestroy(t),this._applyAppearance()))}addTab(){const e=document.createElement("div");e.classList.add(fi.BASE_CLASS+"-tab"),this.tabs.append(e),this.tabs.childElementCount===1&&e.classList.add("active"),this.container.classList.toggle("is-single",this.tabs.childElementCount<=1)}loadNearestToTarget(e){const t=Array.from(e.parentElement.children),s=t.indexOf(e);t.slice(Math.max(0,s-nv),Math.min(t.length,s+nv)).forEach(n=>{const r=this.loadCallbacks.get(n);r&&(r(),this.loadCallbacks.delete(n),this.intersectionObserver.unobserve(n))})}setCollapsed(e){!this.isCollapsed()&&e&&this.listLoader?.index&&this.goWithoutTransition(-this.listLoader.index),this.setCollapsedOn.classList.toggle("is-collapsed",e);const t=this.hasBackgroundColor||!e;this.setCollapsedOn.classList.contains("need-white")!==t&&(this.setCollapsedOn.classList.toggle("need-white",t),D_(this.info,t?"white":"primary-color")),this.updateHeaderFilled()}isCollapsed(){return this.setCollapsedOn.classList.contains("is-collapsed")}updateHeaderFilled(){this.setCollapsedOn.classList.toggle("header-filled",!this.hasBackgroundColor&&this.isCollapsed()&&this.scrollable.scrollPosition>=5||this.scrollable.scrollPosition>=240)}cleanup(){this.listenerSetter.removeAll(),this.swipeHandler.removeListeners(),this.intersectionObserver?.disconnect(),this.middlewareHelper.destroy()}};fi.BASE_CLASS="profile-avatars",fi.SCALE=fc?2:1,fi.TRANSLATE_TEMPLATE=fc?`translate3d({x}, 0, -1px) scale(${fi.SCALE})`:"translate({x}, 0)";let Iy=fi;const po=(a,e)=>{Qt(e.title,a||void 0),e.container.style.display=a?"":"none"};class uM{constructor(e,t,s,i=!0,n,r){this.managers=e,this.scrollable=t,this.listenerSetter=s,this.isDialog=i,this.setCollapsedOn=n,this.onPersonalChannel=r,fc||this.scrollable.container.classList.add("no-parallax"),s||(this.listenerSetter=new $t),this.middlewareHelper=Ht()}init(){this.init=null,this.element=document.createElement("div"),this.element.classList.add("profile-content");const e=document.createElement("span");e.append(P("AccDescrChannel")),e.classList.add("personal-channel-name"),this.personalChannelCounter=document.createElement("span"),this.personalChannelCounter.classList.add("personal-channel-counter"),e.append(this.personalChannelCounter),this.personalChannelSection=new Oe({name:e}),nt.setListClickListener({list:this.personalChannelSection.content,autonomous:!1,openInner:!0}),this.section=new Oe({noDelimiter:!0}),this.name=document.createElement("div"),this.name.classList.add("profile-name"),this.subtitle=document.createElement("div"),this.subtitle.classList.add("profile-subtitle"),this.pinnedGiftsContainer=document.createElement("div"),this.pinnedGiftsContainer.classList.add("profile-pinned-gifts"),this.setCollapsedOn.classList.add("profile-container"),this.bio=new Fe({title:" ",subtitle:!0,icon:"info",clickable:r=>{r.target.tagName!=="A"&&(si(this.bio.title.textContent),Wi(Ne.format("BioCopied",!0)))},listenerSetter:this.listenerSetter,contextMenu:{buttons:[{icon:"copy",text:"Text.CopyLabel_About",onClick:()=>{Xs(this.bio.container)},verify:()=>!this.peerId.isUser()},{icon:"copy",text:"Text.CopyLabel_Bio",onClick:()=>{Xs(this.bio.container)},verify:()=>this.peerId.isUser()},{icon:"premium_translate",text:"TranslateMessage",onClick:async()=>{I.premium?ue.createPopup(VP,{peerId:this.peerId,textWithEntities:{_:"textWithEntities",text:this.bioText,entities:[]},detectedLanguage:await this.bioLanguage}):rs.show({feature:"translations"})},verify:async()=>!!await this.bioLanguage}]}}),this.bio.title.classList.add("pre-wrap"),this.username=new Fe({title:" ",subtitleLangKey:"Username",icon:"username",clickable:()=>{si("@"+this.username.title.textContent),Wi(Ne.format("UsernameCopied",!0))},listenerSetter:this.listenerSetter,contextMenu:{buttons:[{icon:"copy",text:"Text.CopyLabel_Username",onClick:()=>{Xs(this.username.container)}}]}}),this.phone=new Fe({title:" ",subtitle:!0,icon:"phone",clickable:()=>{si(this.phone.title.textContent.replace(/\s/g,"")),Wi(Ne.format("PhoneCopied",!0))},listenerSetter:this.listenerSetter,contextMenu:{buttons:[{icon:"copy",text:"Text.CopyLabel_PhoneNumber",onClick:()=>{Xs(this.phone.container)}},{icon:"info",text:"PeerInfo.Phone.AnonymousInfo",textArgs:[document.createElement("a")],onClick:()=>{Ul("https://fragment.com/numbers")},separator:!0,secondary:!0,verify:async()=>{const{isAnonymous:r}=await this.managers.appUsersManager.getUserPhone(this.peerId.toUserId())||{};return r}}]}}),this.link=new Fe({title:" ",subtitleLangKey:"SetUrlPlaceholder",icon:"link",clickable:()=>{const r="https://"+this.link.title.textContent;si(r);const o=r.includes("/c/");Wi(Ne.format(o?"LinkCopiedPrivateInfo":"LinkCopied",!0))},listenerSetter:this.listenerSetter,contextMenu:{buttons:[{icon:"copy",text:"Text.CopyLabel_ShareLink",onClick:()=>{Xs(this.link.container)}}]}}),this.location=new Fe({title:" ",subtitleLangKey:"ChatLocation",icon:"location"}),this.businessHours=Ft(r=>{this.middlewareHelper.onDestroy(r);const[o,l]=K(),[c,d]=K();return this.setBusinessHours=l,this.setTimezones=d,o8({hours:o,timezones:c})});const t=()=>{si(this._businessLocation.address),$e({langPackKey:"BusinessLocationCopied"})};this.businessLocation=new Fe({title:!0,subtitleLangKey:"BusinessProfileLocation",icon:"location",clickable:async()=>{const r=this._businessLocation;if(!r.geo_point){t();return}await Rt({descriptionLangKey:"Popup.OpenInGoogleMaps",button:{langKey:"Open"}}),Ul(Nb(r.geo_point))},contextMenu:{buttons:[{icon:"copy",text:"Copy",onClick:t}]},listenerSetter:this.listenerSetter}),this.businessLocation.container.classList.add("business-location"),this.section.content.append(this.phone.container,this.username.container,this.location.container,this.bio.container,this.link.container,this.businessHours.container,this.businessLocation.container);const{listenerSetter:s}=this;this.isDialog&&(this.notifications=new Fe({checkboxField:new _t({toggle:!0}),titleLangKey:"Notifications",icon:"unmute",listenerSetter:this.listenerSetter}),s.add(this.notifications.checkboxField.input)("change",r=>{r.isTrusted&&this.managers.appMessagesManager.togglePeerMute({peerId:this.peerId,threadId:this.threadId})}),s.add(I)("dialog_notify_settings",async r=>{if(this.peerId===r.peerId){const o=await this.managers.appNotificationsManager.isPeerLocalMuted({peerId:this.peerId,respectType:!1,threadId:this.threadId});this.notifications.checkboxField.checked=!o}}),this.section.content.append(this.notifications.container)),this.element.append(this.personalChannelSection.container,this.section.container),fc&&this.element.append(Fg()),s.add(I)("peer_typings",({peerId:r})=>{this.peerId===r&&this.setPeerStatus()}),s.add(I)("peer_bio_edit",r=>{r===this.peerId&&this.setMoreDetails(!0)});const i=async({peerId:r,threadId:o})=>this.peerId!==r?!1:!((this.peerId.isAnyChat()?await this.managers.appPeersManager.isForum(this.peerId):!1)&&this.threadId)||this.threadId===o;s.add(I)("peer_title_edit",async r=>{const o=this.middlewareHelper.get();if(await i(r)){if(!o())return;this.fillUsername().then(l=>{o()&&l?.()}),this.setMoreDetails(!0)}}),s.add(I)("user_update",r=>{this.peerId===r.toPeerId()&&this.setPeerStatus()}),s.add(I)("contacts_update",async r=>{this.peerId===r.toPeerId()&&(!(await this.managers.appUsersManager.getUser(r)).pFlags.self||!this.isDialog)&&this.fillUserPhone()}),s.add(I)("avatar_update",async r=>{await i(r)&&this.setAvatar()});const n=()=>{this.peerId.isUser()&&this.managers.appUsersManager.getApiUsers([this.peerId.toUserId()])};s.add(I)("premium_toggle",n),s.add(I)("privacy_update",r=>{r.key._==="privacyKeyStatusTimestamp"&&n()}),this.setPeerStatusInterval=window.setInterval(()=>this.setPeerStatus(),6e4)}async setPeerStatus(e=!1,t){const s=this.peerId,i=[];i.push(()=>{if(this.element.classList.toggle("is-me",s===I.myId),s.isUser()&&Ae.getUser(s.toUserId()).status?.pFlags?.by_me){if(this.subtitle.querySelector(".show-when"))return;const l=P("StatusHiddenShow");l.classList.add("show-when"),J(l,c=>{_e(c),ue.createPopup(GP,s,"lastSeen")}),this.subtitle.append(l)}});let n=Promise.resolve();if(!(!s||I.myId===s&&this.isDialog)&&s!==Oy){const o=await this.managers.appPeersManager.isForum(this.peerId),l=this.middlewareHelper.get();o&&this.threadId?n=cI({peerId:s,wrapOptions:{middleware:l}}).then(({element:c})=>{this.subtitle.replaceChildren(c)}):n=Ce.setPeerStatus({peerId:s,element:this.subtitle,needClear:e,useWhitespace:!0,middleware:l,ignoreSelf:!this.isDialog}),n.then(c=>c&&i.unshift(c))}const r=()=>i.forEach(o=>o());return n.then(()=>{if(t)return r;r()})}cleanupHTML(){[this.bio,this.phone,this.username,this.location,this.link,this.businessHours,this.businessLocation,this.personalChannelSection].forEach(e=>{e.container.style.display="none"}),this.notifications&&(this.notifications.container.style.display="",this.notifications.checkboxField.checked=!0),this.clearSetMoreDetailsTimeout()}isSavedDialog(){return!!(this.peerId===I.myId&&this.threadId)}getDetailsForUse(){const{peerId:e,threadId:t}=this;return this.isSavedDialog()?{peerId:t,threadId:void 0}:{peerId:e,threadId:t}}canBeDetailed(){return this.peerId!==I.myId||!this.isDialog}async _setAvatar(){const e=this.middlewareHelper.get(),{peerId:t,threadId:s}=this.getDetailsForUse(),i=!!(s&&await this.managers.appPeersManager.isForum(t));if(!i&&(await this.managers.appPeersManager.getPeerPhoto(t)||hM)){const l=this.avatars;this.avatars=new Iy(this.scrollable,this.managers,this.setCollapsedOn),await this.avatars.setPeer(t);const c=await this.fillName(e,this.setCollapsedOn.classList.contains("need-white"));return()=>{c(),this.avatars.info.append(this.name,this.subtitle),this.avatars.container.append(this.pinnedGiftsContainer),this.avatar&&this.avatar.node.remove(),this.avatar=void 0,l?l.container.replaceWith(this.avatars.container):this.element.prepend(this.avatars.container),fc&&this.scrollable.container.classList.add("parallax"),this.section.content.classList.remove("has-simple-avatar")}}const n=vs({middleware:e,size:120,isDialog:this.isDialog,peerId:t,threadId:i?s:void 0,wrapOptions:{customEmojiSize:ii(120,120),middleware:e},withStories:!0,meAsNotes:!!(t===I.myId&&this.threadId)});n.node.classList.add("profile-avatar","avatar-120");const[r]=await Promise.all([this.fillName(e,!1),n.readyThumbPromise]);return()=>{r(),fc&&this.scrollable.container.classList.remove("parallax"),this.avatars&&(this.avatars.container.remove(),this.avatars.cleanup(),this.avatars=void 0),this.avatar&&this.avatar.node.remove(),this.avatar=n,this.section.content.classList.add("has-simple-avatar"),this.section.content.prepend(this.avatar.node,this.name,this.subtitle)}}setAvatar(e){const t=this._setAvatar();return e?t:t.then(s=>s())}getUsernamesAlso(e){const t=e.slice(1);if(t.length){const s=t.map(n=>lM({username:n}));return P("UsernameAlso",[Yi(s,!1)])}}async fillUsername(){const{peerId:e}=this;if(e.isUser()&&this.canBeDetailed()){const t=await this.managers.appPeersManager.getPeerActiveUsernames(e),s=this.getUsernamesAlso(t);return()=>{this.username.subtitle.replaceChildren(s||P("Username")),po(t[0],this.username)}}}async fillUserPhone(){const{peerId:e}=this;if(e.isUser()&&this.canBeDetailed()){const{phone:t,isAnonymous:s}=await this.managers.appUsersManager.getUserPhone(e.toUserId())||{};return()=>{this.phone.subtitle.replaceChildren(P(s?"AnonymousNumber":"Phone")),po(t?tw(t):void 0,this.phone)}}}async fillNotifications(){const e=this.notifications;if(e)if(this.canBeDetailed()){const t=await this.managers.appNotificationsManager.isPeerLocalMuted({peerId:this.peerId,respectType:!1,threadId:this.threadId});return()=>{e.checkboxField.checked=!t}}else return()=>{e.container.style.display="none"}}async fillName(e,t){const{peerId:s}=this.getDetailsForUse(),[i]=await Promise.all([qe({peerId:s,dialog:this.isDialog,withIcons:!this.threadId,threadId:this.threadId,wrapOptions:{middleware:e,textColor:t?"white":void 0},meAsNotes:!!(s===I.myId&&this.threadId)})]);return()=>{St(this.name,i)}}async fillRows(e){return Promise.all([this.fillUsername(),this.fillUserPhone(),this.fillNotifications(),this.setMoreDetails(void 0,e),this.setPeerStatus(!0,!0)]).then(t=>()=>{t.forEach(s=>s?.())})}async fillPinnedGifts(){const{peerId:e}=this.getDetailsForUse();if(!e.isUser())return;const t=await this.managers.appGiftsManager.getPinnedGifts(e),s=this.middlewareHelper.get(),i=await Promise.all(t.map(async(n,r)=>{const o=document.createElement("div");return o.className="profile-pinned-gift",o.setAttribute("data-idx",r.toString()),o.style.setProperty("--halo-color",Mc(n.collectibleAttributes.backdrop.center_color)),await ai({doc:n.sticker,static:!0,middleware:s,width:30,height:30,div:o}).then(l=>l.render),o}));return()=>{this.pinnedGiftsContainer.replaceChildren(...i)}}async fillProfileElements(){if(!this.cleaned)return;this.cleaned=!1,this.cleanupHTML();const e=Mt();this.middlewareHelper.get().onClean(()=>{e.reject()});const s=await Promise.all([this.setAvatar(!0),this.fillRows(e)]);return()=>{e.resolve(),s.forEach(i=>i?.())}}async _setMoreDetails(e,t,s,i){const n=this.middlewareHelper.get().create().get(),r=this.getMiddlewarePromise(),o=!!(this.threadId&&await r(this.managers.appPeersManager.isForum(e))),l=e.isUser()?await r(this.managers.appUsersManager.isPremium(e.toUserId())):void 0;if(o){let m="t.me/";const g=An(this.threadId),f=await r(this.managers.appPeersManager.getPeerUsername(e));return f?m+=`${f}/${g}`:m+=`c/${e.toChatId()}/${g}`,()=>{po(m,this.link)}}const c=[];if(c.push(()=>{this.bio.subtitle.replaceChildren(P(e.isUser()?"UserBio":"Info")),po(t.about?jt(t.about,{whitelistedDomains:l?void 0:s.whitelisted_domains}):void 0,this.bio),this.bioLanguage=zP(this.bioText=t.about)}),!e.isUser()){const m=await r(this.managers.appChatsManager.getChat(e.toChatId())),g=ji(m);let f;if(g.length)f=this.getUsernamesAlso(g),c.push(()=>po("t.me/"+g[0],this.link));else{const v=t.exported_invite;v?._==="chatInviteExported"&&c.push(()=>po(v.link.slice(v.link.indexOf("t.me/")),this.link))}c.push(()=>this.link.subtitle.replaceChildren(f||P("SetUrlPlaceholder")))}const d=t.location;d?._=="channelLocation"&&c.push(()=>po(d.address,this.location));const u=t.business_work_hours;u&&pi(()=>{this.setBusinessHours(u),this.setTimezones(i)}),c.push(()=>{this.businessHours.container.style.display=u?"":"none"});const h=t.business_location;if(this._businessLocation=h,h){const m=h.geo_point;if(c.push(()=>{po(je(h.address),this.businessLocation),m||this.businessLocation.media?.remove()}),m){const g=this.businessLocation.createMedia("big");g.remove();const f=[];Bi({photo:LI(m,48,48,16),container:g,middleware:n,onRender:()=>{!n()||this._businessLocation!==h||this.businessLocation.container.append(g)},loadPromises:f}),await Promise.all(f)}}c.push(()=>{this.businessLocation.container.style.display=h?"":"none"});const p=t.personal_channel_id;if(p){const m=p.toPeerId(!0),g=t.personal_channel_message,f=Ae.getChat(p),v=[],y=nt.createChatList(),w=nt.addDialogNew({peerId:m,container:y,rippleEnabled:!0,avatarSize:"abitbigger",append:!0,wrapOptions:{middleware:n},withStories:!0,loadPromises:v});w.container.classList.add("personal-channel");const b=x=>{const[R,B]=K(),N=wi(()=>Qm({children:R,loading:V(()=>!R())}),x.element);return x.element.classList.add("skeleton-container"),x.middleware.onDestroy(N),B},_=!!Ae.getMessageByPeer(m,g)&&!!1,C=this.managers.appMessagesManager.reloadMessages(m,g).then(async x=>{await nt.setLastMessageN({dialog:{_:"dialog",peerId:m},lastMessage:x,dialogElement:w}),L?.(w.subtitle),E?.(w.dom.lastTimeSpan)});let L,E;if(!_){const x=w.subtitle.cloneNode(!0);w.subtitle.replaceWith(x),L=b({element:x,middleware:n});const R=w.dom.lastTimeSpan.cloneNode(!0);w.dom.lastTimeSpan.replaceWith(R),E=b({element:R,middleware:n})}_&&v.push(C),c.push(()=>{this.personalChannelCounter.replaceChildren(P("Subscribers",[ln(f.participants_count)])),this.personalChannelSection.content.querySelector(".chatlist")?.remove(),this.personalChannelSection.content.append(y)}),await Promise.all(v)}return c.push(()=>{this.personalChannelSection.container.style.display=p?"":"none",this.onPersonalChannel?.(!!p)}),this.setMoreDetailsTimeout=window.setTimeout(()=>this.setMoreDetails(!0),6e4),(t._==="userFull"||t._==="channelFull")&&t.stargifts_count>0&&c.push(await r(this.fillPinnedGifts())),()=>{c.forEach(m=>m?.())}}async setMoreDetails(e,t){this.clearSetMoreDetailsTimeout();const{peerId:s}=this,i=this.getMiddlewarePromise();if(!s||!this.canBeDetailed()||await i(this.managers.appPeersManager.isPeerRestricted(s)))return;const n=await i(Promise.all([this.managers.acknowledged.appProfileManager.getProfileByPeerId(s,e),this.managers.acknowledged.apiManager.getAppConfig(),this.managers.acknowledged.apiManager.getTimezonesList()])),r=n.map(l=>l.result),o=i(Promise.all(r)).then(async([l,c,d])=>{if(!await i(this.managers.appPeersManager.isPeerRestricted(s)))return i(this._setMoreDetails(s,l,c,d.timezones))});if(n.every(l=>l.cached)&&t)return o;(t||Promise.resolve()).then(()=>o).then(l=>{l?.()})}getMiddlewarePromise(){return Bl(this.middlewareHelper.get(),Vo("MIDDLEWARE"))}setPeer(e,t){this.peerId===e&&this.threadId===t||(this.init?.(),this.peerId=e,this.threadId=t,this.middlewareHelper.clean(),this.cleaned=!0)}clearSetMoreDetailsTimeout(){this.setMoreDetailsTimeout!==void 0&&(clearTimeout(this.setMoreDetailsTimeout),this.setMoreDetailsTimeout=void 0)}destroy(){this.peerId=this.threadId=void 0,this.clearSetMoreDetailsTimeout(),clearInterval(this.setPeerStatusInterval),this.avatars?.cleanup(),this.middlewareHelper.destroy()}}const hC=64,L8=ii(hC,hC);class Py extends Zt{async init(e,t){this.colorIndex=0;const s=!t,i=t===Tu;this.container.classList.add("edit-topic-container"),this.setTitle(s?"NewTopic":"ForumTopic.Title.Edit");const n=e.toChatId();t&&(this.topic=this.originalTopic=kn(await this.managers.dialogsStorage.getForumTopic(e,t)));{const o=new Oe({name:i?"CreateGeneralTopicTitle":"CreateTopicTitle"}),l=this.iconDiv=document.createElement("div");l.classList.add("edit-topic-icon-container"),!t&&J(l,()=>{this.topic.icon_emoji_id||(this.colorIndex=(this.colorIndex+1)%Xd.length,this.setIcon())},{listenerSetter:this.listenerSetter}),t&&l.classList.add("disable-hover");const c=document.createElement("div");c.classList.add("input-wrapper");const d=this.nameInputField=new Yt({label:"ForumTopic.Name.Placeholder",withLinebreaks:!1,name:"topic-name",maxLength:70,required:!0});this.topic&&d.setOriginalValue(this.topic.title,!0);const u=this.confirmBtn=yt("check btn-confirm blue hide",{noRipple:!0});this.header.append(u),J(u,()=>{const h=os([u],!0);t?this.managers.appChatsManager.editForumTopic({chatId:n,topicId:t,title:d.value,iconEmojiId:this.topic.icon_emoji_id||0}).then(()=>{this.close()}).catch(p=>{console.error("edit topic error",p),h()}):this.managers.appChatsManager.createForumTopic({chatId:n,iconColor:Xd[this.colorIndex],iconEmojiId:this.topic.icon_emoji_id,title:d.value}).then(p=>{this.close(),Ce.setInnerPeer({peerId:e,threadId:p})}).catch(p=>{console.error("create topic error",p),h()})},{listenerSetter:this.listenerSetter}),this.listenerSetter.add(d.input)("input",()=>{this.validate(),this.setIcon(this.topic?.icon_emoji_id)}),c.append(d.container),o.content.append(l,c),this.scrollable.append(o.container)}const r=[];if(i){const o=new Oe({caption:"EditTopicHideInfo"}),l=new _t({checked:!this.topic.pFlags.hidden,text:"EditTopicHide"});this.listenerSetter.add(l.input)("change",()=>{const d=this.managers.appChatsManager.editForumTopic({chatId:n,topicId:t,hidden:!l.checked});c.disableWithPromise(d)});const c=new Fe({checkboxField:l});o.content.append(c.container),this.scrollable.append(o.container)}else{const o=new Oe({});o.container.classList.add("edit-topic-emoticons-container");const l=new Ua({managers:this.managers,isStandalone:!0,noRegularEmoji:!0,mainSets:()=>this.managers.appStickersManager.getLocalStickerSet("inputStickerSetEmojiDefaultTopicIcons").then(d=>d.documents.map(u=>u.id)),onClick:d=>{l.setActive(d.docId?d:{emoji:void 0,docId:void 0}),this.setIcon(d.docId)}});l.getContainerSize=()=>({width:Ri.rect.width,height:400}),this.middlewareHelper.onDestroy(()=>{l.destroy()}),l.container.classList.remove("tabs-tab"),this.emojiElement=document.createElement("span"),this.emojiElement.classList.add("super-emoji-topic-icon");const c=l.init().then(async()=>{const d=l.getCustomCategory(),u=this.topic?.icon_emoji_id;l.addEmojiToCategory({category:d,element:this.emojiElement,batch:!1,prepend:!0,active:!u}),u&&l.setActive({docId:u,emoji:""})});r.push(c),o.content.replaceWith(l.container),this.scrollable.append(o.container)}return Promise.all(r).then(()=>this.s())}validate(){let e=this.nameInputField.isValidToChange();!e&&this.originalTopic&&(e=this.topic.icon_emoji_id!==this.originalTopic.icon_emoji_id),this.confirmBtn.classList.toggle("hide",!e)}s(){return this.topic?.icon_color&&(this.colorIndex=Xd.indexOf(this.topic.icon_color)),this.setIcon(this.topic?.icon_emoji_id,void 0,!0)}async setIcon(e,t=this.iconDiv,s){const i=this.nameInputField.value,n=t===this.iconDiv;if(n){const d={id:this.topic?.id,icon_color:Xd[this.colorIndex],title:DC(i,!0).text||"A",icon_emoji_id:e},u=this.topic;if(this.topic=d,(s||!u||u.icon_color!==d.icon_color||u.title!==d.title)&&this.setIcon(void 0,this.emojiElement),Pn(u,d)&&!s)return;this.validate()}const r=await Pg({topic:n?this.topic:{...this.topic,icon_emoji_id:void 0},customEmojiSize:L8,middleware:this.middlewareHelper.get()}),o=document.createElement("div");o.classList.add("edit-topic-icon"),o.append(r);const l=t.lastElementChild;t.append(o);const c=(d,u)=>{const h=[{opacity:"0",transform:"scale(0.8)"},{opacity:"1",transform:"scale(1)"}],p=d.animate(h,{duration:200,iterations:1,easing:"ease-in-out",fill:"forwards",direction:u?"normal":"reverse"});return new Promise(m=>{p.addEventListener("finish",()=>{m()},{once:!0})})};l&&c(l,!1).then(()=>l.remove()),c(o,!0)}}class uC extends Zt{async init(e){const t=e.toUserId();this.container.classList.add("edit-profile-container"),this.setTitle("EditBot.Title");const s=[],[i,n,r]=await Promise.all([this.managers.apiManager.getLimit("bio"),this.managers.appUsersManager.getUser(t),this.managers.appProfileManager.getBotInfo(t)]);{const o=Xc(this.scrollable,void 0),l=document.createElement("div");l.classList.add("input-wrapper"),this.firstNameInputField=new Yt({label:"EditProfile.FirstNameLabel",name:"first-name",maxLength:70}),this.aboutInputField=new Yt({label:"DescriptionPlaceholder",name:"bio",maxLength:i}),l.append(this.firstNameInputField.container,this.aboutInputField.container),s.push(this.firstNameInputField,this.aboutInputField),this.editPeer=new Ou({peerId:e,inputFields:s,listenerSetter:this.listenerSetter,middleware:this.middlewareHelper.get()}),this.content.append(this.editPeer.nextBtn),o.append(this.editPeer.avatarEdit.container,l)}{const o=Xc(this.scrollable,void 0,"EditBot.Buttons.Caption"),l=ot("btn-primary btn-transparent",{icon:"info",text:"EditBot.Buttons.Intro",asLink:!0}),c=ot("btn-primary btn-transparent",{icon:"botcom",text:"EditBot.Buttons.Commands",asLink:!0}),d=ot("btn-primary btn-transparent",{icon:"bots",text:"EditBot.Buttons.Settings",asLink:!0}),u="t.me/botfather?start="+Yh(n);[[l,"intro"],[c,"commands"],[d,""]].forEach(([p,m])=>{const g=Bo(u+(m?"-"+m:""));p.href=g.url,p.setAttribute("onclick",g.onclick+"(this)")}),o.append(l,c,d)}{const o=new Oe({name:"EditAccount.Username",caption:!0}),l=document.createElement("div");l.classList.add("input-wrapper"),this.usernameInputField=new pb({label:"Username",name:"username",plainText:!0,listenerSetter:this.listenerSetter,onChange:()=>{this.editPeer.handleChange();const{error:h}=this.usernameInputField,p=h?.type==="USERNAME_PURCHASE_AVAILABLE";d(p?this.usernameInputField.value:void 0)},availableText:"EditProfile.Username.Available",takenText:"EditProfile.Username.Taken",invalidText:"EditProfile.Username.Invalid"},this.managers),l.append(this.usernameInputField.container);const c=o.caption,{setUsername:d,element:u}=vb();c.append(P("EditBot.Username.Caption"),u),s.push(this.usernameInputField),o.content.append(l),this.scrollable.append(o.container)}{const o=new fb({peerId:e,peer:n,listenerSetter:this.listenerSetter,usernameInputField:this.usernameInputField,middleware:this.middlewareHelper.get()});this.scrollable.append(o.container)}J(this.editPeer.nextBtn,()=>{this.editPeer.nextBtn.disabled=!0;const o=[],l=this.managers.appProfileManager.setBotInfo(t,this.firstNameInputField.value,this.aboutInputField.value);o.push(l.then(()=>{this.close()},c=>{console.error("updateProfile error:",c)})),this.editPeer.uploadAvatar&&o.push(this.editPeer.uploadAvatar().then(c=>this.managers.appProfileManager.uploadProfilePhoto(c,t))),this.usernameInputField.isValidToChange()&&o.push(this.managers.appUsersManager.updateUsername(this.usernameInputField.value)),Promise.race(o).finally(()=>{this.editPeer.nextBtn.removeAttribute("disabled")})},{listenerSetter:this.listenerSetter}),this.firstNameInputField.setOriginalValue(n.first_name,!0),this.aboutInputField.setOriginalValue(r.about,!0),this.usernameInputField.setOriginalValue(Yh(n),!0),this.editPeer.handleChange()}}const Kd={};class Vl extends Zt{init(){this.init=null,this.container.classList.add("shared-media-container");const e=ot("btn-icon sidebar-close-button",{noRipple:!0});this.closeBtn.replaceWith(e),this.closeBtn=e;const t=document.createElement("div");t.classList.add("animated-close-icon"),e.append(t),this.isFirst&&t.classList.add("state-back");const s=()=>{const y=document.createElement("div");return y.className="transition slide-fade",y},i=s(),n=(y,w,b)=>{const S=document.createElement("div");S.classList.add("transition-item"),b??(b=this.title.cloneNode()),b.append(y);let _;if(w)S.append(b);else{const M=document.createElement("div");M.classList.add("sidebar-header__rows"),_=document.createElement("div"),_.classList.add("sidebar-header__subtitle"),M.append(b,_),S.append(M)}return{element:S,title:b,subtitle:_}};this.titleI18n=new Ne.IntlElement;const r=n(this.titleI18n.element,!0,this.title);this.editBtn=yt("edit");const o=this.btnMenu=ki({listenerSetter:this.listenerSetter,direction:"bottom-left",buttons:[{icon:"message",text:"SavedViewAsMessages",onClick:()=>{Ce.toggleViewAsMessages(I.myId,!0)},verify:()=>this.peerId===I.myId&&this.isFirst}]});r.element.append(this.editBtn);let l;(y=>{y[y.Profile=0]="Profile",y[y.Media=1]="Media"})(l||(l={}));const c=n(P("PeerInfo.SharedMedia"));this.sharedMediaTitle=c.title;const d=s();c.subtitle.append(d);const u=[["savedDialogs","SavedDialogsTabCount"],["stories","StoriesCount"],["members","Members"],["media","MediaFiles"],["gifts","StarGiftsCount"],["saved","SavedMessagesCount"],["files","Files"],["links","Links"],["music","MusicFiles"],["voice","Voice"],["groups","CommonGroups"],["similar","SimilarChannelsCount"]];d.append(...u.map(y=>{y[2]=new Ne.IntlElement({key:"Loading"});const w=document.createElement("div");return w.classList.add("transition-item"),w.append(y[2].element),w})),i.append(...[r,c].map(({element:y})=>y)),this.header.append(i,o),this.noProfile||(this.profile=new uM(this.managers,this.scrollable,this.listenerSetter,!0,this.container),this.profile.init(),this.scrollable.append(this.profile.element));const h=56;this.scrollable.onAdditionalScroll=()=>{const y=this.searchSuper.nav.getBoundingClientRect();if(!y.width)return;const w=y.top-1;m(w<=h)};const p=(y=g.prevId()!==0)=>{let w=0;return y&&(w=1),w},m=y=>{t.classList.toggle("state-back",this.isFirst||y),this.searchSuper.container.classList.toggle("is-full-viewport",y),g(p(y)),y||this.searchSuper.cleanScrollPositions()},g=Sr({content:i,type:"slide-fade",transitionTime:400,isHeavy:!1});g(this.profile?0:1);const f=Sr({content:d,type:"slide-fade",transitionTime:400,isHeavy:!1});f(0),J(this.closeBtn,y=>{g.prevId()&&this.profile?(this.scrollable.scrollIntoViewNew({element:this.scrollable.container.querySelector(".profile-content"),position:"start"}),g(0),this.isFirst||(t.classList.remove("state-back"),this.container.classList.remove("header-filled"))):this.scrollable.isHeavyAnimationInProgress||this.slider.onCloseBtnClick()},{listenerSetter:this.listenerSetter}),J(this.editBtn,async()=>{let y;const{peerId:w,threadId:b}=this;b&&await this.managers.appPeersManager.isForum(w)?y=this.slider.createTab(Py):w.isAnyChat()?y=this.slider.createTab(oC):await this.managers.appUsersManager.isBot(w)?y=this.slider.createTab(uC):y=this.slider.createTab(ry),y&&(y instanceof Py?y.open(w,this.threadId):y instanceof uC?y.open(w):(y instanceof oC?y.chatId=w.toChatId():y.peerId=w,y.open()))},{listenerSetter:this.listenerSetter}),this.listenerSetter.add(I)("contacts_update",y=>{this.peerId===y.toPeerId(!1)&&this.toggleEditBtn()}),this.listenerSetter.add(I)("chat_update",y=>{this.peerId===y.toPeerId(!0)&&this.toggleEditBtn()}),this.listenerSetter.add(I)("history_multiappend",y=>{this.renderNewMessage(y)}),this.listenerSetter.add(I)("history_delete",({peerId:y,msgs:w})=>{this.deleteDeletedMessages(y,w)}),this.searchSuper=new ww({mediaTabs:[{name:"SharedMedia.SavedDialogs",type:"savedDialogs"},{name:"Stories",type:"stories"},{name:"PeerMedia.Members",type:"members"},{inputFilter:"inputMessagesFilterPhotoVideo",name:"SharedMediaTab2",type:"media"},{name:"SharedMedia.Gifts",type:"gifts"},{inputFilter:"inputMessagesFilterEmpty",name:"SharedMedia.Saved",type:"saved"},{inputFilter:"inputMessagesFilterDocument",name:"SharedFilesTab2",type:"files"},{inputFilter:"inputMessagesFilterUrl",name:"SharedLinksTab2",type:"links"},{inputFilter:"inputMessagesFilterMusic",name:"SharedMusicTab2",type:"music"},{inputFilter:"inputMessagesFilterRoundVoice",name:"SharedVoiceTab2",type:"voice"},{name:"ChatList.Filter.Groups",type:"groups"},{name:"SimilarChannels",type:"similar"}],scrollable:this.scrollable,onChangeTab:y=>{f(u.findIndex(b=>b[0]===y.type));const w=y.type==="members"&&wt.isAvailable("animations")?250:0;setTimeout(()=>{v.classList.toggle("is-hidden",y.type!=="members")},w)},managers:this.managers,onLengthChange:(y,w)=>{const b=u.find(S=>S[0]===y);b&&b[2].compareAndUpdate({key:b[1],args:[w]})},openSavedDialogsInner:!this.isFirst,slider:this.slider}),this.searchSuper.scrollStartCallback=()=>{m(!0),this.container.classList.add("header-filled")},this.searchSuper.scrollOffset=56,this.profile?this.profile.element.append(this.searchSuper.container):this.scrollable.append(this.searchSuper.container);const v=Cn({icon:"addmember_filled"});this.content.append(v),J(v,()=>{EP({peerId:this.peerId,slider:this.slider})},{listenerSetter:this.listenerSetter})}_renderNewMessage(e,t=e.peerId,s){const i=Kd[t]?.[s];if(i)for(const n of this.searchSuper.mediaTabs){const r=n.inputFilter,o=i[r];if(!o)continue;let l;if(n.type==="saved"?l=[e].filter(d=>{const u=d.saved_peer_id;return u&&it(u)===this.searchSuper.searchContext.peerId&&!o.some(h=>h.mid===d.mid)}):l=this.searchSuper.filterMessagesByType([e],r),!l.length)continue;const c=l.filter(d=>!o.find(u=>u.mid===d.mid&&u.peerId===d.peerId)).map(d=>({mid:d.mid,peerId:d.peerId}));o.unshift(...c),(n.type==="saved"?this.peerId===s:this.peerId===t)&&this.searchSuper.usedFromHistory[r]!==-1&&this.threadId===s&&(this.searchSuper.usedFromHistory[r]+=l.length,this.searchSuper.performSearchResult(l,n,!1),this.searchSuper.setCounter(n.type,this.searchSuper.counters[n.type]+l.length))}}async renderNewMessage(e){if(this.init)return;const{peerId:t}=e,s=await this.managers.appPeersManager.isForum(t),i=yr(e,s);this._renderNewMessage(e),i&&this._renderNewMessage(e,void 0,i)}_deleteDeletedMessages(e,t,s,i){for(const n of s)for(const r of this.searchSuper.mediaTabs){const o=r.inputFilter,l=e[o];if(!l)continue;const c=r.type==="saved"?this.peerId===i:this.peerId===t&&this.threadId===i;c&&this.searchSuper.setCounter(r.type,this.searchSuper.counters[r.type]-s.length);const d=l.findIndex(u=>u.mid===n);if(d===-1&&l.splice(d,1),c){const u=this.searchSuper.tabs[o],h=u.querySelector(`[data-mid="${n}"][data-peer-id="${t}"]`);if(h){this.searchSuper.selection.isSelecting&&this.searchSuper.selection.toggleByElement(h);const p=u.querySelectorAll("[data-mid][data-peer-id]"),m=Array.from(p).indexOf(h);h.remove(),m!==-1&&this.searchSuper.usedFromHistory[o]>=m+1&&--this.searchSuper.usedFromHistory[o]}}}}deleteDeletedMessages(e,t){if(this.init)return;const s=Kd[e];if(!s)return;const i=[...t.keys()];for(const n in s)this._deleteDeletedMessages(s[n],e,i,isNaN(+n)?void 0:+n);this.scrollable.onScroll()}async cleanupHTML(){const e=this.peerId.isAnyChat(),[t,s]=await Promise.all([e?this.searchSuper.canViewMembers():!1,e?this.managers.appChatsManager.hasRights(this.peerId.toChatId(),"invite_users"):!1]);return()=>{this.profile?.cleanupHTML(),this.editBtn.classList.add("hide"),this.searchSuper.cleanupHTML(!0),this.container.classList.toggle("can-add-members",t&&s)}}setLoadMutex(e){this.searchSuper.loadMutex=e}getHistoryStorage(e,t){var s;return(s=Kd[e]??(Kd[e]={}))[t]??(s[t]={})}setPeer(e,t){var i;if(this.peerId===e&&this.threadId===t)return!1;this.peerId=e,this.threadId=t,this.noProfile??(this.noProfile=e===I.myId),this.peerChanged=!0,this.init&&this.init();const s=this.getHistoryStorage(e,t);return s.inputMessagesFilterEmpty=(i=this.getHistoryStorage(I.myId,e)).inputMessagesFilterEmpty??(i.inputMessagesFilterEmpty=[]),this.searchSuper.setQuery({peerId:e,threadId:t,historyStorage:s}),this.profile?.setPeer(e,t),!0}async changeTitleKey(){const{peerId:e,threadId:t}=this,s=!!(e===I.myId&&t),i=s?t:e,[n,r,o,l]=await Promise.all([this.managers.appPeersManager.isForum(i),this.managers.appPeersManager.isBroadcast(i),this.managers.appPeersManager.isBot(i),qe({peerId:e,threadId:s?void 0:t,meAsNotes:s&&t===I.myId,dialog:!0})]);return()=>{this.titleI18n.compareAndUpdate({key:o?"Profile.Info.Bot":r?"Profile.Info.Channel":t&&n?"Profile.Info.Topic":i.isUser()?"Profile.Info.User":"Profile.Info.Group"}),this.sharedMediaTitle.replaceChildren(l),this.btnMenu.classList.toggle("hide",!this.isFirst||s||e!==I.myId)}}async fillProfileElements(){if(!this.peerChanged)return;this.peerChanged=!1;const e=await Promise.all([this.cleanupHTML(),this.toggleEditBtn(!0),this.profile?.fillProfileElements(),this.changeTitleKey()]);return()=>{e.forEach(t=>{t?.()})}}async toggleEditBtn(e){const{peerId:t}=this;let s;if(t.isUser())s=t!==I.myId&&await this.managers.appUsersManager.canEdit(t.toUserId());else{const n=t.toChatId();this.threadId&&Ae.isForum(t)?s=await this.managers.dialogsStorage.canManageTopic(await this.managers.dialogsStorage.getForumTopic(t,this.threadId)):s=!!Ae.getChat(n).admin_rights||await this.managers.appChatsManager.hasRights(n,"change_info")}const i=()=>{this.editBtn.classList.toggle("hide",!s)};return e?i:i()}loadSidebarMedia(e,t){return this.searchSuper.load(e,t)}onOpenAfterTimeout(){super.onOpenAfterTimeout(),this.scrollable.onScroll()}onCloseAfterTimeout(){super.onCloseAfterTimeout(),this.destroyable&&(this.profile?.destroy(),this.searchSuper.destroy())}destroy(){this.destroyable=!0,this.onCloseAfterTimeout()}static async open(e,t,s){const i=e.createTab(Vl,!0);return i.noProfile=s,i.isFirst=!0,i.setPeer(t),(await i.fillProfileElements())(),await i.loadSidebarMedia(!0),i.open()}}const Lh="is-right-column-shown";class E8 extends cb{constructor(){super({sidebarEl:document.getElementById("column-right"),canHideFirst:!0,navigationType:"right"}),this.isColumnProportionSet=!1}construct(e){this.managers=e,st.addEventListener("changeScreen",(i,n)=>{n===fn.medium&&i!==fn.mobile&&this.toggleSidebar(!1)});let t;const s=i=>{document.querySelectorAll(".chat-background-item-scalable").forEach(n=>{const r=n;i?r.style.removeProperty("transition"):r.style.setProperty("transition","none","important")})};I.addEventListener("resizing_left_sidebar",()=>{window.clearTimeout(t),s(!1),this.setColumnProportion(),t=window.setTimeout(()=>{s(!0)},100)}),st.addEventListener("resize",()=>{this.setColumnProportion()})}createSharedMediaTab(){const e=this.createTab(Vl,!1,!0);return e.slider=this,e}replaceSharedMediaTab(e){const t=this.sharedMediaTab;if(t){const s=this.historyTabIds.indexOf(t);this._selectTab.getFrom()===t.container&&this._selectTab.setFrom(e?.container),e?(s!==-1&&(this.historyTabIds[s]=e),t.container.classList.contains("active")&&e.container.classList.add("active"),t.container.replaceWith(e.container)):(s!==-1&&this.historyTabIds.splice(s,1),t.container.remove())}else this.tabsContainer.prepend(e.container);this.sharedMediaTab=e}onCloseTab(e,t,s){this.historyTabIds.length||this.toggleSidebar(!1,t),super.onCloseTab(e,t,s)}setColumnProportion(){const e=this.sidebarEl.previousElementSibling.scrollWidth,t=this.sidebarEl.scrollWidth/e;return document.documentElement.style.setProperty("--right-column-proportion",""+t),document.documentElement.style.setProperty("--middle-column-width",e+"px"),document.documentElement.style.setProperty("--middle-column-width-value",""+e),t}hide(){document.body.classList.remove(Lh),Pt.removeByType("right")}toggleSidebar(e,t){const s=document.body.classList.contains(Lh);let i;if(e!==void 0?e?s||(i=!0):s&&(i=!0):i=!0,!i)return Promise.resolve();!s&&!this.historyTabIds.length&&this.sharedMediaTab.open(),this.isColumnProportionSet||(this.setColumnProportion(),this.isColumnProportionSet=!0);const n=Ce.selectTab(s?pd.CHAT:pd.PROFILE,t);return e?(document.body.classList.add(Lh),Pt.findItemByType("right")||this.pushNavigationItem(this.sharedMediaTab)):this.hide(),n}}const pM=new E8;Di.appSidebarRight=pM;const Gs=pM;function bw(a){return I1({...a,onSwipe:(e,t,s)=>{if(e*=-1,t*=-1,Math.abs(e)>50)return a.onSwipe(e,t,s),W_(),!0}})}function k8(a){const e=i=>{_e(i)};let t=2;const s=()=>{--t||a.removeEventListener("touchmove",e,{capture:!0})};return a.addEventListener("touchmove",e,{capture:!0,passive:!1}),a.addEventListener("touchend",s,{once:!0}),s}function T8({inputFilter:a,messages:e,limit:t,savedReaction:s}){if(a==="inputMessagesFilterEmpty"&&!s)return e.slice(0,t);const i=[];if(!e.length)return i;let n=!0;const r={},o=[],l=[];switch(a){case"inputMessagesFilterPhotos":r.messageMediaPhoto=!0;break;case"inputMessagesFilterPhotoVideo":r.messageMediaPhoto=!0,r.messageMediaDocument=!0,o.push("video");break;case"inputMessagesFilterVideo":r.messageMediaDocument=!0,o.push("video");break;case"inputMessagesFilterDocument":r.messageMediaDocument=!0,o.push(void 0,"photo","pdf");break;case"inputMessagesFilterVoice":r.messageMediaDocument=!0,o.push("voice");break;case"inputMessagesFilterRoundVoice":r.messageMediaDocument=!0,o.push("round","voice");break;case"inputMessagesFilterRoundVideo":r.messageMediaDocument=!0,o.push("round");break;case"inputMessagesFilterMusic":r.messageMediaDocument=!0,o.push("audio");break;case"inputMessagesFilterUrl":r.url=!0;break;case"inputMessagesFilterChatPhotos":r.avatar=!0;break;case"inputMessagesFilterPinned":l.push("pinned");break;default:n=!1;break}if(!n&&!s?.length)return i;for(let c=0,d=e.length;c<d;++c){const u=e[c];if(!u)continue;let h=!n;if(l?.some(p=>u.pFlags[p]))h=!0;else if(u._==="message"){if(u.media&&r[u.media._]){const p=u.media.document;if(p&&o.length&&!o.includes(p.type))continue;h=!0}else if(r.url&&u.message){const p=["messageEntityTextUrl","messageEntityUrl"];(u.totalEntities.find(m=>p.includes(m._))||Xm(u.message))&&(h=!0)}if(h&&s){const p=u.reactions?.results;h=p?s.every(m=>p.some(g=>Wn(g.reaction,m))):!1}}else r.avatar&&u.action&&["messageActionChannelEditPhoto","messageActionChatEditPhoto","messageActionChannelEditVideo","messageActionChatEditVideo"].includes(u.action._)&&(h=!0);if(h&&i.push(u)>=t)break}return i}const x8=Y("<div class=grid>");function A8(a){const[e,t]=ec(),[s,i]=K(),[n,r]=K(0),[o,l]=K(),c=new Map;Or(()=>{const h=T(Cs,{get each(){return e.peer.stories},children:u});le(()=>{const p=h(),m=p.length;r(m),i(p),a.onLengthChange?.(m)}),a.onLengthChange&&le(()=>{a.onLengthChange(e.peer?.count)}),a.onReady?.()})(()=>e.ready),le(()=>{const h=o();if(!h)return;const p=()=>{l(void 0)},m=V(()=>{const g=e.peer.stories[e.peer.index].id;return c.get(g)});Ot(()=>{const g=e.peer,f=g.stories.findIndex(v=>v.id===h);t.set({peer:g,index:f})}),Ju({onExit:p,target:m,splitByDays:!0})});const u=h=>{const{container:p,div:m,media:g,thumb:f}=zu({peerId:e.peer.peerId,storyItem:h,forPreview:!0,noAspecter:!0,containerProps:{"data-mid":h.id,"data-peer-id":e.peer.peerId,class:"grid-item search-super-item",onClick:y=>{l(h.id)}},childrenClassName:"grid-item-media",noPlayButton:!0});let v;return le(()=>{const y=f(),b=g()||y;if(b){if(c.set(h.id,b),ze(()=>{c.delete(h.id)}),n()===1){const S=h.media,_=S.photo||S.document,C=zh({photo:_,cacheContext:{type:"x",url:"",downloaded:0},useBlur:!0,ignoreCache:!0,onlyStripped:!0}).image;b.parentElement.prepend(C),ze(()=>{C.remove()})}b.parentElement&&a.pinned&&h.pinnedIndex!==void 0?(v??(v=Be("pin2","grid-item-pin")),b.parentElement.append(v)):v&&v.remove()}}),a.selection?.isSelecting&&a.selection.toggleElementCheckbox(m,!0),p};return(()=>{const h=x8();return k(h,s),Me(p=>{const m=n()===2,g=n()===1;return m!==p._v$&&h.classList.toggle("two",p._v$=m),g!==p._v$2&&h.classList.toggle("one",p._v$2=g),p},{_v$:void 0,_v$2:void 0}),h})()}function R8(a){const[,e]=wa(a,["onReady","onLengthChange","selection"]);return T(uw,ni(e,{get children(){return T(A8,ni(a,{get pinned(){return e.pinned}}))}}))}function F8(a,e){return a._==="inputSavedStarGiftChat"&&e._==="inputSavedStarGiftChat"?a.saved_id===e.saved_id&&it(a.peer)===it(e.peer):a._==="inputSavedStarGiftUser"&&e._==="inputSavedStarGiftUser"?a.msg_id===e.msg_id:!1}const B8=Y("<div class=star-gifts-profile-tab>");function D8(a){const[e,t]=K([]),[s,i]=K(!0);let n="",r=!1;async function o(){if(r||!s())return;r=!0;const u=await I.managers.appGiftsManager.getProfileGifts({peerId:a.peerId,offset:n,limit:99});n=u.next,t(e().concat(u.gifts)),i(!!u.next),a.onCountChange?.(u.count),r=!1}function l(u){if(!s())return;const h=u.target;h.scrollTop+h.clientHeight>=h.scrollHeight-300&&o()}const c=new $t;return Jt(()=>{o(),c.add(I)("star_gift_update",({input:u,unsaved:h,converted:p,togglePinned:m})=>{const g=e().findIndex(f=>F8(f.input,u));if(g!==-1){let f=e().slice();const v={...f[g]};f[g]=v,h!==void 0&&(f[g].saved.pFlags.unsaved=h?!0:void 0),p!==void 0&&(v.isConverted=p),m&&(v.saved.pFlags.pinned_to_top=v.saved.pFlags.pinned_to_top?void 0:!0,f=f.sort((y,w)=>y.saved.pFlags.pinned_to_top&&!w.saved.pFlags.pinned_to_top?-1:!y.saved.pFlags.pinned_to_top&&w.saved.pFlags.pinned_to_top?1:w.saved.date-y.saved.date)),t(f)}})}),ze(()=>c.removeAll()),{render:(()=>{const u=B8();return u.addEventListener("scroll",l),k(u,T(Js,{get when(){return V(()=>!e().length)()&&s()},get children(){return T(VE,{})}}),null),k(u,T(fI,{get items(){return e()},view:"profile",get scrollParent(){return a.scrollParent},onClick:h=>{ue.createPopup(iu,h)}}),null),u})(),loadNext:o}}class $8{constructor(e,t,s,i){this.attachTo=e,this.searchSuper=t,this.listenerSetter=s,this.storiesPinned=i,this.onGotoClick=()=>{Ce.setInnerPeer({peerId:this.peerId,lastMsgId:this.mid,threadId:this.searchSuper.mediaTab.type==="saved"?this.searchSuper.searchContext.peerId:this.searchSuper.searchContext.threadId})},this.onForwardClick=()=>{this.searchSuper.selection.isSelecting?Xs(this.searchSuper.selection.selectionForwardBtn):ue.createPopup(kr,{[this.peerId]:[this.mid]})},this.onSelectClick=()=>{this.searchSuper.selection.toggleByElement(this.target)},this.onClearSelectionClick=()=>{this.searchSuper.selection.cancelSelection()},this.onDeleteClick=()=>{this.storyItem?this.searchSuper.selection.onDeleteStoriesClick([this.storyItem.id]):this.searchSuper.selection.isSelecting?Xs(this.searchSuper.selection.selectionDeleteBtn):ue.createPopup(Md,this.peerId,[this.mid],we.Chat)},this.onStoryTogglePinClick=r=>{this.searchSuper.selection.onPinClick([this.storyItem.id],r)},this.onStoryToggleToTopClick=r=>{this.searchSuper.selection.onPinToTopClick([this.storyItem.id],r)},this.managers=t.managers,Er({element:e,callback:r=>{this.init&&(this.init(),this.init=null);let o;try{o=ne(r.target,"search-super-item")}catch{}const l=!!ne(r.target,"search-super-content-stories");if(!o)return;if(r instanceof MouseEvent&&r.preventDefault(),this.element.classList.contains("active"))return!1;r instanceof MouseEvent&&(r.cancelBubble=!0),(async()=>{this.target=o,this.peerId=o.dataset.peerId.toPeerId(),this.mid=+o.dataset.mid,this.isSelected=t.selection.isMidSelected(this.peerId,this.mid),this.message=l?void 0:await this.managers.appMessagesManager.getMessageByPeer(this.peerId,this.mid),this.storyItem=l?await this.managers.appStoriesManager.getStoryById(this.peerId,this.mid):void 0,this.noForwards=l||(t.selection.isSelecting?this.searchSuper.selection.selectionForwardBtn.classList.contains("hide"):!await this.managers.appMessagesManager.canForward(this.message)),this.selectedMessages=!l&&t.selection.isSelecting?await t.selection.getSelectedMessages():void 0,(await Promise.all(this.buttons.map(async u=>{let h;return this.searchSuper.selection.isSelecting&&!u.withSelection?h=!1:h=u.verify?!!await u.verify():!0,u.element.classList.toggle("hide",!h),h}))).some(u=>u)&&(o.classList.add("menu-open"),Ql(r,this.element),Li.openBtnMenu(this.element,()=>{o.classList.remove("menu-open")}))})()},listenerSetter:s})}init(){this.buttons=[{icon:"forward",text:"Forward",onClick:this.onForwardClick,verify:()=>!this.noForwards},{icon:"forward",text:"Message.Context.Selection.Forward",onClick:this.onForwardClick,verify:()=>this.searchSuper.selection.isSelecting&&!this.noForwards,withSelection:!0},{icon:"download",text:"MediaViewer.Context.Download",onClick:()=>In.onDownloadClick(this.message,this.noForwards),verify:()=>!this.searchSuper.selection.isSelecting&&In.canDownload(this.message,void 0,this.noForwards)},{icon:"download",text:"Message.Context.Selection.Download",onClick:()=>In.onDownloadClick(this.selectedMessages,this.noForwards),verify:()=>this.searchSuper.selection.isSelecting&&In.canDownload(this.selectedMessages,void 0,this.noForwards),withSelection:!0},{icon:"message",text:"Message.Context.Goto",onClick:this.onGotoClick,verify:()=>!this.storyItem,withSelection:!0},{icon:"archive",text:"Archive",onClick:()=>this.onStoryTogglePinClick(!1),verify:()=>this.storyItem&&this.storyItem.pFlags.pinned&&this.managers.appStoriesManager.hasRights(this.peerId,this.storyItem.id,"pin")},{icon:"unarchive",text:"Unarchive",onClick:()=>this.onStoryTogglePinClick(!0),verify:()=>this.storyItem&&!this.storyItem.pFlags.pinned&&this.managers.appStoriesManager.hasRights(this.peerId,this.storyItem.id,"pin")},{icon:"pin",text:"ChatList.Context.Pin",onClick:()=>this.onStoryToggleToTopClick(!0),verify:()=>this.storiesPinned&&this.storyItem&&this.storyItem.pinnedIndex===void 0&&this.managers.appStoriesManager.hasRights(this.peerId,this.storyItem.id,"pin")},{icon:"unpin",text:"ChatList.Context.Unpin",onClick:()=>this.onStoryToggleToTopClick(!1),verify:()=>this.storiesPinned&&this.storyItem&&this.storyItem.pinnedIndex!==void 0&&this.managers.appStoriesManager.hasRights(this.peerId,this.storyItem.id,"pin")},{icon:"select",text:"Message.Context.Select",onClick:this.onSelectClick,verify:()=>!this.isSelected&&(!this.storyItem||this.storyItem.pFlags.out),withSelection:!0},{icon:"select",text:"Message.Context.Selection.Clear",onClick:this.onClearSelectionClick,verify:()=>this.isSelected,withSelection:!0},{icon:"delete",className:"danger",text:"Delete",onClick:this.onDeleteClick,verify:()=>this.storyItem?this.managers.appStoriesManager.hasRights(this.peerId,this.storyItem.id,"delete"):!this.searchSuper.selection.isSelecting&&this.managers.appMessagesManager.canDeleteMessage(this.message)},{icon:"delete",className:"danger",text:"Message.Context.Selection.Delete",onClick:this.onDeleteClick,verify:()=>this.searchSuper.selection.isSelecting&&this.searchSuper.selection.selectionDeleteBtn&&!this.searchSuper.selection.selectionDeleteBtn.classList.contains("hide"),withSelection:!0}],this.element=xa({buttons:this.buttons,listenerSetter:this.listenerSetter}),this.element.classList.add("search-contextmenu","contextmenu"),document.getElementById("page-chats").append(this.element)}}class ww{constructor(e){this.tabs={},this.prevTabId=-1,this.lazyLoadQueue=new sr,this.middleware=Ht(),this.historyStorage={},this.usedFromHistory={},this.nextRates={},this.loadPromises={},this.loaded={},this.loadedChats=!1,this.firstLoad=!0,this.log=Ni("SEARCH-SUPER"),this.monthContainers={},this.mediaTabsMap=new Map,this.asChatList=!1,this.groupByMonth=!0,this.hideEmptyTabs=!0,this.showSender=!1,this.counters={},this.onTransitionStart=()=>{this.container.classList.add("sliding")},this.onTransitionEnd=()=>{this.container.classList.remove("sliding")},Nt(this,e),this.slider??(this.slider=Gs),this.container=document.createElement("div"),this.container.classList.add("search-super"),this.listenerSetter=new $t,this.searchContextMenu=new $8(this.container,this,this.listenerSetter,!this.storiesArchive),this.selection=new D6(this,this.managers,this.listenerSetter),this.storiesArchive&&(this.selection.isStoriesArchive=!0);const t=this.navScrollableContainer=document.createElement("div");t.classList.add("search-super-tabs-scrollable","menu-horizontal-scrollable","sticky");const s=this.navScrollable=new io(t);s.container.classList.add("search-super-nav-scrollable");const i=this.nav=document.createElement("nav");i.classList.add("search-super-tabs","menu-horizontal-div"),this.tabsMenu=i,s.container.append(i);for(const o of this.mediaTabs){const l=document.createElement("div");l.classList.add("menu-horizontal-div-item");const c=document.createElement("span");c.classList.add("menu-horizontal-div-item-span");const d=document.createElement("i");c.append(o.menuTabName=P(o.name)),c.append(d),l.append(c),Ei(l),this.tabsMenu.append(l),this.mediaTabsMap.set(o.type,o),o.menuTab=l}this.tabsContainer=document.createElement("div"),this.tabsContainer.classList.add("search-super-tabs-container","tabs-container");let n;pt&&(this.swipeHandler=bw({element:this.tabsContainer,onSwipe:(o,l,c)=>{o*=-1;const d=this.selectTab.prevId(),u=Array.from(this.tabsMenu.children);let h;if(o>0){for(let p=d+1;p<u.length;++p)if(!u[p].classList.contains("hide")){h=p;break}}else for(let p=d-1;p>=0;--p)if(!u[p].classList.contains("hide")){h=p;break}h!==void 0&&(n=k8(this.tabsContainer),this.selectTab(h))},verifyTouchTarget:o=>!ne(o.target,"scrollable-x")}));for(const o of this.mediaTabs){const l=document.createElement("div");l.classList.add("search-super-tab-container","search-super-container-"+o.type,"tabs-tab");const c=document.createElement("div");c.classList.add("search-super-content-container","search-super-content-"+o.type),l.append(c),this.tabsContainer.append(l);const{inputFilter:d}=o;d&&(this.tabs[d]=c),o.contentTab=c}this.container.append(t,this.tabsContainer),this.searchGroupMedia=new aa(!1,"messages",!0),this.scrollable.onScrolledBottom=()=>{this.mediaTab.contentTab&&this.canLoadMediaTab(this.mediaTab)&&this.load(!0,void 0,"bottom")},this.selectTab=vd(this.tabsMenu,this.tabsContainer,(o,l,c)=>{if(this.prevTabId===o&&!this.skipScroll){this.scrollToStart();return}const d=this.mediaTabs[o];this.onChangeTab?.(d),this.selection&&(this.selection.isStories=d.type==="stories");const u=this.mediaTab;if(this.mediaTab=d,this.prevTabId!==-1&&c&&this.onTransitionStart(),this.skipScroll)this.skipScroll=!1;else{const h=this.container.offsetTop-(this.scrollOffset||0);let p=this.scrollable.scrollPosition;if(p<h&&(this.scrollToStart(),p=h),u.scroll={scrollTop:p,scrollHeight:this.scrollable.scrollSize},d.scroll===void 0){const m=this.container.getBoundingClientRect(),g=this.container.parentElement.getBoundingClientRect(),f=m.y-g.y;p>f&&(d.scroll={scrollTop:f,scrollHeight:0})}if(d.scroll){const m=u.scroll.scrollTop-d.scroll.scrollTop;m&&(d.contentTab.style.transform=`translateY(${m}px)`)}}this.prevTabId!==-1&&!d.contentTab.childElementCount&&this.load(!0),this.prevTabId=o},()=>{this.scrollable.onScroll(),this.mediaTab.scroll!==void 0&&(this.mediaTab.contentTab.style.transform="",this.scrollable.scrollPosition=this.mediaTab.scroll.scrollTop),n&&(n(),n=void 0),this.onTransitionEnd()},void 0,s,this.listenerSetter),J(this.tabsContainer,o=>{this.selection.isSelecting&&(PI(o),this.selection.toggleByElement(ne(o.target,"search-super-item")))},{capture:!0,passive:!1,listenerSetter:this.listenerSetter});const r=async(o,l,c,d)=>{const u=ne(d.target,o);if(!u)return;const h=+u.dataset.mid;if(!h){this.log.warn("no messageId by click on target:",u);return}const p=u.querySelector(".media-spoiler-container");if(p){X1({event:d,mediaSpoiler:p});return}const m=u.dataset.peerId.toPeerId(),g=Array.from(this.tabs[c].querySelectorAll("."+l)).map(w=>{const b=ne(w,o);return{element:w,mid:+b.dataset.mid,peerId:b.dataset.peerId.toPeerId()}}),f=g.findIndex(w=>w.mid===h&&w.peerId===m),v=this.mediaTabs.find(w=>w.inputFilter===c),y=await this.managers.appMessagesManager.getMessageByPeer(m,h);new zl().setSearchContext(this.copySearchContext(c,this.nextRates[v.type])).openMedia({message:y,target:g[f].element,fromRight:0,reverse:!1,prevTargets:g.slice(0,f),nextTargets:g.slice(f+1)})};this.tabs.inputMessagesFilterPhotoVideo&&J(this.tabs.inputMessagesFilterPhotoVideo,r.bind(null,"grid-item","grid-item","inputMessagesFilterPhotoVideo"),{listenerSetter:this.listenerSetter}),this.tabs.inputMessagesFilterDocument&&J(this.tabs.inputMessagesFilterDocument,r.bind(null,"document-with-thumb","media-container","inputMessagesFilterDocument"),{listenerSetter:this.listenerSetter}),this.mediaTab=this.mediaTabs[0],yg(()=>{this.lazyLoadQueue.lock()},()=>{this.lazyLoadQueue.unlockAndRefresh()},this.listenerSetter)}scrollToStart(){this.scrollable.scrollIntoViewNew({element:this.container,position:"start",startCallback:this.scrollStartCallback,getElementPosition:this.scrollOffset?({elementPosition:e})=>Math.max(0,e-this.scrollOffset):void 0})}setCounter(e,t){this.counters[e]=t,this.onLengthChange?.(e,t)}filterMessagesByType(e,t){return T8({inputFilter:t,messages:e,limit:e.length})}async processEmptyFilter({message:e,searchGroup:t,mediaTab:s}){const i=s.type==="saved";let n=e.peerId;i&&(n=e.fromId),n=await this.managers.appPeersManager.getPeerMigratedTo(n)||n;const r=this.middleware.get(),o=[],l=nt.addDialogNew({peerId:n,container:t?.list||!1,avatarSize:"bigger",loadPromises:o,wrapOptions:{middleware:r},withStories:!0,meAsSaved:!i,autonomous:i,fromName:n?void 0:Aa(e.fwd_from)}),c=nt.setLastMessageN({dialog:{_:"dialog",peerId:n},lastMessage:e,dialogElement:l,highlightWord:this.searchContext.query,noForwardIcon:i});return o.push(c),Promise.all(o).then(()=>{if(!t)return{element:l.container,message:e}})}async processPhotoVideoFilter({message:e,promises:t,middleware:s}){const i=Vi(e,!0),n=document.createElement("div");n.classList.add("grid-item");let r;const o=ha(i,200,200);if(i._!=="photo"?r=(await Xa({doc:i,message:e,container:n,boxWidth:0,boxHeight:0,lazyLoadQueue:this.lazyLoadQueue,middleware:s,onlyPreview:!0,withoutPreloader:!0,noPlayButton:!0,photoSize:o})).thumb:r=await Bi({photo:i,message:e,container:n,boxWidth:0,boxHeight:0,lazyLoadQueue:this.lazyLoadQueue,middleware:s,withoutPreloader:!0,noBlur:!0,size:o}),e.media.pFlags.spoiler){const l=await ju({animationGroup:"chat",media:i,middleware:s,width:140,height:140,multiply:.3});n.append(l)}return[r.images.thumb,r.images.full].filter(Boolean).forEach(l=>{l.classList.add("grid-item-media")}),t.push(r.loadPromises.thumb),{element:n,message:e}}async processDocumentFilter({message:e,inputFilter:t}){const s=Vi(e,!0),i=this.showSender||["voice","round"].includes(s.type),n=await rd({message:e,withTime:!i,fontWeight:400,voiceAsMusic:!0,showSender:i,searchContext:this.copySearchContext(t,this.nextRates.files),lazyLoadQueue:this.lazyLoadQueue,autoDownloadSize:0,getSize:()=>320});return["audio","voice","round"].includes(s.type)&&n.classList.add("audio-48"),{message:e,element:n}}async processUrlFilter({message:e,promises:t,middleware:s}){let i=e.media?.webpage;if(!i){const h=e.totalEntities?e.totalEntities.find(v=>v._==="messageEntityUrl"||v._==="messageEntityTextUrl"):null;let p,m,g;if(h)g=e.message.slice(h.offset,h.offset+h.length);else{const v=Xm(e.message);if(!v)return;p=v[0]}h?._==="messageEntityTextUrl"?p=h.url:p=p||g,m=p;const f=e.message===p;p.match(/^(ftp|http|https):\/\//)||(m="https://"+p,p=p.includes("@")?p:"https://"+p),m=new URL(m).hostname,i={_:"webPage",pFlags:{},url:p,display_url:m,id:"",hash:0},f||(i.description=e.message)}if(i._==="webPageEmpty")return;const n=document.createElement("div");n.classList.add("preview"),i.photo?Bi({container:n,message:null,photo:i.photo,boxWidth:0,boxHeight:0,withoutPreloader:!0,lazyLoadQueue:this.lazyLoadQueue,middleware:s,size:ha(i.photo,60,60,!1),loadPromises:t,noBlur:!0}):(n.classList.add("empty"),Qt(n,Cg(i.title||i.display_url||i.description||i.url,!0)));const r=nI(i),o=Db(i),c=$u(jt(i.url||"")).firstElementChild,d=c instanceof HTMLAnchorElement;if(d)try{c.innerText=decodeURIComponent(c.href)}catch{}o.firstChild&&o.append(`
- `),o.append(c),this.showSender&&o.append(`
- `,await Sm(e)),r.textContent||r.append(Oo(i.display_url.split("/",1)[0]));const u=new Fe({title:r,titleRight:Ib(e),subtitle:o,havePadding:!0,clickable:!0,noRipple:!0,asLink:d});if(d){u.container.href=c.href;const h=c.getAttribute("onclick");h&&u.container.setAttribute("onclick",h),c.target==="_blank"&&jl(u.container)}if(u.applyMediaElement(n,"big"),u.container.innerText.trim().length)return{message:e,element:u.container}}async performSearchResult(e,t,s=!0){const i=[],n=t.contentTab,r=[],o=this.middleware.get(),l=t.type==="saved";let c=t.inputFilter;await vi();let d;c==="inputMessagesFilterPhotoVideo"&&this.searchContext.query.trim()?(c="inputMessagesFilterEmpty",d=this.searchGroupMedia,n.append(d.container)):c==="inputMessagesFilterEmpty"&&!l&&(d=this.searchGroups.messages);const u={elemsToAppend:i,inputFilter:c,message:void 0,middleware:o,promises:r,searchGroup:d,mediaTab:t};let h;switch(c){case"inputMessagesFilterEmpty":{h=this.processEmptyFilter;break}case"inputMessagesFilterPhotoVideo":{h=this.processPhotoVideoFilter;break}case"inputMessagesFilterVoice":case"inputMessagesFilterRoundVoice":case"inputMessagesFilterMusic":case"inputMessagesFilterDocument":{h=this.processDocumentFilter;break}case"inputMessagesFilterUrl":{h=this.processUrlFilter;break}}if(h){h=h.bind(this);const m=e.map(async f=>{try{return u.message=f,await h(u)}catch(v){this.log.error("error rendering filter",c,u,f,v)}}),g=(await Promise.all(m)).filter(Boolean);i.push(...g)}if(d&&d.list.childElementCount&&d.setActive(),this.loadMutex&&r.push(this.loadMutex),r.length&&(await Promise.all(r),!o()))return;const p=i.length;if(p){const m=s?"append":"prepend",g=this.groupByMonth&&!l,f=l?this.searchContext.peerId:void 0;if(i.forEach(v=>{const{element:y,message:w}=v;if(!w)debugger;const b=this.getMonthContainerByTimestamp(g?w.date:0,c);y.classList.add("search-super-item"),y.dataset.mid=""+w.mid,y.dataset.peerId=""+w.peerId,f&&(y.dataset.threadId=""+f),b.items[m](y),this.selection?.isSelecting&&this.selection.toggleElementCheckbox(y,!0)}),l){let v=n.querySelector(".chatlist");if(!v){v=nt.createChatList({new:!0});const y=this.getMonthContainerByTimestamp(0,c).container;y.replaceWith(v),v.append(y),nt.setListClickListener({list:v,onFound:()=>{if(this.selection.isSelecting)return!1},withContext:void 0,autonomous:!0,openInner:!0})}}}this.afterPerforming(c==="inputMessagesFilterEmpty"?1:p,n)}afterPerforming(e,t){if(!t)return;const s=t.parentElement;if(Array.from(s.children).slice(1).forEach(i=>{i.remove()}),!e&&!t.childElementCount){const i=document.createElement("div");i.append(P("Chat.Search.NothingFound")),i.classList.add("position-center","text-center","content-empty","no-select"),s.append(i)}}loadChats(){const e=new Set,t=this.middleware.get();for(const i in this.searchGroups){const n=this.searchGroups[i];this.tabs.inputMessagesFilterEmpty.append(n.container),n.clear()}const s=this.searchContext.query;if(s){const i=(r,o,l=!1)=>{r.map(c=>{if(e.has(c))return;e.add(c);const{dom:d}=nt.addDialogNew({peerId:c,container:o.list,avatarSize:"abitbigger",autonomous:o.autonomous,wrapOptions:{middleware:t},withStories:!0});return{dom:d,peerId:c}}).filter(Boolean).forEach(async({dom:c,peerId:d})=>{const u=await this.managers.appPeersManager.getPeer(d);if(d===I.myId)c.lastMessageSpan.append(P("Presence.YourChat"));else{let h=await this.managers.appPeersManager.getPeerUsername(d);if(h)h="@"+h;else{const m=await this.managers.appUsersManager.getUser(d);m?.phone&&(h="+"+bd(m.phone).formatted)}const p=[h];(u.participants_count||u.participants)&&p.push(await ja(d.toChatId())),c.lastMessageSpan.append(...Yi(p.filter(Boolean),!1))}}),o.toggle()},n=r=>{if(t())return r};return Promise.all([this.managers.appUsersManager.getContactsPeerIds(s,!0,void 0,10).then(n).then(r=>{r&&i(r,this.searchGroups.contacts,!0)}),this.managers.appUsersManager.searchContacts(s,20).then(n).then(r=>{if(r&&(i(r.my_results,this.searchGroups.contacts,!0),i(r.results,this.searchGroups.globalContacts),this.searchGroups.globalContacts.container.classList.add("is-short"),this.searchGroups.globalContacts.nameEl.lastElementChild!==this.searchGroups.globalContacts.nameEl.firstElementChild&&this.searchGroups.globalContacts.nameEl.lastElementChild.remove(),this.searchGroups.globalContacts.list.childElementCount>3)){const o=document.createElement("div");o.classList.add("search-group__show-more");const l=new Ne.IntlElement({key:"Separator.ShowMore"});o.append(l.element),this.searchGroups.globalContacts.nameEl.append(o),J(o,()=>{const c=this.searchGroups.globalContacts.container.classList.toggle("is-short");l.key=c?"Separator.ShowMore":"Separator.ShowLess",l.update()})}}),this.managers.dialogsStorage.getDialogs({query:s,offsetIndex:0,limit:20,filterId:0}).then(n).then(r=>{r&&i(r.dialogs.map(o=>o.peerId),this.searchGroups.contacts,!0)})])}else if(!this.searchContext.peerId&&!this.searchContext.minDate){const i=(n=!0)=>Ae.getState().then(r=>{t()&&(this.searchGroups.recent.list.replaceChildren(),r.recentSearch.slice(0,20).forEach(async o=>{const{dom:l}=nt.addDialogNew({peerId:o,container:this.searchGroups.recent.list,meAsSaved:!0,avatarSize:"abitbigger",autonomous:!0,wrapOptions:{middleware:t},withStories:!0});l.lastMessageSpan.append(await(o.isUser()?Promise.resolve(qo(await this.managers.appUsersManager.getUser(o.toUserId()))):ja(o.toChatId())))}),r.recentSearch.length?n&&this.searchGroups.recent.setActive():this.searchGroups.recent.clear())});return Promise.all([this.managers.appUsersManager.getTopPeers("correspondents").then(n=>{if(!t())return;n=n.slice(0,15);const r=n.findIndex(o=>o.id===I.myId);r!==-1&&(n=n.slice(),n.splice(r,1)),n.forEach(o=>{const{dom:l}=nt.addDialogNew({peerId:o.id,container:this.searchGroups.people.list,onlyFirstName:!0,avatarSize:"bigger",autonomous:!1,noIcons:this.searchGroups.people.noIcons,wrapOptions:{middleware:t},withStories:!0});l.subtitleEl.remove()}),this.searchGroups.people.toggle()}),i()])}else return Promise.resolve()}async loadMembers({mediaTab:e}){const t=e.type==="members"?this.searchContext.peerId.toChatId():void 0,s=e.type==="groups"?this.searchContext.peerId.toUserId():void 0,i=this.middleware.get();let n;const r=async o=>{if(this.loadMutex&&(await this.loadMutex,!i()))return;let l=this.membersList,c=this.membersParticipantMap,d=this.membersMiddlewareHelper;if(!l&&(c=this.membersParticipantMap=new Map,d=this.membersMiddlewareHelper=Ht(),l=this.membersList=new qh({lazyLoadQueue:this.lazyLoadQueue,rippleEnabled:!1,managers:this.managers,middleware:i}),J(l.list,p=>{if(ne(p.target,"has-stories"))return;const m=Mn(p.target,tc);if(!m)return;const g=m.dataset.peerId.toPeerId();let f=Promise.resolve();this.slider===Gs&&st.isMobile&&(f=this.slider.toggleSidebar(!1)),f.then(()=>{Ce.setInnerPeer({peerId:g})})}),e.contentTab.append(l.list),this.afterPerforming(1,e.contentTab),t)){const p=d.get();ef({chatId:t,listenTo:l.list,participants:this.membersParticipantMap,slider:this.slider,middleware:p});const m=g=>{const f=Zc(g.prev_participant||g.new_participant),v=l.has(f);(v||g.new_participant.pFlags?.left)&&(l.ranks.delete(f),l.delete(f),c.delete(f),this.setCounter(e.type,this.counters[e.type]-1)),(!g.prev_participant||v)&&g.new_participant&&(r([g.new_participant]),this.setCounter(e.type,this.counters[e.type]+1))};I.addEventListener("chat_participant",m),p.onClean(()=>{I.removeEventListener("chat_participant",m)})}const u=o.map(p=>{const m=s?p.id.toPeerId(!0):Zc(p);if(!(t?m.isAnyChat():m.isUser()))return{peerId:m,rank:ub(p),participant:p}}).filter(Boolean),h=await zn(u,async({peerId:p})=>{const m=await this.managers.appPeersManager.getPeer(p);return!(!i()||!m||m.pFlags.deleted)});for(const{peerId:p,rank:m,participant:g}of h)m&&l.ranks.set(p,m),c.set(p,g),l.add(p)};if(s){const o=this.membersList?200:50;n=this.managers.appUsersManager.getCommonChats(s,o,this.nextRates[e.type]).then(l=>{if(!i())return;const c=l.count??l.chats.length;this.counters[e.type]||this.setCounter(e.type,c);const d=l.chats[l.chats.length-1];return this.nextRates[e.type]=d?.id,l.chats.length<o&&(this.loaded[e.type]=!0),r(l.chats)})}else if(await this.managers.appChatsManager.isChannel(t)){const o=this.membersList?200:50;n=this.managers.appProfileManager.getChannelParticipants({id:t,limit:o,offset:this.nextRates[e.type]}).then(l=>{if(!i())return;const c=e.contentTab.firstElementChild;return this.nextRates[e.type]=(c?c.childElementCount:0)+l.participants.length,l.participants.length<o&&(this.loaded[e.type]=!0),this.setCounter(e.type,l.count),r(l.participants)})}else n=this.managers.appProfileManager.getChatFull(t).then(o=>{if(!i())return;this.loaded[e.type]=!0;const l=o.participants;if(l._!=="chatParticipantsForbidden")return this.setCounter(e.type,l.participants.length),r(l.participants)});return n}async loadStories({mediaTab:e}){if(this._loadStories)return this._loadStories();const t=this.middleware.get(),s=Mt();return Ft(i=>{t.onClean(()=>{this._loadStories=void 0,i(),s.reject()});const n=R8({peerId:this.searchContext.peerId,pinned:!this.storiesArchive,archive:this.storiesArchive,onReady:()=>{s.resolve();const r=n();e.contentTab.append(typeof r=="function"?r():r),this.afterPerforming(1,e.contentTab)},onLoadCallback:r=>{this._loadStories=async()=>{const l=await r();t()&&l&&(this.loaded[e.type]=!0)}},onLengthChange:r=>{this.onStoriesLengthChange?.(r),this.setCounter(e.type,r)},selection:this.selection});this._loadStories()}),s}async loadSimilarChannels({mediaTab:e}){const t=this.middleware.get().create(),s=async(l,c)=>{const d=nt.createChatList({new:!0}),u=l.map(async h=>{const p=[],{dom:m}=nt.addDialogNew({peerId:h.id.toPeerId(!0),container:d,avatarSize:"abitbigger",autonomous:!1,wrapOptions:{middleware:c},loadPromises:p});return m.lastMessageSpan.append(await ja(h.id,this.managers,h)),Promise.all(p)});return await Promise.all(u),d},i=l=>{const c=document.createElement("div");c.classList.add("similar-channels-paywall");const d=ot("btn-primary btn-color-primary",{icon:"premium_unlock",text:"UnlockSimilar"});d.classList.add("similar-channels-paywall-button");const u=()=>rs.show(),h=xi(u);J(d,u),h.classList.add("primary");const p=P("SimilarChannels.Unlock",[h,l]);return p.classList.add("similar-channels-paywall-subtitle"),c.append(d,p),c};let n,r;const o=async l=>{if(r===l)return;t.clean();const c=t.get(),[d,u,h]=await Promise.all([this.managers.appChatsManager.getChannelRecommendations(this.searchContext.peerId.toChatId()),this.managers.apiManager.getLimit("recommendedChannels",!0),Ae.isPremiumFeaturesHidden()]),p=await s(d.chats,c);if(!c())return;e.contentTab.replaceChildren(p),this.afterPerforming(1,e.contentTab),this.loaded[e.type]=!0;const m=d.count??d.chats.length;this.setCounter(e.type,m),!l&&!h&&(n||(n=i(u)),e.contentTab.append(n))};return I.addEventListener("premium_toggle",o),this.middleware.get().onClean(()=>{I.removeEventListener("premium_toggle",o)}),o(I.premium)}async loadSavedDialogs({mediaTab:e,middleware:t,side:s}){if(this._loadSavedDialogs)return this._loadSavedDialogs(s);const i=nt.createChatList();nt.setListClickListener({list:i,withContext:!0,openInner:this.openSavedDialogsInner});const n=new VM;n.scrollable=this.scrollable,n.sortedList=new rf({managers:this.managers,log:this.log,list:i,indexKey:"index_0",virtualFilterId:I.myId});const r=async()=>(await this.managers.dialogsStorage.getDialogs({filterId:I.myId})).count;return(n.onAnyUpdate=async()=>{if(!t())return;const l=await r();this.setCounter(e.type,l)})(),e.contentTab.append(i),this.afterPerforming(1,e.contentTab),this._loadSavedDialogs=n.onChatsScroll.bind(n),t.onClean(()=>{n.destroy(),this._loadSavedDialogs=void 0}),n.onChatsScroll()}appendShowMoreButton(e,t="is-short-5"){let s=!1;const i=gr(`
- <div class="search-group__show-more"></div>
- `);e.nameEl.append(i),n(),J(i,()=>{s=!s,n()});function n(){i.replaceChildren(P(s?"Separator.ShowLess":"Separator.ShowMore")),e.container.classList.toggle(t,!s)}}async renderPeerDialogs(e,t,s,i){if(s())for(const n of e){const{dom:r}=nt.addDialogNew({peerId:n,container:t.list,avatarSize:"abitbigger",wrapOptions:{middleware:s}}),o=await this.managers.appPeersManager.getPeer(n),l=await this.managers.appPeersManager.getPeerUsername(n);"participants_count"in o?r.lastMessageSpan.append(await ja(n.toChatId())):"bot_active_users"in o?r.lastMessageSpan.append(P("BotUsers",[ln(o.bot_active_users)])):l?r.lastMessageSpan.append("@"+l):i==="bots"&&r.lastMessageSpan.append(P("UnknownBotUsers"))}}async loadChannels({mediaTab:e,middleware:t}){if(this.searchContext.query){const o=new aa("Channels","channels");o.setActive(),o.nameEl.style.display="none";const l=200,{results:c}=await this.managers.appUsersManager.searchContacts(this.searchContext.query,l),u=(await Promise.all(c.map(async h=>await this.managers.appPeersManager.isBroadcast(h)?h:void 0))).filter(Boolean);this.renderPeerDialogs(u.map(h=>h.toPeerId(!0)),o,t),u.length&&e.contentTab.append(o.container),this.afterPerforming(u.length,e.contentTab),this.loaded[e.type]=!0;return}const s=await this.managers.dialogsStorage.getCachedDialogs(),n=(await Promise.all(s.map(async o=>await this.managers.appPeersManager.isBroadcast(o.peerId)?o:void 0))).filter(Boolean);if(n.length){const o=new aa("Chat.Search.JoinedChannels","channels");o.setActive(),e.contentTab.append(o.container),n.length>5&&this.appendShowMoreButton(o),this.renderPeerDialogs(n.map(c=>c.peerId),o,t)}const r=await this.managers.appChatsManager.getGenericChannelRecommendations();if(r.chats.length){const o=new aa("SimilarChannels","channels");o.setActive(),e.contentTab.append(o.container),this.renderPeerDialogs(r.chats.map(l=>l.id.toPeerId(!0)),o,t)}this.afterPerforming(1,e.contentTab),this.loaded[e.type]=!0}async loadApps({mediaTab:e,middleware:t}){if(this.searchContext.query){const d=new aa("ChatList.Filter.Bots","apps");d.setActive();const u=200,{results:h}=await this.managers.appUsersManager.searchContacts(this.searchContext.query,u),m=(await Promise.all(h.map(async g=>await this.managers.appPeersManager.isBot(g)?g:void 0))).filter(Boolean);this.renderPeerDialogs(m.map(g=>g.toPeerId(!1)),d,t,"bots"),m.length&&e.contentTab.append(d.container),this.afterPerforming(m.length,e.contentTab),this.loaded[e.type]=!0;return}const s=await I.managers.appUsersManager.getTopPeers("bots_app");if(s.length){const d=new aa("MiniApps.Apps","apps");d.setActive(),e.contentTab.append(d.container),s.length>5&&this.appendShowMoreButton(d),this.renderPeerDialogs(s.map(h=>h.id.toPeerId(!1)),d,t,"bots")}const i=new aa("MiniApps.Popular","apps");i.setActive(),e.contentTab.append(i.container);let n="",r;const o=20,l=async()=>{if(r||!t()||n===null)return;r=I.managers.appAttachMenuBotsManager.getPopularAppBots(n,o);const{nextOffset:d,userIds:u}=await r;await this.renderPeerDialogs(u.map(h=>h.toPeerId(!1)),i,t,"bots"),n=d||null,r=void 0},c=this.scrollable.container;c.addEventListener("scroll",()=>{this.mediaTab===e&&c.scrollTop+c.clientHeight>=c.scrollHeight-120&&l()}),await l(),this.afterPerforming(1,e.contentTab),this.loaded[e.type]=!0}async loadGifts({mediaTab:e}){if(!this._loadedGifts){const t=this.middleware.get();Ft(s=>{t.onClean(()=>s());const i=this.scrollable.container,{render:n,loadNext:r}=D8({peerId:this.searchContext.peerId,scrollParent:i,onCountChange:o=>{this.setCounter("gifts",o)}});i.addEventListener("scroll",()=>{this.mediaTab===e&&i.scrollTop+i.clientHeight>=i.scrollHeight-400&&r()}),e.contentTab.append(jE(n,o=>o instanceof Element))}),this._loadedGifts=!0}return Promise.resolve()}loadType(e){var u;const{mediaTab:t,justLoad:s,loadCount:i,middleware:n,side:r}=e,{type:o,inputFilter:l}=t;let c=this.loadPromises[o];if(c)return c;if(o==="members"||o==="groups"?c=this.loadMembers(e):o==="stories"?c=this.loadStories(e):o==="similar"?c=this.loadSimilarChannels(e):o==="savedDialogs"?c=this.loadSavedDialogs(e):o==="channels"?c=this.loadChannels(e):o==="apps"?c=this.loadApps(e):o==="gifts"&&(c=this.loadGifts(e)),c)return this.loadPromises[o]=c.finally(()=>{n()&&(this.loadPromises[o]=null)});const d=(u=this.historyStorage)[l]??(u[l]=[]);return l==="inputMessagesFilterEmpty"&&!d.length&&o!=="saved"&&(this.loadedChats||(this.loadChats(),this.loadedChats=!0),!this.searchContext.query.trim()&&!this.searchContext.peerId&&!this.searchContext.minDate)?(this.loaded[o]=!0,Promise.resolve()):(c=this.loadPromises[o]=Promise.resolve().then(async()=>{var y;if(d.length&&this.usedFromHistory[l]<d.length&&!s){const w=[];let b=Math.max(0,this.usedFromHistory[l]),S=0;do{const _=d.slice(b,b+i);b+=_.length,S+=_.length;const M=_.map(C=>Ae.getMessageByPeer(C.peerId,C.mid));w.push(...this.filterMessagesByType(M,l))}while(S<i&&b<d.length);return this.usedFromHistory[l]=b,this.performSearchResult(w,t).finally(()=>{setTimeout(()=>{this.scrollable.checkForTriggers()},0)})}const h=d[d.length-1],p=h?.mid||0,m=h?.peerId||Wt,g={...this.searchContext,inputFilter:{_:l},offsetId:p,offsetPeerId:m,limit:i,nextRate:(y=this.nextRates)[o]??(y[o]=0),...o==="saved"?{inputFilter:void 0,peerId:I.myId,threadId:this.searchContext.peerId}:{}},f=await this.managers.appMessagesManager.getHistory(g);let v=f.messages;if(!v&&f.history&&(v=f.history.map(w=>Ae.getMessageByPeer(g.peerId,w))),d.push(...v.map(w=>({mid:w.mid,peerId:w.peerId}))),this.counters[o]||this.setCounter(o,f.count),!!n()&&((f.history.length<i||this.searchContext.folderId!==void 0&&!f.nextRate||f.isEnd.top)&&(this.loaded[o]=!0),this.nextRates[o]=f.nextRate,!s))return this.usedFromHistory[l]=d.length,this.loaded[o]||c.then(()=>{setTimeout(()=>{if(n()&&this.mediaTab===t){const w=this.load(!0,!0);w&&w.then(()=>{n()&&setTimeout(()=>{this.scrollable.checkForTriggers()},0)})}},0)}),this.performSearchResult(this.filterMessagesByType(v,l),t)}).catch(h=>{this.log.error("load error:",h)}).finally(()=>{this.loadPromises[o]=null}),c)}canLoadMediaTab(e){const t=e.inputFilter;return!this.loaded[e.type]||this.historyStorage[t]&&this.usedFromHistory[t]<this.historyStorage[t].length}async loadFirstTime(){const e=this.middleware.get(),{peerId:t,threadId:s}=this.searchContext;if(!this.hideEmptyTabs)return;const i=this.mediaTabs.filter(C=>C.inputFilter&&C.inputFilter!=="inputMessagesFilterEmpty"),n=i.map(C=>({_:C.inputFilter})),[r,o,l,c,d,u,h,p]=await Promise.all([this.managers.appMessagesManager.getSearchCounters(t,n,void 0,s),this.canViewSavedDialogs(),this.canViewSaved(),this.canViewMembers(),this.canViewGroups(),this.canViewStories(),this.canViewSimilar(),this.getGiftsCount()]);if(!e()||this.loadMutex&&(await this.loadMutex,!e()))return;let m,g=0;i.forEach(C=>{const L=r.find(E=>E.filter._===C.inputFilter);C.menuTab.classList.toggle("hide",!L.count),C.menuTab.classList.remove("active"),this.setCounter(C.type,L.count),L.count&&(m===void 0&&(m=C),++g)});const f=this.mediaTabsMap.get("savedDialogs"),v=this.mediaTabsMap.get("saved"),y=this.mediaTabsMap.get("members"),w=this.mediaTabsMap.get("stories"),b=this.mediaTabsMap.get("groups"),S=this.mediaTabsMap.get("similar"),_=this.mediaTabsMap.get("gifts");if([[f,o],[v,l],[w,u],[y,c],[b,d],[S,h],[_,p!==0]].forEach(([C,L])=>{C&&(C.menuTab.classList.toggle("hide",!L),L&&++g)}),this.setCounter("gifts",p),u){m=w;const C=P(t.isUser()?"Stories":"ProfileStories");w.menuTabName.replaceWith(w.menuTabName=C)}c&&(m=y),o&&(m=f),this.container.classList.toggle("hide",!m),this.container.parentElement.classList.toggle("search-empty",!m),m&&(this.skipScroll=!0,this.selectTab(this.mediaTabs.indexOf(m),!1),this.navScrollableContainer.classList.toggle("is-single",g<=1))}async load(e=!1,t=!1,s="bottom"){const i=this.searchContext.peerId;this.log("load",e,i,this.loadPromises);const n=this.middleware.get();if(this.firstLoad){if(await(this.loadFirstTimePromise??(this.loadFirstTimePromise=this.loadFirstTime())),!n())return;this.loadFirstTimePromise=void 0,this.firstLoad=!1}let r=e?[this.mediaTab]:this.mediaTabs.filter(c=>c!==this.mediaTab);if(r=r.filter(c=>this.canLoadMediaTab(c)),i.isUser()?tr(r,c=>c.type==="members"):a_(r,c=>c.type==="groups"),!r.length)return;const o=t?50:Math.round((It.height/130|0)*3*1.25),l=r.map(c=>this.loadType({mediaTab:c,justLoad:t,loadCount:o,middleware:n,side:s}));return Promise.all(l).catch(c=>{this.log.error("Load error all promises:",c)})}getMonthContainerByTimestamp(e,t){const s=new Date(e*1e3);s.setHours(0,0,0),s.setDate(1);const i=s.getTime(),n=this.monthContainers[t]??(this.monthContainers[t]={});if(!(i in n)){const r=document.createElement("div");r.className="search-super-month";const o=document.createElement("div");o.classList.add("search-super-month-name");const l={month:"long"};s.getFullYear()!==new Date().getFullYear()&&(l.year="numeric");const c=new Ne.IntlDateElement({date:s,options:l}).element;o.append(c),r.append(o);const d=document.createElement("div");d.classList.add("search-super-month-items"),r.append(o,d);const u=t_(n,"desc");let h=0;for(;h<u.length;++h){const p=u[h];if(i>p)break}n[i]={container:r,items:d},di(r,this.tabs[t],h)}return n[i]}async canViewSavedDialogs(){if(this.searchContext.peerId!==I.myId||this.searchContext.threadId||!this.mediaTabsMap.has("savedDialogs"))return!1;try{return await this.managers.dialogsStorage.getDialogs({filterId:I.myId}),!0}catch{return!1}}canViewSaved(){const{peerId:e,threadId:t}=this.searchContext;return t||I.myId===e?!1:this.managers.appMessagesManager.getHistory({peerId:I.myId,threadId:this.searchContext.peerId,limit:50}).then(s=>!!s.count).catch(()=>!1)}canViewMembers(){const{peerId:e}=this.searchContext;if(!e.isAnyChat()||!this.mediaTabsMap.has("members"))return Promise.resolve(!1);const s=e.toChatId();return Promise.all([this.managers.appChatsManager.isBroadcast(s),this.managers.appChatsManager.hasRights(s,"view_participants"),this.managers.appChatsManager.isForum(s)]).then(([i,n,r])=>!i&&n&&(!this.searchContext.threadId||!r))}async canViewGroups(){const{peerId:e}=this.searchContext;return!e.isUser()||!this.mediaTabsMap.has("groups")?!1:!!(await this.managers.appProfileManager.getProfile(e.toUserId())).common_chats_count}async canViewStories(){const{peerId:e,threadId:t}=this.searchContext;return!this.mediaTabsMap.has("stories")||t||e===I.myId&&!this.onStoriesLengthChange?!1:e.isUser()?(this.storiesArchive?this.managers.appStoriesManager.getStoriesArchive(e,1):this.managers.appStoriesManager.getPinnedStories(e,1)).then(({count:n})=>!!n).catch(()=>!1):!!(await this.managers.appProfileManager.getChatFull(e.toChatId())).pFlags.stories_pinned_available}async canViewSimilar(){const{peerId:e}=this.searchContext;if(e.isUser())return!1;try{return!!(await this.managers.appChatsManager.getChannelRecommendations(e.toChatId())).chats.length}catch{return!1}}async getGiftsCount(){const{peerId:e}=this.searchContext;return(e.isUser()?await this.managers.appProfileManager.getProfile(e.toUserId()):await this.managers.appProfileManager.getChannelFull(e.toChatId())).stargifts_count??0}cleanup(){this.loadPromises={},this.loaded={},this.loadedChats=!1,this.nextRates={},this.firstLoad=!0,this.prevTabId=-1,this.counters={},this.lazyLoadQueue.clear(),this.mediaTabs.forEach(e=>{const{inputFilter:t}=e;t&&(this.usedFromHistory[t]=-1)}),this.selection?.isSelecting&&this.selection.cancelSelection(),this.middleware.clean(),this.loadFirstTimePromise=void 0,this.cleanScrollPositions(),this.membersList=void 0,this.membersParticipantMap=void 0,this.membersMiddlewareHelper?.destroy(),this.membersMiddlewareHelper=void 0}cleanScrollPositions(){this.mediaTabs.forEach(e=>{e.scroll=void 0})}cleanupHTML(e=!1){this.mediaTabs.forEach(t=>{if(t.contentTab.replaceChildren(),this.hideEmptyTabs&&(this.container.classList.add("hide"),this.container.parentElement.classList.add("search-empty")),t.type!=="chats"&&t.inputFilter&&!this.historyStorage[t.inputFilter]){const s=t.contentTab.parentElement;s.querySelector(".preloader")||Yn(s,!0),s.querySelector(".content-empty")?.remove()}}),this.monthContainers={},this.searchGroupMedia.clear(),this.scrollable.scrollPosition=0}copySearchContext(e,t){const s=kn(this.searchContext);return s.inputFilter={_:e},s.nextRate=t,s}setQuery({peerId:e,query:t,threadId:s,historyStorage:i,folderId:n,minDate:r,maxDate:o}){this.searchContext={peerId:e,query:t||"",inputFilter:{_:this.mediaTab.inputFilter},threadId:s,folderId:n,minDate:r,maxDate:o},this.historyStorage=i??{},this.cleanup()}destroy(){this.cleanup(),this.listenerSetter.removeAll(),this.scrollable.destroy(),this.swipeHandler?.removeListeners(),this.selection?.cleanup(),this.scrollStartCallback=this.onChangeTab=this.selectTab=this.searchContextMenu=this.swipeHandler=this.selection=void 0}}var li=(a=>(a[a.Everybody=2]="Everybody",a[a.Contacts=1]="Contacts",a[a.Nobody=0]="Nobody",a))(li||{});function mM(a){const e=[],t={users:[],chats:[]},s={users:[],chats:[]};return a.forEach(i=>{switch(i._){case"privacyValueAllowAll":e.push(li.Everybody);break;case"privacyValueDisallowAll":e.push(li.Nobody);break;case"privacyValueAllowContacts":e.push(li.Contacts);break;case"privacyValueAllowChatParticipants":t.chats.push(...i.chats);break;case"privacyValueAllowUsers":t.users.push(...i.users);break;case"privacyValueDisallowChatParticipants":s.chats.push(...i.chats);break;case"privacyValueDisallowUsers":s.users.push(...i.users);break}}),{type:e[0],disallowPeers:s,allowPeers:t}}class Mr{constructor(e){this.options=e,this.onTabDestroy=async()=>{if(this.isLocked()||!this.options.inputKey)return;const o=[];switch(this.type){case li.Everybody:o.push({_:"inputPrivacyValueAllowAll"});break;case li.Contacts:o.push({_:"inputPrivacyValueAllowContacts"});break;case li.Nobody:o.push({_:"inputPrivacyValueDisallowAll"});break}if(this.exceptions){const l=[["allow","inputPrivacyValueAllowChatParticipants","inputPrivacyValueAllowUsers"],["disallow","inputPrivacyValueDisallowChatParticipants","inputPrivacyValueDisallowUsers"]];for(const[c,d,u]of l){if(this.exceptions.get(c).row.container.classList.contains("hide"))continue;const h=this.peerIds[c];if(!h)continue;const p=this.splitPeersByType(h);p.chats.length&&o.push({_:d,chats:p.chats}),p.users.length&&o.push({_:u,users:await Promise.all(p.users.map(m=>I.managers.appUsersManager.getUserInput(m)))})}}I.managers.appPrivacyManager.setPrivacy(this.options.inputKey,o)},this.onRadioChange=o=>{o=+o,this.type=o,this.replaceCaption(),this.exceptions&&(this.exceptions.get("allow").row.container.classList.toggle("hide",this.type===li.Everybody),this.exceptions.get("disallow").row.container.classList.toggle("hide",this.type===li.Nobody)),this.options.onRadioChange&&this.options.onRadioChange(o)},e.captions&&e.captions.reverse();const t=e.managers;this.radioSection=new Oe({name:e.title,caption:!0}),this.radioRows=new Map;let s=[{type:li.Everybody,langKey:"PrivacySettingsController.Everbody"},{type:li.Contacts,langKey:"PrivacySettingsController.MyContacts"},{type:li.Nobody,langKey:"PrivacySettingsController.Nobody"}];if(e.myContactsAndPremium){const o=s.find(l=>l.type===li.Contacts);o.langKey="PrivacyMessagesContactsAndPremium"}e.skipTypes&&(s=s.filter(o=>!e.skipTypes.includes(o.type)));const i=xu();s.forEach(({type:o,langKey:l})=>{const c=new Fe({radioField:new rn({langKey:l,name:i,value:""+o}),clickable:d=>{c.radioField.locked&&(_e(d),$e({langPackKey:e.premiumError,langPackArguments:[xi(()=>{no(),rs.show()})]}))},listenerSetter:e.tab.listenerSetter});this.radioRows.set(o,c)});const n=Sd([...this.radioRows.values()],this.onRadioChange);if(this.radioSection.content.append(n),e.appendTo&&e.appendTo.append(this.radioSection.container),!e.noExceptions){const o=this.exceptionsSection=new Oe({name:"PrivacyExceptions",caption:"PrivacySettingsController.PeerInfo"});this.exceptions=new Map([["disallow",{titleLangKey:e.exceptionTexts[0],key:"disallow",row:null,icon:"deleteuser",subtitleLangKey:"PrivacySettingsController.AddUsers",clickable:!0}],["allow",{titleLangKey:e.exceptionTexts[1],key:"allow",row:null,icon:"adduser",subtitleLangKey:"PrivacySettingsController.AddUsers",clickable:!0}]]),this.exceptions.forEach(l=>{l.row=new Fe(l),J(l.row.container,()=>{r.then(()=>{const c=this.peerIds[l.key];e.tab.slider.createTab(Zu).open({type:"privacy",skippable:!0,title:l.titleLangKey,placeholder:"PrivacyModal.Search.Placeholder",takeOut:d=>{c.length=0,c.push(...d),l.row.subtitle.replaceChildren(...this.generateStr(this.splitPeersByType(d))),this.onRadioChange(this.type)},selectedPeerIds:c})})},{listenerSetter:e.tab.listenerSetter}),o.content.append(l.row.container)}),e.appendTo&&e.appendTo.append(o.container)}const r=(e.inputKey?t.appPrivacyManager.getPrivacy(e.inputKey):Promise.resolve()).then(o=>{const l=o?mM(o):void 0,c=e.privacyType||l?.type;if(this.exceptions&&(this.peerIds={},["allow","disallow"].forEach(d=>{const u=[],h=d==="allow"?l.allowPeers:l.disallowPeers;u.push(...h.users.map(m=>m.toPeerId())),u.push(...h.chats.map(m=>m.toPeerId(!0))),this.peerIds[d]=u;const p=this.exceptions.get(d).row.subtitle;p.replaceChildren(),p.append(...this.generateStr(h))})),e.premiumOnly){const d=()=>{const u=this.isLocked();this.radioRows.forEach((h,p)=>{p!==li.Everybody&&(h.radioField.locked=u)}),this.setRadio(this.isLocked()?li.Everybody:c),this.exceptionsSection&&this.exceptionsSection.container.classList.toggle("hide",u)};d(),e.tab.listenerSetter.add(I)("premium_toggle",d)}else this.setRadio(this.isLocked()?li.Everybody:c);e.tab.eventListener.addEventListener("destroy",this.onTabDestroy,{once:!0})})}isLocked(){return this.options.premiumOnly&&!I.premium}replaceCaption(e=this.isLocked()?this.options.premiumCaption:this.options.captions[this.type]){const t=this.radioSection.caption;e?e instanceof HTMLElement?St(t,e):ks(t,e):t.replaceChildren(),t.classList.toggle("hide",!e)}setRadio(e){const t=this.radioRows.get(e);this.onRadioChange(e),t.radioField.input.checked=!0}splitPeersByType(e){const t={users:[],chats:[]};return e.forEach(s=>{t[s.isAnyChat()?"chats":"users"].push(s.isAnyChat()?s.toChatId():s)}),t}generateStr(e){return!e.users.length&&!e.chats.length?[P("PrivacySettingsController.AddUsers")]:Yi([e.users.length?P("Users",[e.users.length]):null,e.chats.length?P("Chats",[e.chats.length]):null].filter(Boolean),!1)}}class N8 extends Bs{async init(){this.container.classList.add("privacy-tab","privacy-phone-number"),this.setTitle("PrivacyPhone");const e="+"+(await this.managers.appUsersManager.getSelf()).phone,t=document.createElement("div");t.append(P("PrivacyPhoneInfo"),document.createElement("br"),document.createElement("br"),P("PrivacyPhoneInfo4"),document.createElement("br"),lM({mePath:e}));const s=new Mr({tab:this,title:"PrivacyPhoneTitle",inputKey:"inputPrivacyKeyPhoneNumber",captions:[t,t,""],exceptionTexts:["PrivacySettingsController.NeverShare","PrivacySettingsController.AlwaysShare"],appendTo:this.scrollable,onRadioChange:r=>{n.setRadio(li.Everybody),n.radioSection.container.classList.toggle("hide",r!==li.Nobody)},managers:this.managers}),i="PrivacyPhoneInfo3",n=new Mr({tab:this,title:"PrivacyPhoneTitle2",inputKey:"inputPrivacyKeyAddedByPhone",captions:[i,i,""],noExceptions:!0,skipTypes:[li.Nobody],managers:this.managers});this.scrollable.container.insertBefore(n.radioSection.container,s.radioSection.container.nextSibling)}}class gM extends Zt{init(){this.container.classList.add("two-step-verification","two-step-verification-set"),this.setTitle("TwoStepVerificationPasswordSet");const e=new Oe({captionOld:"TwoStepVerificationPasswordSetInfo",noDelimiter:!0}),t="🥳",s=document.createElement("div");Xo({emoji:t,div:s,width:160,height:160}),e.content.append(s);const i=e.generateContentElement(),n=document.createElement("div");n.classList.add("input-wrapper");const r=ot("btn-primary btn-color-primary",{text:"TwoStepVerificationPasswordReturnSettings"});J(r,o=>{this.close()}),this.slider.sliceTabsUntilTab(Eh,this),n.append(r),i.append(n),this.scrollable.append(e.container)}}function nf(a){return!wr||!a}class fM extends Zt{constructor(){super(...arguments),this.isFirst=!1}init(){this.container.classList.add("two-step-verification","two-step-verification-email-confirmation"),this.setTitle("TwoStepAuth.RecoveryTitle");const e=new Oe({captionOld:!0,noDelimiter:!0});ks(e.caption,"TwoStepAuth.ConfirmEmailCodeDesc",[this.email]);const t="📬",s=document.createElement("div");Xo({div:s,width:160,height:160,emoji:t}),e.content.append(s);const i=e.generateContentElement(),n=document.createElement("div");n.classList.add("input-wrapper");const r=this.codeInputField=new tk({name:"recovery-email-code",label:"TwoStepAuth.RecoveryCode",length:this.length,onFill:u=>{d(!0),this.managers.passwordManager.confirmPasswordEmail(""+u).then(h=>{c()}).catch(h=>{switch(h.type){case"CODE_INVALID":r.input.classList.add("error"),St(r.label,P("TwoStepAuth.RecoveryCodeInvalid"));break;case"EMAIL_HASH_EXPIRED":r.input.classList.add("error"),St(r.label,P("TwoStepAuth.RecoveryCodeExpired"));break;default:console.error("confirm error",h);break}d(!1)})}}),o=ot("btn-primary btn-primary-transparent primary",{text:"TwoStepAuth.EmailCodeChangeEmail"}),l=ot("btn-primary btn-secondary btn-primary-transparent primary",{text:"ResendCode"}),c=()=>{this.slider.createTab(gM).open()},d=u=>{os([r.input,o,l],u)};J(o,u=>{d(!0),this.managers.passwordManager.cancelPasswordEmail().then(h=>{this.slider.sliceTabsUntilTab(Sw,this),this.close()},()=>{d(!1)})}),J(l,u=>{d(!0);const h=Yn(l);this.managers.passwordManager.resendPasswordEmail().then(p=>{h.remove(),d(!1)})}),n.append(r.container,o,l),i.append(n),this.scrollable.append(e.container)}onOpenAfterTimeout(){nf(this.isFirst)&&this.codeInputField.input.focus()}}class Sw extends Zt{constructor(){super(...arguments),this.isFirst=!1}init(){this.container.classList.add("two-step-verification","two-step-verification-email"),this.setTitle("RecoveryEmailTitle");const e=new Oe({captionOld:!0,noDelimiter:!0}),t="💌",s=document.createElement("div");Xo({div:s,width:160,height:160,emoji:t}),e.content.append(s);const i=e.generateContentElement(),n=document.createElement("div");n.classList.add("input-wrapper");const r=this.inputField=new Yt({name:"recovery-email",label:"RecoveryEmail",plainText:!0});r.input.addEventListener("keypress",h=>{if(h.key==="Enter")return _e(h),d()}),r.input.addEventListener("input",h=>{r.input.classList.remove("error")});const o=ot("btn-primary btn-color-primary",{text:"Continue"}),l=ot("btn-primary btn-secondary btn-primary-transparent primary",{text:"YourEmailSkip"}),c=()=>{this.slider.createTab(gM).open()},d=()=>{const h=r.value.trim(),p=F1(h);if(!p||p[0].length!==h.length){r.input.classList.add("error");return}u(!0);const m=Yn(o);this.managers.passwordManager.updateSettings({hint:this.hint,currentPassword:this.plainPassword,newPassword:this.newPassword,email:h}).then(g=>{c()},g=>{if(g.type.includes("EMAIL_UNCONFIRMED")){const f=+g.type.match(/^EMAIL_UNCONFIRMED_(\d+)/)[1],v=this.slider.createTab(fM);v.state=this.state,v.email=h,v.length=f,v.open()}else console.log("password set error",g);u(!1),m.remove()})};J(o,d);const u=h=>{h?(o.setAttribute("disabled","true"),l.setAttribute("disabled","true")):(o.removeAttribute("disabled"),l.removeAttribute("disabled"))};J(l,h=>{ue.createPopup(mi,"popup-skip-email",{buttons:[{langKey:"Cancel",isCancel:!0},{langKey:"YourEmailSkip",callback:()=>{u(!0),Yn(l),this.managers.passwordManager.updateSettings({hint:this.hint,currentPassword:this.plainPassword,newPassword:this.newPassword,email:""}).then(()=>{c()},m=>{u(!1)})},isDanger:!0}],titleLangKey:"YourEmailSkipWarning",descriptionLangKey:"YourEmailSkipWarningText"}).show()}),n.append(r.container,o,l),i.append(n),this.scrollable.append(e.container)}onOpenAfterTimeout(){nf(this.isFirst)&&this.inputField.input.focus()}}class O8 extends Zt{init(){this.container.classList.add("two-step-verification","two-step-verification-hint"),this.setTitle("TwoStepAuth.SetupHintTitle");const e=new Oe({noDelimiter:!0}),t="💡",s=document.createElement("div");Xo({div:s,width:160,height:160,emoji:t}),e.content.append(s);const i=document.createElement("div");i.classList.add("input-wrapper");const n=this.inputField=new Yt({name:"hint",label:"TwoStepAuth.SetupHintPlaceholder"});n.input.addEventListener("keypress",u=>{if(u.key==="Enter")return _e(u),n.value?c():d()});const r=(u,h)=>{u&&_e(u);const p=h?n.value:void 0;if(p&&this.newPassword===p){Wi(Ne.format("PasswordAsHintError",!0));return}const m=this.slider.createTab(Sw);m.state=this.state,m.plainPassword=this.plainPassword,m.newPassword=this.newPassword,m.hint=p,m.open()},o=ot("btn-primary btn-color-primary",{text:"Continue"}),l=ot("btn-primary btn-secondary btn-primary-transparent primary",{text:"YourEmailSkip"}),c=u=>r(u,!0),d=u=>r(u,!1);J(o,c),J(l,d),i.append(n.container,o,l),e.content.append(i),this.scrollable.append(e.container)}onOpenAfterTimeout(){this.inputField.input.focus()}}class U8 extends Zt{init(){this.container.classList.add("two-step-verification","two-step-verification-enter-password","two-step-verification-re-enter-password"),this.setTitle("PleaseReEnterPassword");const e=new Oe({noDelimiter:!0}),t=document.createElement("div");t.classList.add("input-wrapper");const s=this.passwordInputField=new gg({name:"re-enter-password",label:"PleaseReEnterPassword"}),i=new sk(s,157),n=ot("btn-primary btn-color-primary",{text:"Continue"});t.append(s.container,n),e.content.append(i.container,t),this.scrollable.append(e.container),s.input.addEventListener("keypress",l=>{if(s.input.classList.contains("error")&&s.setState(ra.Neutral),l.key==="Enter")return o()});const r=()=>this.newPassword!==s.value?(s.setError(),!1):!0,o=l=>{if(l&&_e(l),!r())return;const c=this.slider.createTab(O8);c.state=this.state,c.plainPassword=this.plainPassword,c.newPassword=this.newPassword,c.open()};return J(n,o),i.load()}onOpenAfterTimeout(){this.passwordInputField.input.focus()}}class My extends Zt{constructor(){super(...arguments),this.isFirst=!0}init(){const e=!this.state.pFlags.has_password||this.plainPassword;this.container.classList.add("two-step-verification","two-step-verification-enter-password"),this.setTitle(e?"PleaseEnterFirstPassword":"PleaseEnterCurrentPassword");const t=new Oe({noDelimiter:!0}),s=document.createElement("div");s.classList.add("input-wrapper");const i=this.passwordInputField=new gg({name:"enter-password",label:e?"PleaseEnterFirstPassword":this.state.hint?void 0:"LoginPassword",labelText:!e&&this.state.hint?je(this.state.hint):void 0}),n=new l_(i,157),r=ot("btn-primary btn-color-primary"),o=new Ne.IntlElement({key:"Continue"});r.append(o.element),s.append(i.container,r),t.content.append(n.container,s),this.scrollable.append(t.container),i.input.addEventListener("keypress",d=>{if(i.input.classList.contains("error")&&(i.input.classList.remove("error"),o.key="Continue",o.update()),d.key==="Enter")return c()});const l=()=>i.value.length?!0:(i.input.classList.add("error"),!1);let c;if(e)c=d=>{if(d&&_e(d),!l())return;const u=this.slider.createTab(U8);u.state=this.state,u.newPassword=i.value,u.plainPassword=this.plainPassword,u.open()};else{let d;const u=()=>(d||(d=window.setInterval(u,1e4)),this.managers.passwordManager.getState().then(p=>{this.state=p,this.state.hint?Qt(i.label,je(this.state.hint)):St(i.label,P("LoginPassword"))}));c=p=>{if(!l()){_e(p);return}r.setAttribute("disabled","true"),o.key="PleaseWait",o.update();const m=Yn(r),g=i.value;this.managers.passwordManager.check(i.value,this.state).then(f=>{if(f._==="auth.authorization"){clearInterval(d),n&&n.remove();const v=this.slider.createTab(vM);v.state=this.state,v.plainPassword=g,v.open(),this.slider.removeTabFromHistory(this)}},f=>{switch(r.removeAttribute("disabled"),i.input.classList.add("error"),f.type){default:o.key="PASSWORD_HASH_INVALID",o.update(),m.remove(),i.select();break}u()})},u()}return J(r,c),n.load()}onOpenAfterTimeout(){nf(this.isFirst)&&this.passwordInputField.input.focus()}}class vM extends Zt{init(){this.container.classList.add("two-step-verification","two-step-verification-main"),this.setTitle("TwoStepVerificationTitle");const e=new Oe({captionOld:!0,noDelimiter:!0}),t="🔐",s=document.createElement("div");Xo({div:s,width:168,height:168,emoji:t}),e.content.append(s);const i=e.generateContentElement();if(this.state.pFlags.has_password){ks(e.caption,"TwoStepAuth.GenericHelp");const n=ot("btn-primary btn-transparent",{icon:"edit",text:"TwoStepAuth.ChangePassword"}),r=ot("btn-primary btn-transparent",{icon:"passwordoff",text:"TwoStepAuth.RemovePassword"}),o=ot("btn-primary btn-transparent",{icon:"email",text:this.state.pFlags.has_recovery?"TwoStepAuth.ChangeEmail":"TwoStepAuth.SetupEmail"});J(n,()=>{const l=this.slider.createTab(My);l.state=this.state,l.plainPassword=this.plainPassword,l.open()}),J(r,()=>{ue.createPopup(mi,"popup-disable-password",{buttons:[{langKey:"Disable",callback:()=>{this.managers.passwordManager.updateSettings({currentPassword:this.plainPassword}).then(()=>{this.slider.sliceTabsUntilTab(Eh,this),this.close()})},isDanger:!0}],titleLangKey:"TurnPasswordOffQuestionTitle",descriptionLangKey:"TurnPasswordOffQuestion"}).show()}),J(o,()=>{const l=this.slider.createTab(Sw);l.state=this.state,l.hint=this.state.hint,l.plainPassword=this.plainPassword,l.newPassword=this.plainPassword,l.isFirst=!0,l.open()}),i.append(n,r,o)}else{ks(e.caption,"TwoStepAuth.SetPasswordHelp");const n=document.createElement("div");n.classList.add("input-wrapper");const r=ot("btn-primary btn-color-primary",{text:"TwoStepVerificationSetPassword"});n.append(r),i.append(n),J(r,o=>{const l=this.slider.createTab(My);l.state=this.state,l.open()})}this.scrollable.append(e.container)}}class H8 extends Bs{init(e){this.container.classList.add("privacy-tab","privacy-last-seen"),this.setTitle("PrivacyLastSeen");const t=()=>i.type!==li.Everybody||!!i.peerIds.disallow.length,s="PrivacySettingsController.LastSeenDescription",i=new Mr({tab:this,title:"LastSeenTitle",inputKey:"inputPrivacyKeyStatusTimestamp",captions:[s,s,s],exceptionTexts:["PrivacySettingsController.NeverShare","PrivacySettingsController.AlwaysShare"],appendTo:this.scrollable,onRadioChange:()=>{[n,r].forEach(o=>{o.container.classList.toggle("hide",!t())})},managers:this.managers});let n;{const o=n=new Oe({caption:"HideReadTimeInfo"}),l=new Fe({titleLangKey:"HideReadTime",checkboxField:new _t({toggle:!0,checked:!!e.pFlags.hide_read_marks}),listenerSetter:this.listenerSetter});this.eventListener.addEventListener("destroy",()=>{const c=l.checkboxField.checked&&t();if(!!e.pFlags.hide_read_marks===c)return;const d=this.managers.appPrivacyManager.setGlobalPrivacySettings({_:"globalPrivacySettings",pFlags:{...e.pFlags,hide_read_marks:c||void 0}});return this.eventListener.dispatchEvent("privacy",d),d}),o.content.append(l.container),this.scrollable.append(o.container)}let r;{const o=r=new Oe({caption:!0}),l=()=>{const d=ot("btn-primary btn-transparent primary",{text:I.premium?"PrivacyLastSeenPremiumForPremium":"PrivacyLastSeenPremium"});return J(d,()=>{rs.show()},{listenerSetter:this.listenerSetter}),d},c=()=>{o.content.replaceChildren(l()),o.caption.replaceChildren(P(I.premium?"PrivacyLastSeenPremiumInfoForPremium":"PrivacyLastSeenPremiumInfo"))};c(),this.listenerSetter.add(I)("premium_toggle",c),this.scrollable.append(o.container)}}}class G8 extends Bs{init(){this.container.classList.add("privacy-tab","privacy-profile-photo"),this.setTitle("PrivacyProfilePhoto");const e="PrivacySettingsController.ProfilePhoto.CustomHelp";new Mr({tab:this,title:"PrivacyProfilePhotoTitle",inputKey:"inputPrivacyKeyProfilePhoto",captions:[e,e,e],exceptionTexts:["PrivacySettingsController.NeverShare","PrivacySettingsController.AlwaysShare"],appendTo:this.scrollable,skipTypes:[li.Nobody],managers:this.managers})}}class V8 extends Bs{init(){this.container.classList.add("privacy-tab","privacy-forward-messages"),this.setTitle("PrivacySettings.Forwards");const e="PrivacySettingsController.Forwards.CustomHelp";new Mr({tab:this,title:"PrivacyForwardsTitle",inputKey:"inputPrivacyKeyForwards",captions:[e,e,e],exceptionTexts:["PrivacySettingsController.NeverAllow","PrivacySettingsController.AlwaysAllow"],appendTo:this.scrollable,managers:this.managers})}}class z8 extends Bs{init(){this.container.classList.add("privacy-tab","privacy-add-to-groups"),this.setTitle("PrivacySettings.Groups");const e="PrivacySettingsController.GroupDescription";new Mr({tab:this,title:"WhoCanAddMe",inputKey:"inputPrivacyKeyChatInvite",captions:[e,e,e],exceptionTexts:["PrivacySettingsController.NeverAllow","PrivacySettingsController.AlwaysAllow"],appendTo:this.scrollable,managers:this.managers})}}class W8 extends Bs{init(){this.container.classList.add("privacy-tab","privacy-calls"),this.setTitle("PrivacySettings.VoiceCalls");const e="PrivacySettingsController.PhoneCallDescription";new Mr({tab:this,title:"WhoCanCallMe",inputKey:"inputPrivacyKeyPhoneCall",captions:[e,e,e],exceptionTexts:["PrivacySettingsController.NeverAllow","PrivacySettingsController.AlwaysAllow"],appendTo:this.scrollable,managers:this.managers});{const t="PrivacySettingsController.P2p.Desc";new Mr({tab:this,title:"PrivacyP2PHeader",inputKey:"inputPrivacyKeyPhoneP2P",captions:[t,t,t],exceptionTexts:["PrivacySettingsController.NeverAllow","PrivacySettingsController.AlwaysAllow"],appendTo:this.scrollable,managers:this.managers})}}}class yM extends Bs{init(){this.container.classList.add("active-sessions-container"),this.setTitle("SessionsTitle");const e=l=>{const c=new Fe({title:[l.app_name,l.app_version].join(" "),subtitle:[l.ip,l.country].filter(Boolean).join(" - "),clickable:!0,titleRight:l.pFlags.current?void 0:Au(new Date(Math.max(l.date_active,l.date_created)*1e3))});return c.container.dataset.hash=""+l.hash,c.midtitle.textContent=[l.device_model,l.system_version||l.platform].filter(Boolean).join(", "),c},t=this.authorizations.slice();{const l=new Oe({name:"CurrentSession",caption:"ClearOtherSessionsHelp"}),c=tr(t,u=>u.pFlags.current),d=e(c);if(l.content.append(d.container),t.length){const u=ot("btn-primary btn-transparent danger",{icon:"stop",text:"TerminateAllSessions"});J(u,h=>{ue.createPopup(mi,"revoke-session",{buttons:[{langKey:"Terminate",isDanger:!0,callback:()=>{const p=os([u],!0);this.managers.apiManager.invokeApi("auth.resetAuthorizations").then(m=>{u.remove(),s.container.remove()},i).finally(()=>{p()})}}],titleLangKey:"AreYouSureSessionsTitle",descriptionLangKey:"AreYouSureSessions"}).show()},{listenerSetter:this.listenerSetter}),l.content.append(u)}this.scrollable.append(l.container)}if(!t.length)return;const s=new Oe({name:"OtherSessions",caption:"SessionsListInfo"});t.forEach(l=>{s.content.append(e(l).container)}),this.scrollable.append(s.container);const i=l=>{l.type==="FRESH_RESET_AUTHORISATION_FORBIDDEN"&&Wi(Ne.format("RecentSessions.Error.FreshReset",!0))};let n;const r=()=>{const l=n.dataset.hash;ue.createPopup(mi,"revoke-session",{buttons:[{langKey:"Terminate",isDanger:!0,callback:()=>{this.managers.apiManager.invokeApi("account.resetAuthorization",{hash:l}).then(c=>{c&&n.remove()},i)}}],titleLangKey:"AreYouSureSessionTitle",descriptionLangKey:"TerminateSessionText"}).show()},o=this.menuElement=xa({buttons:[{icon:"stop",text:"Terminate",onClick:r}]});o.id="active-sessions-contextmenu",o.classList.add("contextmenu"),document.getElementById("page-chats").append(o),Er({element:this.scrollable.container,callback:l=>{n=ne(l.target,"row"),!(!n||n.dataset.hash==="0")&&(l instanceof MouseEvent&&l.preventDefault(),l instanceof MouseEvent&&(l.cancelBubble=!0),Ql(l,o),Li.openBtnMenu(o))},listenerSetter:this.listenerSetter}),J(this.scrollable.container,l=>{n=ne(l.target,"row"),!(!n||n.dataset.hash==="0")&&r()},{listenerSetter:this.listenerSetter})}onCloseAfterTimeout(){return this.menuElement?.remove(),super.onCloseAfterTimeout()}}class K8 extends Zt{init(){this.container.classList.add("blocked-users-container"),this.setTitle("BlockedUsers");const e=new Oe({caption:"BlockedUsersInfo"});e.caption.parentElement.prepend(e.caption),this.scrollable.append(e.container);const t=Cn({icon:"add",className:"is-visible"});this.content.append(t),J(t,d=>{ue.createPopup(Rs,{peerType:["contacts"],placeholder:"BlockModal.Search.Placeholder",onSelect:u=>{this.managers.appUsersManager.toggleBlock(u,!0)}})},{listenerSetter:this.listenerSetter});const s=nt.createChatList();this.scrollable.container.classList.add("chatlist-container"),e.content.append(s);const i=async(d,u)=>{const h=nt.addDialogNew({peerId:d,container:s,rippleEnabled:!0,avatarSize:"abitbigger",append:u,wrapOptions:{middleware:this.middlewareHelper.get()}});h.container.dialogElement=h;const{dom:p}=h,m=await this.managers.appUsersManager.getUser(d.toUserId());if(!m)return;const f=ji(m)[0];m.pFlags.bot?p.lastMessageSpan.append("@"+f):m.phone?p.lastMessageSpan.textContent=tw(m.phone):p.lastMessageSpan.append(f?"@"+f:qo(m))};for(const d of this.peerIds)i(d,!0);let n;const r=()=>{const d=n.dataset.peerId.toPeerId();this.managers.appUsersManager.toggleBlock(d,!1)},o=this.menuElement=xa({buttons:[{icon:"lockoff",text:"Unblock",onClick:r,options:{listenerSetter:this.listenerSetter}}]});o.id="blocked-users-contextmenu",o.classList.add("contextmenu"),document.getElementById("page-chats").append(o),Er({element:this.scrollable.container,callback:d=>{n=Mn(d.target,tc),n&&(d instanceof MouseEvent&&d.preventDefault(),d instanceof MouseEvent&&(d.cancelBubble=!0),Ql(d,o),Li.openBtnMenu(o))},listenerSetter:this.listenerSetter}),this.listenerSetter.add(I)("peer_block",d=>{const{peerId:u,blocked:h,blockedMyStoriesFrom:p}=d;if(p)return;const m=s.querySelector(`[data-peer-id="${u}"]`);h?m||i(u,!1):m&&m.dialogElement.remove()});const l=50;let c=!1;this.scrollable.onScrolledBottom=()=>{c||(c=!0,this.managers.appUsersManager.getBlocked(s.childElementCount,l).then(d=>{for(const u of d.peerIds)i(u,!0);(d.peerIds.length<l||s.childElementCount===d.count)&&(this.scrollable.onScrolledBottom=null),this.scrollable.checkForTriggers()}).finally(()=>{c=!1}))}}onOpenAfterTimeout(){this.scrollable.onScroll()}onCloseAfterTimeout(){return this.menuElement&&this.menuElement.remove(),super.onCloseAfterTimeout()}}function bM(a){return a=a[0].toUpperCase()+a.slice(1),a="input"+a,a}class j8 extends Bs{init(){this.container.classList.add("privacy-tab","privacy-voices"),this.setTitle("PrivacyVoiceMessages");const e="PrivacyVoiceMessagesInfo";new Mr({tab:this,title:"PrivacyVoiceMessagesTitle",inputKey:"inputPrivacyKeyVoiceMessages",captions:[e,e,e],exceptionTexts:["PrivacySettingsController.NeverAllow","PrivacySettingsController.AlwaysAllow"],appendTo:this.scrollable,managers:this.managers,premiumOnly:!0,premiumCaption:P("Privacy.VoiceMessagesPremiumCaption",[xi(()=>{rs.show()})]),premiumError:"PrivacySettings.Voice.PremiumError"})}}class q8 extends Bs{async init(e){this.container.classList.add("active-sessions-container"),this.setTitle("WebSessionsTitle");const t=async s=>{const i=s.bot_id.toPeerId(),n=new Fe({title:await qe({peerId:i}),subtitle:[s.ip,s.region].join(" - "),clickable:!0,titleRight:Au(new Date(Math.max(s.date_active,s.date_created)*1e3))}),r=n.createMedia("big"),o=vs({middleware:this.middlewareHelper.get(),size:48,peerId:i});return await o.readyThumbPromise,r.append(o.node),n.container.dataset.hash=""+s.hash,n.container.dataset.peerId=""+i,n.midtitle.textContent=[s.domain,s.browser,s.platform].filter(Boolean).join(", "),n};{const s=new Oe({caption:"ClearOtherWebSessionsHelp"}),i=ot("btn-primary btn-transparent danger",{icon:"stop",text:"TerminateAllWebSessions"});J(i,async()=>{await Rt({descriptionLangKey:"AreYouSureWebSessions",button:{langKey:"Disconnect",isDanger:!0}}),os([i],!0),this.managers.appSeamlessLoginManager.resetWebAuthorizations().then(()=>{this.close()})},{listenerSetter:this.listenerSetter}),s.content.append(i),this.scrollable.append(s.container)}{const s=new Oe({name:"OtherWebSessions",caption:"TerminateWebSessionInfo"}),i=await Promise.all(e.map(t));s.content.append(...i.map(r=>r.container));let n=i.length;J(s.content,async r=>{const o=ne(r.target,"row");if(!o)return;await Rt({descriptionLangKey:"TerminateWebSessionText",descriptionLangArgs:[await qe({peerId:o.dataset.peerId.toPeerId()})],button:{langKey:"Disconnect",isDanger:!0}});const l=o.dataset.hash;o.classList.add("is-disabled"),this.managers.appSeamlessLoginManager.resetWebAuthorization(l).then(()=>{--n?o.remove():this.close()})},{listenerSetter:this.listenerSetter}),this.scrollable.append(s.container)}}}class Y8 extends Bs{init(){this.container.classList.add("privacy-tab","privacy-about"),this.setTitle("UserBio");const e="Privacy.BioCaption";new Mr({tab:this,title:"Privacy.Bio",inputKey:"inputPrivacyKeyAbout",captions:[e,e,e],exceptionTexts:["PrivacySettingsController.NeverAllow","PrivacySettingsController.AlwaysAllow"],appendTo:this.scrollable,skipTypes:[li.Nobody],managers:this.managers})}}class wM extends Bs{static getInitArgs(e){return{appConfig:e.managers.apiManager.getAppConfig(),globalPrivacy:e.managers.appPrivacyManager.getGlobalPrivacySettings(),contentSettings:e.managers.apiManager.invokeApi("account.getContentSettings"),webAuthorizations:e.managers.appSeamlessLoginManager.getWebAuthorizations()}}async init(e){this.container.classList.add("dont-u-dare-block-me"),this.setTitle("PrivacySettings");const t="Loading",s=[];{const i=new Oe({noDelimiter:!0,caption:"SessionsInfo"});let n;const r=new Fe({icon:"deleteuser",titleLangKey:"BlockedUsers",subtitleLangKey:t,clickable:()=>{const y=this.slider.createTab(K8);y.peerIds=n,y.open()},listenerSetter:this.listenerSetter});r.freezed=!0;let o;const l={icon:"lock",titleLangKey:"TwoStepVerification",subtitleLangKey:t,clickable:y=>{let w;o.pFlags.has_password?w=this.slider.createTab(My):o.email_unconfirmed_pattern?(w=this.slider.createTab(fM),w.email=o.email_unconfirmed_pattern,w.length=6,w.isFirst=!0,this.managers.passwordManager.resendPasswordEmail()):w=this.slider.createTab(vM),w.state=o,w.open()},listenerSetter:this.listenerSetter},c=new Fe(l);c.freezed=!0;const d={icon:"key",titleLangKey:"PasscodeLock.Item.Title",subtitleLangKey:t,clickable:()=>{f?this.slider.createTab(LP).open({buttonText:"PasscodeLock.Next",inputLabel:"PasscodeLock.EnterYourPasscode",onSubmit:async(y,w,{isMyPasscode:b})=>{const S=await b(y);if(y="",!S)throw{};this.slider.createTab(dy).open()}}):this.slider.createTab(dy).open()},listenerSetter:this.listenerSetter},u=new Fe(d);u.freezed=!0;const h=this.activeSessionsRow=new Fe({icon:"activesessions",titleLangKey:"SessionsTitle",subtitleLangKey:t,clickable:()=>{const y=this.slider.createTab(yM);y.authorizations=this.authorizations,y.eventListener.addEventListener("destroy",()=>{this.updateActiveSessions()},{once:!0}),y.open()},listenerSetter:this.listenerSetter});h.freezed=!0;const p=this.websitesRow=new Fe({icon:"mention",titleLangKey:"OtherWebSessions",subtitleLangKey:t,clickable:()=>{const y=this.slider.createTab(q8);y.eventListener.addEventListener("destroy",()=>{this.updateActiveWebsites()}),y.open(this.websites)},listenerSetter:this.listenerSetter});p.freezed=!0,i.content.append(r.container,u.container,c.container,h.container,p.container),this.scrollable.append(i.container);const m=y=>{y?St(r.subtitle,P("PrivacySettingsController.UserCount",[y])):St(r.subtitle,P("BlockedEmpty",[y]))};this.listenerSetter.add(I)("peer_block",()=>{g()});const g=()=>{this.managers.appUsersManager.getBlocked().then(y=>{r.freezed=!1,m(y.count),n=y.peerIds})};g(),this.managers.passwordManager.getState().then(y=>{o=y,St(c.subtitle,P(y.pFlags.has_password?"PrivacyAndSecurity.Item.On":"PrivacyAndSecurity.Item.Off")),c.freezed=!1});let f;const v=y=>{f=y,St(u.subtitle,P(y?"PrivacyAndSecurity.Item.On":"PrivacyAndSecurity.Item.Off"))};this.managers.appStateManager.getState().then(y=>{u.freezed=!1,v(y.settings?.passcode?.enabled||!1)}),this.listenerSetter.add(I)("settings_updated",({key:y,value:w})=>{y===ci("settings","passcode","enabled")&&v(w)}),this.updateActiveSessions(),s.push(this.updateActiveWebsites(e.webAuthorizations))}{const i=await Ae.isPremiumFeaturesHidden(),n=new Oe({name:"PrivacyTitle",caption:i?"GroupsAndChannelsHelp":"Privacy.MessagesCaption"});n.content.classList.add("privacy-navigation-container");const r={},o=async(w,b)=>{const S=await e.globalPrivacy,_=this.slider.createTab(w);_.open(S),_.eventListener.addEventListener("privacy",M=>{e.globalPrivacy=M,y(b)})},l=r.inputPrivacyKeyPhoneNumber=new Fe({titleLangKey:"PrivacyPhoneTitle",subtitleLangKey:t,clickable:()=>{this.slider.createTab(N8).open()},listenerSetter:this.listenerSetter}),c=r.inputPrivacyKeyStatusTimestamp=new Fe({titleLangKey:"LastSeenTitle",subtitleLangKey:t,clickable:()=>{o(H8,"inputPrivacyKeyStatusTimestamp")},listenerSetter:this.listenerSetter}),d=r.inputPrivacyKeyProfilePhoto=new Fe({titleLangKey:"PrivacyProfilePhotoTitle",subtitleLangKey:t,clickable:()=>{this.slider.createTab(G8).open()},listenerSetter:this.listenerSetter}),u=r.inputPrivacyKeyAbout=new Fe({titleLangKey:"Privacy.BioRow",subtitleLangKey:t,clickable:()=>{this.slider.createTab(Y8).open()},listenerSetter:this.listenerSetter}),h=r.inputPrivacyKeyPhoneCall=new Fe({titleLangKey:"WhoCanCallMe",subtitleLangKey:t,clickable:()=>{this.slider.createTab(W8).open()},listenerSetter:this.listenerSetter}),p=r.inputPrivacyKeyForwards=new Fe({titleLangKey:"PrivacyForwardsTitle",subtitleLangKey:t,clickable:()=>{this.slider.createTab(V8).open()},listenerSetter:this.listenerSetter}),m=r.inputPrivacyKeyChatInvite=new Fe({titleLangKey:"WhoCanAddMe",subtitleLangKey:t,clickable:()=>{this.slider.createTab(z8).open()},listenerSetter:this.listenerSetter}),g=w=>{const b=document.createDocumentFragment(),S=Be("star","privacy-premium-icon");b.append(P(w),S);const _=()=>{S.classList.toggle("hide",!I.premium)};return _(),this.listenerSetter.add(I)("premium_toggle",_),b};let f;i||(f=r.inputPrivacyKeyVoiceMessages=new Fe({title:g("PrivacyVoiceMessagesTitle"),subtitleLangKey:t,clickable:()=>{this.slider.createTab(j8).open()},listenerSetter:this.listenerSetter}));let v;i||(v=r.new_noncontact_peers_require_premium=new Fe({title:g("PrivacyMessagesTitle"),subtitleLangKey:t,clickable:()=>{this.slider.createTab(y7).open({onSaved:w=>{e.globalPrivacy=w,y("new_noncontact_peers_require_premium")}})},listenerSetter:this.listenerSetter}));const y=w=>{const b=r[w];if(!b)return;const S={[li.Everybody]:"PrivacySettingsController.Everbody",[li.Contacts]:"PrivacySettingsController.MyContacts",[li.Nobody]:"PrivacySettingsController.Nobody"},_=M=>I.premium?+M.noncontact_peers_paid_stars?"PrivacySettingsController.Paid":M.pFlags.new_noncontact_peers_require_premium?"Privacy.ContactsAndPremium":S[li.Everybody]:S[li.Everybody];if(!w.startsWith("inputPrivacy")){e.globalPrivacy.then(M=>{const C=_(M);b.subtitle.replaceChildren(P(C))});return}this.managers.appPrivacyManager.getPrivacy(w).then(M=>{const C=mM(M),L=S[C.type],E=C.disallowPeers.users.length+C.disallowPeers.chats.length,x=C.allowPeers.users.length+C.allowPeers.chats.length,R=P(L);b.subtitle.replaceChildren(R),(E||x)&&b.subtitle.append(` (${[-E,x?"+"+x:0].filter(Boolean).join(", ")})`)})};n.content.append(...[l,c,d,u,h,p,m,f,v].filter(Boolean).map(w=>w.container)),this.scrollable.append(n.container);for(const w in r)y(w);I.addEventListener("privacy_update",w=>{y(bM(w.key._))})}{const i=new Oe({name:"NewChatsFromNonContacts",caption:"ArchiveAndMuteInfo"}),n=new _t({text:"ArchiveAndMute"}),r=new Fe({checkboxField:n});i.content.append(r.container);let o,l;this.eventListener.addEventListener("destroy",async()=>{if(l=!0,!(o===void 0||o===n.checked))return this.managers.appPrivacyManager.setGlobalPrivacySettings({_:"globalPrivacySettings",pFlags:{...(await e.globalPrivacy).pFlags,archive_and_mute_new_noncontact_peers:n.checked||void 0}})},{once:!0});const c=Promise.all([e.appConfig,e.globalPrivacy]).then(([d,u])=>{if(l)return;const h=p=>{i.container.classList.toggle("hide",!p&&!d.autoarchive_setting_available)};this.listenerSetter.add(I)("premium_toggle",h),h(I.premium),o=!!u.pFlags.archive_and_mute_new_noncontact_peers,n.setValueSilently(o)});s.push(c),this.scrollable.append(i.container)}{const i=new Oe({name:"Privacy.SensitiveContent",caption:"PrivacyAndSecurity.SensitiveDesc"});i.container.classList.add("hide");const n=new _t({text:"PrivacyAndSecurity.SensitiveText"}),r=new Fe({checkboxField:n});i.content.append(r.container);let o;this.eventListener.addEventListener("destroy",()=>{if(o===void 0)return;const c=r.checkboxField.checked;if(c!==o)return this.managers.apiManager.invokeApi("account.setContentSettings",{sensitive_enabled:c})},{once:!0});const l=e.contentSettings.then(c=>{c.pFlags.sensitive_can_change&&(o=!!c.pFlags.sensitive_enabled,n.setValueSilently(o),i.container.classList.remove("hide"))});s.push(l),this.scrollable.append(i.container)}{const i=new Oe({name:"PrivacyPayments",caption:"PrivacyPaymentsClearInfo"}),n=()=>{const o={titleLangKey:"PrivacyPaymentsClearAlertTitle",descriptionLangKey:"PrivacyPaymentsClearAlertText",button:{langKey:"Clear"},checkboxes:[{text:"PrivacyClearShipping",checked:!0},{text:"PrivacyClearPayment",checked:!0}]};Rt(o).then(()=>{const[l,c]=o.checkboxes.map(u=>u.checkboxField.checked),d=os([r],!0);this.managers.appPaymentsManager.clearSavedInfo(l,c).then(()=>{!l&&!c||(d(),$e({langPackKey:l&&c?"PrivacyPaymentsPaymentShippingCleared":l?"PrivacyPaymentsShippingInfoCleared":"PrivacyPaymentsPaymentInfoCleared"}))})},as)},r=ot("btn-primary btn-transparent",{icon:"delete",text:"PrivacyPaymentsClear"});this.listenerSetter.add(r)("click",n),i.content.append(r),this.scrollable.append(i.container)}{const i=new Oe({name:"FilterChats"}),n=()=>{ue.createPopup(mi,"popup-delete-drafts",{buttons:[{langKey:"Delete",callback:()=>{const l=os([r],!0);this.managers.appDraftsManager.clearAllDrafts().then(()=>{l()})},isDanger:!0}],titleLangKey:"AreYouSureClearDraftsTitle",descriptionLangKey:"AreYouSureClearDrafts"}).show()},r=ot("btn-primary btn-transparent",{icon:"delete",text:"PrivacyDeleteCloudDrafts"});this.listenerSetter.add(r)("click",n),i.content.append(r),this.scrollable.append(i.container)}return Promise.all(s)}updateActiveSessions(){return this.managers.apiManager.invokeApi("account.getAuthorizations").then(e=>{this.activeSessionsRow.freezed=!1,this.authorizations=e.authorizations,ks(this.activeSessionsRow.subtitle,"Privacy.Devices",[this.authorizations.length])})}updateActiveWebsites(e=this.managers.appSeamlessLoginManager.getWebAuthorizations()){return e.then(t=>{this.websitesRow.freezed=!1,this.websites=t,ks(this.websitesRow.subtitle,"Privacy.Websites",[this.websites.length]),this.websitesRow.container.classList.toggle("hide",!this.websites.length)})}}tf.AppPrivacyAndSecurityTab=wM;class Q8 extends Zt{constructor(){super(...arguments),this._applyColor=(e,t=!0)=>{if(t)this.colorPicker.setColor(e);else{const s=JC(e),i=this.theme.settings,n=ib(s),r={_:"wallPaperNoFile",id:0,pFlags:{},settings:{_:"wallPaperSettings",background_color:parseInt(e.slice(1),16),pFlags:{}}};i.wallpaper=r,i.highlightingColor=n,this.managers.appStateManager.pushToState("settings",I.settings),Ce.applyCurrentTheme({broadcastEvent:!0}),this.setActive()}},this.onColorChange=e=>{this.applyColor(e.hex,!1)}}init(){this.container.classList.add("background-container","background-color-container"),this.setTitle("SetColor"),this.theme=Ls.getTheme();const e=new Oe({});this.colorPicker=new rP,e.content.append(this.colorPicker.container),this.scrollable.append(e.container);const t=new Oe({}),s=this.grid=document.createElement("div");s.classList.add("grid"),["#E6EBEE","#B2CEE1","#008DD0","#C6E7CB","#C4E1A6","#60B16E","#CCD0AF","#A6A997","#7A7072","#FDD7AF","#FDB76E","#DD8851"].forEach(n=>{const r=document.createElement("div");r.classList.add("grid-item"),r.dataset.color=n.toLowerCase();const o=document.createElement("div");o.classList.add("grid-item-media"),o.style.backgroundColor=n,r.append(o),s.append(r)}),J(s,n=>{const r=ne(n.target,"grid-item");if(!r||r.classList.contains("active"))return;const o=r.dataset.color;o&&this.applyColor(o)},{listenerSetter:this.listenerSetter}),t.content.append(s),this.scrollable.append(t.container),this.applyColor=fa(this._applyColor,16,!0)}setActive(){const e=this.grid.querySelector(".active"),i=this.theme.settings.wallpaper.settings.background_color,n=i?this.grid.querySelector(`.grid-item[data-color="${i}"]`):null;e!==n&&(e&&e.classList.remove("active"),n&&n.classList.add("active"))}onOpen(){setTimeout(()=>{const e=this.theme.settings,t=e?.wallpaper?.settings?.background_color,s=!!t&&e.wallpaper._==="wallPaperNoFile";s&&(this.colorPicker.onChange=this.onColorChange),this.colorPicker.setColor(t&&"#"+t.toString(16)||"#cccccc"),s||(this.colorPicker.onChange=this.onColorChange)},0)}onCloseAfterTimeout(){return this.colorPicker.onChange=void 0,this.colorPicker=void 0,super.onCloseAfterTimeout()}}function X8(a){const e=document.createElement("input");e.type="file",e.style.display="none",e.accept=a,document.body.append(e);const t=new Promise((s,i)=>{e.addEventListener("change",n=>{const r=n.target.files[0];if(!r){i("NO_FILE_SELECTED");return}s(r)},{once:!0})}).finally(()=>{e.remove()});return e.click(),t}const Np=(a,e=!0)=>!!(a?.settings?.pFlags?.blur&&(!e||!a.pFlags.pattern)),lr=class lr extends Zt{constructor(){super(...arguments),this.clicked=new Set,this.wallPapersByElement=new Map,this.elementsByKey=new Map,this.onUploadClick=()=>{X8("image/x-png,image/png,image/jpeg").then(async e=>{if(e.name.endsWith(".png")){const c=document.createElement("img"),d=URL.createObjectURL(e);await Vn(c,d,!1);const u="image/jpeg",{blob:h}=await Fm({media:c,size:new Lv(c.naturalWidth,c.naturalHeight),mimeType:u});e=new File([h],e.name.replace(/\.png$/,".jpg"),{type:u})}const t=await this.managers.appDocsManager.prepareWallPaperUpload(e),s=this.managers.appDocsManager.uploadWallPaper(t.id),i=fs.getNewDeferredForUpload(e.name,s),n=Mt();n.addNotifyListener=i.addNotifyListener.bind(i),n.cancel=i.cancel,i.then(c=>{this.clicked.delete(r),this.elementsByKey.delete(r),this.wallPapersByElement.set(l,c);const d=this.getWallPaperKey(c);this.elementsByKey.set(d,l),this.setBackgroundDocument(c).then(n.resolve.bind(n),n.reject.bind(n))},n.reject.bind(n));const r=this.getWallPaperKey(t);n.catch(()=>{l.remove()});const o=new Kn({isUpload:!0,cancelable:!0,tryAgainOnFail:!1}),{container:l}=await this.addWallPaper(t,!1);this.clicked.add(r),o.attach(l,!1,n)})},this.onResetClick=()=>{const e=wl.themes.find(t=>t.name===this.theme.name);e&&(++lr.tempId,this.theme.settings=kn(e.settings),this.managers.appStateManager.pushToState("settings",I.settings),Ce.applyCurrentTheme({broadcastEvent:!0}),this.blurCheckboxField.setValueSilently(Np(this.theme.settings?.wallpaper,!1)))},this.onGridClick=e=>{const t=ne(e.target,"grid-item");if(!t)return;const s=this.wallPapersByElement.get(t);if(s._==="wallPaperNoFile"){this.setBackgroundDocument(s);return}const i=this.getWallPaperKey(s);if(this.clicked.has(i))return;this.clicked.add(i);const n=s.document,r=new Kn({cancelable:!0,tryAgainOnFail:!1}),o=async()=>{const l=this.setBackgroundDocument(s);(!(await this.managers.thumbsStorage.getCacheContext(n)).url||Np(s))&&r.attach(t,!0,l)};r.construct(),J(t,l=>{r.preloader.parentElement?(r.onClick(l),r.detach()):o()},{listenerSetter:this.listenerSetter}),o()},this.setBackgroundDocument=async(e,t)=>(this.blurCheckboxField.isDisabled()||await this.changeWallPaperBlur(e,this.blurCheckboxField.checked),lr.setBackgroundDocument(e,t)),this.setActive=()=>{const e=this.grid.querySelector(".active"),t=this.elementsByKey.get(this.getWallPaperKeyFromTheme(this.theme));e!==t&&(this.toggleBlurCheckbox(),e&&e.classList.remove("active"),t&&t.classList.add("active"))}}static getInitArgs(){return{backgrounds:I.managers.appThemesManager.getWallPapers()}}get theme(){return Ls.getTheme()}init(e=lr.getInitArgs()){this.container.classList.add("background-container","background-image-container"),this.setTitle("ChatBackground");{const n=Xc(this.scrollable),r=ot("btn-primary btn-transparent",{icon:"cameraadd",text:"ChatBackground.UploadWallpaper"}),o=ot("btn-primary btn-transparent",{icon:"colorize",text:"SetColor"}),l=ot("btn-primary btn-transparent",{icon:"favourites",text:"Appearance.Reset"});J(r,this.onUploadClick,{listenerSetter:this.listenerSetter}),J(o,()=>{this.slider.createTab(Q8).open()},{listenerSetter:this.listenerSetter}),J(l,this.onResetClick,{listenerSetter:this.listenerSetter});const c=this.theme.settings?.wallpaper,d=this.blurCheckboxField=new _t({text:"ChatBackground.Blur",name:"blur",checked:Np(c,!1)});this.toggleBlurCheckbox(),this.listenerSetter.add(d.input)("change",async()=>{await this.changeWallPaperBlur(this.theme.settings.wallpaper,d.checked),setTimeout(()=>{const u=i.querySelector(".active");if(!u)return;const h=this.wallPapersByElement.get(u);h.pFlags.pattern||h._==="wallPaperNoFile"||this.setBackgroundDocument(h)},100)}),n.append(r,o,l,jr(d).container)}I.addEventListener("background_change",this.setActive);const t=e.backgrounds.then(n=>{const r=n.map(o=>this.addWallPaper(o));return Promise.all(r)}),s=Xc(this.scrollable),i=this.grid=document.createElement("div");return i.classList.add("grid"),J(i,this.onGridClick,{listenerSetter:this.listenerSetter}),s.append(i),t}getWallPaperKey(e){return""+e.id}getWallPaperKeyFromTheme(e){return""+(this.getWallPaperKey(e.settings?.wallpaper)||"")}static addWallPaper(e,t=document.createElement("div")){const s=_v(e),i=e._==="wallPaper";if(i&&e.pFlags.pattern&&!s)return;const n=!!e.pFlags.dark;let r=i?e.document:void 0;i&&!r&&(r={_:"webDocumentNoProxy",attributes:[],size:1e5,url:"assets/img/pattern.svg",w:1440,h:2960,mime_type:"image/svg+xml"}),t.classList.add("background-item"),t.dataset.id=""+e.id;const o=document.createElement("div");o.classList.add("background-item-media");const l=[];let c,d;if(i){d=ha(r,200,200),c=Bi({photo:r,message:null,container:o,withoutPreloader:!0,size:d,noFadeIn:e.pFlags.pattern}),e.pFlags.pattern&&o.classList.add("is-pattern");const u=c.then(async({loadPromises:h,images:p})=>(await h.thumb||h.full,p)).then(h=>(e.pFlags.pattern&&(n?(h.full.style.display="none",h.thumb&&(h.thumb.style.display="none")):e.settings?.intensity&&(h.full.style.opacity=""+Math.abs(e.settings.intensity)/100)),lm.mutate(()=>{t.append(o)})));l.push(u)}else t.append(o);if(e.settings?.background_color){const{canvas:u}=kv.create(s);if(u.classList.add("background-colors-canvas"),n&&i){const h=c.then(({loadPromises:p})=>p.full.then(async()=>{const m=await I.managers.thumbsStorage.getCacheContext(r,d.type);u.style.webkitMaskImage=`url(${m.url})`,u.style.opacity=""+(e.pFlags.dark?100+e.settings.intensity:e.settings.intensity)/100,o.append(u)}));l.push(h)}else o.append(u)}return{container:t,media:o,loadPromise:Promise.all(l)}}addWallPaper(e,t=!0){const s=lr.addWallPaper(e);if(s){const{container:i,media:n}=s;i.classList.add("grid-item"),n.classList.add("grid-item-media");const r=this.getWallPaperKey(e);this.wallPapersByElement.set(i,e),this.elementsByKey.set(r,i),this.getWallPaperKeyFromTheme(this.theme)===r&&i.classList.add("active"),this.grid[t?"append":"prepend"](i)}return s&&s.loadPromise.then(()=>s)}async changeWallPaperBlur(e,t){(e.settings??(e.settings={_:"wallPaperSettings",pFlags:{}})).pFlags.blur=t||void 0,await this.managers.appStateManager.pushToState("settings",I.settings)}toggleBlurCheckbox(){const e=this.theme.settings?.wallpaper;this.blurCheckboxField.toggleDisability(!e||e._==="wallPaperNoFile"||!!e?.pFlags?.pattern)}};lr.tempId=0,lr.setBackgroundDocument=(e,t)=>{const s=++lr.tempId,i=()=>s===lr.tempId,n=e.document,r=Mt();let o;return n?(o=fs.downloadMediaURL({media:n,queueId:Ce.chat.bubbles?Ce.chat.bubbles.lazyLoadQueue.queueId:0}),r.addNotifyListener=o.addNotifyListener.bind(o),r.cancel=o.cancel):o=Promise.resolve(),o.then(async()=>{if(!i()){r.resolve();return}const l=!!t;t??(t=Ls.getTheme().settings);const c=u=>{let h;const p=_v(e);if(u&&!p)h=qE(u);else{const{canvas:g}=kv.create(p);h=Promise.resolve(g_(g))}const m=e.slug;Promise.all([h,kc.saveWallPaperToCache(m,u)]).then(([g])=>{if(!i()){r.resolve();return}const f=ib(Array.from(g));t.wallpaper=e,t.highlightingColor=f,l||I.managers.appStateManager.pushToState("settings",I.settings),Ce.applyCurrentTheme({slug:m,backgroundUrl:u,broadcastEvent:!0}).then(r.resolve.bind(r))})};if(!n){c();return}const d=await I.managers.thumbsStorage.getCacheContext(n);Np(e)?setTimeout(()=>{kc.blurWallPaperImage(d.url).then(u=>{if(!i()){r.resolve();return}c(u)})},200):i()&&c(d.url)}),r};let Dc=lr;function Z8(a,e){return Bb(a,()=>(60-new Date().getSeconds())*1e3,e)}class SM extends Zt{init(){this.container.classList.add("power-saving-container"),this.setTitle("LiteMode.Title");const e=document.createElement("form");let t;{const o=t=new Oe({caption:"LiteMode.Info"});e.append(o.container)}const s=["all","video","gif",["stickers",["stickers_panel","stickers_chat"]],["effects",["effects_reactions","effects_premiumstickers","effects_emoji"]],["chat",["chat_background","chat_spoilers"]],"animations"];let i,n;{const o=new Oe({}),l=c=>{const d=Array.isArray(c),u=d?c[0]:c,h=d?va(c[1].map(l)):void 0,p=I.settings.liteMode[u];return[{key:u,text:u==="all"?"LiteMode.EnableText":`LiteMode.Key.${u}.Title`,checked:u==="all"?p:!p,nested:h,name:"power-saving-"+u},...h||[]]};i=va(s.map(l)),n=new $g({fields:i,listenerSetter:this.listenerSetter}),i.forEach((c,d)=>{const u=n.createField(c);if(!u)return;const{row:h,nodes:p}=u;(d===0?t:o).content.append(...p)}),J(o.content,()=>{I.settings.liteMode.all&&$e({langPackKey:"LiteMode.DisableAlert"})},{listenerSetter:this.listenerSetter}),e.append(o.container)}const r=o=>{i.forEach(l=>{l.key!=="all"&&(l.nested&&n.setNestedCounter(l,o?0:void 0),l.checkboxField.input.classList.toggle("is-fake-disabled",o),l.row.toggleDisability(o))})};this.listenerSetter.add(e)("change",async()=>{const o={};i.forEach(c=>{const d=c.checkboxField.checked;o[c.key]=c.key==="all"?d:!d});const l=I.settings.liteMode.all;l!==o.all&&(r(!l),o.all&&await ns(200)),await this.managers.appStateManager.setByKey(ci("settings","liteMode"),I.settings.liteMode=o)}),r(I.settings.liteMode.all),this.scrollable.append(e)}}class CM{constructor(e,t,s,i,n,r=!0){const o="range-setting-selector";this.container=document.createElement("div"),this.container.classList.add(o);const l=document.createElement("div");l.classList.add(o+"-details");const c=document.createElement("div");c.classList.add(o+"-name"),ks(c,e);const d=this.valueContainer=document.createElement("div");d.classList.add(o+"-value"),r&&(d.innerHTML=""+s),l.append(c,d),this.range=new Xl({step:t,min:i,max:n},s),this.range.setListeners(),this.range.setHandlers({onScrub:u=>{this.onChange&&this.onChange(u),r&&(d.innerText=""+u)}}),this.container.append(l,this.range.container)}}class J8 extends Bs{static getInitArgs(){return{themes:I.managers.appThemesManager.getThemes()}}init(e){this.container.classList.add("general-settings-container"),this.setTitle("General");const t=Xc.bind(null,this.scrollable),s=[];{const i=t("Settings"),n=new CM("TextSize",1,I.settings.messagesTextSize,12,20);n.onChange=m=>{I.managers.appStateManager.setByKey(ci("settings","messagesTextSize"),m)};const r=ot("btn-primary btn-transparent",{icon:"image",text:"ChatBackground"}),o=Dc.getInitArgs();J(r,()=>{this.slider.createTab(Dc).open(o)});const l=()=>I.settings.liteMode.all?"Checkbox.Enabled":"Checkbox.Disabled",c=new Ne.IntlElement,d=()=>{c.compareAndUpdate({key:l()}),u.setValueSilently(wt.isAvailable("animations")),u.toggleDisability(wt.isEnabled())},u=new _t({text:"EnableAnimations",name:"animations",stateKey:ci("settings","liteMode","animations"),stateValueReverse:!0,checked:!1,listenerSetter:this.listenerSetter}),h=new Fe({checkboxField:u,clickable:()=>{u.isDisabled()&&$e({langPackKey:"LiteMode.DisableAlert"})},listenerSetter:this.listenerSetter}),p=new Fe({icon:"animations",titleLangKey:"LiteMode.EnableText",titleRightSecondary:c.element,clickable:()=>{this.slider.createTab(SM).open()},listenerSetter:this.listenerSetter});d(),this.listenerSetter.add(I)("settings_updated",d),i.append(n.container,r,h.container,p.container)}{const i=t("ColorTheme"),n=new io(null),r=n.container;r.classList.add("themes-container");const o=new Map;let l=Ls.getTheme(),c=Ls.isNight();const d=b=>{Ls.applyTheme(b.theme,b.container),b.container.querySelector(".background-item")?.remove();const _=b.wallPaperContainers[c?"baseThemeNight":"baseThemeClassic"];_&&b.container.prepend(_)};let u;J(r,async b=>{const S=ne(b.target,"theme-container");if(!S)return;const _=r.querySelector(".active");_&&_.classList.remove("active");const M=o.get(S);if(S.classList.add("active"),await Ls.applyNewTheme(M.theme),u?.(-1),M.player&&wt.isAvailable("animations"))if(dn)M.player.paused&&M.player.restart();else{M.player.paused&&M.player.stop(!0),M.player.el[0].style.transform="scale(2)";const C=u=L=>{(M.player.maxFrame===L||L===-1)&&(M.player.el[0].style.transform="",M.player.removeEventListener("enterFrame",C),u===C&&(u=void 0))};setTimeout(()=>{u===C&&(M.player.play(),M.player.addEventListener("enterFrame",C))},250)}},{listenerSetter:this.listenerSetter});const h=new Set(["baseThemeClassic","baseThemeNight"]),p=e.themes.then(async b=>{const S=b.filter(C=>C.pFlags.default);S.unshift(pE);const _=S.map(async C=>{const L=document.createElement("div"),E={container:L,theme:C,wallPaperContainers:{}},x=C.settings.filter($=>h.has($.base_theme._)).map($=>{const H=$.wallpaper,D=Dc.addWallPaper(H);return E.wallPaperContainers[$.base_theme._]=D.container,D});o.set(L,E),d(E),C.id===l.id&&L.classList.add("active");const R=C.emoticon,B=[];let N;if(R){N=document.createElement("div"),N.classList.add("theme-emoticon");const $=28*1.75;Xo({div:N,width:$,height:$,emoji:C.emoticon,managers:this.managers,loadPromises:B,middleware:this.middlewareHelper.get(),play:!1}).then(({render:H})=>H).then(H=>{E.player=H})}const G=document.createElement("div");G.classList.add("theme-bubble");const O=G.cloneNode();return O.classList.add("is-in"),G.classList.add("is-out"),B.push(...x.map($=>$.loadPromise)),L.classList.add("theme-container"),await Promise.all(B),N&&L.append(N),L.append(O,G),L}),M=await Promise.all(_);n.append(...M)});s.push(p);const m=document.createElement("form");m.style.marginTop=".5rem";const g="theme",f=ci("settings","theme"),v=new Fe({radioField:new rn({langKey:"ThemeDay",name:g,value:"day",stateKey:f})}),y=new Fe({radioField:new rn({langKey:"ThemeNight",name:g,value:"night",stateKey:f})}),w=new Fe({radioField:new rn({langKey:"AutoNightSystemDefault",name:g,value:"system",stateKey:f})});this.listenerSetter.add(I)("settings_updated",({key:b,value:S,settings:_})=>{b===f&&I.dispatchEvent("theme_change")}),this.listenerSetter.add(I)("theme_changed",()=>{l=Ls.getTheme();const b=Ls.isNight();if(c===b)return;c=b;const S=r.querySelector(".active");S&&S.classList.remove("active");let _;o.forEach(M=>{d(M),M.theme.id===l.id&&(M.container.classList.add("active"),_=M.container)}),_&&n.scrollIntoViewNew({element:_,position:"center",axis:"x"})}),m.append(v.container,y.container,w.container),i.append(r,m)}{const i=t("General.Keyboard"),n=document.createElement("form"),r="send-shortcut",o=ci("settings","sendShortcut"),l=new Fe({radioField:new rn({langKey:"General.SendShortcut.Enter",name:r,value:"enter",stateKey:o}),subtitleLangKey:"General.SendShortcut.NewLine.ShiftEnter"}),c=new Fe({radioField:new rn({name:r,value:"ctrlEnter",stateKey:o}),subtitleLangKey:"General.SendShortcut.NewLine.Enter"});ks(c.radioField.main,"General.SendShortcut.CtrlEnter",[$o?"⌘":"Ctrl"]),n.append(l.container,c.container),i.append(n)}if(mE){const i=t("DistanceUnitsTitle"),n=document.createElement("form"),r="distance-unit",o=ci("settings","distanceUnit"),l=new Fe({radioField:new rn({langKey:"DistanceUnitsKilometers",name:r,value:"kilometers",stateKey:o})}),c=new Fe({radioField:new rn({langKey:"DistanceUnitsMiles",name:r,value:"miles",stateKey:o})});n.append(l.container,c.container),i.append(n)}{const i=t("General.TimeFormat"),n=document.createElement("form"),r="time-format",o=ci("settings","timeFormat"),l=[["h12","General.TimeFormat.h12"],["h23","General.TimeFormat.h23"]],c=l.map(([u,h])=>new Fe({radioField:new rn({langKey:h,name:r,value:u,stateKey:o})})),d=Z8(()=>{const u=new Date;l.forEach(([h],p)=>{const m=u.toLocaleTimeString("en-us-u-hc-"+h,{hour:"2-digit",minute:"2-digit"});c[p].subtitle.textContent=m})});this.eventListener.addEventListener("destroy",d),n.append(...c.map(u=>u.container)),i.append(n)}return Promise.all(s)}}class eN extends Bs{init(){this.container.classList.add("notifications-container"),this.setTitle("Telegram.NotificationSettingsViewController");const e=i=>{const n=new Oe({name:i.name}),r=new Fe({checkboxField:new _t({text:i.typeText,checked:!0}),subtitleLangKey:"Loading",listenerSetter:this.listenerSetter,withCheckboxSubtitle:!0}),o=new Fe({checkboxField:new _t({text:"MessagePreview",checked:!0}),subtitleLangKey:"Loading",listenerSetter:this.listenerSetter,withCheckboxSubtitle:!0});n.content.append(r.container,o.container),this.scrollable.append(n.container);const l={_:i.inputKey},c=this.managers.appNotificationsManager.getNotifySettings(l);(c instanceof Promise?c:Promise.resolve(c)).then(d=>{const u=async()=>{const h=await this.managers.appNotificationsManager.isMuted(d);return r.checkboxField.checked=!h,o.checkboxField.checked=d.show_previews,h};u(),this.eventListener.addEventListener("destroy",async()=>{const h=!r.checkboxField.checked,p=o.checkboxField.checked;if(h===await this.managers.appNotificationsManager.isMuted(d)&&p===d.show_previews)return;const m=kn(d);m._="inputPeerNotifySettings",m.mute_until=h?NC:0,m.show_previews=p,this.managers.appNotificationsManager.updateNotifySettings(l,m)},{once:!0}),this.listenerSetter.add(I)("notify_settings",h=>{const p=bM(h.peer._);i.inputKey===p&&(d=h.notify_settings,u())})})},t=new Oe({name:"MultiAccount.ShowNotificationsFrom",caption:"MultiAccount.ShowNotificationsFromCaption"}),s=new Fe({titleLangKey:"MultiAccount.AllAccounts",checkboxField:new _t({name:"all-accounts",stateKey:ci("settings","notifyAllAccounts"),toggle:!0})});t.content.append(s.container),this.scrollable.append(t.container),e({name:"NotificationsPrivateChats",typeText:"NotificationsForPrivateChats",inputKey:"inputNotifyUsers"}),e({name:"NotificationsGroups",typeText:"NotificationsForGroups",inputKey:"inputNotifyChats"}),e({name:"NotificationsChannels",typeText:"NotificationsForChannels",inputKey:"inputNotifyBroadcasts"});{const i=new Oe({name:"NotificationsOther"}),n=new Fe({checkboxField:new _t({text:"ContactJoined",checked:!0}),subtitleLangKey:"Loading",listenerSetter:this.listenerSetter,withCheckboxSubtitle:!0}),r=new Fe({checkboxField:new _t({text:"Notifications.Sound",checked:I.settings.notifications.sound,stateKey:ci("settings","notifications","sound"),listenerSetter:this.listenerSetter}),subtitleLangKey:"Loading",listenerSetter:this.listenerSetter,withCheckboxSubtitle:!0});i.content.append(n.container,r.container),this.scrollable.append(i.container),this.managers.appNotificationsManager.getContactSignUpNotification().then(o=>{n.checkboxField.checked=o,this.eventListener.addEventListener("destroy",()=>{const l=n.checkboxField.checked;o!==l&&this.managers.appNotificationsManager.setContactSignUpNotification(!l)},{once:!0})})}}}class pC extends Zt{static getInitArgs(){return{languages1:I.managers.apiManager.invokeApiCacheable("langpack.getLanguages",{lang_pack:"web"}),languages2:Promise.resolve([])}}init(e){this.header.classList.add("with-border"),this.container.classList.add("language-container"),this.setTitle("Telegram.LanguageViewController");const t=Ft(r=>{this.middlewareHelper.get().onDestroy(r);const[o,l]=Ho(),c=Ig(),d=V(()=>{const h=o.translations.doNotTranslate;return h.length?h:[Ne.langCodeNormalized()]});let u;return T(Ms,{ref(h){const p=u;typeof p=="function"?p(h):u=h},name:"TranslateMessages",get caption(){return c()?"Translation.DoNotShow":"Language.TranslateMessages.Channel.Premium"},get captionArgs(){return[xi(()=>{rs.show({feature:"translations"})})]},get children(){return[T(En,{get title(){return P("ShowTranslateButton")},get checkboxFieldToggle(){return T(xc,{get checked(){return o.translations.showInMenu},toggle:!0,onChange:h=>{l("translations","showInMenu",h)}})}}),T(En,{get title(){return P("ShowTranslateChatButton")},get checkboxFieldToggle(){return T(xc,{get checked(){return o.translations.enabled},toggle:!0,onChange:h=>{l("translations","enabled",h)}})},get fakeDisabled(){return!c()},clickable:h=>{c()||(h.preventDefault(),rs.show({feature:"translations"}))}}),V(()=>V(()=>!!o.translations.enabled)()&&T(En,{get title(){return P("DoNotTranslate")},get titleRight(){return V(()=>d().length<3)()?Yi(d().map(h=>P(`Language.${h}`)),!1):P("Languages",[d().length])},titleRightSecondary:!0,clickable:async()=>{const h=await ow(!0,d());l("translations","doNotTranslate",h)}}))]}}),u}),s=new Oe({}),i=new Map,n=Promise.all([e.languages1,e.languages2]).then(([r,o])=>{const l=new Set,c=r.map(h=>h.lang_code),d=xu();r.concat(o).forEach(h=>{if(l.has(h.lang_code))return;l.add(h.lang_code);const p=new Fe({radioField:new rn({text:h.name,name:d,value:h.lang_code}),subtitle:h.native_name});i.set(h.lang_code,p)});const u=Sd([...i.values()],h=>{Ne.getLangPack(h,c.includes(h))});Ne.getCacheLangPack().then(h=>{const p=i.get(h.lang_code);if(!p){console.error("no row",p,h);return}p.radioField.setValueSilently(!0)}),s.content.append(u)});return this.scrollable.append(t,s.container),n}}function Cw(a,e,t){const s=new Oe({name:e}),i=ci("settings","autoDownload",a),n=new _t({text:"AutodownloadContacts",name:"contacts",stateKey:ci(i,"contacts"),listenerSetter:t}),r=new _t({text:"AutodownloadPrivateChats",name:"private",stateKey:ci(i,"private"),listenerSetter:t}),o=new _t({text:"AutodownloadGroupChats",name:"groups",stateKey:ci(i,"groups"),listenerSetter:t}),l=new _t({text:"AutodownloadChannels",name:"channels",stateKey:ci(i,"channels"),listenerSetter:t});return s.content.append(jr(n).container,jr(r).container,jr(o).container,jr(l).container),s}class tN extends Bs{init(){this.setTitle("AutoDownloadPhotos");const e=Cw("photo","AutoDownloadPhotosTitle",this.listenerSetter);this.scrollable.append(e.container)}}class sN extends Bs{init(){this.setTitle("AutoDownloadFiles");const e=$i(d=>{this.managers.appStateManager.setByKey(ci("settings","autoDownloadNew","file_size_max"),d)},200,!1,!0),t=Cw("file","AutoDownloadFilesTitle",this.listenerSetter),s=512*1024,n=20*1024*1024-s,r=I.settings.autoDownloadNew.file_size_max,o=Math.sqrt(Math.sqrt((r-s)/n)),l=new Ne.IntlElement({key:"AutodownloadSizeLimitUpTo",args:[ur(r)]}),c=new CM("AutoDownloadMaxFileSize",.01,o,0,1,!1);c.onChange=d=>{const u=d**4*n+s|0;l.compareAndUpdate({args:[ur(u)]}),e(u)},c.valueContainer.append(l.element),t.content.append(c.container),this.scrollable.append(t.container)}}class iN extends Bs{init(){this.setTitle("AutoDownloadVideos");const e=Cw("video","AutoDownloadVideosTitle",this.listenerSetter);this.scrollable.append(e.container)}}const nN={contacts:"AutoDownloadContacts",private:"AutoDownloadPm",groups:"AutoDownloadGroups",channels:"AutoDownloadChannels"};class aN extends Bs{init(){this.setTitle("DataSettings");{const e=new Oe({name:"AutomaticMediaDownload",caption:"AutoDownloadAudioInfo"}),t=new _t({text:"AutoDownloadMedia",name:"auto",checked:!I.settings.autoDownloadNew.pFlags.disabled,listenerSetter:this.listenerSetter}),s=new Fe({checkboxField:t,listenerSetter:this.listenerSetter}),i=()=>{os([d],Pn(I.settings.autoDownload,wl.autoDownload)&&Pn(I.settings.autoDownloadNew,wl.autoDownloadNew))},n=()=>{this.setAutoDownloadSubtitle(o,I.settings.autoDownload.photo),this.setAutoDownloadSubtitle(l,I.settings.autoDownload.video),this.setAutoDownloadSubtitle(c,I.settings.autoDownload.file,I.settings.autoDownloadNew.file_size_max)},r=h=>{const p=this.slider.createTab(h);p.open(),this.listenerSetter.add(p.eventListener)("destroy",()=>{n(),i()},{once:!0})},o=new Fe({titleLangKey:"AutoDownloadPhotos",subtitle:"",clickable:()=>{r(tN)},listenerSetter:this.listenerSetter}),l=new Fe({titleLangKey:"AutoDownloadVideos",subtitle:"",clickable:()=>{r(iN)},listenerSetter:this.listenerSetter}),c=new Fe({titleLangKey:"AutoDownloadFiles",subtitle:"",clickable:()=>{r(sN)},listenerSetter:this.listenerSetter}),d=ot("btn-primary btn-transparent primary",{icon:"delete",text:"ResetAutomaticMediaDownload"});J(d,()=>{Rt({titleLangKey:"ResetAutomaticMediaDownloadAlertTitle",descriptionLangKey:"ResetAutomaticMediaDownloadAlert",button:{langKey:"Reset"}}).then(()=>{const h=I.settings;h.autoDownloadNew=kn(wl.autoDownloadNew),h.autoDownload=kn(wl.autoDownload),I.settings=h,this.managers.appStateManager.setByKey("settings",h),n(),t.checked=!I.settings.autoDownloadNew.pFlags.disabled})});const u=()=>{const h=!t.checked,p=I.settings.autoDownloadNew;h?p.pFlags.disabled=!0:delete p.pFlags.disabled,[o,l,c].forEach(m=>{m.container.classList.toggle("is-disabled",h)}),this.managers.appStateManager.setByKey(ci("settings","autoDownloadNew"),p),i()};t.input.addEventListener("change",u),u(),n(),e.content.append(s.container,o.container,l.container,c.container,d),this.scrollable.append(e.container)}}setAutoDownloadSubtitle(e,t,s){let i;const n=[],r=Object.keys(t),o=r.map(l=>t[l]?nN[l]:void 0).filter(Boolean);if(!o.length||s===0)i="AutoDownloadOff";else{const l=o.length===r.length;if(s!==void 0?(i=l?"AutoDownloadUpToOnAllChats":"AutoDownloadOnUpToFor",n.push(ur(s))):i=l?"AutoDownloadOnAllChats":"AutoDownloadOnFor",!l){const c=document.createElement("span");c.append(...Yi(o.map(d=>P(d)),!0,!1)),n.push(c)}}St(e.subtitle,P(i,n))}}class rN extends Zt{init(){return this.setTitle("DoubleTapSetting"),this.container.classList.add("quick-reaction-container"),Promise.all([this.managers.appReactionsManager.getQuickReaction(),this.managers.appReactionsManager.getAvailableReactions()]).then(([e,t])=>{t=t.filter(o=>!o.pFlags.inactive);const s=new Oe,i="quick-reaction",n=t.map(o=>{const l=new rn({name:i,text:o.title,value:o.reaction,alignRight:!0}),c=new Fe({radioField:l,havePadding:!0});return l.main.classList.add("quick-reaction-title"),vw({row:c,doc:o.static_icon,size:"small"}),o.reaction===e.reaction&&l.setValueSilently(!0),c}),r=Sd(n,o=>{this.managers.appReactionsManager.setDefaultReaction({_:"reactionEmoji",emoticon:o})});s.content.append(r),this.scrollable.append(s.container)})}}class _w extends Zt{static getInitArgs(){return{allStickers:I.managers.appStickersManager.getAllStickers(),quickReaction:I.managers.appReactionsManager.getQuickReaction()}}init(e){this.container.classList.add("stickers-emoji-container"),this.setTitle("StickersName");const t=[];{const s=new Oe({caption:"LoopAnimatedStickersInfo"}),i=new Fe({icon:"lamp",titleLangKey:"Stickers.SuggestStickers",clickable:!0,listenerSetter:this.listenerSetter,titleRightSecondary:!0}),n={all:"SuggestStickersAll",installed:"SuggestStickersInstalled",none:"SuggestStickersNone"},r=()=>{i.titleRight.replaceChildren(P(n[I.settings.stickers.suggest]))};r();const o=u=>{if(I.settings.stickers.suggest!==u)return I.settings.stickers.suggest=u,r(),this.managers.appStateManager.setByKey(ci("settings","stickers","suggest"),u)};Dn({buttons:[{icon:"stickers_face",text:"SuggestStickersAll",onClick:o.bind(this,"all")},{icon:"newprivate",text:"SuggestStickersInstalled",onClick:o.bind(this,"installed")},{icon:"stop",text:"SuggestStickersNone",onClick:o.bind(this,"none")}],listenTo:i.container,middleware:this.middlewareHelper.get(),listenForClick:!0});const l=new Fe({titleLangKey:"DoubleTapSetting",havePadding:!0,clickable:()=>{this.slider.createTab(rN).open()},listenerSetter:this.listenerSetter}),c=()=>{e.quickReaction.then(u=>u._==="availableReaction"?u.static_icon:this.managers.appEmojiManager.getCustomEmojiDocument(u.document_id)).then(u=>{vw({row:l,doc:u,size:"small"})})};c(),this.listenerSetter.add(I)("quick_reaction",()=>{e=_w.getInitArgs(),c()});const d=new Fe({icon:"flip",titleLangKey:"InstalledStickers.LoopAnimated",checkboxField:new _t({name:"loop",stateKey:ci("settings","stickers","loop"),listenerSetter:this.listenerSetter,toggle:!0}),listenerSetter:this.listenerSetter});s.content.append(l.container,i.container,d.container),this.scrollable.append(s.container)}{const s=new Oe({name:"Emoji"}),i=new Fe({icon:"lamp",titleLangKey:"GeneralSettings.EmojiPrediction",checkboxField:new _t({name:"suggest-emoji",stateKey:ci("settings","emoji","suggest"),listenerSetter:this.listenerSetter,toggle:!0}),listenerSetter:this.listenerSetter}),n=new Fe({icon:"smile",titleLangKey:"GeneralSettings.BigEmoji",checkboxField:new _t({name:"emoji-big",stateKey:ci("settings","emoji","big"),listenerSetter:this.listenerSetter,toggle:!0}),listenerSetter:this.listenerSetter});s.content.append(i.container,n.container),this.scrollable.append(s.container)}{const s=new Oe({name:"DynamicPackOrder",caption:"DynamicPackOrderInfo"}),i=new Fe({titleLangKey:"DynamicPackOrder",icon:"replace",checkboxField:new _t({name:"dynamic-pack-order",stateKey:ci("settings","stickers","dynamicPackOrder"),listenerSetter:this.listenerSetter,toggle:!0}),listenerSetter:this.listenerSetter});s.content.append(i.container),this.scrollable.append(s.container)}{const s=new Oe({name:"Telegram.InstalledStickerPacksController",caption:"StickersBotInfo"}),i={},n=s.generateContentElement(),r=new sr,o=(c,d="append")=>{const u=new Fe({title:je(c.title),subtitleLangKey:"Stickers",subtitleLangArgs:[c.count],havePadding:!0,clickable:()=>{ue.createPopup(ga,{id:c.id,access_hash:c.access_hash}).show()},listenerSetter:this.listenerSetter});u.container.dataset.id=""+c.id,u.makeSortable(),i[c.id]=u;const h=document.createElement("div");h.classList.add("row-media"),gw({set:c,container:h,group:"GENERAL-SETTINGS",lazyLoadQueue:r,width:36,height:36,autoplay:!0,middleware:this.middlewareHelper.get()}),u.container.append(h),n[d](u.container)},l=e.allStickers.then(c=>{const d=c.sets.map(u=>o(u));return Promise.all(d)});t.push(l),this.listenerSetter.add(I)("stickers_installed",c=>{i[c.id]||o(c,"prepend")}),this.listenerSetter.add(I)("stickers_deleted",c=>{i[c.id]&&(i[c.id].container.remove(),delete i[c.id])}),this.listenerSetter.add(I)("stickers_order",({type:c,order:d})=>{c==="stickers"&&d.forEach((u,h)=>{const p=i[u];p&&di(p.container,n,h)})}),this.listenerSetter.add(I)("stickers_top",c=>{const d=i[c];d&&di(d.container,n,0)}),new mb({list:n,middleware:this.middlewareHelper.get(),onSort:(c,d)=>{const u=Array.from(n.children).map(h=>h.dataset.id);this.managers.appStickersManager.reorderStickerSets(u)}}),this.scrollable.append(s.container)}return Promise.all(t)}}class Eh extends Zt{constructor(){super(...arguments),this.buttons={}}async init(){this.container.classList.add("settings-container"),this.setTitle("Settings");const e=ki({listenerSetter:this.listenerSetter,direction:"bottom-left",buttons:[{icon:"logout",text:"EditAccount.Logout",onClick:()=>{ue.createPopup(mi,"logout",{titleLangKey:"LogOut",descriptionLangKey:"LogOut.Description",buttons:[{langKey:"LogOut",callback:()=>{this.managers.apiManager.logOut()},isDanger:!0}]}).show()}}]});this.buttons.edit=yt("edit"),this.header.append(this.buttons.edit,e),this.profile=new uM(this.managers,this.scrollable,this.listenerSetter,!1,this.container,v=>{let y=this.profile.element.lastElementChild;v&&(y=y.previousElementSibling),y.firstElementChild.append(s)}),this.profile.init(),this.profile.setPeer(I.myId);const t=this.profile.fillProfileElements(),s=Cn({icon:"cameraadd",className:"profile-change-avatar"});J(s,()=>{const v=document.createElement("canvas");ue.createPopup(p_).open(v,y=>{y().then(w=>this.managers.appProfileManager.uploadProfilePhoto(w))})},{listenerSetter:this.listenerSetter}),this.profile.element.lastElementChild.firstElementChild.append(s);const i=async()=>{const v=await this.managers.appUsersManager.getSelf();s.classList.toggle("hide",v.photo?._!=="userProfilePhoto")};i(),this.listenerSetter.add(I)("avatar_update",({peerId:v})=>{I.myId===v&&i()});const n=document.createElement("div");n.classList.add("profile-buttons");const r=(v,y,w,b)=>{if(!b){const S=w.getInitArgs;S&&(b=()=>[S(this)])}return{icon:v,text:y,tabConstructor:w,getInitArgs:b,args:b?.()}},l=[r("unmute","AccountSettings.Notifications",eN),r("data","DataSettings",aN),r("lock","AccountSettings.PrivacyAndSecurity",wM),r("settings","Telegram.GeneralSettingsViewController",J8),r("folder","AccountSettings.Filters",Cd),r("stickers_face","StickersName",_w)].map(v=>{const{icon:y,text:w,tabConstructor:b,getInitArgs:S}=v;return new Fe({titleLangKey:w,icon:y,clickable:async()=>{const _=v.args?await v.args:[],M=this.slider.createTab(b);M.open(..._),M instanceof Bs&&S&&M.eventListener.addEventListener("destroyAfter",C=>{v.args=C.then(()=>S())})},listenerSetter:this.listenerSetter})}),c=pC.getInitArgs();l.push(this.devicesRow=new Fe({titleLangKey:"Devices",titleRightSecondary:" ",icon:"activesessions",clickable:async()=>{this.authorizations||await this.updateActiveSessions();const v=this.slider.createTab(yM);v.authorizations=this.authorizations,v.eventListener.addEventListener("destroy",()=>{this.authorizations=void 0,this.updateActiveSessions(!0)},{once:!0}),v.open()},listenerSetter:this.listenerSetter}),this.languageRow=new Fe({titleLangKey:"AccountSettings.Language",titleRightSecondary:P("LanguageName"),icon:"language",clickable:()=>{this.slider.createTab(pC).open(c)},listenerSetter:this.listenerSetter})),n.append(...l.map(v=>v.container)),this.premiumRow=new Fe({titleLangKey:"Premium.Boarding.Title",icon:"star",iconClasses:["row-icon-premium-color"],clickable:()=>{rs.show()},listenerSetter:this.listenerSetter});const d=new Fe({titleLangKey:"MenuTelegramStars",titleRightSecondary:!0,icon:"star",iconClasses:["row-icon-stars-color"],clickable:()=>{ue.createPopup(ba)},listenerSetter:this.listenerSetter});Ft(v=>{this.middlewareHelper.onDestroy(v);const y=Jl();le(()=>{d.titleRight.textContent=""+y(),d.container.classList.toggle("hide",!y())})});const u=new Fe({titleLangKey:"GiftPremiumGifting",icon:"gift",clickable:()=>{Ce.initGifting()},listenerSetter:this.listenerSetter}),h=P("New");h.classList.add("row-title-badge"),u.title.append(h);const p=new Oe;p.content.append(n);let m;await Ae.isPremiumPurchaseBlocked()||(m=new Oe,m.content.append(this.premiumRow.container,d.container,u.container)),this.scrollable.append(...[this.profile.element,p.container,m?.container].filter(Boolean));const g=()=>{f=bm.getInitArgs()};let f;J(this.buttons.edit,()=>{this.slider.createTab(bm).open(f)},{listenerSetter:this.listenerSetter}),g(),this.listenerSetter.add(I)("user_update",v=>{I.myId.toUserId()===v&&g()}),Ns.loadLottieWorkers(),this.updateActiveSessions(),(await t)()}getAuthorizations(e){if(this.getAuthorizationsPromise&&!e)return this.getAuthorizationsPromise;const t=this.getAuthorizationsPromise=this.managers.apiManager.invokeApi("account.getAuthorizations").finally(()=>{this.getAuthorizationsPromise===t&&(this.getAuthorizationsPromise=void 0)});return t}updateActiveSessions(e){return this.getAuthorizations(e).then(t=>{this.authorizations=t.authorizations,this.devicesRow.titleRight.textContent=""+this.authorizations.length})}onCloseAfterTimeout(){return this.profile.destroy(),super.onCloseAfterTimeout()}}class oN extends Zt{constructor(){super(...arguments),this.uploadAvatar=null}init(){this.container.classList.add("new-channel-container"),this.setTitle("NewChannel"),this.avatarEdit=new db(i=>{this.uploadAvatar=i});const e=new Oe({caption:"Channel.DescriptionHolderDescrpiton"}),t=document.createElement("div");t.classList.add("input-wrapper"),this.channelNameInputField=new Yt({label:"EnterChannelName",maxLength:128}),this.channelDescriptionInputField=new Yt({label:"DescriptionOptionalPlaceholder",maxLength:255,withLinebreaks:!0}),t.append(this.channelNameInputField.container,this.channelDescriptionInputField.container);const s=()=>{this.nextBtn.classList.toggle("is-visible",!!this.channelNameInputField.value.length&&!this.channelNameInputField.input.classList.contains("error")&&!this.channelDescriptionInputField.input.classList.contains("error"))};this.channelNameInputField.input.addEventListener("input",s),this.channelDescriptionInputField.input.addEventListener("input",s),this.nextBtn=Cn({icon:"arrow_next"}),J(this.nextBtn,()=>{const i=this.channelNameInputField.value,n=this.channelDescriptionInputField.value;this.nextBtn.disabled=!0,this.managers.appChatsManager.createChannel({title:i,about:n,broadcast:!0}).then(r=>{this.uploadAvatar&&this.uploadAvatar().then(o=>{this.managers.appChatsManager.editPhoto(r,o)}),Ce.setInnerPeer({peerId:r.toPeerId(!0)}),Ri.removeTabFromHistory(this),this.slider.createTab(Zu).open({type:"channel",skippable:!0,title:"GroupAddMembers",placeholder:"SendMessageTo",takeOut:o=>this.managers.appChatsManager.inviteToChannel(r,o)})})},{listenerSetter:this.listenerSetter}),this.content.append(this.nextBtn),e.content.append(this.avatarEdit.container,t),this.scrollable.append(e.container)}onCloseAfterTimeout(){return this.avatarEdit.clear(),this.uploadAvatar=null,this.channelNameInputField.value="",this.channelDescriptionInputField.value="",this.nextBtn.disabled=!1,super.onCloseAfterTimeout()}}class lN extends ue{constructor(){super("popup-create-contact popup-send-photo popup-new-media",{closable:!0,withConfirm:"Add",title:"AddContactTitle"}),this.construct()}async construct(){J(this.btnConfirm,()=>{const d=this.managers.appUsersManager.importContact(s.value,i.value,n.value);d.then(()=>{this.hide()},u=>{u.type==="NO_USER"&&($e({langPackKey:"Contacts.PhoneNumber.NotRegistred"}),c.disabled=!1)}),c.lockWithPromise(d)},{listenerSetter:this.listenerSetter});const e=[],t=document.createElement("div");t.classList.add("name-fields");const s=new Yt({label:"FirstName",name:"create-contact-name",maxLength:70,required:!0});s.container.classList.add("input-field-name");const i=new Yt({label:"LastName",name:"create-contact-lastname",maxLength:70}),n=new v_({required:!0});e.push(s,i,n);const r=()=>{const d=s.value+" "+i.value;c.avatarElem.render({peerTitle:d})};this.listenerSetter.add(s.input)("input",r),this.listenerSetter.add(i.input)("input",r),n.validate=()=>!!n.value.match(/\d/);const o=await this.managers.appUsersManager.getSelf(),l=bd(o.phone);l.code&&(n.value="+"+l.code.country_code);const c=new Ou({inputFields:e,listenerSetter:this.listenerSetter,doNotEditAvatar:!0,nextBtn:this.btnConfirm,avatarSize:100,middleware:this.middlewareHelper.get()});t.append(s.container,i.container,c.avatarElem.node),this.container.append(t,n.container),this.show()}}class mC extends Zt{init(){this.container.id="contacts-container";const e=Cn({icon:"add",className:"is-visible"});this.content.append(e),J(e,()=>{ue.createPopup(lN)},{listenerSetter:this.listenerSetter}),this.inputSearch=new jo({placeholder:"Search",onChange:s=>{this.openContacts(s)}}),this.listenerSetter.add(I)("contacts_update",async s=>{const i=await this.managers.appUsersManager.isContact(s),n=s.toPeerId();i?this.sortedUserList.add(n):this.sortedUserList.delete(n)}),this.title.replaceWith(this.inputSearch.container),this.middlewareHelperLoad=Ht();const t=this.listsContainer=document.createElement("div");this.scrollable.append(t),this.openContacts()}createList(){const e=new qh({managers:this.managers,middleware:this.middlewareHelper.get()}),t=e.list;return t.id="contacts",t.classList.add("contacts-container"),nt.setListClickListener({list:t,onFound:()=>{this.close()},withContext:void 0,autonomous:!0}),e}onClose(){this.middlewareHelperLoad.clean()}onOpenAfterTimeout(){Gi||!nf(!0)||this.inputSearch.input.focus()}openContacts(e){this.middlewareHelperLoad.clean();const t=this.middlewareHelperLoad.get();this.scrollable.onScrolledBottom=null,this.listsContainer.replaceChildren(),this.managers.appUsersManager.getContactsPeerIds(e,void 0,"online").then(s=>{if(!t())return;const i=this.sortedUserList=this.createList();let n=()=>{const r=It.height/56*1.25|0;s.splice(0,r).forEach(l=>{i.add(l)}),s.length||(n=void 0,this.scrollable.onScrolledBottom=null)};n(),this.scrollable.onScrolledBottom=()=>{n?n():this.scrollable.onScrolledBottom=null},St(this.listsContainer,i.list)})}}const $r=class $r extends Zt{init(){if(this.wasFilterId=nt.filterId,this.container.id="chats-archived-container",this.setTitle("ArchivedChats"),this.header.classList.add("can-have-forum"),this.content.classList.add("can-have-forum"),!nt.xds[$r.filterId]){const{ul:s,scrollable:i}=nt.l({title:void 0,id:$r.filterId,localId:yn});i.append(s)}const e=this.storiesListContainer=document.createElement("div");e.classList.add("stories-list"),this.header.after(e);const t=nt.xds[$r.filterId].scrollable;return this.scrollable.container.replaceWith(t.container),t.attachBorderListeners(this.container),nt.setFilterIdAndChangeTab($r.filterId).then(({cached:s,renderPromise:i})=>{if(s)return i})}renderStories(){this.disposeStories=wi(()=>aM({foldInto:this.header,setScrolledOn:this.container,getScrollable:()=>nt.xds[$r.filterId].scrollable.container,listenWheelOn:this.content,archive:!0,offsetX:-84}),this.storiesListContainer)}onOpenAfterTimeout(){this.renderStories(),nt.xds[this.wasFilterId].clear()}onClose(){this.scrollable.onAdditionalScroll=void 0,nt.setFilterIdAndChangeTab(this.wasFilterId)}onCloseAfterTimeout(){return this.disposeStories?.(),this.disposeStories=void 0,nt.xds[$r.filterId].clear(),super.onCloseAfterTimeout()}};$r.filterId=yn;let Ly=$r;function cN({element:a,triggerEvent:e,direction:t,level:s,offset:i=[0,0],createMenu:n,canOpen:r=()=>!0}){let o=!1;const l=()=>{(async()=>{if(o||!r())return;o=!0;const c=a.getBoundingClientRect(),d=await n(),u=async()=>{o=!1};document.body.append(d);const h=16;if(t==="right-start"){d.style.transformOrigin="0 0";let p=c.right+i[0];const m=p+d.clientWidth;m+h>window.innerWidth&&(p-=m-window.innerWidth+h);let g=c.top+i[1];const f=g+d.clientHeight;f+h>window.innerHeight&&(g-=f-window.innerHeight+h),d.style.left=p+"px",d.style.top=g+"px"}await hi(),Li.addAdditionalMenu(d,a,s,u)})()};return a.addEventListener(e,l),()=>{a.removeEventListener(e,l)}}const dN=Y("<div><div class=accounts-limit__pin-container><img class=accounts-limit__pin-image src=assets/img/accounts-limit-pin-shape.svg><span class=accounts-limit__pin-count></span></div><div class=accounts-limit__bar><div class=accounts-limit__bar-left></div><div class=accounts-limit__bar-right><span></span></div></div><div class=accounts-limit__description></div><div class=accounts-limit__actions>"),hN=Y('<svg width=24 height=18 viewBox="0 0 24 18"fill=none xmlns=http://www.w3.org/2000/svg><g clip-path=url(#clip0_6002_2313)><path d="M0 6.4C0 4.15979 0 3.03968 0.435974 2.18404C0.819467 1.43139 1.43139 0.819467 2.18404 0.435974C3.03968 0 4.15979 0 6.4 0H17.6C19.8402 0 20.9603 0 21.816 0.435974C22.5686 0.819467 23.1805 1.43139 23.564 2.18404C24 3.03968 24 4.15979 24 6.4V11.6C24 13.8402 24 14.9603 23.564 15.816C23.1805 16.5686 22.5686 17.1805 21.816 17.564C20.9603 18 19.8402 18 17.6 18H6.4C4.15979 18 3.03968 18 2.18404 17.564C1.43139 17.1805 0.819467 16.5686 0.435974 15.816C0 14.9603 0 13.8402 0 11.6V6.4Z"fill=currentColor></path><path fill-rule=evenodd clip-rule=evenodd d="M16.165 12.1651H15.5C15.0388 12.1651 14.665 12.539 14.665 13.0001C14.665 13.4613 15.0388 13.8351 15.5 13.8351H17H18.5C18.9612 13.8351 19.335 13.4613 19.335 13.0001C19.335 12.539 18.9612 12.1651 18.5 12.1651H17.835V4.50011C17.835 4.09058 17.538 3.7415 17.1338 3.6759C16.7295 3.6103 16.3374 3.84755 16.2079 4.23606L16.1551 4.39442C15.902 5.15375 15.4755 5.84371 14.9096 6.40968C14.5835 6.73577 14.5835 7.26446 14.9096 7.59055C15.2357 7.91664 15.7643 7.91664 16.0904 7.59055C16.1155 7.56549 16.1404 7.54024 16.165 7.51481V12.1651ZM8 12.8351C7.53884 12.8351 7.165 12.4613 7.165 12.0001V9.83511H5C4.53884 9.83511 4.165 9.46127 4.165 9.00011C4.165 8.53896 4.53884 8.16511 5 8.16511H7.165V6.00011C7.165 5.53896 7.53884 5.16511 8 5.16511C8.46116 5.16511 8.835 5.53896 8.835 6.00011V8.16511H11C11.4612 8.16511 11.835 8.53896 11.835 9.00011C11.835 9.46127 11.4612 9.83511 11 9.83511H8.835V12.0001C8.835 12.4613 8.46116 12.8351 8 12.8351Z"fill=white></path></g><defs><clipPath id=clip0_6002_2313><rect width=24 height=18 fill=white>');function uN(a){return(()=>{const e=dN(),t=e.firstChild,s=t.firstChild,i=s.nextSibling,n=t.nextSibling,r=n.firstChild,o=r.nextSibling,l=o.firstChild,c=n.nextSibling,d=c.nextSibling;return k(t,T(hs,{class:"accounts-limit__pin-icon",icon:"person"}),i),k(i,d_),k(r,()=>P("LimitFree")),k(o,()=>P("LimitPremium"),l),k(l,gE),k(c,()=>Rh({key:"MultiAccount.AccountsLimitDescription"})),k(d,()=>{const u=ot("popup-button btn primary",{text:"Cancel"});return u.addEventListener("click",a.onCancel),u},null),k(d,()=>{const u=ot("popup-button btn primary");return u.append(P("IncreaseLimit"),pN()),u.addEventListener("click",a.onSubmit),u},null),e})()}function pN(){return hN()}class mN extends ue{constructor(){super("accounts-limit-popup",{overlayClosable:!0,body:!0,title:"LimitReached"}),this.body.append(uN({onCancel:()=>{this.hide()},onSubmit:()=>{this.hide(),rs.show({feature:"double_limits"})}}))}}const gN=!1,xs=class xs{constructor(){this.notificationsShown={},this.notificationIndex=0,this.soundsPlayed={},this.vibrateSupport=fE,this.settings={},this.pushInited=!1,this.updateLocalSettings=()=>{const t=["notify_nodesktop","notify_volume","notify_novibrate","notify_nopreview","notify_nopush"].map(()=>{});Promise.all(t).then(s=>{if(this.settings.nodesktop=s[0],this.settings.volume=s[1]===void 0?.5:s[1],this.settings.novibrate=s[2],this.settings.nopreview=s[3],this.settings.nopush=s[4],this.pushInited){const i=!this.settings.nopush&&!this.settings.nodesktop&&ea.isAvailable||!1,n=this.registeredDevice!==!1;i!==n&&(i?ea.subscribe():ea.unsubscribe())}ea.setSettings(this.settings)}),this.settings.nosound=!I.settings.notifications.sound},this.requestPermission=()=>{Notification.requestPermission(),window.removeEventListener("click",this.requestPermission)},this.clear=()=>{xs.log.warn("clear");for(const e in this.notificationsShown){const t=this.notificationsShown[e];this.closeNotification(t)}this.notificationsShown={},this.setNotificationCount(0),ea.hidePushNotifications()}}static async getNotificationsCountForAllAccounts(){return await Qw.get("notificationsCount",!1)||{}}static async getNotificationsCountForAllAccountsForTitle(){const e=await this.getNotificationsCountForAllAccounts(),t=i=>i===Vr()||gN;return Object.entries(e).reduce((i,[n,r])=>i+(t(+n)?r:0)||0,0)}async getNotificationsCount(){return(await xs.getNotificationsCountForAllAccounts())?.[this.accountNumber]||0}async setNotificationCount(e){await navigator.locks.request("notificationsCount",async()=>{const t=await xs.getNotificationsCountForAllAccounts();let s=e instanceof Function?e(t[this.accountNumber]||0):e;s=Math.max(0,s),t[this.accountNumber]!==s&&(await Qw.set({notificationsCount:{...t,[this.accountNumber]:s}}),I.dispatchEvent("notification_count_update"))})}construct(e){this.managers=pm(e),this.accountNumber=e,this.notificationsQueue=new c_(1),navigator.vibrate=navigator.vibrate||navigator.mozVibrate||navigator.webkitVibrate,this.setAppBadge=navigator.setAppBadge?.bind(navigator),this.setAppBadge?.(0),this.notificationsUiSupport="Notification"in window||"mozNotification"in navigator,this.notifySoundEl=document.createElement("div"),this.notifySoundEl.id="notify-sound",document.body.append(this.notifySoundEl),this.topMessagesDeferred=Mt(),I.addEventListener("settings_updated",this.updateLocalSettings),I.addEventListener("notification_reset",t=>{this.soundReset(t)}),I.addEventListener("notification_cancel",t=>{this.cancel(t)}),this.setAppBadge&&I.addEventListener("folder_unread",t=>{t.id===Fi&&this.setAppBadge(t.unreadUnmutedPeerIds.size)}),ea.addEventListener("push_init",t=>{this.pushInited=!0,!this.settings.nodesktop&&!this.settings.nopush?t?this.registerDevice(t):ea.subscribe():this.unregisterDevice(t)}),ea.addEventListener("push_subscribe",t=>{this.registerDevice(t)}),ea.addEventListener("push_unsubscribe",t=>{this.unregisterDevice(t)}),I.addEventListener("dialogs_multiupdate",()=>{this.topMessagesDeferred.resolve()},{once:!0}),ea.addEventListener("push_notification_click",t=>{if(t.action==="push_settings")return;if(t.action==="mute1d"){this.managers.apiManager.invokeApi("account.updateDeviceLocked",{period:86400}).then(()=>{});return}const s=t.custom&&t.custom.peerId.toPeerId();s&&this.topMessagesDeferred.then(async()=>{const i=s.isAnyChat()?s.toChatId():void 0;let n;if(i){if(!await this.managers.appChatsManager.hasChat(i))return;n=await this.managers.appChatsManager.isChannel(i)?i:void 0}if(!i&&!await this.managers.appUsersManager.hasUser(s.toUserId()))return;const r=await this.managers.appMessagesIdsManager.generateMessageId(+t.custom.msg_id,n);Ce.setInnerPeer({peerId:s,lastMsgId:r})})})}async buildNotificationQueue(e){this.notificationsQueue.push({load:()=>this.buildNotification(e)})}async buildNotification({message:e,fwdCount:t,peerReaction:s,peerTypeNotifySettings:i,isOtherTabActive:n}){const r=e.peerId,o=r.isAnyChat(),l={},[c,d=!1]=await Promise.all([this.managers.appPeersManager.getPeerString(r),o&&this.managers.appPeersManager.isForum(r)]);let u,h=!1;const p=mm.getIsLocked();if(i.show_previews&&!p)if(e._==="message"&&e.fwd_from&&t>1)u=Ne.format("Notifications.Forwarded",!0,[t]);else{u=await To({message:e,plain:!0});const C=s?.reaction;if(C&&C._!=="reactionEmpty"){let L=C.emoticon;L||(L=(await this.managers.appEmojiManager.getCustomEmojiDocument(C.document_id)).stickerEmojiRaw);const E="Notification.Contact.Reacted",x=[rb(L),u];u=Ne.format(E,!0,x)}else h=!0}else u=Ne.format("Notifications.New",!0);s&&(l.noIncrement=!0,l.silent=!0);const m={plainText:!0,managers:this.managers},g=d?yr(e,d):void 0,f=s?it(s.peer_id):e.fromId,v=l.title=await Gr({...m,peerId:r,threadId:g,managers:this.managers,useManagers:!0});if(d){const C=await Gr({...m,peerId:r});l.title+=` (${C})`,h&&f!==e.peerId&&(u=await Gr({...m,peerId:f,managers:this.managers,useManagers:!0})+": "+u)}else o&&f!==e.peerId&&(l.title=await Gr({...m,peerId:f,managers:this.managers,useManagers:!0})+" @ "+l.title);function y(C){let L=C.first_name;return C.last_name&&(L+=" "+C.last_name),L=Ya(L,12,15),Oo(L)}const w=await this.managers.apiManager.getAccountNumber(),b=w!==Vr();if((await vc.getTotalAccounts()>1&&n||b)&&(l.title+=" ➜ "+y(await this.managers.appUsersManager.getSelf())),l.title=Oo(l.title),l.onclick=()=>{if(b){const C=vE(w,{p:""+r,message:""+(e.mid||""),thread:""+(g||"")});window.open(C,"_blank")}else Ce.setInnerPeer({peerId:r,lastMsgId:e.mid,threadId:g})},l.message=u,l.key=`msg_${this.accountNumber}_${e.peerId}_${e.mid}`,l.tag=c,l.silent=!0,l.image=p?void 0:await yE(this.managers,r,v),!s&&(e=await this.managers.appMessagesManager.getMessageByPeer(e.peerId,e.mid),!e||!e.pFlags.unread))return;const _={custom:{msg_id:""+e.mid,peerId:""+r},description:"",loc_key:"",loc_args:[],mute:"",random_id:0,title:""};p&&(l.title=Ne.format("PasscodeLock.NotificationTitle",!0),l.message=Ne.format("PasscodeLock.NotificationDescription",!0)),await this.notify(l,_)&&this.registeredDevice&&ea.ignorePushByMid(r,e.mid)}static constructAndStartNotificationManagerFor(e){if(this.byAccount[e]){this.byAccount[e].start();return}pm(e).apiUpdatesManager.attach(Ne.lastRequestedLangCode);const s=this.byAccount[e]=new xs;s.construct(e),s.start()}static constructAndStartAll(){this.start(),I.addEventListener("account_logged_in",async({accountNumber:e})=>{this.byAccount[e]||this.constructAndStartNotificationManagerFor(e)}),cm.addEventListener("deactivated",()=>{this.stop()}),cm.addEventListener("activated",()=>{this.stopped&&this.start()}),qr.addEventListener("change",e=>{if(!this.stopped){if(!e)for(const t in this.byAccount){const s=+t;s===Vr()&&this.byAccount[s].clear()}this.toggleToggler()}})}static async start(){this.stopped=!1;const e=await vc.getTotalAccounts();for(let t=1;t<=e;t++){const s=t;this.constructAndStartNotificationManagerFor(s)}this.byAccount[Vr()].setNotificationCount(0)}static resetTitle(e){this.titleChanged&&(this.titleChanged=!1,document.title=this.titleBackup,this.setFavicon())}static async toggleToggler(e=qr.isIdle){if(Gi)return;this.titleMiddlewareHelper.clean();const t=this.titleMiddlewareHelper.get();if(!e)this.resetTitle();else{const s=await Ae.setInterval(xs.onTitleInterval,1e3);t.onClean(()=>{Ae.clearInterval(s)})}}static setFavicon(e){this.prevFavicon!==e&&(this.prevFavicon=e,this.faviconElements.forEach((t,s,i)=>{var r;const n=t.cloneNode();(r=n.dataset).href||(r.href=n.href),e??(e=n.dataset.href),n.href=e,t.replaceWith(i[s]=n)}))}async notify(e,t){if(xs.log("notify",e,qr.isIdle,this.notificationsUiSupport,xs.stopped),xs.stopped)return;e.image||(e.image=bE),e.noIncrement||this.setNotificationCount(l=>++l),xs.toggleToggler();const s=++this.notificationIndex,i=e.key||"k"+s;this.notificationsShown[i]=!0;const n=Qs();if(this.settings.volume>0&&!this.settings.nosound&&(this.testSound(this.settings.volume),this.soundsPlayed[e.tag]=n),!this.notificationsUiSupport||"Notification"in window&&Notification.permission!=="granted")return;if(this.settings.nodesktop){if(this.vibrateSupport&&!this.settings.novibrate){navigator.vibrate([200,100,200]);return}return}if(!("Notification"in window))return;let r;const o={badge:wE,icon:e.image||"",body:e.message||"",tag:e.tag||"",silent:e.silent||!1,data:t};try{if(e.tag)for(const l in this.notificationsShown){const c=this.notificationsShown[l];typeof c!="boolean"&&c.tag===e.tag&&(c.hidden=!0)}r=new Notification(e.title,o)}catch{try{const c=await navigator.serviceWorker.ready;await c.showNotification(e.title,o);const d=await c.getNotifications({tag:o.tag});r=d[d.length-1]}catch(c){xs.log.error("creating push error",c,e,o)}if(!r){this.notificationsUiSupport=!1,ea.setLocalNotificationsDisabled();return}}return r.onclick=()=>{xs.log("notification onclick"),r.close(),h_.focus(),this.clear(),e.onclick?.()},r.onclose=()=>{xs.log("notification onclose"),r.hidden||(delete this.notificationsShown[i],this.clear())},r.show?.(),this.notificationsShown[i]=r,Gi||setTimeout(()=>{this.hide(i)},8e3),!0}getLocalSettings(){return this.settings}hide(e){const t=this.notificationsShown[e];t&&this.closeNotification(t)}soundReset(e){delete this.soundsPlayed[e]}testSound(e){const t=Qs();if(this.nextSoundAt&&t<this.nextSoundAt&&this.prevSoundVolume===e)return;this.nextSoundAt=t+1e3,this.prevSoundVolume=e;const s="assets/audio/notification.mp3",i=document.createElement("audio");i.autoplay=!0,i.setAttribute("mozaudiochannel","notification"),i.volume=e,i.innerHTML=`
- <source src="${s}" type="audio/mpeg" />
- <embed hidden="true" autostart="true" loop="false" volume="${e*100}" src="${s}" />
- `,this.notifySoundEl.append(i),i.addEventListener("ended",()=>{i.remove()},{once:!0})}async cancel(e){const t=this.notificationsShown[e];xs.log("cancel",e,t),t&&(this.setNotificationCount(s=>--s),this.closeNotification(t),delete this.notificationsShown[e])}closeNotification(e){try{typeof e!="boolean"&&e.close&&(xs.log("close notification",e),e.hidden=!0,e.close())}catch{}}start(){if(xs.log("start"),this.updateLocalSettings(),this.managers.appStateManager.getState().then(e=>{xs.stopped||ea.start()}),!this.notificationsUiSupport)return!1;"Notification"in window&&Notification.permission!=="granted"&&Notification.permission!=="denied"&&window.addEventListener("click",this.requestPermission);try{"onbeforeunload"in window&&window.addEventListener("beforeunload",this.clear)}catch{}}static stop(){xs.log("stop");for(const e in this.byAccount){const t=e;this.byAccount[t].clear()}this.titleMiddlewareHelper.clean(),this.setFavicon(),this.stopped=!0}registerDevice(e){if(this.registeredDevice&&Pn(this.registeredDevice,e))return!1;this.managers.apiManager.invokeApi("account.registerDevice",{token_type:e.tokenType,token:e.tokenValue,other_uids:[],app_sandbox:!1,secret:new Uint8Array}).then(()=>{xs.log("registered device"),this.registeredDevice=e})}unregisterDevice(e){if(!this.registeredDevice)return!1;this.managers.apiManager.invokeApi("account.unregisterDevice",{token_type:e.tokenType,token:e.tokenValue,other_uids:[]}).then(()=>{this.registeredDevice=!1})}};xs.faviconElements=Array.from(document.head.querySelectorAll('link[rel="icon"], link[rel="alternate icon"]')),xs.titleBackup=document.title,xs.titleChanged=!1,xs.titleMiddlewareHelper=Ht(),xs.stopped=!1,xs.log=Ni("NOTIFICATIONS"),xs.byAccount={},xs.onTitleInterval=async()=>{const e=xs.titleMiddlewareHelper.get(),t=await xs.getNotificationsCountForAllAccountsForTitle();if(!e())return;const s=xs.titleChanged;if(s&&xs.resetTitle(!0),!t||s)return;xs.titleChanged=!0,document.title=Ne.format("Notifications.Count",!0,[t]);const i=document.createElement("canvas");i.width=32*window.devicePixelRatio,i.height=i.width;const n=i.getContext("2d");n.beginPath(),n.arc(i.width/2,i.height/2,i.width/2,0,2*Math.PI,!1),n.fillStyle="#3390ec",n.fill();let r=24,o=""+t;t<10?r=22:t<100?r=20:(o="99+",r=16),r*=window.devicePixelRatio,n.font=`700 ${r}px ${Fh}`,n.textBaseline="middle",n.textAlign="center",n.fillStyle="white",n.fillText(o,i.width/2,i.height*.5625),xs.setFavicon(i.toDataURL())};let hd=xs;function _M({appSidebarLeft:a,AppChatFoldersTab:e,AppEditFolderTab:t,managers:s,className:i,listenTo:n}){async function r(c){if(oa.has(c))return;const d=await s.filtersStorage.getFilter(c);a.closeTabsBefore(()=>{const u=a.createTab(t);u.setInitFilter(d),u.open()})}let o;const{destroy:l}=Dn({buttons:[{icon:"edit",text:"FilterEdit",onClick:()=>{r(o)},verify:()=>o!==Fi},{icon:"edit",text:"FilterEditAll",onClick:()=>{a.closeTabsBefore(()=>{a.createTab(e).open()})},verify:()=>o===Fi},{icon:"readchats",text:"MarkAllAsRead",onClick:()=>{s.dialogsStorage.markFolderAsRead(o)},verify:async()=>!!(await s.dialogsStorage.getFolderUnreadCount(o)).unreadCount},{icon:"delete",className:"danger",text:"Delete",onClick:()=>{t.deleteFolder(o)},verify:()=>o!==Fi}],listenTo:n,findElement:c=>ne(c.target,i),onOpen:(c,d)=>{o=+d.dataset.filterId}});return{destroy:l,openSettingsForFilter:r}}async function gC(a,e){const{unreadUnmutedCount:t,unreadCount:s}=await e.dialogsStorage.getFolderUnreadCount(a);return{count:a===Fi?t:s,muted:!t&&!!s}}function fN(a){if(a.id===Fi)return"round_chats_filled";const e=[];return a.pFlags.contacts&&e.push("person"),a.pFlags.bots&&e.push("bot_filled"),a.pFlags.broadcasts&&e.push("channel_filled"),a.pFlags.groups&&e.push("group_filled"),a.pFlags.non_contacts&&e.push("noncontacts"),e.length===1?e[0]:"limit_folders"}async function fC(a,e){const t=new Map,s=a.filter(n=>n.id).map(n=>e.filtersStorage.getFilter(n.id)),i=await Promise.all(s);for(const n of i)t.set(n.id,n);return a.sort((n,r)=>!n.id||!r.id?0:t.get(n.id)?.localId-t.get(r.id)?.localId)}function vN(a){return T(Ru,{get component(){return a.tag},get class(){return Ge("badge",`badge-${a.size}`,`badge-${a.color}`,!a.children&&"is-badge-empty",a.class)},get children(){return a.children}})}const yN=Y("<div class=folders-sidebar__folder-item-name>"),bN=Y("<div class=folders-sidebar__folder-item>");function av(a){let e;Jt(()=>{Ei(e)});const t=()=>!!a.notifications?.count;return(()=>{const s=bN();return Ue(i=>{e=i,a.ref?.(i)},s),so(s,ni({get classList(){return{[a.class]:!!a.class,"folders-sidebar__folder-item--selected":a.selected}}},()=>a.id!==void 0?{"data-filter-id":a.id}:{},{get onClick(){return a.onClick}}),!1,!0),k(s,T(hs,{get icon(){return a.icon},class:"folders-sidebar__folder-item-icon"}),null),k(s,T(Js,{get when(){return a.name},get children(){const i=yN();return k(i,()=>a.name),i}}),null),k(s,T(Js,{get when(){return t()},get children(){return T(vN,{class:"folders-sidebar__folder-item-badge",tag:"div",get color(){return a.notifications.muted&&!a.selected?"gray":"primary"},size:18,get children(){return""+a.notifications.count}})}}),null),s})()}const wN=Y("<div class=folders-sidebar__scrollable-position>"),SN=Y("<div class=folders-sidebar__add-folders-button><div class=folders-sidebar__add-folders-button-name>");function CN(a){const{rootScope:e,appSidebarLeft:t,AppChatFoldersTab:s,AppEditFolderTab:i,showLimitPopup:n}=Xy(),r=ui(),[o,l]=K(Fi),[c,d]=Qr([]),[u,h]=K(0),[p,m]=K(!1),g=()=>p()&&o()&&!oa.has(o())&&c.find($=>$.id===o())?.chatsCount===0,[f,v]=Qr({}),y=SE(o);let w,b,S;function _($,H){const D=c.findIndex(j=>j.id===$);if(D===-1)return;const U=c[D];U.middlewareHelper?.destroy(),d(D,Ec({...U,...H}))}async function M($){_($,{notifications:await gC($,e.managers)})}async function C(){const $=c;for(const H of $)H.id&&M(H.id)}async function L($){function H(W){const ee=document.createElement("span");return ee.append(W),ee}const D=r.get().create(),[U,j,q]=await Promise.all([gC($.id,e.managers),e.managers.dialogsStorage.getFolder($.id),$.id===Fi?P("FilterAllChats"):fr($.title,D.get()).then(H)]);return{id:$.id,name:q,icon:fN($),notifications:U,chatsCount:j?.dialogs?.length||0,middlewareHelper:D}}async function E($){const H=[...c];if(H.find(q=>q.id===$.id)){_($.id,await L($));return}const[U,j]=await Promise.all([L($),fC(H,e.managers)]);H.push(U),d(j)}async function x($){const H=[...c],D=H.findIndex(j=>j.id===$);if(D===-1)return;H[D].middlewareHelper?.destroy(),H.splice(D,1),d(H)}async function R($){$=[...$],Vs($,yn);const H=[...c];H.sort((D,U)=>{const j=$.indexOf(D.id),q=$.indexOf(U.id);return j===-1?-1:q===-1?1:j-q}),d(H)}async function B($){if(!await e.managers.filtersStorage.isFilterIdAvailable($))return n("folders"),!1;l($);const D=t.hasSomethingOpenInside();t.closeEverythingInside(),D&&await ns(300),e.dispatchEventSingle("changing_folder_from_sidebar",{id:$})}let N;Jt(()=>{const $=new $t;t.createToolsMenu(w,!0),w.classList.add("sidebar-tools-button","is-visible"),w.append(a.notificationsElement),N=_M({appSidebarLeft:t,AppChatFoldersTab:s,AppEditFolderTab:i,managers:e.managers,className:"folders-sidebar__folder-item",listenTo:b}),(async()=>{const D=(await e.managers.filtersStorage.getDialogFilters()).filter(q=>q.id!==yn),U=await Promise.all(D.map(L)),j=await fC(U,e.managers);d(j)})(),$.add(e)("dialog_flush",({dialog:H})=>{H&&C()}),$.add(e)("folder_unread",H=>{H.id<0||M(H.id)}),$.add(e)("filter_update",H=>{oa.has(H.id)||E(H)}),$.add(e)("filter_delete",H=>{x(H.id)}),$.add(e)("filter_order",H=>{R(H)}),$.add(e)("changing_folder_from_chatlist",H=>{l(H)}),ze(()=>{$.removeAll(),N.destroy()})}),le(()=>{g()&&Ei(S)});const G=()=>{const $=f[o()];if(!$)return;const H=b.getBoundingClientRect(),D=$.getBoundingClientRect(),U=D.top+D.height/2-H.top,j=50;m(U>j&&U<H.height-j),h(U)};le(G);let O=!1;return[T(av,{ref:$=>w=$,class:"folders-sidebar__menu-button",icon:"menu"}),(()=>{const $=wN();return k($,T(od,{ref(H){const D=b;typeof D=="function"?D(H):b=H},class:"folders-sidebar__scrollable",onScroll:G,withBorders:"both",get children(){return T(Cs,{each:c,children:H=>{const{id:D}=H;return ze(()=>{v({[D]:void 0})}),T(av,ni(H,{ref:U=>v({[D]:U}),get selected(){return y(D)},onClick:()=>B(D)}))}})}}),null),k($,T(Yo,{type:"cross-fade",mode:"add-remove",get children(){return V(()=>!!g())()&&(()=>{const H=SN(),D=H.firstChild;H.$$click=()=>N.openSettingsForFilter(o());const U=S;return typeof U=="function"?Ue(U,H):S=H,k(H,T(hs,{icon:"plus",class:"folders-sidebar__add-folders-button-icon"}),D),k(D,()=>P("ChatList.Filter.Include.AddChat")),Me(()=>u()!=null?H.style.setProperty("--offset",u()):H.style.removeProperty("--offset")),H})()}}),null),$})(),T(av,{class:"folders-sidebar__menu-button",icon:"equalizer",onClick:()=>{O||t.getTab(s)||(O=!0,t.closeTabsBefore(()=>{t.createTab(s).open().finally(()=>{O=!1})}))}})]}function _N(a,e,t,s){Ft(i=>{wi(()=>T(t,{get children(){return T(CN,{notificationsElement:e})}}),a),s.onDestroy(()=>i())})}Fs(["click"]);class IN extends cb{constructor(e){super(e),this.managers=e.managers}}class PN extends ue{constructor(e){super("settings-slider-popup",{overlayClosable:!0,body:!0,title:!1}),this.middlewareHelper.onDestroy(()=>{ns(200).then(()=>{this.slider.closeAllTabs()})});const t=document.createElement("div");t.classList.add("settings-slider-popup__height-limit");const s=document.createElement("div");s.classList.add("sidebar-slider","tabs-container"),t.append(s),this.slider=new IN({navigationType:"settings-popup",sidebarEl:t,managers:e}),this.slider.onTabsCountChange=()=>{this.slider.hasTabsInNavigation()||this.hide()},this.body.append(t)}}const MN=Y('<svg width=23 height=22 viewBox="0 0 23 22"fill=none xmlns=http://www.w3.org/2000/svg><path d="M1.5 13.8C1.5 12.1198 1.5 11.2798 1.82698 10.638C2.1146 10.0735 2.57354 9.6146 3.13803 9.32698C3.77976 9 4.61984 9 6.3 9H11.7C13.3802 9 14.2202 9 14.862 9.32698C15.4265 9.6146 15.8854 10.0735 16.173 10.638C16.5 11.2798 16.5 12.1198 16.5 13.8V16.2C16.5 17.8802 16.5 18.7202 16.173 19.362C15.8854 19.9265 15.4265 20.3854 14.862 20.673C14.2202 21 13.3802 21 11.7 21H6.3C4.61984 21 3.77976 21 3.13803 20.673C2.57354 20.3854 2.1146 19.9265 1.82698 19.362C1.5 18.7202 1.5 17.8802 1.5 16.2V13.8Z"stroke=currentColor stroke-width=2></path><path class=lock-icon-shackle d="M20.5 8C20.5 8.55228 20.9477 9 21.5 9C22.0523 9 22.5 8.55228 22.5 8H20.5ZM13.5 8V5.5H11.5V8H13.5ZM20.5 5.5V8H22.5V5.5H20.5ZM17 2C18.933 2 20.5 3.567 20.5 5.5H22.5C22.5 2.46243 20.0376 0 17 0V2ZM13.5 5.5C13.5 3.567 15.067 2 17 2V0C13.9624 0 11.5 2.46243 11.5 5.5H13.5Z"fill=currentColor>'),LN=Y('<button class="btn-icon sidebar-lock-button"><span class=sidebar-lock-button-icon>'),EN=()=>MN(),kN=()=>{let a,e,t;const[s,i]=K(!1),n=()=>{i(!1),window.clearTimeout(t),t=void 0};return le(()=>{if(!s())return;const{close:r}=Ra({element:a,mountOn:a.parentElement,vertical:"bottom",textElement:P("PasscodeLock.TapToLock"),onClose:()=>{},lighter:!0});ze(()=>{r()})}),(()=>{const r=LN(),o=r.firstChild;r.addEventListener("mouseleave",()=>{n()}),r.addEventListener("mouseenter",()=>{t=window.setTimeout(()=>{i(!0)},500)}),r.$$click=()=>{mm.lock(e,()=>{I.dispatchEvent("toggle_locked",!0),n()})};const l=a;typeof l=="function"?Ue(l,r):a=r;const c=e;return typeof c=="function"?Ue(c,o):e=o,k(o,T(EN,{})),r})(),a},TN=()=>{let a;return{element:Ft(t=>(a=t,kN())),dispose:a}};Fs(["click"]);const kh="is-left-column-shown",hg=class hg extends cb{constructor(){super({sidebarEl:document.getElementById("column-left"),navigationType:"left"}),this.searchGroups={},this.isSearchActive=!1,this.isAnimatingCollapse=!1,this.onSomethingOpenInsideChange=(e=!1,t=!1)=>{const s=this.sidebarEl.classList.contains("has-open-tabs"),i=t||this.hasSomethingOpenInside(),n=this.isCollapsed();this.sidebarEl.classList.toggle("has-open-tabs",i),this.sidebarEl.classList.toggle("has-real-tabs",this.hasTabsInNavigation()),this.sidebarEl.classList.toggle("has-forum-open",!!nt.forumTab);const r=document.querySelector(".sidebar-left-placeholder");if(!n&&!this.hasSomethingOpenInside()){ns(300).then(()=>{I.dispatchEvent("resizing_left_sidebar")});return}if(s===i)return;const o=80,l=420,c=200,d=150;i?(this.sidebarEl.classList.add("force-hide-large-content","force-hide-menu","force-chatlist-thin"),!this.isSearchActive&&this.sidebarEl.classList.add("force-hide-search"),this.isAnimatingCollapse=!0,zi(o,l,c,u=>{this.sidebarEl.style.setProperty("--sidebar-left-width-when-collapsed",u+"px")},{onEnd:async()=>{await ns(d),this.isAnimatingCollapse=!1,this.sidebarEl.style.removeProperty("--sidebar-left-width-when-collapsed"),this.sidebarEl.classList.remove("force-hide-large-content","force-hide-menu","force-hide-search","force-chatlist-thin")}}),nt.xd.toggleAvatarUnreadBadges(!1,void 0)):(r.classList.add("keep-active"),this.sidebarEl.classList.add("force-fixed","hide-add-folders","force-chatlist-thin"),e&&this.sidebarEl.classList.add("animate-search-out"),this.buttonsContainer.classList.add("force-static","is-visible"),e&&this.hasFoldersSidebar()&&this.toolsBtn.parentElement.firstElementChild.classList.add("state-back"),this.isAnimatingCollapse=!0,zi(l,o,c,u=>{this.sidebarEl.style.setProperty("--sidebar-left-width-when-collapsed",u+"px")},{onEnd:async()=>{await ns(d),this.sidebarEl.style.removeProperty("--sidebar-left-width-when-collapsed"),this.sidebarEl.classList.remove("force-fixed","hide-add-folders","animate-search-out","force-chatlist-thin"),r.classList.remove("keep-active"),nt.xd.toggleAvatarUnreadBadges(!0,void 0),this.buttonsContainer.classList.remove("force-static"),this.buttonsContainer.classList.remove("is-visible"),this.buttonsContainer.style.transition="none",ns(200).then(()=>{this.buttonsContainer.style.removeProperty("transition"),this.isAnimatingCollapse=!1,!this.isSearchActive&&this.toolsBtn.parentElement.firstElementChild.classList.toggle("state-back",!1)})}}))}}construct(e){this.managers=e,this.chatListContainer=document.getElementById("chatlist-container"),this.inputSearch=new jo,this.inputSearch.input.placeholder=" ";const t=this.sidebarEl.querySelector(".item-main .sidebar-header");t.append(this.inputSearch.container),this.backBtn=this.sidebarEl.querySelector(".sidebar-back-button"),this.toolsBtn=this.createToolsMenu(),this.toolsBtn.classList.add("sidebar-tools-button","is-visible"),this.totalNotificationsCount=xo("span",20,"primary"),this.totalNotificationsCount.classList.add("sidebar-tools-button-notifications"),this.totalNotificationsCountSidebar=this.totalNotificationsCount.cloneNode(!0),this.toolsBtn.append(this.totalNotificationsCount);const s=this.middlewareHelper.get(),i=document.getElementById("folders-sidebar");_N(i,this.totalNotificationsCountSidebar,ep,s),ns(1e3).then(()=>{this.sidebarEl.classList.add("can-menu-have-z-index")}),I.addEventListener("notification_count_update",async()=>{const m=await hd.getNotificationsCountForAllAccounts(),g=Object.entries(m).reduce((f,[v,y])=>f+(+v!==Vr()&&y||0),0);[this.totalNotificationsCount,this.totalNotificationsCountSidebar].forEach(f=>{Ro(f,""+(g||""))})}),this.backBtn.parentElement.insertBefore(this.toolsBtn,this.backBtn),this.buttonsContainer=this.backBtn.parentElement,this.newBtnMenu=this.createNewChatsMenuButton(),t.nextElementSibling.append(this.newBtnMenu),this.updateBtn=document.createElement("div"),this.updateBtn.className="btn-circle rp btn-corner z-depth-1 btn-update is-hidden",this.updateBtn.tabIndex=-1,Ei(this.updateBtn),this.updateBtn.append(P("Update")),J(this.updateBtn,()=>{this.updateBtn.classList.contains("is-hidden")||location.reload()}),t.nextElementSibling.append(this.updateBtn),this.inputSearch.input.addEventListener("focus",()=>this.initSearch(),{once:!0}),this.archivedCount=xo("span",24,"gray"),this.archivedCount.classList.add("archived-count"),I.addEventListener("folder_unread",m=>{if(m.id===yn){const g=m.unreadPeerIds.size;Ro(this.archivedCount,g?""+un(g,1):"")}});let n,r;const o=this.getMiddleware().create(),l=yt(" sidebar-emoji-status",{noRipple:!0}),c=TN();J(l,()=>{const m=new Ua({noRegularEmoji:!0,managers:I.managers,mainSets:()=>{const v=this.managers.appStickersManager.getLocalStickerSet("inputStickerSetEmojiDefaultStatuses").then(w=>w.documents.map(b=>b.id)),y=w=>w.statuses.map(b=>b.document_id).filter(Boolean);return[Promise.all([v,this.managers.appUsersManager.getRecentEmojiStatuses().then(y),this.managers.appUsersManager.getDefaultEmojiStatuses().then(y),this.managers.appEmojiManager.getRecentEmojis("custom")]).then(w=>eo(va(w)))]},onClick:async v=>{g.hideAndDestroy();const y=zC("star")===v.emoji;let w;y?w={_:"emojiStatusEmpty"}:(w={_:"emojiStatus",document_id:v.docId},r=!0),this.managers.appUsersManager.updateEmojiStatus(w)},canHaveEmojiTimer:!0}),g=new Gl({tabsToRender:[m],customParentElement:document.body,getOpenPosition:()=>{const v=l.getBoundingClientRect(),y=HP(v);return y.left=v.left+v.width/2,y.top=v.top+v.height/2,y}}),f="primary-color";g.setTextColor(f),g.addEventListener("closed",()=>{g.hideAndDestroy()}),g.onButtonClick(),m.initPromise.then(()=>{const v=Be("star","super-emoji-premium-icon");v.style.color=`var(--${f})`;const y=m.getCustomCategory();m.addEmojiToCategory({category:y,element:v,batch:!1,prepend:!0})})});const d=async m=>{const f=Ae.getUser(I.myId.toUserId()).emoji_status;if(!f){l.replaceChildren(),Wo(l,"star");return}r&&Qo.fireAroundAnimation({middleware:n?.get()||this.getMiddleware(),reaction:{_:"reactionCustomEmoji",document_id:f.document_id},sizes:{genericEffect:26,genericEffectSize:100,size:40,effectSize:80},stickerContainer:l,cache:l,textColor:"primary-color"}),r=!1;const v=await b_({wrapOptions:{middleware:m},emojiStatus:f,size:ii(24,24)});v.classList.replace("emoji-status","sidebar-emoji-status-emoji"),l.replaceChildren(v)},u=async m=>{o.clean();const g=o.get();if(m){if(await d((n=g.create()).get()),!g())return;t.append(l),h(!0,await gp.isUsingPasscode());const f=()=>{const v=n;d((n=g.create()).get()).finally(()=>{v.destroy()})};I.addEventListener("emoji_status_change",f),g.onClean(()=>{I.removeEventListener("emoji_status_change",f)})}else h(!1,await gp.isUsingPasscode());nt.resizeStoriesList?.()},h=(m,g)=>{m?t.append(l):l.remove(),g?t.append(c.element):c.element.remove()};Ce.addEventListener("premium_toggle",u),I.addEventListener("toggle_using_passcode",m=>{h(I.premium,m)}),h(I.premium,I.settings?.passcode?.enabled),this.managers.appUsersManager.getTopPeers("correspondents"),this.initNavigation(),Ae.getState().then(m=>{const f=setInterval(()=>{fetch("version",{cache:"no-cache"}).then(v=>v.status===200&&v.ok&&v.text()||Promise.reject()).then(v=>{v!==_o.versionFull&&(this.hasUpdate=!0,clearInterval(f),this.newBtnMenu.classList.contains("is-hidden")||this.updateBtn.classList.remove("is-hidden"))}).catch(as)},18e5)}),this.onResize=()=>{const m=this.rect=this.tabsContainer.getBoundingClientRect();document.documentElement.style.setProperty("--left-column-width",m.width+"px")},$s(this.onResize),st.addEventListener("resize",this.onResize),this.searchTriggerWhenCollapsed=document.createElement("div"),this.searchTriggerWhenCollapsed.className="sidebar-header-search-trigger",this.searchTriggerWhenCollapsed.append(yt("search")),this.searchTriggerWhenCollapsed.addEventListener("click",()=>{this.initSearch().open()}),this.buttonsContainer.parentElement.prepend(this.searchTriggerWhenCollapsed),document.querySelector(".sidebar-left-overlay").addEventListener("click",()=>{this.closeEverythingInside()}),this.initSidebarResize(),nt.onForumTabToggle=()=>{this.onSomethingOpenInsideChange()},zm(["ctrl+f","alt+f","meta+f"],()=>{Pt.findItemByType("popup")||this.initSearch().open()}),zm(["ctrl+0","meta+0"],()=>{Pt.findItemByType("popup")||Ce.chat.peerId===Ce.myId||Ce.setPeer({peerId:Ce.myId})})}initNavigation(){const e={type:"global-search-focus",onPop:()=>(setTimeout(()=>{this.isAnimatingCollapse||this.initSearch().open()},0),!1),noHistory:!0};Pt.removeByType("global-search-focus"),Pt.pushItem(e)}isCollapsed(){return this.sidebarEl.classList.contains("is-collapsed")}hasFoldersSidebar(){return document.body.classList.contains("has-folders-sidebar")}onCollapsedChange(e=!1){this.chatListContainer.parentElement.classList.toggle("fade",this.isCollapsed()),this.chatListContainer.parentElement.classList.toggle("zoom-fade",!this.isCollapsed()),nt.xd.toggleAvatarUnreadBadges(this.isCollapsed(),void 0),e&&this.isCollapsed()&&!this.hasFoldersSidebar()&&this.showCtrlFTip()}hasSomethingOpenInside(){return this.hasTabsInNavigation()||this.isSearchActive||!!nt.forumTab}closeEverythingInside(){return this.closeSearch(),nt.toggleForumTab(),this.closeAllTabs()}showCtrlFTip(){const e="ctrlf-toast-to-show-again",t=parseInt(localStorage.getItem(e)),s=Qs(!0);if(t&&s<t)return;$e({langPackKey:$o?"CtrlFSearchTipMac":"CtrlFSearchTip"});const i=(Math.round(Math.random()*7*7)+7)*24*60*60;localStorage.setItem(e,s+i+"")}initSidebarResize(){this.onTabsCountChange=()=>{this.onSomethingOpenInsideChange()};const e=document.createElement("div");e.classList.add("sidebar-resize-handle"),this.sidebarEl.append(e);const t=fa(s=>{localStorage.setItem("sidebar-left-width",s+"")},200);new Qn({element:e,setCursorTo:document.body,onStart:()=>{e.classList.add("is-active"),document.body.classList.add("resizing-left-sidebar")},onSwipe:(s,i,n)=>{const r=ym(n),o=this.sidebarEl.getBoundingClientRect(),l=Math.round(r.clientX-o.left),c=zt(l%2?l+1:l,Xw,ME);document.documentElement.style.setProperty("--current-sidebar-left-width",c+"px"),this.onResize(),I.dispatchEvent("resizing_left_sidebar");const d=this.isCollapsed(),u=!this.hasSomethingOpenInside()&&l<Xw*CE;this.sidebarEl.classList.toggle("is-collapsed",u),u!==d&&this.onCollapsedChange(!0),Ce.adjustChatPatternBackground(),t(u?0:c)},onReset:()=>{e.classList.remove("is-active"),document.body.classList.remove("resizing-left-sidebar")}})}createToolsMenu(e,t){const s=async h=>{t&&this.closeEverythingInside()&&await ns(200),h()},i={icon:"archive",text:"ArchivedChats",onClick:()=>{s(()=>{this.createTab(Ly).open()})},verify:async()=>{const h=await this.managers.dialogsStorage.getFolderDialogs(yn,!1),p=await this.managers.appStoriesManager.hasArchive();return!!h.length||p||!await this.managers.dialogsStorage.isDialogsLoaded(yn)}},n=()=>{s(()=>{this.createTab(mC).open()})},r=this.createSubmenuHelper({text:"MultiAccount.More",icon:"more"},()=>this.createMoreSubmenu(r,s)),o=this.createSubmenuHelper({text:"CreateANew",icon:"edit",verify:()=>this.isCollapsed(),separator:!0},()=>this.createNewChatsSubmenu()),c=[{icon:"plus",text:"MultiAccount.AddAccount",onClick:async h=>{const p=await vc.getTotalAccounts();if(p>=Zw)return;const m=await Ae.hasSomeonePremium();if(p===d_&&!m){new mN().show();return}localStorage.setItem("previous-account",Vr()+"");const g=await gp.isUsingPasscode(),f=Ae.getOpenTabsCount(),v=h.ctrlKey||h.metaKey||f<=1&&g;if(!v){Ce.goOffline(),localStorage.setItem("should-animate-auth","true");const y=document.querySelector(".page-chats");y.classList.add("main-screen-exit"),await hi(),y.classList.add("main-screen-exiting"),await ns(200)}Jw(p+1,v)},verify:async()=>await vc.getTotalAccounts()<Zw},o.menuBtnOptions,{icon:"savedmessages",text:"SavedMessages",onClick:()=>{setTimeout(()=>{Ce.setPeer({peerId:Ce.myId})},0)},separator:!0},i,{icon:"stories",text:"MyStories.Title",onClick:()=>{s(()=>{this.createTab(dd).open()})},verify:()=>!_E},{icon:"user",text:"Contacts",onClick:n},{id:"settings",icon:"settings",text:"Settings",separator:!0,onClick:()=>{s(()=>{this.createTab(Eh).open()})}},r.menuBtnOptions].filter(Boolean),d=c.slice();return ki({direction:"bottom-right",buttons:c,container:e,onOpenBefore:async()=>{const h=await this.managers.appAttachMenuBotsManager.getAttachMenuBots(),p=d.slice(),m=h.filter(b=>b.pFlags.show_in_side_menu).map(b=>{const S=hw(b);return{regularText:je(b.short_name),onClick:()=>{Ce.openWebApp({attachMenuBot:b,botId:b.bot_id,isSimpleWebView:!0,fromSideMenu:!0})},iconDoc:S?.icon,new:b.pFlags.side_menu_disclaimer_needed||b.pFlags.inactive}});function g(b){let S=b.first_name;return b.last_name&&(S+=" "+b.last_name),S=Ya(S,15,18),je(S)}const f=p.findIndex(b=>b.id==="settings");p[f].separator=!!m.length,p.splice(f,0,...m),p[f].separator=!0;const[v,y]=await Promise.all([vc.getTotalAccounts(),hd.getNotificationsCountForAllAccounts()]),w=[];for(let b=1;b<=v;b++){const S=b;if(S===Vr()){const _=await this.managers.appUsersManager.getSelf();w.push({avatarInfo:{accountNumber:Vr(),peerId:I.myId.toPeerId(),active:!0},regularText:g(_),onClick:()=>{s(()=>{this.createTab(Eh).open()})}})}else{const _=pm(S),C=(await vc.get(S))?.userId?.toPeerId(),L=await _.appUsersManager.getSelf(),E=document.createElement("span");if(E.append(g(L)),y[S]){const x=xo("span",20,"primary");Ro(x,""+y[S]),E.append(x)}w.push({avatarInfo:{accountNumber:S,peerId:C,peer:L},className:"btn-menu-account-item",regularText:E,onClick:async x=>{const R=x.ctrlKey||x.metaKey;if(!R){Ce.goOffline();const B=document.querySelector(".chatlist-container")?.firstElementChild;B.classList.add("chatlist-exit"),await hi(),B.classList.add("chatlist-exiting"),await ns(200),await this.saveEncryptionKeyBeforeSwitchingAccounts()}Jw(S,R)}})}}p.splice(0,0,...w),c.splice(0,c.length,...p)},onOpen:()=>{r.onOpen(),o.onOpen(),i.element?.append(this.archivedCount)},onClose:()=>{r.onClose(),o.onClose()},noIcon:!0})}async saveEncryptionKeyBeforeSwitchingAccounts(){if(!await gp.isUsingPasscode())return;Ae.getOpenTabsCount()<=1&&await pf.set({encryption_key:await IE.getAsBase64()})}async createMoreSubmenu(e,t){const s=()=>Ls.getTheme().name==="night",i=()=>{const v=o[0].element.querySelector(".tgico").getBoundingClientRect();Ls.switchTheme(s()?"day":"night",{x:v.left+v.width/2,y:v.top+v.height/2})},n=document.createElement("span");n.append(P(s()?"DisableDarkMode":"EnableDarkMode"));const r=document.createElement("span"),o=[{icon:"darkmode",regularText:n,onClick:()=>{}},{id:"animations-toggle",icon:"animations",regularText:r,onClick:()=>{d()},verify:()=>!wt.isEnabled()},{icon:"animations",text:"LiteMode.Title",onClick:()=>{t(()=>{this.createTab(SM).open()})},verify:()=>wt.isEnabled()},{icon:"aversion",text:"ChatList.Menu.SwitchTo.A",onClick:()=>{Promise.all([pf.set({kz_version:"Z"}),pf.delete("tgme_sync")]).then(()=>{location.href="https://web.telegram.org/a/"})},separator:_o.isMainDomain,verify:()=>_o.isMainDomain},{icon:"help",text:"TelegramFeatures",onClick:()=>{const g=Ne.format("TelegramFeaturesUrl",!0);Ce.openUrl(g)},separator:!_o.isMainDomain},{icon:"bug",text:"ReportBug",onClick:()=>{const g=document.createElement("a");jl(g),g.href="https://bugs.telegram.org/?tag_ids=40&sort=time",document.body.append(g),g.click(),setTimeout(()=>{g.remove()},0)}},{icon:"plusround",text:"PWA.Install",onClick:()=>{eS()?.()},verify:()=>!!eS()}];async function l(){return!I.settings.liteMode.animations}async function c(){u(await l())}async function d(){u(!await l()),I.managers.appStateManager.setByKey(ci("settings","liteMode","animations"),await l())}async function u(g){const f=o.find(y=>y.id==="animations-toggle")?.element;if(!f)return;const v=f.querySelector(".tgico");g?v?.classList.add("animations-icon-off"):v?.classList.remove("animations-icon-off"),r.replaceChildren(P(g?"DisableAnimations":"EnableAnimations"))}const h=await zn(o,g=>g?.verify?g.verify()??!1:!0),p=await Kh({buttons:h});return p.append(xN()),p.classList.add("sidebar-tools-submenu"),o[0].element.addEventListener(Eo,g=>{g.stopPropagation(),i(),ns(20).then(()=>Li.close())},!0),c(),p}createSubmenuHelper(e,t){const s={...e,get regularText(){const o=document.createElement("span");return o.classList.add("submenu-label"),o.append(P(e.text),Be("arrowhead")),o},onClick:as,id:hg.submenuHelperIdSeed++};delete s.text;let i=!1;return{menuBtnOptions:s,onOpen:()=>{s.element&&(s.element.addEventListener(Eo,o=>{o.stopPropagation()},!0),s.element.classList.add("disable-click"),cN({element:s.element,direction:"right-start",createMenu:t,offset:[-5,-5],level:2,triggerEvent:"mouseenter",canOpen:()=>!i}))},onClose:async()=>{i=!0,await ns(200),i=!1}}}createNewChatsMenuOptions(e,t){const s=async r=>{e&&this.closeEverythingInside()&&await ns(200),r()};return[{icon:"newchannel",text:t?"Channel":"NewChannel",onClick:()=>{s(()=>{this.createTab(oN).open()})}},{icon:"newgroup",text:t?"Group":"NewGroup",onClick:()=>{s(()=>{this.createTab(Zu).open({type:"chat",skippable:!0,takeOut:r=>this.createTab(Q_).open({peerIds:r}),title:"GroupAddMembers",placeholder:"SendMessageTo"})})}},{icon:"newprivate",text:t?"PrivateChat":"NewPrivateChat",onClick:()=>{s(()=>{this.createTab(mC).open()})}}]}createNewChatsMenuButton(){const e=ki({direction:"top-left",buttons:this.createNewChatsMenuOptions(!1),noIcon:!0});e.className="btn-new-menu btn-circle rp btn-corner z-depth-1 btn-menu-toggle animated-button-icon",e.tabIndex=-1;const t=["newchat_filled","close"];return e.prepend(...t.map((s,i)=>Be(s,"animated-button-icon-icon","animated-button-icon-icon-"+(i===0?"first":"last")))),e.id="new-menu",e}createNewChatsSubmenu(){return Kh({buttons:this.createNewChatsMenuOptions(!0,!0)})}initSearch(){if(this.searchInitResult)return this.searchInitResult;const e=this.sidebarEl.querySelector("#search-container"),t=new tn(e),s=()=>{Xs(this.backBtn)};this.searchGroups={contacts:new aa("SearchAllChatsShort","contacts",void 0,void 0,void 0,void 0,s),globalContacts:new aa("GlobalSearch","contacts",void 0,void 0,void 0,void 0,s),messages:new aa("SearchMessages","messages"),people:new aa(!1,"contacts",!0,"search-group-people",!0,!1,s,!0),recent:new aa("Recent","contacts",!0,"search-group-recent",!0,!0,s)};const i=this.searchSuper=new ww({mediaTabs:[{inputFilter:"inputMessagesFilterEmpty",name:"FilterChats",type:"chats"},{name:"ChannelsTab",type:"channels"},{name:"MiniApps.AppsSearch",type:"apps"},{inputFilter:"inputMessagesFilterPhotoVideo",name:"SharedMediaTab2",type:"media"},{inputFilter:"inputMessagesFilterUrl",name:"SharedLinksTab2",type:"links"},{inputFilter:"inputMessagesFilterDocument",name:"SharedFilesTab2",type:"files"},{inputFilter:"inputMessagesFilterMusic",name:"SharedMusicTab2",type:"music"},{inputFilter:"inputMessagesFilterRoundVoice",name:"SharedVoiceTab2",type:"voice"}],scrollable:t,searchGroups:this.searchGroups,asChatList:!0,hideEmptyTabs:!1,showSender:!0,managers:this.managers});this.watchChannelsTabVisibility(),e.prepend(i.nav.parentElement.parentElement),t.append(i.container),(()=>{i.setQuery({peerId:"".toPeerId(),folderId:0}),i.selectTab(0),i.load(!0)})();const r=[];let o="".toPeerId(),l=0,c=0;const d=()=>{this.inputSearch.container.classList.toggle("is-picked-twice",r.length===2),this.inputSearch.container.classList.toggle("is-picked",!!r.length),r.forEach((C,L)=>{C.classList.remove("is-first","is-last"),C.classList.add(L===0?"is-first":"is-last")}),r.length?this.inputSearch.input.style.setProperty("--paddingLeft",r[r.length-1].getBoundingClientRect().right-this.inputSearch.input.getBoundingClientRect().left+"px"):this.inputSearch.input.style.removeProperty("--paddingLeft")},u=this.middlewareHelper.get().create(),h=document.createElement("div");h.classList.add("search-helper","hide"),h.addEventListener("click",C=>{const L=ne(C.target,"selector-user");if(!L)return;const E=L.dataset.key;if(E.indexOf("date_")===0){const[x,R,B]=E.split("_");l=+R,c=+B}else o=E.toPeerId();L.addEventListener("click",()=>{m(L)}),this.inputSearch.container.append(L),this.inputSearch.onChange(this.inputSearch.value=""),r.push(L),d()}),i.nav.parentElement.append(h);const p=(C,L)=>wn.renderEntity({key:C,title:L,middleware:u.get(),avatarSize:30,fallbackIcon:"calendarfilter"}).element,m=C=>{C.dataset.key.indexOf("date_")===0?l=c=0:o="".toPeerId(),C.middlewareHelper.destroy(),C.remove(),Vs(r,C),setTimeout(()=>{d(),this.inputSearch.onChange(this.inputSearch.value)},0)};this.inputSearch.onClear=()=>{r.forEach(C=>{m(C)}),h.replaceChildren(),g()};const g=(C=!h.firstElementChild)=>{h.classList.toggle("hide",C),i.nav.classList.toggle("hide",!C)},f=C=>{h.append(...C),g()};this.inputSearch.onChange=C=>{i.cleanupHTML(),i.setQuery({peerId:o,folderId:o?void 0:0,query:C,minDate:l,maxDate:c}),i.load(!0),u.clean(),g(!0);const L=[];if(!l&&C.trim()){const E=[];PE(C,E);const x=E.map(R=>p("date_"+R.minDate+"_"+R.maxDate,R.title));L.push(x)}if(!o&&C.trim()){const E=i.middleware.get(),x=Promise.all([this.managers.dialogsStorage.getDialogs({query:C}).then(({dialogs:R})=>R.map(B=>B.peerId)),this.managers.appUsersManager.getContactsPeerIds(C,!0)]).then(R=>E()?[...new Set(R[0].concat(R[1]).slice(0,20))].map(N=>p(N)):void 0);L.push(x)}Promise.all(L).then(E=>{h.replaceChildren();const x=va(E);f(x)})},i.tabs.inputMessagesFilterEmpty.addEventListener("mousedown",C=>{const L=Mn(C.target,tc);if(!L)return;const E=ne(L,"search-group");if(!E||E.classList.contains("search-group-recent")||E.classList.contains("search-group-people"))return;const x=L.getAttribute("data-peer-id").toPeerId();this.managers.appUsersManager.pushRecentSearch(x)},{capture:!0});const v=document.createElement("div");v.classList.add("search-group-scrollable"),v.append(this.searchGroups.people.list),this.searchGroups.people.container.append(v),new io(v);let y=!0,w;const b=Sr({content:e.parentElement,type:"zoom-fade",transitionTime:150,onTransitionStart:C=>{e.parentElement.parentElement.classList.toggle("is-search-active",C===1)},onTransitionEnd:C=>{w&&clearTimeout(w),C===0&&!y&&(i.selectTab(0,!1),this.inputSearch.onClearClick(),w=window.setTimeout(()=>{w=0,this.newBtnMenu.classList.remove("is-hidden"),this.hasUpdate&&this.updateBtn.classList.remove("is-hidden")},150)),y=!1}});b(0);const S="is-visible",_=()=>{this.toolsBtn.classList.remove(S),this.backBtn.classList.add(S),this.newBtnMenu.classList.add("is-hidden"),this.updateBtn.classList.add("is-hidden"),this.toolsBtn.parentElement.firstElementChild.classList.toggle("state-back",!0);const C="global-search";!wr&&!Pt.findItemByType(C)&&Pt.pushItem({onPop:()=>{if(this.isAnimatingCollapse)return!1;s()},type:C}),b(1),this.buttonsContainer.classList.add("is-visible"),this.isSearchActive=!0,this.onSomethingOpenInsideChange()};this.inputSearch.input.addEventListener("focus",_),_(),J(this.backBtn,C=>{this.toolsBtn.classList.add(S),this.backBtn.classList.remove(S),this.toolsBtn.parentElement.firstElementChild.classList.toggle("state-back",!1),Pt.removeByType("global-search"),b(0),this.buttonsContainer.classList.remove("is-visible"),this.isSearchActive=!1,this.onSomethingOpenInsideChange(!0)});const M=yt("close");return this.searchGroups.recent.nameEl.append(M),M.addEventListener("click",()=>{Rt({descriptionLangKey:"Search.Confirm.ClearHistory",button:{langKey:"ClearButton",isDanger:!0}}).then(()=>this.managers.appUsersManager.clearRecentSearch().then(()=>{this.searchGroups.recent.clear()}))}),this.searchInitResult={open:(C=!0)=>{_(),C&&this.inputSearch.input.focus()},close:()=>{s()}}}async watchChannelsTabVisibility(){const e=async()=>{const t=await this.managers.dialogsStorage.getCachedDialogs();let s=!1;for(const n of t)if(s=await this.managers.appPeersManager.isBroadcast(n.peerId),s)break;this.searchSuper.mediaTabs.find(n=>n.type==="channels").menuTab?.classList.toggle("hide",!s)};e(),I.addEventListener("channel_update",()=>{ns(200).then(()=>e())}),I.addEventListener("peer_deleted",()=>{e()})}closeSearch(){Xs(this.backBtn)}createTab(e,t=!0,s){const i=[Eh,vr,Cd];if(this.isCollapsed()&&!st.isLessThanFloatingLeftSidebar&&i.includes(e)){const n=new PN(this.managers);return n.show(),n.slider.createTab(e,t,s)}return super.createTab(e,t,s)}async closeTabsBefore(e){this.closeEverythingInside()&&await ns(200),e()}};hg.submenuHelperIdSeed=0;let Ey=hg;const IM=new Ey;Di.appSidebarLeft=IM;const Ri=IM;function xN(){const a=document.createElement("a");a.href="https://github.com/morethanwords/tweb/blob/master/CHANGELOG.md",jl(a),a.classList.add("btn-menu-footer"),a.addEventListener(Eo,t=>{t.stopPropagation(),Li.close()});const e=document.createElement("span");return e.classList.add("btn-menu-footer-text"),e.textContent=`Telegram Web${_o.suffix} ${_o.version} (${_o.build})`,a.append(e),a}class rv{constructor(e,t){this.options=t,this.onDragOver=r=>{this.container.classList.add("is-dragover")},this.onDragLeave=r=>{this.container.classList.remove("is-dragover")},this.onDrop=r=>{this.options.onDrop(r)},this.container=document.createElement("div"),this.container.classList.add("drop","z-depth-1"),this.outlineWrapper=document.createElement("div"),this.outlineWrapper.classList.add("drop-outline-wrapper"),this.svg=document.createElementNS("http://www.w3.org/2000/svg","svg"),this.svg.classList.add("drop-outline"),this.path=document.createElementNS("http://www.w3.org/2000/svg","path"),this.path.classList.add("drop-outline-path");let s;t.icon&&(s=document.createElement("div"),s.classList.add("drop-icon"),s.append(Be(t.icon)),this.container.classList.add("has-icon"));const i=document.createElement("div");i.classList.add("drop-header"),i.append(P(t.header,t.headerArgs));let n;t.subtitle&&(n=document.createElement("div"),n.classList.add("drop-subtitle"),n.append(P(t.subtitle))),this.svg.append(this.path),this.outlineWrapper.append(this.svg),this.container.append(...[s,i,n,this.outlineWrapper].filter(Boolean)),e.append(this.container),this.container.addEventListener("dragover",this.onDragOver),this.container.addEventListener("dragleave",this.onDragLeave),this.container.addEventListener("drop",this.onDrop)}destroy(){delete this.options,this.container.remove(),this.container.removeEventListener("dragover",this.onDragOver),this.container.removeEventListener("dragleave",this.onDragLeave),this.container.removeEventListener("drop",this.onDrop)}setPath(){const e=this.outlineWrapper.getBoundingClientRect();this.svg.setAttributeNS(null,"preserveAspectRatio","none"),this.svg.setAttributeNS(null,"viewBox",`0 0 ${e.width} ${e.height}`),this.svg.setAttributeNS(null,"width",`${e.width}`),this.svg.setAttributeNS(null,"height",`${e.height}`);const t=10,s=e.width-t,i=e.height-t,n=t/2,r=_c(n,n,s,i,t,t,t,t);this.path.setAttributeNS(null,"d",r)}}function vC(a){a.forEach(e=>e.classList.add("no-transition")),hi().then(()=>{a.forEach(e=>e.classList.remove("no-transition"))})}const AN=8.2,RN=.8;class ov{constructor(e){this.maxRadius=10,this.minRadius=0,this.N=e,this.radius=new Array(e+1),this.radiusNext=new Array(e+1),this.progress=new Array(e+1),this.speed=new Array(e+1);for(let t=0;t<=e;t++)this.generateBlob(this.radius,t),this.generateBlob(this.radiusNext,t),this.progress[t]=0}generateBlob(e,t){const{maxRadius:s,minRadius:i,speed:n}=this,r=s-i;e[t]=i+Math.random()*r,n[t]=.017+.003*Math.random()}generateNextBlob(){const{radius:e,radiusNext:t,progress:s,N:i}=this;for(let n=0;n<i;n++)this.generateBlob(e,n),this.generateBlob(t,n),s[n]=0}update(e,t){const{N:s,progress:i,speed:n,radius:r,radiusNext:o}=this;for(let l=0;l<=s;l++)i[l]+=n[l]*RN+e*n[l]*AN*t,i[l]>=1&&(i[l]=0,r[l]=o[l],this.generateBlob(o,l))}draw(e,t,s,i,n,r,o,l){if(n.getContext){const c=n.getContext("2d");c.beginPath(),c.moveTo(s,i),c.lineTo(e,i);const{radius:d,radiusNext:u,N:h}=this;for(let p=0;p<=h;p++)if(p===0){const m=this.progress[p],g=d[p]*(1-m)+u[p]*m,f=(t-g)*l+o*(1-l);c.lineTo(e,f)}else{const m=this.progress[p-1],g=d[p-1]*(1-m)+u[p-1]*m,f=this.progress[p],v=d[p]*(1-f)+u[p]*f,y=(s-e)/h*(p-1),w=(s-e)/h*p,b=y+(w-y)/2,S=(t-g)*l+o*(1-l),_=(t-v)*l+o*(1-l);c.bezierCurveTo(b,S,b,_,w,_),p===h&&c.lineTo(s,i)}r(c),c.fill(),c.closePath()}}}class ig{constructor(e,t){this.type=e,this.state=t,this.createGradient()}createGradient(){this.shader=(e,t,s,i,n)=>{e.fillStyle=ig.getGradientFromType(e,this.type,this.state,t,s,i,n)}}update(e,t,s,i){}static createStates(e,t){return t.map(s=>[s,new ig(e,s)])}static getGradientFromType(e,t,s,i,n,r,o){const l=e.createLinearGradient(i,n,r,o),c=[[0,"#F05459"],[.4,"#766EE9"],[1,"#57A4FE"]],d=[[0,"#52CE5D"],[1,"#00B1C0"]],u=[[0,"#0976E3"],[1,"#2BCEFF"]],h=[[0,"#8599aa"],[1,"#8599aa"]],p=[[0,"#4588E3"],[.5,"#976FFF"],[1,"#E46ACE"]],g={group:[[[qs.MUTED_BY_ADMIN],c],[[qs.UNMUTED],d],[[qs.MUTED],u],[[qs.CONNECTING],h]],rtmp:[[[qn.PLAYING],p],[[qn.BUFFERING,qn.CONNECTING],h]]}[t];for(const[f,v]of g)if(f.includes(s)){for(const[y,w]of v)l.addColorStop(y,w);return l}}}class FN{constructor(){this.handleDevicePixelRatioChanged=t=>{this.setSize(),this.forceUpdate()},this.handleResize=()=>{this.resizeHandler&&(clearTimeout(this.resizeHandler),this.resizeHandler=null),this.resizing=!0,this.resizeCanvas(),this.resizeHandler=window.setTimeout(()=>{this.resizing=!1,this.invokeDraw()},250)},this.handleFocus=()=>{this.focused=!0,this.invokeDraw()},this.handleBlur=()=>{this.focused=!1},this.invokeDraw=()=>{this.raf||this.draw()},this.draw=(t=!1)=>{if(this.raf=null,!this.mounted)return;const{lbd:s,lbd1:i,lbd2:n,scale:r,left:o,top:l,right:c,bottom:d,currentState:u,previousState:h,focused:p,resizing:m,canvas:g}=this;if(!p&&!m&&this.progressToState>=1)return;let v=Date.now()-this.lastUpdateTime;v>20&&(v=17),this.animateToAmplitude!==this.amplitude&&(this.amplitude+=this.animateAmplitudeDiff*v,this.animateAmplitudeDiff>0?this.amplitude>this.animateToAmplitude&&(this.amplitude=this.animateToAmplitude):this.amplitude<this.animateToAmplitude&&(this.amplitude=this.animateToAmplitude)),this.animateToAmplitude!==this.amplitude2&&(this.amplitude2+=this.animateAmplitudeDiff2*v,this.animateAmplitudeDiff2>0?this.amplitude2>this.animateToAmplitude&&(this.amplitude2=this.animateToAmplitude):this.amplitude2<this.animateToAmplitude&&(this.amplitude2=this.animateToAmplitude)),h&&(this.progressToState+=v/250,this.progressToState>1&&(this.progressToState=1,this.previousState=null));const{amplitude:y,amplitude2:w,progressToState:b}=this,S=6*w*r,_=6*w*r;g.getContext("2d").clearRect(0,0,g.width,g.height),s.minRadius=0,s.maxRadius=(2+2*y)*r,i.minRadius=0,i.maxRadius=(3+9*y)*r,n.minRadius=0,n.maxRadius=(3+9*y)*r,s.update(y,.3),i.update(y,.7),n.update(y,.7);for(let C=0;C<2;C++){if(C===0&&!h)continue;let L=1,E;C===0?(L=1-b,E=h):(L=h?b:1,u.update(d-l,c-o,v,y),E=u);const x=B=>{B.globalAlpha=.3*L,E.shader(B,o,l,c,d)},R=B=>{B.globalAlpha=C===0?1:L,E.shader(B,o,l,c,d)};i.draw(o,l-S,c,d,g,x,l,1),n.draw(o,l-_,c,d,g,x,l,1),s.draw(o,l,c,d,g,R,l,1)}t||(this.raf=requestAnimationFrame(()=>this.draw()))},this.setCurrentState=(t,s,i)=>{const{currentState:n}=this;n?.state===s&&n.type===t||(this.type=t,this.previousState=i?n:null,this.currentState=this.states.get(s),this.progressToState=this.previousState?0:1)},this.focused=!0,this.resizing=!1,this.lastUpdateTime=Date.now(),this.amplitude=0,this.amplitude2=0;const e=[["group",[qs.UNMUTED,qs.MUTED,qs.MUTED_BY_ADMIN,qs.CONNECTING]],["rtmp",[qn.PLAYING,qn.BUFFERING,qn.CONNECTING]]];this.allStates=new Map(e.map(([t,s])=>[t,new Map(ig.createStates(t,s))])),this.type="group",this.previousState=null,this.currentState=this.states.get(qs.CONNECTING),this.progressToState=1}get states(){return this.allStates.get(this.type)}componentDidMount(){this.mounted||(this.mounted=!0,window.addEventListener("resize",this.handleResize),this.media=window.matchMedia("screen and (min-resolution: 2dppx)"),this.media.addEventListener("change",this.handleDevicePixelRatioChanged),this.setSize(),this.forceUpdate(),this.lbd=new ov(3),this.lbd1=new ov(7),this.lbd2=new ov(8),this.setAmplitude(this.amplitude),this.draw())}componentWillUnmount(){this.mounted=!1,window.removeEventListener("resize",this.handleResize),this.media.removeEventListener("change",this.handleDevicePixelRatioChanged);const{canvas:e}=this;e.getContext("2d").clearRect(0,0,e.width,e.height)}setSize(){this.scale=window.devicePixelRatio,this.top=20*this.scale,this.right=(this.mounted?this.container.offsetWidth:1261)*this.scale,this.bottom=(this.mounted?this.container.offsetHeight:68)*this.scale,this.left=0*this.scale,this.setCanvasSize()}setCanvasSize(){this.canvas.width=this.right,this.canvas.height=this.bottom}resizeCanvas(){this.scale=window.devicePixelRatio,this.right=this.container.offsetWidth*this.scale,this.forceUpdate(),this.invokeDraw()}setAmplitude(e){const{amplitude:t}=this;this.animateToAmplitude=e,this.animateAmplitudeDiff=(e-t)/250,this.animateAmplitudeDiff2=(e-t)/120}forceUpdate(){this.setCanvasSize()}render(e){const t=this.container=document.createElement("div");t.classList.add(e);const s=this.canvas=document.createElement("canvas");return s.classList.add(e+"-canvas"),t.append(s),t}}class yC{constructor(e,t){this.item=e,Nt(this,t)}play(e){return this.item.playPart(this,e)}}class BN{constructor(e,t){this.icon=e,this.autoplay=!1,Nt(this,t),this.parts=this.parts.map(s=>this.createPart(s))}load(){let e=this.loadPromise;if(e)return e;const{container:t,canvas:s,width:i,height:n}=this.icon;return e=Ns.loadAnimationAsAsset({container:t,canvas:s,width:i,height:n,group:"none",loop:!1,autoplay:this.autoplay??!1,initFrame:this.initFrame,skipFirstFrameRendering:this.initFrame===void 0,color:this.color},this.name).then(r=>Ns.waitForFirstFrame(r)).then(r=>{this.player=r,this.onLoadForColor&&(this.onLoadForColor(),this.onLoadForColor=void 0),this.onLoadForPart&&(this.onLoadForPart(),this.onLoadForPart=void 0)}),this.loadPromise=e,this.icon.loadPromises.set(this.name,e),e}createPart(e){return new yC(this,e)}getPart(e){return e instanceof yC?e:typeof e=="string"?this.parts.find(t=>t.name===e):this.parts[e]}playPart(e,t){return this.icon.playPart(this,e,t)}}class PM{constructor(e){Nt(this,e),this.container||(this.container=document.createElement("div")),this.container.classList.add("rlottie-icon");const{width:t,height:s}=this;this.container.style.width=t+"px",this.container.style.height=s+"px";const i=this.canvas=document.createElement("canvas");i.classList.add("rlottie"),i.width=t,i.height=s,this.items=new Map,this.loadPromises=new Map}get loadPromise(){return Promise.all([...this.loadPromises.values()]).then(as)}getItem(e){return!e&&this.items.size===1?this.items.values().next().value:this.items.get(e)}add(e){const t=new BN(this,e);return this.items.set(e.name,t),t}playPart(e,t,s){if(!e.player){e.onLoadForPart=()=>{this.playPart(e,t,s)};return}const i=e.getPart(t);e.player.playPart({from:wt.isAvailable("animations")&&!this.skipAnimation?i.startFrame:i.endFrame,to:i.endFrame,callback:s})}static generateEqualParts(e,t){return new Array(e).fill(0).map((s,i)=>{const n=i*t;return{startFrame:n,endFrame:n+t-1}})}}class Iw extends PM{constructor(e){super({width:e.width,height:e.height}),Nt(this,e)}load(e,t){if(this.loaded)return this.loadPromise;this.loaded=!0,this.partState=e,this.colorState=t;const s=this.getPart(e),i=t!==void 0&&this.getColor&&this.getColor(t),n=s.item;n.initFrame=s.endFrame,n.color=i;const r=[...this.items.values()].map(o=>o.load());return Promise.all(r).then(as)}setState(e,t,s){this.loaded||this.load(e,t);let i=!1,n=!1;return e!==void 0?i=this.setPartState(e,t,s):t!==void 0&&(n=this.setColorState(t)),i||n}setPartState(e,t,s){const{partState:i}=this;return i===e?t!==void 0?this.setColorState(t):!1:(t!==void 0&&this.setColorState(t,!1),this.partState=e,this.getPart(e,i).play(s),!0)}setColorState(e,t=!0){const{colorState:s}=this;if(s===e||!this.getColor)return!1;this.colorState=e;const i=this.getItem(),n=this.getColor(e,s),r=()=>{i.player.setColor(n,t)};return i.player?r():i.onLoadForColor=r,!0}destroy(){this.items.forEach(e=>{e.loadPromise.then(()=>{e.player.remove()})})}}class DN extends Iw{constructor(){super({width:36,height:36,getPart:(s,i)=>{const n=Lw;let r;switch(s){case n.HAND:r=i===n.MUTED?"muted-to-hand":"unmuted-to-hand";break;case n.MUTED:r=i===n.HAND?"hand-to-muted":"mute";break;case n.UNMUTED:r="unmute";break}return this.getItem().getPart(r)}}),this.container.classList.add("group-call-microphone-icon"+"-container");const t=[{startFrame:0,endFrame:35,name:"hand-to-muted"},{startFrame:36,endFrame:68,name:"unmute"},{startFrame:69,endFrame:98,name:"mute"},{startFrame:99,endFrame:135,name:"muted-to-hand"},{startFrame:136,endFrame:172,name:"unmuted-to-hand"},{startFrame:173,endFrame:201,name:"scheduled-crossing"},{startFrame:202,endFrame:236,name:"scheduled-to-muted"},{startFrame:237,endFrame:273,name:"scheduled-to-hand"},{startFrame:274,endFrame:310,name:"scheduled-crossed-to-hand"},{startFrame:311,endFrame:343,name:"scheduled-uncrossing"},{startFrame:344,endFrame:375,name:"scheduled-to-muted"},{startFrame:376,endFrame:403,name:"play-to-muted"}];this.add({name:"voip_filled",parts:t})}}class MM extends Iw{constructor(e){super({width:32,height:32,getPart:(i,n)=>{const r=Ed;let o;switch(i){case r.HAND:o=3;break;case r.MUTED:o=n===r.HAND?0:2;break;case r.UNMUTED:o=1;break}return this.getItem().getPart(o)},getColor:e?(i,n)=>VN(i):void 0}),this.colored=e,this.container.classList.add("group-call-participant-muted-icon"+"-container");const s=PM.generateEqualParts(4,21);this.add({name:"voice_outlined2",parts:s})}setState(e){return super.setState(GN(e),e)}}const Op="group-call-participant-status";class LM{constructor(e){this.withIcons=e,this.container=document.createElement("div"),this.container.classList.add(Op+"-container")}setState(e,t){const s=Ed,i=this.withIcons.filter(l=>!!t[l]).map(l=>Be(`${l==="presentation"?"listscreenshare":"videocamera_filled"}`,Op+"-icon",Op+"-icon-"+l));let n,r;if(e===s.MUTED_FOR_ME)n=P("VoiceChat.Status.MutedForYou"),r="is-muted";else if(e===s.UNMUTED)n=P("VoiceChat.Status.Speaking"),r="is-speaking";else if(e===s.HAND)n=P("VoiceChat.Status.WantsSpeak"),r="is-waiting";else if(t.about&&!i.length){Qt(this.container,je(t.about));return}else n=P("VoiceChat.Status.Listening"),r="is-listening";const o=document.createElement("span");o.classList.add(Op,r),o.append(...i,n),St(this.container,o)}}class $N extends Bg{constructor(e){super({getIndex:async t=>(await this.instance.getParticipantByPeerId(t.id)).date,onDelete:t=>{t.dom.listEl.remove(),this.onElementDestroy(t)},onUpdate:async t=>{const s=await this.instance.getParticipantByPeerId(t.id),i=AM(s);t.mutedIcon.setState(i),t.status.setState(i,s)},onSort:(t,s)=>{di(t.dom.listEl,this.list,s)},onElementCreate:t=>{const s=Ht(),{dom:i}=nt.addDialogNew({peerId:t.id,container:!1,avatarSize:this.avatarSize,autonomous:this.autonomous,meAsSaved:!1,rippleEnabled:this.rippleEnabled,wrapOptions:{lazyLoadQueue:this.lazyLoadQueue,middleware:s.get()}});i.listEl.classList.add("group-call-participant");const r=new MM(!0),o=new LM(["presentation","video"]);return St(i.lastMessageSpan,o.container),i.listEl.append(r.container),t.mutedIcon=r,t.status=o,t.middlewareHelper=s,t.dom=i,t},updateElementWith:$s}),this.instance=e,this.avatarSize="abitbigger",this.rippleEnabled=!0,this.autonomous=!0,this.createChatListOptions={dialogSize:72},this.list=nt.createChatList(this.createChatListOptions)}destroy(){super.clear(),this.elements.forEach(e=>{this.onElementDestroy(e)})}onElementDestroy(e){e.mutedIcon.destroy(),e.middlewareHelper.destroy()}}function EM(a){const e=document.createElement("canvas");e.classList.add("call-video-blur");const t=16;e.width=t,e.height=t;const s=e.getContext("2d",{alpha:!1});s.filter="blur(2px)";const i=()=>{s.drawImage(a,0,0,a.videoWidth,a.videoHeight,0,0,e.width,e.height)};return No(()=>(i(),e.isConnected)),i(),e}const il="group-call-participant-video";class NN{constructor(e,t,s){this.managers=e,this.instance=t,this.source=s,this.container=document.createElement("div"),this.container.classList.add(il+"-container"),this.info=document.createElement("div"),this.info.classList.add(il+"-info"),this.left=document.createElement("div"),this.left.classList.add(il+"-info-left"),this.right=document.createElement("div"),this.right.classList.add(il+"-info-right"),this.info.append(this.left,this.right),this.container.append(this.info)}setPinned(e){if(e){if(this.header)return}else{this.header&&(this.header.remove(),this.header=void 0);return}this.header=document.createElement("div"),this.header.classList.add(il+"-header");const t=Be("pin","group-call-pin-icon");this.header.append(t),this.container.append(this.header)}setParticipant(e,t,s){let i;e.pFlags.self?(i=P("VoiceChat.Status.You"),i.classList.add("peer-title")):(this.peerTitle=new Xt({peerId:it(e.peer)}),i=this.peerTitle.element),this.groupCallParticipantMutedIcon=new MM(!1),this.groupCallParticipantStatus=new LM([t]),this.left.append(i,this.groupCallParticipantStatus.container),this.right.append(this.groupCallParticipantMutedIcon.container),s.classList.add(il,"call-video"),s.paused&&Sn(s);const n=EM(s);n.classList.add(il+"-blur"),this.container.prepend(n,s),this.updateParticipant(e)}updateParticipant(e){const t=AM(e);this.groupCallParticipantMutedIcon.setState(t),this.groupCallParticipantStatus.setState(t,e)}destroy(){this.groupCallParticipantMutedIcon.destroy()}}class kM extends Mb{constructor(e){super(),Nt(this,e);const t="group-call-participants-video",s=this.container=document.createElement("div");this.container.classList.add(t+"-container"),e.appendTo.append(s),this.participantsElements=new Map,this.containers=new Map;const{listenerSetter:i}=this;i.add(I)("group_call_participant",({groupCallId:n,participant:r})=>{this.instance.id===n&&this.updateParticipant(r)}),i.add(this.instance)("pinned",n=>{this.participantsElements.forEach(r=>{r.forEach(o=>{this.setElementDisplay(o,n)})})}),J(this.container,n=>{const r=ne(n.target,"group-call-participant-video-container");if(!r)return;const o=this.containers.get(r);if(this.instance.pinnedSource===o.source){this.instance.unpinAll();return}this.instance.pinSource(o.source)},{listenerSetter:i}),this.setInstance(this.instance),this.setup({element:s,listenerSetter:i,showOnLeaveToClassName:"group-call-buttons"})}shouldDisplayElement(e,t){return this.displayPinned?!t||e.source===t:t&&e.source!==t}setElementDisplay(e,t){const s=this.shouldDisplayElement(e,t);e.container.classList.toggle("video-hidden",!s);const i=e.source===t;e.setPinned(i)}updateParticipant(e){const t=it(e.peer),s=["video","presentation"],i=s.some(r=>!!e[r]);let n=this.participantsElements.get(t);!i&&!n||(n||this.participantsElements.set(t,n=new Map),s.forEach(r=>{let o=n.get(r);const l=e[r];if(!!l==!!o){o&&o.updateParticipant(e);return}if(l){const c=this.instance.getVideoElementFromParticipantByType(e,r);if(!c)return;const{video:d,source:u}=c;o=new NN(this.managers,this.instance,u),this.containers.set(o.container,o),this.setElementDisplay(o,this.instance.pinnedSource),n.set(r,o),o.setParticipant(e,r,d),this.container.prepend(o.container)}else n.delete(r),o.container.remove(),n.size||(this.participantsElements.delete(t),this.containers.delete(o.container),o.destroy());this._onLengthChange()}))}_onLengthChange(){const e=this.container.childElementCount;this.container.dataset.length=""+e,this.container.dataset.layout=e<=2?"1":e===3?"3":"4",this.onLengthChange&&this.onLengthChange(e)}async setInstance(e){(await e.participants).forEach(t=>{this.updateParticipant(t)})}destroy(){this.containers.forEach(e=>{e.destroy()})}}class ON{constructor(e){this.onOpenProfileClick=()=>{const i=ue.getPopups(ng)[0];i&&i.hide(),Ce.setInnerPeer({peerId:this.targetPeerId})},this.toggleParticipantMuted=i=>{this.instance.editParticipant(this.participant,{muted:i})},this.buttons=[{icon:"gc_microphoneoff",text:"VoiceChat.MutePeer",verify:()=>this.canManageCall&&this.participant.pFlags.can_self_unmute,onClick:()=>this.toggleParticipantMuted(!0)},{icon:"gc_microphone",text:"VoiceChat.UnmutePeer",verify:()=>this.canManageCall&&!this.participant.pFlags.can_self_unmute,onClick:()=>this.toggleParticipantMuted(!1)},{icon:"gc_microphoneoff",text:"VoiceChat.MuteForMe",verify:()=>!this.canManageCall&&!this.participant.pFlags.muted_by_you,onClick:()=>this.toggleParticipantMuted(!0)},{icon:"gc_microphone",text:"VoiceChat.UnmuteForMe",verify:()=>!this.canManageCall&&this.participant.pFlags.muted_by_you,onClick:()=>this.toggleParticipantMuted(!1)},{icon:"newprivate",text:"VoiceChat.OpenProfile",verify:()=>!0,onClick:this.onOpenProfileClick},{icon:"deleteuser",className:"danger",text:"VoiceChat.RemovePeer",verify:()=>this.managers.appChatsManager.hasRights(this.chatId,"ban_users"),onClick:async()=>{Rt({peerId:this.targetPeerId,title:new Xt({peerId:this.targetPeerId}).element,descriptionLangKey:await this.managers.appChatsManager.isBroadcast(this.chatId)?"VoiceChat.RemovePeer.Confirm.Channel":"VoiceChat.RemovePeer.Confirm",descriptionLangArgs:[new Xt({peerId:this.targetPeerId}).element],button:{langKey:"VoiceChat.RemovePeer.Confirm.OK",isDanger:!0}}).then(()=>{this.managers.appChatsManager.kickFromChat(this.chatId,this.targetPeerId)},as)}}];const{listenerSetter:t}=e;this.managers=e.managers,this.instance=e.instance,this.chatId=this.instance.chatId,this.element=xa({buttons:this.buttons,listenerSetter:t}),this.element.classList.add("group-call-participant-menu","night"),Er({element:e.onContextElement,callback:async i=>{const n=ne(i.target,"group-call-participant");if(!n)return;this.element.parentElement!==s&&s.append(this.element),_e(i);const r=this.targetPeerId=n.dataset.peerId.toPeerId();this.participant=await this.instance.getParticipantByPeerId(r),!this.participant.pFlags.self&&(this.canManageCall=await this.managers.appChatsManager.hasRights(this.chatId,"manage_call"),await zn(this.buttons,async o=>{const l=await o.verify(r);return o.element.classList.toggle("hide",!l),l}),Ql(i.touches?i.touches[0]:i,this.element,"right"),Li.openBtnMenu(this.element))},listenerSetter:t}),t.add(I)("group_call_participant",({groupCallId:i,participant:n})=>{if(this.instance.id===i){const r=it(n.peer);this.targetPeerId===r&&Li.close()}});let s=document.body;pg(document.body,()=>{const i=pa();s=i?ue.getPopups(ng)[0].getContainer():document.body,i||Li.close()},t)}}class UN{constructor(e){Nt(this,e);const t="group-call-participants",s=new tn(void 0);s.container.classList.add(t+"-scrollable");const i=this.container=document.createElement("div");i.classList.add(t);const n=this.sortedList=new $N(this.instance),{instance:r,listenerSetter:o}=this;this.contextMenu=new ON({...e,onContextElement:n.list,listenerSetter:o,instance:r}),this.groupCallParticipantsVideo=new kM({...e,appendTo:s.container,displayPinned:!1}),s.append(n.list),i.append(s.container),e.appendTo.append(i),o.add(I)("group_call_participant",({groupCallId:l,participant:c})=>{this.instance.id===l&&this.updateParticipant(c)}),new yb({scrollable:s,getPromise:()=>this.managers.appGroupCallsManager.getGroupCallParticipants(this.instance.id).then(({participants:l,isEnd:c})=>(l.forEach(d=>{this.updateParticipant(d)}),c))}),this.setInstance(r)}updateParticipant(e){const t=it(e.peer),s=this.sortedList.has(t);if(e.pFlags.left){s&&this.sortedList.delete(t);return}if(!s){this.sortedList.add(t);return}this.sortedList.update(t)}async setInstance(e){(await e.participants).forEach(s=>{this.updateParticipant(s)})}destroy(){this.sortedList.destroy(),this.groupCallParticipantsVideo.destroy()}}class ky{constructor(e){this.appendTo=e,this.descriptionIntl=new Ne.IntlElement({key:"VoiceChat.Status.Connecting"}),this.descriptionIntl.element.classList.add("group-call-description")}detach(){this.descriptionIntl.element.remove()}update(e){const{state:t}=e;let s,i;t===qs.CONNECTING?s="VoiceChat.Status.Connecting":(s="VoiceChat.Status.Members",i=[e.groupCall.participants_count]);const{descriptionIntl:n}=this;n.compareAndUpdate({key:s,args:i}),this.descriptionIntl.element.parentElement||this.appendTo.append(this.descriptionIntl.element)}}class TM{constructor(e){this.appendTo=e,this.peerTitle=new Xt({peerId:Wt})}update(e){const{peerTitle:t,appendTo:s}=this,i=e.groupCall,n=e.chatId.toPeerId(!0);i.title?Qt(s,je(i.title)):(t.options.peerId!==n&&(t.options.peerId=n,t.update()),t.element.parentElement!==s&&s.append(t.element))}}function xM(a,e,t){const s=a+"-button",i=document.createElement("div");i.classList.add(s,"call-button","rp-overflow"),t.icon&&i.append(Be(t.icon)),t.noRipple||Ei(i),t.isDanger&&i.classList.add(s+"-red"),t.isConfirm&&i.classList.add(s+"-green"),t.callback&&J(i,t.callback,{listenerSetter:e});let n=i;if(t.text){const r=document.createElement("div");r.classList.add(s+"-container","call-button-container");const o=typeof t.text=="string"?P(t.text):t.text;o.classList.add(s+"-text","call-button-text"),r.append(i,o),n=r}return n}const nm="movable-element",lv=nm+"-resize-handler";class HN extends pn{constructor(e){super(!0),this.onResize=()=>{this.fixDimensions(!0),this.fixPosition(),this.setPosition()},Nt(this,e),this.top=this.left=this.width=this.height=0,this.element.classList.add(nm),this.addResizeHandlers(),this.setSwipeHandler(),st.addEventListener("resize",this.onResize)}toggleResizable(e){e?this.addResizeHandlers():this.destroyResizeHandlers()}destroyElements(){this.element.classList.remove(nm),this.destroyResizeHandlers()}destroyResizeHandlers(){this.handlers&&(this.handlers.forEach(e=>{e.remove()}),this.handlers=void 0)}destroy(){st.removeEventListener("resize",this.onResize),this.swipeHandler.removeListeners()}addResizeHandlers(){if(this.handlers)return;const e=["n","e","s","w","ne","se","sw","nw"];this.handlers=e.map(t=>{const s=document.createElement("div");return s.dataset.side=t,s.classList.add(lv,lv+"-side-"+t),this.element.append(s),s})}setSwipeHandler(){let e,t,s,i,n,r,o;const l=this.swipeHandler=new Qn({element:this.element,onSwipe:(c,d,u)=>{if(o){const h=o.includes("e")||o.includes("w"),p=o.includes("n")||o.includes("s"),m=o.includes("e")||!h?It.width-t:s+t,g=o.includes("s")||!p?It.height-e:i+e;if(h){const f=o.includes("e")&&c>0||o.includes("w")&&c<0,v=Math.abs(c)*(f?1:-1);this.width=zt(s+v,this.minWidth,m),this.aspectRatio&&(this.height=zt(this.width/this.aspectRatio+n,this.minHeight,g),this.width=this.height*this.aspectRatio+r)}if(p){const f=o.includes("s")&&d>0||o.includes("n")&&d<0,v=Math.abs(d)*(f?1:-1);this.height=zt(i+v,this.minHeight,g),this.aspectRatio&&(this.width=zt(this.height*this.aspectRatio+r,this.minWidth,m),this.height=this.width/this.aspectRatio+n)}o.includes("w")&&(this.left=Math.min(t+s-this.minWidth,t+c)),o.includes("n")&&(this.top=Math.min(e+i-this.minHeight,e+d))}else this.top=e+d,this.left=t+c;this.fixPosition(),this.setPosition()},verifyTouchTarget:c=>{const d=c.target,u=ne(d,lv);if(this.verifyTouchTarget&&!this.verifyTouchTarget(c,u?"resize":"move"))return!1;if(u){o=u.dataset.side;let h="col-resize";o==="nw"||o==="se"?h="nwse-resize":o==="ne"||o==="sw"?h="nesw-resize":(o==="n"||o==="s")&&(h="row-resize"),l.setCursor(h)}else o=void 0,l.setCursor("grabbing");return!0},onFirstSwipe:()=>{e=this.top,t=this.left,s=this.width,i=this.height,this.overlay||(this.overlay=document.createElement("div"),this.overlay.classList.add(nm+"-overlay")),this.element.append(this.overlay),this.aspectRatio&&(r=this.width-this.height*this.aspectRatio,n=this.height-this.width/this.aspectRatio),this.resetTransition&&(this.element.classList.add("no-transition"),this.element.offsetLeft)},onReset:()=>{this.resetTransition&&this.element.classList.remove("no-transition"),this.overlay.remove()},setCursorTo:document.body})}setPositionToCenter(){this.top=It.height/2-this.height/2,this.left=It.width/2-this.width/2,this.setPosition()}fixDimensions(e){if(e&&this.aspectRatio){const t=this.width-this.height*this.aspectRatio,s=this.height-this.width/this.aspectRatio,i=It.width-this.left,n=It.height-this.top;if(this.width>i)this.width=i,this.height=this.width/this.aspectRatio+s;else if(this.height>n)this.height=n,this.width=this.height*this.aspectRatio+t;else return}this.width=zt(this.width,this.minWidth,It.width),this.height=zt(this.height,this.minHeight,It.height)}fixPosition(){this.top=zt(this.top,0,It.height-this.height),this.left=zt(this.left,0,It.width-this.width)}setPosition(){this.element.style.top=this.top+"px",this.element.style.left=this.left+"px",this.element.style.right="auto",this.element.style.bottom="auto",this.element.style.width=this.width+"px",this.element.style.height=this.height+"px",this.dispatchEvent("resize",this.state)}get width(){return this._width}get height(){return this._height}set width(e){this._width=e}set height(e){this._height=e}get state(){const{top:e,left:t,width:s,height:i}=this;return{top:e,left:t,width:s,height:i}}set state(e){const{top:t,left:s,width:i,height:n}=e;this.top=t,this.left=s,this.width=i,this.height=n,this.onResize()}setMinValues(e,t){this.minWidth=e,this.minHeight=t}}var Wc;class Pw{constructor(e){Ks(this,Wc,void 0);Nt(this,e),this.toggleMovable(!pt),this.listenerSetter.add(st)("changeScreen",(t,s)=>{(s===fn.mobile||t===fn.mobile)&&this.toggleMovable(!pt)})}destroy(){const e=this.movable;e&&e.destroy()}get movable(){return ls(this,Wc)}get state(){return this.movable?this.movable.state:this.previousState}set state(e){this.previousState=e}toggleMovable(e){let{movable:t}=this;if(e){if(t)return;t=ss(this,Wc,new HN(this.movableOptions)),t.state=this.previousState,this.previousState.top===void 0&&t.setPositionToCenter(),this.onResize&&this.listenerSetter.add(t)("resize",this.onResize)}else{if(!t)return;this.previousState=t.state,t.destroyElements(),t.destroy(),ss(this,Wc,void 0)}}}Wc=new WeakMap;function Mw(a,e,t){return e.forEach(s=>{s.classList.toggle(a,t)}),()=>Mw(a,e,!t)}var Ed=(a=>(a[a.UNMUTED=0]="UNMUTED",a[a.MUTED=1]="MUTED",a[a.MUTED_FOR_ME=2]="MUTED_FOR_ME",a[a.MUTED_BY_ADMIN=3]="MUTED_BY_ADMIN",a[a.HAND=4]="HAND",a))(Ed||{});function AM(a){const e=Ed;return a.pFlags.muted_by_you?e.MUTED_FOR_ME:a.raise_hand_rating!==void 0?e.HAND:a.pFlags.muted?a.pFlags.can_self_unmute?e.MUTED:e.MUTED_BY_ADMIN:e.UNMUTED}function GN(a){const e=Ed;switch(a){case e.MUTED_BY_ADMIN:case e.MUTED_FOR_ME:return e.MUTED;default:return a}}function VN(a){const e=Ed;let t;switch(a){case e.HAND:t="blue";break;case e.MUTED:case e.MUTED_FOR_ME:case e.MUTED_BY_ADMIN:t=a===e.MUTED?"secondary":"red";break;case e.UNMUTED:t="green";break}const s=yi.getProperty("gc-"+t+"-text-color");return Pa(s)}var Lw=(a=>(a[a.HAND=0]="HAND",a[a.MUTED=1]="MUTED",a[a.UNMUTED=2]="UNMUTED",a))(Lw||{});function zN(a,e){const t=Lw;return e.pFlags.can_self_unmute?e.pFlags.muted?t.MUTED:t.UNMUTED:t.HAND}let bC={width:420,height:640};const ar="group-call";class ng extends ue{constructor(){super("popup-group-call",{body:!0,withoutOverlay:!0,closable:!0,title:!0}),this.onFullScreenClick=()=>{zy(this.container)},this.onToggleControls=u=>{this.container.classList.toggle("show-controls",u),this.buttonsContainer.classList.toggle("show-controls",u)},this.toggleDisability=Mw.bind(null,"btn-disabled"),this.onVideoClick=()=>{const u=this.toggleDisability([this.btnVideo],!0);this.instance.toggleVideoSharing().finally(()=>{u()})},this.onScreenClick=()=>{const u=this.toggleDisability([this.btnScreen],!0);this.instance.toggleScreenSharing().finally(()=>{u()})},this.onMuteClick=()=>{const u=this.instance.participant;u.pFlags.can_self_unmute?this.instance.toggleMuted():u.raise_hand_rating===void 0&&this.instance.changeRaiseHand(!0)},this.onLeaveClick=async()=>{const u=h=>{this.instance.hangUp(h)};await this.managers.appChatsManager.hasRights(this.instance.chatId,"manage_call")?ue.createPopup(mi,"popup-end-video-chat",{titleLangKey:"VoiceChat.End.Title",descriptionLangKey:"VoiceChat.End.Text",checkboxes:[{text:"VoiceChat.End.Third"}],buttons:[{langKey:"VoiceChat.End.OK",callback:(h,p)=>{u(!!p.size)},isDanger:!0}]}).show():u(!1)},this.onFullScreenChange=()=>{this.toggleBigLayout();const u=pa(),{btnFullScreen:h,btnExitFullScreen:p}=this,m=this.container.classList.contains("is-full-screen");this.container.classList.toggle("is-full-screen",u),h&&h.classList.toggle("hide",u),p&&p.classList.toggle("hide",!u),this.btnClose.classList.toggle("hide",u),u!==m&&(Ut.checkAnimations2(u),Ls.setThemeColor(u?"#000000":void 0))},this.toggleBigLayout=()=>{const u=pa(),h=this.movablePanel?.movable,p=(u||!!(h&&h.width>=680))&&!!this.videosCount,m=this.container.classList.contains("is-big-layout");let g;p&&!m&&(g=Array.from(this.buttonsContainer.children),g.forEach(f=>{f.style.opacity="0"}),this.buttonsContainer.offsetLeft),this.container.classList.toggle("is-big-layout",p),this.btnInvite.classList.toggle("hide",p),this.btnShowColumn.classList.toggle("hide",!p),g&&g.forEach(f=>{f.style.opacity=""})},this.toggleRightColumn=()=>{this.container.classList.toggle("is-right-column-shown")},this.videosCount=0,this.container.classList.add(ar,"night");const e=this.instance=Wa.groupCall,{listenerSetter:t}=this;if(!Vy){const u=this.btnFullScreen=yt("fullscreen"),h=this.btnFullScreen2=yt("fullscreen "+ar+"-cfs"),p=this.btnExitFullScreen=yt("smallscreen");J(u,this.onFullScreenClick,{listenerSetter:t}),J(h,this.onFullScreenClick,{listenerSetter:t}),J(p,()=>{Bh()},{listenerSetter:t}),pg(this.container,this.onFullScreenChange,t)}this.btnInvite=yt("adduser");const s=this.btnShowColumn=yt("rightpanel "+ar+"-only-big");J(s,this.toggleRightColumn,{listenerSetter:t});const i=document.createElement("div");i.classList.add(ar+"-header-info"),this.title.classList.add(ar+"-header-title");const n=document.createElement("div");n.classList.add(ar+"-header-subtitle"),i.append(this.title,n),this.header.classList.add(ar+"-header"),this.header.append(...[this.btnExitFullScreen,i,this.btnFullScreen,s].filter(Boolean));const r=this.header.cloneNode(!1),o=i.cloneNode(!1),l=this.title.cloneNode(!1);o.append(l);const c=yt("rightpanel");r.append(...[c,o,this.btnFullScreen2].filter(Boolean)),J(c,this.toggleRightColumn,{listenerSetter:t}),this.body.prepend(r);const d=new tn(void 0);d.container.classList.add("group-call-big-video-container"),this.container.append(d.container),this.groupCallTitle=new TM(this.title),this.groupCallDescription=new ky(n),this.groupCallBodyHeaderDescription=new ky(l),this.constructButtons(),this.groupCallParticipantsVideo=new kM({appendTo:d.container,instance:e,listenerSetter:t,displayPinned:!0,onLengthChange:u=>{this.videosCount=u,this.toggleBigLayout()},managers:this.managers}),this.groupCallParticipants=new UN({appendTo:this.body,instance:e,listenerSetter:t,managers:this.managers}),this.movablePanel=new Pw({listenerSetter:t,movableOptions:{minWidth:400,minHeight:480,element:this.element,verifyTouchTarget:u=>{const h=u.target;return!(ne(h,"chatlist")||ne(h,"group-call-button")||ne(h,"btn-icon")||ne(h,"group-call-participants-video-container")||pa())}},onResize:()=>this.toggleBigLayout(),previousState:bC}),t.add(e)("state",()=>{this.updateInstance()}),t.add(I)("group_call_update",u=>{this.instance?.id===u.id&&this.updateInstance()}),t.add(e)("pinned",()=>{this.setHasPinned()}),t.add(this.groupCallParticipantsVideo)("toggleControls",this.onToggleControls),this.addEventListener("close",()=>{const{movablePanel:u}=this;bC=u.state,this.groupCallParticipantsVideo.destroy(),this.groupCallParticipants.destroy(),this.groupCallMicrophoneIcon.destroy(),u.destroy()}),this.toggleRightColumn(),this.onFullScreenChange(),this.updateInstance()}constructButtons(){const e=this.buttonsContainer=document.createElement("div");e.classList.add(ar+"-buttons");const t=xM.bind(null,ar,this.listenerSetter),s=this.btnVideo=t({callback:this.onVideoClick,icon:"videocamera_filled"}),i=this.btnScreen=t({callback:this.onScreenClick,icon:"sharescreen_filled"});i.classList.toggle("hide",!Ev);const n=t({noRipple:!0,callback:fa(this.onMuteClick,600,!0)});n.classList.add(ar+"-microphone-button");const r=this.groupCallMicrophoneIcon=new DN;n.append(r.container);const o=t({icon:"settings_filled"});o.classList.add("btn-disabled"),o.classList.toggle("hide",!Ev);const l=t({isDanger:!0,callback:this.onLeaveClick,icon:"close"});e.append(s,i,n,o,l),this.container.append(e)}getContainer(){return this.container}setHasPinned(){this.container.classList.toggle("has-pinned",!!this.instance.pinnedSource)}updateInstance(){if(this.instance.state===qs.CLOSED){this.container.classList.contains("is-full-screen")&&Bh(),this.hide();return}const{participant:e,groupCall:t}=this.instance;if(!e)return;this.setTitle(),this.setDescription(),this.setHasPinned();const s=zN(t,e);this.container.dataset.micState=s===0?"hand":s===1?"muted":"unmuted",this.groupCallMicrophoneIcon.setState(s)}setTitle(){this.groupCallTitle.update(this.instance)}setDescription(){this.groupCallDescription.update(this.instance),this.groupCallBodyHeaderDescription.update(this.instance)}}var ds=(a=>(a[a.CONNECTED=0]="CONNECTED",a[a.CONNECTING=1]="CONNECTING",a[a.EXCHANGING_KEYS=2]="EXCHANGING_KEYS",a[a.PENDING=3]="PENDING",a[a.REQUESTING=4]="REQUESTING",a[a.CLOSING=5]="CLOSING",a[a.CLOSED=6]="CLOSED",a))(ds||{});class RM{constructor(e){this.appendTo=e,this.container=document.createElement("div"),this.container.classList.add("call-description")}detach(){this.interval!==void 0&&(clearInterval(this.interval),this.interval=void 0),this.container.remove(),this.state=void 0}update(e){const{connectionState:t}=e;if(this.state===t)return;this.state=t;let s;if(t===ds.CONNECTED){s=document.createElement("span"),s.classList.add("call-description-duration");const i=()=>{s.innerText=bn(e.duration,!0)};this.interval=window.setInterval(i,1e3),i()}else{let i;switch(t){case ds.PENDING:i=e.isOutgoing?"Call.StatusRinging":"Call.StatusCalling";break;case ds.REQUESTING:i="Call.StatusRequesting";break;case ds.EXCHANGING_KEYS:i="VoipExchangingKeys";break;case ds.CLOSED:i=e.connectedAt!==void 0?"Call.StatusEnded":"Call.StatusFailed";break;default:i="Call.StatusConnecting";break}s=P(i),this.interval!==void 0&&(clearInterval(this.interval),this.interval=void 0)}this.container.classList.toggle("has-duration",t===ds.CONNECTED),St(this.container,s),this.container.parentElement||this.appendTo.append(this.container)}}class Ty extends Iw{constructor(e,t){super({width:36,height:36,getPart:s=>this.getItem().getPart(s?"unmute":"mute"),getColor:e?s=>s?[255,255,255]:[158,158,158]:void 0,skipAnimation:t}),this.add({name:"voice_mini",parts:[{startFrame:0,endFrame:35,name:"hand-to-muted"},{startFrame:36,endFrame:68,name:"unmute"},{startFrame:69,endFrame:98,name:"mute"},{startFrame:99,endFrame:135,name:"muted-to-hand"},{startFrame:136,endFrame:171,name:"unmuted-to-hand"}]})}}const Sa="call",FM=400,BM=580,DM={width:FM,height:BM};let wC={...DM};class xy extends ue{constructor(e){super("popup-call",{withoutOverlay:!0,closable:!0}),this.instance=e,this.onFullScreenClick=()=>{zy(this.container)},this.onFullScreenChange=()=>{const m=pa(),{btnFullScreen:g,btnExitFullScreen:f}=this,v=this.container.classList.contains("is-full-screen");this.container.classList.toggle("is-full-screen",m),g&&g.classList.toggle("hide",m),f&&f.classList.toggle("hide",!m),this.btnClose.classList.toggle("hide",m),m!==v&&(Ut.checkAnimations(m),Ls.setThemeColor(m?"#000000":void 0),this.resizeVideoContainers())},this.videoContainers={};const{container:t,listenerSetter:s}=this;t.classList.add(Sa,"night");const i=document.createElement("div");i.classList.add(Sa+"-avatar");const n=this.peerId=this.instance.interlocutorUserId.toPeerId(),{node:r}=vs({middleware:this.middlewareHelper.get(),isBig:!0,peerId:n,size:"full"});i.append(r);const o=new Xt({peerId:n}).element;o.classList.add(Sa+"-title");const l=document.createElement("div");l.classList.add(Sa+"-subtitle"),this.description=new RM(l);const c=this.emojisSubtitle=document.createElement("div");c.classList.add(Sa+"-emojis"),t.append(i,o,l),Gi?this.header.append(c):(this.btnFullScreen=yt("fullscreen"),this.btnExitFullScreen=yt("smallscreen hide"),J(this.btnFullScreen,this.onFullScreenClick,{listenerSetter:s}),J(this.btnExitFullScreen,()=>Bh(),{listenerSetter:s}),pg(this.container,this.onFullScreenChange,s),this.header.prepend(this.btnExitFullScreen),this.header.append(this.btnFullScreen),t.append(c)),this.partyStates=document.createElement("div"),this.partyStates.classList.add(Sa+"-party-states"),this.partyMutedState=document.createElement("div"),this.partyMutedState.classList.add(Sa+"-party-state");const d=P("VoipUserMicrophoneIsOff",[new Xt({peerId:n,onlyFirstName:!0,limitSymbols:18}).element]);d.classList.add(Sa+"-party-state-text");const u=new Ty(!1,!0);u.setState(!1,!1),this.partyMutedState.append(u.container,d),this.partyStates.append(this.partyMutedState),this.container.append(this.partyStates),this.makeButton=xM.bind(null,Sa,this.listenerSetter),this.constructFirstButtons(),this.constructSecondButtons(),s.add(e)("state",()=>{this.updateInstance()}),s.add(e)("mediaState",()=>{this.updateInstance()}),this.movablePanel=new Pw({listenerSetter:s,movableOptions:{minWidth:FM,minHeight:BM,element:this.element,verifyTouchTarget:m=>{const g=m.target;return!(ne(g,"call-button")||ne(g,"btn-icon")||pa())}},previousState:!this.instance.wasTryingToJoin&&!this.instance.isOutgoing?{...DM}:wC});const h=this.movablePanel.movable;h&&this.listenerSetter.add(h)("resize",()=>{this.resizeVideoContainers()});const p=this.controlsHover=new Mb;p.setup({element:this.container,listenerSetter:this.listenerSetter,showOnLeaveToClassName:"call-buttons"}),p.showControls(!1),this.addEventListener("close",()=>{const{movablePanel:m}=this;wC=m.state,this.microphoneIcon.destroy(),m.destroy()}),this.updateInstance()}getCallInstance(){return this.instance}constructFirstButtons(){const e=this.firstButtonsRow=document.createElement("div");e.classList.add(Sa+"-buttons","is-first");const t=Mw.bind(null,"btn-disabled"),s=this.btnVideo=this.makeButton({text:"Call.Camera",icon:"videocamera_filled",callback:()=>{const o=t([s,i],!0);this.instance.toggleVideoSharing().finally(o)}}),i=this.btnScreen=this.makeButton({text:"Call.Screen",icon:"sharescreen_filled",callback:()=>{const o=t([s,i],!0);this.instance.toggleScreenSharing().finally(o)}});Ev||(i.classList.add("hide"),this.container.classList.add("no-screen")),this.muteI18nElement=new Ne.IntlElement({key:"Call.Mute"});const n=this.btnMute=this.makeButton({text:this.muteI18nElement.element,callback:()=>{this.instance.toggleMuted()}}),r=this.microphoneIcon=new Ty(!0,!0);n.firstElementChild.append(r.container),e.append(s,i,n),this.container.append(e)}constructSecondButtons(){const e=this.secondButtonsRow=document.createElement("div");e.classList.add(Sa+"-buttons","is-second"),this.declineI18nElement=new Ne.IntlElement({key:"Call.Decline"});const t=this.btnDecline=this.makeButton({text:this.declineI18nElement.element,icon:"endcall_filled",callback:()=>{this.instance.hangUp("phoneCallDiscardReasonHangup")},isDanger:!0}),s=this.btnAccept=this.makeButton({text:"Call.Accept",icon:"phone_filled",callback:()=>{this.instance.acceptCall()},isConfirm:!0});e.append(t,s),this.container.append(e)}createVideoContainer(e){const t=Sa+"-video",s=document.createElement("div");s.classList.add(t+"-container"),e.classList.add(t),e.paused&&Sn(e),J(s,()=>{if(!s.classList.contains("small"))return;const n=Object.values(this.videoContainers).find(r=>!r.classList.contains("small"));n.classList.add("small"),n.style.cssText=s.style.cssText,s.classList.remove("small"),s.style.cssText="",this.resizeVideoContainers()});const i=EM(e);return i.classList.add(t+"-blur"),s.append(i,e),s}updateInstance(){const{instance:e}=this,{connectionState:t}=e;if(t===ds.CLOSED){this.container.classList.contains("is-full-screen")&&Bh(),this.btnVideo.classList.add("disabled"),this.hide();return}const s=!e.isOutgoing&&t===ds.PENDING;this.declineI18nElement.compareAndUpdate({key:t===ds.PENDING?"Call.Decline":"Call.End"}),this.btnAccept.classList.toggle("disable",!s),this.btnAccept.classList.toggle("hide-me",!s),this.container.classList.toggle("two-button-rows",s);const i=e.isMuted,n=()=>{this.btnMute.firstElementChild.classList.toggle("active",i)},r=this.microphoneIcon.getItem().player;this.microphoneIcon.setState(!i,!i,n),r||n(),this.muteI18nElement.compareAndUpdate({key:i?"VoipUnmute":"Call.Mute"});const o=e.isSharingVideo;this.btnVideo.firstElementChild.classList.toggle("active",o);const l=e.isSharingScreen;this.btnScreen.firstElementChild.classList.toggle("active",l);const c=e.getMediaState("output");Dt({element:this.partyMutedState,className:"is-visible",forwards:!!c?.muted,duration:300});const d=this.videoContainers,u={...d};["input","output"].forEach(h=>{const p=e.getMediaState(h),m=e.getVideoElement(h),g=!!(m&&m.videoWidth&&m.videoHeight);m&&!g&&!m.dataset.hasPromise&&(m.dataset.hasPromise="1",ua(m).then(()=>{delete m.dataset.hasPromise,this.updateInstance()}));const f=!!m&&g&&!!(p&&(p.videoState==="active"||p.screencastState==="active"));let v=d[h];f&&m&&!v&&(v=d[h]=this.createVideoContainer(m),this.container.append(v)),!f&&v&&(v.remove(),delete d[h])});{const h=d.input,p=d.output;Object.keys(u).length!==Object.keys(d).length&&h&&h.classList.toggle("small",!!p),p&&!h&&p.classList.remove("small")}this.resizeVideoContainers(),this.container.classList.toggle("no-video",!Object.keys(d).length),!this.emojisSubtitle.textContent&&t<ds.EXCHANGING_KEYS&&Promise.resolve(e.getEmojisFingerprint()).then(h=>{St(this.emojisSubtitle,je(h.join("")))}),this.setDescription()}resizeVideoContainers(){Object.values(this.videoContainers).forEach(e=>{if(e.classList.contains("small")){const s=e.querySelector("video"),i=this.movablePanel.state,n=240,r=240,o=s.videoHeight>s.videoWidth,l=o?r:n,c=1/3*(pa()?65535:o?i.height:i.width),d=o?s.videoWidth/s.videoHeight:1,u=o?1:s.videoHeight/s.videoWidth;e.style.width=c*d+"px",e.style.height=c*u+"px",e.style.maxWidth=l*d+"px",e.style.maxHeight=l*u+"px"}else e.style.cssText=""})}setDescription(){this.description.update(this.instance)}}function $M(a){const e=Ym(a,a.media[0]),t={"@type":"InitialSetup",fingerprints:[e.fingerprint],ufrag:e.ufrag,pwd:e.pwd,audio:void 0,video:void 0,screencast:void 0},s=i=>""+i;for(const i of a.media){const n=i.mediaType;if(n==="application"||!i.isSending)continue;const r=t[n==="video"&&t.video?"screencast":n]={},o=Ym(a,i);r.ssrc=s(o.source),o.sourceGroups&&(r.ssrcGroups=o.sourceGroups.map(u=>({semantics:u.semantics,ssrcs:u.sources.map(s)})));const l=r.rtpExtensions=[];i.attributes.get("extmap").forEach(u=>{l.push({id:+u.key,uri:u.value})});const c=new Map,d=u=>{let h=c.get(u);return h||c.set(u,h={id:u}),h};i.attributes.get("rtpmap").forEach(u=>{const h=+u.key,p=d(h),m=u.value.split("/"),[g,f,v]=m;p.name=g,p.clockrate=+f,p.channels=v?+v:0}),i.attributes.get("rtcp-fb").forEach(u=>{const h=+u.key,p=d(h);p.feedbackTypes=u.lines.map(m=>{const g=m.split(" "),[f,v]=g;return{type:f,subtype:v||""}})}),i.attributes.get("fmtp").forEach(u=>{const h=+u.key,p=d(h),m=p.parameters={},g=u.value.split(";");for(const f of g){const[v,y]=f.split("=");m[v]=y}}),r.payloadTypes=Array.from(c.values())}return t}class WN extends _P{constructor(e){super(e)}async negotiateInternal(){const{connection:e,call:t}=this;if(!e.localDescription&&!e.remoteDescription&&!t.isOutgoing)return;let s;if(t.offerReceived){t.offerReceived=!1;const n=s=await e.createAnswer();this.log("[sdp] local",n.type,n.sdp),await e.setLocalDescription(n),this.log("[InitialSetup] send 2")}else{const n=s=await e.createOffer();this.log("[sdp] local",n.sdp),await e.setLocalDescription(n),t.offerSent=!0,this.log("[InitialSetup] send 0")}const i=$M(qm(s.sdp));t.sendCallSignalingData(i)}}let KN;function jN(){return KN??(KN=new pP(["call_busy.mp3","call_connect.mp3","call_end.mp3","call_incoming.mp3","call_outgoing.mp3","voip_failed.mp3"]))}const cv=45e3;class qN extends pn{construct(e){this.managers=e,this.log=Ni("CC"),Gh&&(this.audioAsset=jN(),this.tempId=0,this.instances=new Map,this.sortedInstances=[],I.addEventListener("call_update",async t=>{let s=this.instances.get(t.id);switch(s&&s.setPhoneCall(t),t._){case"phoneCallDiscarded":{s&&s.hangUp(t.reason,!0);break}case"phoneCallAccepted":{s&&s.confirmCall();break}case"phoneCallRequested":{s||(s=this.createCallInstance({isOutgoing:!1,interlocutorUserId:t.admin_id}),s.overrideConnectionState(ds.PENDING),s.setPhoneCall(t),s.setHangUpTimeout(cv,"phoneCallDiscardReasonMissed"));break}case"phoneCall":{if(!s||s.encryptionKey)break;const i=s.dh.g_a=t.g_a_or_b,n=s.dh,r=await Ae.invokeCrypto("sha256",i);if(!QE(n.g_a_hash,r)){this.log.error("Incorrect g_a_hash",n.g_a_hash,r);break}const{key:o,key_fingerprint:l}=await this.managers.appCallsManager.computeKey(i,n.b,n.p);if(t.key_fingerprint!==l){this.log.error("Incorrect key fingerprint",t.key_fingerprint,l,i,n),s.hangUp("phoneCallDiscardReasonDisconnect");break}s.encryptionKey=o,s.joinCall();break}}}),I.addEventListener("call_signaling",({callId:t,data:s})=>{const i=this.instances.get(t);i?.id===t&&i.onUpdatePhoneCallSignalingData(s)}))}get currentCall(){return this.sortedInstances?.[0]}getCallByUserId(e){for(const[t,s]of this.instances)if(s.interlocutorUserId===e)return s}createCallInstance(e){const t=new am({managers:this.managers,...e});return t.addEventListener("state",s=>{const i=this.currentCall;s===ds.CLOSED?(this.instances.delete(t.id),Vs(this.sortedInstances,t)):Tl(this.sortedInstances,t,"sortIndex"),s===ds.EXCHANGING_KEYS&&(t.wasTryingToJoin=!0);const n=t.connectedAt!==void 0;s===ds.EXCHANGING_KEYS||s===ds.CONNECTING&&n?t.setHangUpTimeout(cv,"phoneCallDiscardReasonDisconnect"):t.clearHangUpTimeout(),(i===t||!i)&&(s===ds.CLOSED?!t.isOutgoing&&!t.wasTryingToJoin?this.audioAsset.stopSound():t.wasTryingToJoin&&!n?this.audioAsset.playSound("voip_failed.mp3"):this.audioAsset.playSound(t.discardReason._==="phoneCallDiscardReasonBusy"?"call_busy.mp3":"call_end.mp3"):s===ds.PENDING?this.audioAsset.playSound(t.isOutgoing?"call_outgoing.mp3":"call_incoming.mp3",!0):s===ds.EXCHANGING_KEYS?this.audioAsset.playSoundIfDifferent("call_connect.mp3"):s===ds.CONNECTING?t.duration&&this.audioAsset.playSound("voip_connecting.mp3",!0):this.audioAsset.stopSound())}),t.addEventListener("id",(s,i)=>{i!==void 0&&this.instances.delete(i);const n=!!this.currentCall;this.instances.set(s,t),i===void 0&&this.dispatchEvent("instance",{instance:t,hasCurrent:n})}),t}async startCallInternal(e,t){this.log("p2pStartCallInternal",e,t);const s=await this.managers.appProfileManager.getProfile(e);if(!s)return;const{video_calls_available:i}=s.pFlags,n=this.createCallInstance({isOutgoing:!0,interlocutorUserId:e});n.requestInputSource(!0,!!(t&&i),!1),n.overrideConnectionState(ds.REQUESTING),n.setPhoneCall({_:"phoneCallWaiting",access_hash:"",admin_id:Wt,date:Qs(!0),id:--this.tempId,participant_id:e,protocol:n.protocol,pFlags:{video:t||void 0}}),this.managers.appCallsManager.generateDh().then(async r=>(n.dh=r,this.managers.appCallsManager.requestCall(e,n.protocol,n.dh.g_a_hash,t&&i))).then(r=>{n.overrideConnectionState(ds.PENDING),n.setPhoneCall(r),n.setHangUpTimeout(cv,"phoneCallDiscardReasonHangup")})}}const Un=new qN;Di&&(Di.callsController=Un);function YN(){return{_:"phoneCallProtocol",pFlags:{udp_p2p:!0,udp_reflector:!0},min_layer:92,max_layer:92,library_versions:["4.0.0"]}}function QN(a){const e=[];return a.connections.forEach(t=>{switch(t._){case"phoneConnectionWebrtc":{const{ip:s,ipv6:i,port:n,username:r,password:o}=t,l=[];t.pFlags.turn?(s&&l.push(`turn:${s}:${n}`),i&&l.push(`turn:[${i}]:${n}`)):t.pFlags.stun&&(s&&l.push(`stun:${s}:${n}`),i&&l.push(`stun:[${i}]:${n}`)),l.length>0&&e.push({urls:l,username:r,credential:o});break}}}),{iceServers:e,iceTransportPolicy:a.pFlags.p2p_allowed?"all":"relay"}}const Ay=typeof window<"u"&&"crypto"in window?window.crypto.subtle:self.crypto.subtle;function XN(a){return Ay.digest("SHA-256",LE(a)).then(e=>new Uint8Array(e))}const ZN=128*1024*1024;class SC{constructor(e,t){this.isOutgoing=e,this.p2pKey=t,this.type="Signaling",this.counter=0,this.seqMap=new Map}concatSHA256(e){return XN(EE(...e))}async encryptPrepared(e){const t={counter:0,bytes:new Uint8Array(16+e.length)},s=(this.isOutgoing?0:8)+(this.type==="Signaling"?128:0),i=this.p2pKey,n=await this.concatSHA256([i.subarray(s+88,s+88+32),e]),r=t.bytes;for(let c=0;c<16;++c)r[c]=n[c+8];const o=await this.prepareAesKeyIv(i,r,s),l=await this.aesProcessCtr(e,e.length,o,!0);return t.bytes=new Uint8Array([...t.bytes.subarray(0,16),...l]),t}encryptRawPacket(e){const t=++this.counter,s=new ArrayBuffer(4);new DataView(s).setUint32(0,t>>>0,!1);const n=new Uint8Array([...new Uint8Array(s),...e]);return this.encryptPrepared(n)}async prepareAesKeyIv(e,t,s){const[i,n]=await Promise.all([this.concatSHA256([t.subarray(0,16),e.subarray(s,s+36)]),this.concatSHA256([e.subarray(40+s,40+s+36),t.subarray(0,16)])]);return{key:new Uint8Array([...i.subarray(0,8),...n.subarray(8,24),...i.subarray(24,32)]),iv:new Uint8Array([...n.subarray(0,4),...i.subarray(8,16),...n.subarray(24,28)])}}async aesProcessCtr(e,t,s,i=!0){const n=await Ay.importKey("raw",s.key,{name:"AES-CTR"},!1,[i?"encrypt":"decrypt"]),r=await Ay[i?"encrypt":"decrypt"]({name:"AES-CTR",counter:s.iv,length:s.iv.length*8},n,e);return new Uint8Array(r)}constTimeIsDifferent(e,t,s){let i=!0;for(let n=0;n<s;++n)e[n]!==t[n]&&(i=!1);return!i}async decryptRawPacket(e){if(e.length<21||e.length>ZN)return;const{isOutgoing:t,type:s}=this,i=(t?8:0)+(s==="Signaling"?128:0),n=this.p2pKey,r=e.subarray(0,16),o=e.subarray(16),l=e.length-16,c=await this.prepareAesKeyIv(n,r,i),d=await this.aesProcessCtr(o,l,c,!1),u=await this.concatSHA256([n.subarray(88+i,88+i+32),d]);if(this.constTimeIsDifferent(u.subarray(8),r,16))return;const p=new DataView(d.buffer).getUint32(0);if(!this.seqMap.has(p))return this.seqMap.set(p,p),d.slice(4)}}class CC{static generateOffer(e){const{fingerprints:t,ufrag:s,pwd:i,audio:n,video:r}=e;n.type="audio",r.type="video";const o=[n,r],l=new oy;l.add("v=0","o=- 1 2 IN IP4 127.0.0.1","s=-","t=0 0"),t&&t.forEach(d=>{const{hash:u,fingerprint:h,setup:p}=d;l.add(`a=fingerprint:${u} ${h}`,`a=setup:${p}`)}),s&&i&&l.add(`a=ice-ufrag:${s}`,`a=ice-pwd:${i}`),l.add("a=group:BUNDLE 0 1 2","a=extmap-allow-mixed","a=msid-semantic: WMS *");const c="stream"+o.map(d=>d.ssrc).join("_");for(let d=0;d<o.length;d++){const u=o[d],{type:h,ssrc:p,ssrcGroups:m,payloadTypes:g,rtpExtensions:f}=u;switch(h){case"audio":{l.add(`m=audio 56930 UDP/TLS/RTP/SAVPF ${g.map(v=>v.id).join(" ")}`,"c=IN IP4 0.0.0.0","a=rtcp:9 IN IP4 0.0.0.0","a=ice-options:trickle",`a=mid:${d}`,"a=sendrecv",Ma(f)),p&&l.add(`a=msid:${c} audio${p}`),l.add("a=rtcp-mux",La(g),Ea(h,p,m,c));break}case"video":{l.add(`m=video 61986 UDP/TLS/RTP/SAVPF ${g.map(v=>v.id).join(" ")}`,"c=IN IP4 0.0.0.0","a=rtcp:9 IN IP4 0.0.0.0","a=ice-options:trickle",`a=mid:${d}`,"a=sendrecv",Ma(f)),p&&l.add(`a=msid:${c} video${p}`),l.add("a=rtcp-mux","a=rtcp-rsize",La(g),Ea(h,p,m,c));break}}}return l.add(ud()),l.finalize()}static generateAnswer(e){const{fingerprints:t,ufrag:s,pwd:i,audio:n,video:r}=e;n.type="audio",r.type="video";const o=[n,r],l=new oy;l.add("v=0","o=- 1 2 IN IP4 127.0.0.1","s=-","t=0 0"),t&&t.forEach(d=>{const{hash:u,fingerprint:h,setup:p}=d;l.add(`a=fingerprint:${u} ${h}`,`a=setup:${p}`)}),s&&i&&l.add(`a=ice-ufrag:${s}`,`a=ice-pwd:${i}`),l.add("a=group:BUNDLE 0 1 2","a=extmap-allow-mixed","a=msid-semantic: WMS *");const c="stream"+o.map(d=>d.ssrc).join("_");for(let d=0;d<o.length;d++){const u=o[d],{type:h,ssrc:p,ssrcGroups:m,payloadTypes:g,rtpExtensions:f}=u;switch(h){case"audio":{l.add(`m=audio 56930 UDP/TLS/RTP/SAVPF ${g.map(v=>v.id).join(" ")}`,"c=IN IP4 0.0.0.0","a=rtcp:9 IN IP4 0.0.0.0","a=ice-options:trickle",`a=mid:${d}`,"a=sendrecv",Ma(f)),p&&l.add(`a=msid:${c} audio${p}`),l.add("a=rtcp-mux",La(g),Ea(h,p,m,c));break}case"video":{l.add(`m=video 61986 UDP/TLS/RTP/SAVPF ${g.map(v=>v.id).join(" ")}`,"c=IN IP4 0.0.0.0","a=rtcp:9 IN IP4 0.0.0.0","a=ice-options:trickle",`a=mid:${d}`,"a=sendrecv",Ma(f)),p&&l.add(`a=msid:${c} video${p}`),l.add("a=rtcp-mux","a=rtcp-rsize",La(g),Ea(h,p,m,c));break}}}return l.add(ud()),l.finalize()}}class _C{static generateOffer(e){const{fingerprints:t,ufrag:s,pwd:i,audio:n,video:r}=e;n.type="audio",r.type="video";const o=[n,r];let l=`v=0
- o=- 1 0 IN IP4 0.0.0.0
- s=-
- t=0 0`;t&&t.forEach(d=>{const{hash:u,fingerprint:h,setup:p}=d;l+=`
- a=fingerprint:${u} ${h}
- a=setup:${p}`}),s&&i&&(l+=`
- a=ice-ufrag:${s}
- a=ice-pwd:${i}`),l+=`
- a=group:BUNDLE 0 1 2
- a=ice-options:trickle
- a=msid-semantic:WMS *`;const c="stream"+o.map(d=>d.ssrc).join("_");for(let d=0;d<o.length;d++){const u=o[d],{type:h,ssrc:p,ssrcGroups:m,payloadTypes:g,rtpExtensions:f}=u;switch(h){case"audio":{l+=`
- m=audio 9 UDP/TLS/RTP/SAVPF ${g.map(v=>v.id).join(" ")}
- c=IN IP4 0.0.0.0
- a=mid:${d}
- a=sendrecv`,l+=Ma(f),l+=`
- a=rtcp-mux`,l+=La(g),l+=Ea(h,p,m,c);break}case"video":{l+=`
- m=video 9 UDP/TLS/RTP/SAVPF ${g.map(v=>v.id).join(" ")}
- c=IN IP4 0.0.0.0
- a=mid:${d}
- a=sendrecv`,l+=Ma(f),l+=`
- a=rtcp-mux
- a=rtcp-rsize`,l+=La(g),l+=Ea(h,p,m,c);break}}}return l+=ud(),l+=`
- `,l}static generateAnswer(e){const{fingerprints:t,ufrag:s,pwd:i,audio:n,video:r}=e;n.type="audio",r.type="video";const o=[n,r];let l=`v=0
- o=- 1 0 IN IP4 0.0.0.0
- s=-
- t=0 0`;t&&t.forEach(d=>{const{hash:u,fingerprint:h,setup:p}=d;l+=`
- a=fingerprint:${u} ${h}
- a=setup:${p}`}),s&&i&&(l+=`
- a=ice-ufrag:${s}
- a=ice-pwd:${i}`),l+=`
- a=group:BUNDLE 0 1 2
- a=ice-options:trickle
- a=msid-semantic:WMS *`;const c="stream"+o.map(d=>d.ssrc).join("_");for(let d=0;d<o.length;d++){const u=o[d],{type:h,mid:p,ssrc:m,ssrcGroups:g,payloadTypes:f,dir:v,rtpExtensions:y}=u;switch(h){case"audio":{l+=`
- m=audio 9 UDP/TLS/RTP/SAVPF ${f.map(w=>w.id).join(" ")}
- c=IN IP4 0.0.0.0
- a=mid:${d}
- a=sendrecv`,l+=Ma(y),l+=`
- a=rtcp-mux`,l+=La(f),l+=Ea(h,m,g,c);break}case"video":{l+=`
- m=video 9 UDP/TLS/RTP/SAVPF ${f.map(w=>w.id).join(" ")}
- c=IN IP4 0.0.0.0
- a=mid:${d}
- a=sendrecv`,l+=Ma(y),l+=`
- a=rtcp-mux
- a=rtcp-rsize`,l+=La(f),l+=Ea(h,m,g,c);break}}}return l+=ud(),l+=`
- `,l}}class IC{static generateOffer(e){const{fingerprints:t,ufrag:s,pwd:i,audio:n,video:r}=e;n.type="audio",r.type="video";const o=[n,r];if(!o.length)return`v=0
- o=- 1 2 IN IP4 127.0.0.1
- s=-
- t=0 0
- a=msid-semantic: WMS
- `;let l=`v=0
- o=- 1 2 IN IP4 127.0.0.1
- s=-
- t=0 0`;t&&t.forEach(d=>{const{hash:u,fingerprint:h,setup:p}=d;l+=`
- a=fingerprint:${u} ${h}
- a=setup:${p}`}),s&&i&&(l+=`
- a=ice-ufrag:${s}
- a=ice-pwd:${i}`),l+=`
- a=group:BUNDLE 0 1 2
- a=extmap-allow-mixed
- a=msid-semantic: WMS *`;const c="stream"+o.map(d=>d.ssrc).join("_");for(let d=0;d<o.length;d++){const u=o[d],{type:h,ssrc:p,ssrcGroups:m,payloadTypes:g,rtpExtensions:f}=u;switch(h){case"audio":{l+=`
- m=audio 9 UDP/TLS/RTP/SAVPF ${g.map(v=>v.id).join(" ")}
- c=IN IP4 0.0.0.0
- a=rtcp:9 IN IP4 0.0.0.0
- a=ice-options:trickle
- a=mid:${d}
- a=sendrecv`,l+=Ma(f),p&&(l+=`
- a=msid:${c} audio${p}`),l+=`
- a=rtcp-mux`,l+=La(g),l+=Ea(h,p,m,c);break}case"video":{l+=`
- m=video 9 UDP/TLS/RTP/SAVPF ${g.map(v=>v.id).join(" ")}
- c=IN IP4 0.0.0.0
- a=rtcp:9 IN IP4 0.0.0.0
- a=ice-options:trickle
- a=mid:${d}
- a=sendrecv`,l+=Ma(f),p&&(l+=`
- a=msid:${c} video${p}`),l+=`
- a=rtcp-mux
- a=rtcp-rsize`,l+=La(g),l+=Ea(h,p,m,c);break}}}return l+=ud(),l+=`
- `,l}static generateAnswer(e){const{fingerprints:t,ufrag:s,pwd:i,audio:n,video:r}=e;n.type="audio",r.type="video";const o=[n,r];if(!o.length)return`v=0
- o=- 1 2 IN IP4 127.0.0.1
- s=-
- t=0 0
- a=msid-semantic: WMS
- `;let l=`v=0
- o=- 1 2 IN IP4 127.0.0.1
- s=-
- t=0 0`;t&&t.forEach(d=>{const{hash:u,fingerprint:h,setup:p}=d;l+=`
- a=fingerprint:${u} ${h}
- a=setup:${p}`}),s&&i&&(l+=`
- a=ice-ufrag:${s}
- a=ice-pwd:${i}`),l+=`
- a=group:BUNDLE 0 1 2
- a=extmap-allow-mixed
- a=msid-semantic: WMS *`;const c="stream"+o.map(d=>d.ssrc).join("_");for(let d=0;d<o.length;d++){const u=o[d],{type:h,ssrc:p,ssrcGroups:m,payloadTypes:g,rtpExtensions:f}=u;switch(h){case"audio":{l+=`
- m=audio 9 UDP/TLS/RTP/SAVPF ${g.map(v=>v.id).join(" ")}
- c=IN IP4 0.0.0.0
- a=rtcp:9 IN IP4 0.0.0.0
- a=ice-options:trickle
- a=mid:${d}
- a=sendrecv`,l+=Ma(f),p&&(l+=`
- a=msid:${c} audio${p}`),l+=`
- a=rtcp-mux`,l+=La(g),l+=Ea(h,p,m,c);break}case"video":{l+=`
- m=video 9 UDP/TLS/RTP/SAVPF ${g.map(v=>v.id).join(" ")}
- c=IN IP4 0.0.0.0
- a=rtcp:9 IN IP4 0.0.0.0
- a=ice-options:trickle
- a=mid:${d}
- a=sendrecv`,l+=Ma(f),p&&(l+=`
- a=msid:${c} video${p}`),l+=`
- a=rtcp-mux
- a=rtcp-rsize`,l+=La(g),l+=Ea(h,p,m,c);break}}}return l+=ud(),l+=`
- `,l}}function JN(a){if(!a||!a.startsWith("candidate:"))return;const e=a;a=a.substr(10);const[t,s,i,n,r,o,...l]=a.split(" "),c={sdpString:e,foundation:t,component:s,protocol:i,priority:n,address:{ip:r,port:o}};for(let d=0;d<l.length;d+=2)switch(l[d]){case"typ":{c.type=l[d+1];break}case"raddr":{c.relAddress||(c.relAddress={}),c.relAddress.ip=l[d+1];break}case"rport":{c.relAddress||(c.relAddress={}),c.relAddress.port=l[d+1];break}case"generation":{c.generation=l[d+1];break}case"tcptype":{c.tcpType=l[d+1];break}case"network-id":{c.networkId=l[d+1];break}case"network-cost":{c.networkCost=l[d+1];break}case"ufrag":{c.username=l[d+1];break}}return c}function PC(){return navigator.userAgent.toLowerCase().indexOf("firefox")>-1}function MC(){return navigator.userAgent.toLowerCase().indexOf("safari")>-1&&navigator.userAgent.toLowerCase().indexOf("chrome")===-1}function Ma(a){let e=[];for(let t=0;t<a.length;t++){const s=a[t],{id:i,uri:n}=s;console.log("[extmap] add",i,n),e.push(`a=extmap:${i} ${n}`)}return e.join(`
- `)}function La(a){let e=[];console.log("[SDP] addPayloadTypes",a);for(let t=0;t<a.length;t++){const s=a[t],{id:i,name:n,clockrate:r,channels:o,feedbackTypes:l,parameters:c}=s;if(e.push(`a=rtpmap:${i} ${n}/${r}${o?"/"+o:""}`),l&&l.forEach(d=>{const{type:u,subtype:h}=d;e.push(`a=rtcp-fb:${i} ${[u,h].join(" ")}`)}),c){const d=[];Object.getOwnPropertyNames(c).forEach(u=>{d.push(`${u}=${c[u]}`)}),e.push(`a=fmtp:${i} ${d.join(";")}`)}}return e.join(`
- `)}function Ea(a,e,t,s){let i=[];return t&&t.length>0?t.forEach(n=>{n&&n.ssrcs.length>0&&(i.push(`a=ssrc-group:${n.semantics} ${n.ssrcs.join(" ")}`),n.ssrcs.forEach(r=>{i.push(`a=ssrc:${r} cname:stream${r}`,`a=ssrc:${r} msid:${s} ${a}${r}`,`a=ssrc:${r} mslabel:${a}${r}`,`a=ssrc:${r} label:${a}${r}`)}))}):e&&i.push(`a=ssrc:${e} cname:stream${e}`,`a=ssrc:${e} msid:${s} ${a}${e}`,`a=ssrc:${e} mslabel:${a}${e}`,`a=ssrc:${e} label:${a}${e}`),i.join(`
- `)}function ud(a){return`m=application 9 UDP/DTLS/SCTP webrtc-datachannel
- c=IN IP4 0.0.0.0
- a=ice-options:trickle
- a=mid:2
- a=sctp-port:5000
- a=max-message-size:262144`}class eO{static generateCandidate(e){if(!e)return null;const{sdpString:t,sdpMLineIndex:s,sdpMid:i,foundation:n,component:r,protocol:o,priority:l,address:c,type:d,relAddress:u,generation:h,tcpType:p,networkId:m,networkCost:g,username:f}=e;if(t)return{candidate:t,sdpMLineIndex:s,sdpMid:i};throw"no sdpString"}static generateOffer(e){return PC()?_C.generateOffer(e):MC()?IC.generateOffer(e):CC.generateOffer(e)}static generateAnswer(e){return PC()?_C.generateAnswer(e):MC()?IC.generateAnswer(e):CC.generateAnswer(e)}}class am extends CP{constructor(e){super(),this.log=Ni("CALL"),this.protocol||(this.protocol=YN()),Nt(this,e),this.createdAt=Date.now(),this.offerReceived=!1,this.offerSent=!1,this.decryptQueue=[],this.candidates=[],this.addEventListener("state",n=>{this.log("state",ds[n]),n===ds.CLOSED&&this.cleanup()});const t=this.streamManager=new Ol(yP);t.direction="sendrecv",t.types.push("screencast"),this.isOutgoing||(t.locked=!0,t.canCreateConferenceEntry=!1);let s={"@type":"MediaState",type:"input",lowBattery:!1,muted:!0,screencastState:"inactive",videoRotation:0,videoState:"inactive"};const i=this;s=new Proxy(s,{set:function(n,r,o){return n[r]=o,i.setMediaState(s),i.sendMediaState(),!0}}),this.mediaStates={input:s},this.sendMediaState=$i(this._sendMediaState.bind(this),0,!1,!0)}get connectionState(){const{_connectionState:e,connectionInstance:t}=this;if(e!==void 0)return e;if(t){const{iceConnectionState:s}=t.connection;return s==="closed"?ds.CLOSED:s!=="connected"&&(!dn||s!=="completed")?ds.CONNECTING:ds.CONNECTED}else return ds.CONNECTING}get sortIndex(){const e=this.connectionState;let s=(ds.CLOSED-e+1)*1e13;return s+=2147483647e3-(e===ds.PENDING&&this.isOutgoing?0:this.createdAt),s}getVideoElement(e){if(e==="input")return this.elements.get("main");{const t=this.getMediaState("output");if(!t)return;const s=t.videoState==="active"?"video":t.screencastState==="active"?"screencast":void 0;if(!s)return;const i=this.description.findEntry(n=>n.type===s);return i?this.elements.get(""+i.recvEntry.source):void 0}}async startScreenSharingInternal(){try{this.wasStartingScreen=!0,this.wasStartingVideo=!1,this.streamManager.types=["audio","screencast"],await this.requestScreen()}catch(e){this.log.error("startScreenSharing error",e)}}async toggleScreenSharing(){return this.isSharingVideo&&await this.stopVideoSharing(),this.isSharingScreen?this.stopVideoSharing():this.startScreenSharingInternal()}async startVideoSharingInternal(){try{this.wasStartingScreen=!1,this.wasStartingVideo=!0,this.streamManager.types=["audio","video"],await this.requestInputSource(!1,!0,!1)}catch(e){this.log.error("startVideoSharing error",e)}}async stopVideoSharing(){const e=this.getMediaState("input");e.videoState=e.screencastState="inactive";const{streamManager:t,description:s}=this,i=t.inputStream.getVideoTracks()[0];i&&(Qg(i),t.appendToConference(s))}async toggleVideoSharing(){return this.isSharingScreen&&await this.stopVideoSharing(),this.isSharingVideo?this.stopVideoSharing():this.startVideoSharingInternal()}getMediaState(e){return this.mediaStates[e]}setMediaState(e){this.mediaStates[e.type]=e,this.dispatchEvent("mediaState",e)}isSharingVideoType(e){try{return super.isSharingVideo&&!!(this.wasStartingScreen&&e==="screencast"||this.wasStartingVideo&&e==="video")}catch{return!1}}get isSharingVideo(){return this.isSharingVideoType("video")}get isSharingScreen(){return this.isSharingVideoType("screencast")}get isMuted(){return!this.streamManager.inputStream.getAudioTracks()[0]?.enabled}get isClosing(){const{connectionState:e}=this;return e===ds.CLOSING||e===ds.CLOSED}get description(){return this.connectionInstance?.description}setHangUpTimeout(e,t){this.clearHangUpTimeout(),this.hangUpTimeout=dm.setTimeout(()=>{this.hangUpTimeout=void 0,this.hangUp(t)},e)}clearHangUpTimeout(){this.hangUpTimeout!==void 0&&(clearTimeout(this.hangUpTimeout),this.hangUpTimeout=void 0)}setPhoneCall(e){this.call=e;const{id:t}=e;if(this.id!==t){const s=this.id;this.id=t,this.dispatchEvent("id",t,s)}}async acceptCall(){const e=(await Promise.all(this.dispatchResultableEvent("acceptCallOverride")))[0]??!0;if(this.isClosing||!e)return;this.overrideConnectionState(ds.EXCHANGING_KEYS);const t=this.call;this.requestInputSource(!0,!!t.pFlags.video,!1);const s=t.g_a_hash;this.managers.appCallsManager.generateDh().then(async i=>(this.dh={g_a_hash:s,b:i.a,g_b:i.g_a,g_b_hash:i.g_a_hash,p:i.p},this.managers.apiManager.invokeApi("phone.acceptCall",{peer:await this.managers.appCallsManager.getCallInput(this.id),protocol:this.protocol,g_b:this.dh.g_b}))).then(async i=>{await this.managers.appCallsManager.savePhonePhoneCall(i)}).catch(i=>{this.log.error("accept call error",i),this.hangUp("phoneCallDiscardReasonHangup")})}joinCall(){this.log("joinCall"),this.getEmojisFingerprint(),this.overrideConnectionState();const{isOutgoing:e,encryptionKey:t,streamManager:s}=this,i=QN(this.call);if(this.log("joinCall configuration",i),!i)return;const n=this.connectionInstance=new WN({call:this,streamManager:s,log:this.log.bindPrefix("connection")}),r=n.createPeerConnection(i);r.addEventListener("iceconnectionstatechange",()=>{const o=this.connectionState;this.connectedAt===void 0&&o===ds.CONNECTED&&(this.connectedAt=Date.now()),this.dispatchEvent("state",o)}),r.addEventListener("negotiationneeded",()=>{n.negotiate()}),r.addEventListener("icecandidate",o=>{const{candidate:l}=o;r.log("onicecandidate",l),l?.candidate&&this.sendIceCandidate(l)}),r.addEventListener("track",o=>{const{track:l}=o;r.log("ontrack",l),this.onTrack(o)}),n.createDescription(),this.encryptor=new SC(e,t),this.decryptor=new SC(!e,t),this.log("currentCall",this),e&&n.appendStreamToConference(),this.createDataChannel(),this.processDecryptQueue()}createDataChannelEntry(){const e=this.description.createEntry("application");e.setDirection("sendrecv"),e.sendEntry=e.recvEntry=e}createDataChannel(){if(this.connectionInstance.dataChannel)return;const e=this.connectionInstance.createDataChannel({id:0,negotiated:!0});e.addEventListener("message",t=>{this.applyDataChannelData(JSON.parse(t.data))}),e.addEventListener("open",()=>{this.sendMediaState()})}applyDataChannelData(e){switch(e["@type"]){case"MediaState":{e.type="output",this.log("got output media state",e),this.setMediaState(e);break}default:this.log.error("unknown data channel data:",e);break}}_sendMediaState(){const{connectionInstance:e}=this;if(!e)return;const t={...this.getMediaState("input")};delete t.type,this.log("sendMediaState",t),e.sendDataChannelData(t)}async sendCallSignalingData(e){const t=JSON.stringify(e),s=new TextEncoder().encode(t),{bytes:i}=await this.encryptor.encryptRawPacket(s);this.log("sendCallSignalingData",this.id,t),await this.managers.apiManager.invokeApi("phone.sendSignalingData",{peer:await this.managers.appCallsManager.getCallInput(this.id),data:i})}sendIceCandidate(e){this.log("sendIceCandidate",e);const{candidate:t,sdpMLineIndex:s}=e;if(s!==0)return;const i=JN(t);this.sendCallSignalingData({"@type":"Candidates",candidates:[i]})}async confirmCall(){const{protocol:e,id:t,call:s}=this,i=this.dh;this.overrideConnectionState(ds.EXCHANGING_KEYS);const{key:n,key_fingerprint:r}=await this.managers.appCallsManager.computeKey(s.g_b,i.a,i.p),o=await this.managers.apiManager.invokeApi("phone.confirmCall",{peer:await this.managers.appCallsManager.getCallInput(t),protocol:e,g_a:i.g_a,key_fingerprint:r});this.encryptionKey=n,await this.managers.appCallsManager.savePhonePhoneCall(o),this.joinCall()}getEmojisFingerprint(){return this.emojisFingerprint?this.emojisFingerprint:this.getEmojisFingerprintPromise?this.getEmojisFingerprintPromise:this.getEmojisFingerprintPromise=Ae.invokeCrypto("get-emojis-fingerprint",this.encryptionKey,this.dh.g_a).then(e=>(this.getEmojisFingerprintPromise=void 0,this.emojisFingerprint=e.map(t=>eb(t))))}unlockStreamManager(){this.connectionInstance.streamManager.locked=!1,this.connectionInstance.appendStreamToConference()}async doTheMagic(){this.connectionInstance.appendStreamToConference();const e=this.connectionInstance.connection;let t=await e.createAnswer();this.log("[sdp] local",t.type,t.sdp),await e.setLocalDescription(t),e.getTransceivers().filter(l=>l.direction==="recvonly").forEach(l=>{const c=this.connectionInstance.description.getEntryByMid(l.mid);c.transceiver=c.recvEntry.transceiver=l,l.direction="sendrecv"});const s=!1,i=this.description,n=i.entries.map(l=>l.mid),r={type:"offer",sdp:i.generateSdp({bundle:n,entries:i.entries.filter(l=>n.includes(l.mid)),isAnswer:!s})};await e.setRemoteDescription(r),t=await e.createAnswer(),await e.setLocalDescription(t);const o=$M(qm(t.sdp));this.log("[InitialSetup] send 1"),this.sendCallSignalingData(o),this.unlockStreamManager()}overrideConnectionState(e){this._connectionState=e,this.dispatchEvent("state",this.connectionState)}get duration(){return this.connectedAt!==void 0?(Date.now()-this.connectedAt)/1e3|0:0}onInputStream(e){super.onInputStream(e);const t=e.getVideoTracks()[0];if(t){const s=this.getMediaState("input");!this.wasStartingScreen&&!this.wasStartingVideo&&(this.wasStartingVideo=!0),this.isSharingVideo?s.videoState="active":this.isSharingScreen&&(s.screencastState="active"),t.addEventListener("ended",()=>{this.stopVideoSharing()},{once:!0})}e.getAudioTracks().length&&this.onMutedChange()}onMutedChange(){const e=this.isMuted;this.dispatchEvent("muted",e);const t=this.getMediaState("input");t.muted=e}toggleMuted(){return this.requestAudioSource(!0).then(()=>{this.setMuted(),this.onMutedChange()})}async hangUp(e,t){if(!this.isClosing&&(e=typeof e=="string"?{_:e}:e,this.discardReason=e,this.log("hangUp",e),this.overrideConnectionState(ds.CLOSED),this.connectionInstance&&this.connectionInstance.closeConnectionAndStream(!0),e&&!t)){let s=!1;for(const i in this.mediaStates){const n=this.mediaStates[i];s=n.videoState==="active"||n.screencastState==="active"||s}await this.managers.appCallsManager.discardCall(this.id,this.duration,e,s)}}performCodec(e){const t=e.payloadTypes.map(i=>({...i,"rtcp-fbs":i.feedbackTypes}));return{"rtp-hdrexts":e.rtpExtensions,"payload-types":t}}setDataToDescription(e){this.description.setData({transport:{pwd:e.pwd,ufrag:e.ufrag,fingerprints:e.fingerprints,"rtcp-mux":!0},audio:this.performCodec(e.audio),video:e.video?this.performCodec(e.video):void 0,screencast:e.screencast?this.performCodec(e.screencast):void 0})}filterNotVP8(e){this.isOutgoing||[e.video,e.screencast].filter(Boolean).forEach(t=>{const s=t.payloadTypes,i=s.findIndex(o=>o.name==="VP8"),n=s[i],r=s.findIndex(o=>+o.parameters?.apt===n.id);t.payloadTypes=[s[i],s[r]]})}async applyCallSignalingData(e){this.log("applyCallSignalingData",this,e);const{connection:t,description:s}=this.connectionInstance;switch(e["@type"]){case"InitialSetup":{this.log("[sdp] InitialSetup",e),this.filterNotVP8(e),this.setDataToDescription(e);const i=c=>c.map(d=>({_:"groupCallParticipantVideoSourceGroup",semantics:d.semantics,sources:d.ssrcs.map(u=>+u)}));[im("audio",+e.audio.ssrc),e.video?im("video",i(e.video.ssrcGroups)):void 0,e.screencast?im("screencast",i(e.screencast.ssrcGroups)):void 0].filter(Boolean).forEach(c=>{let d=s.getEntryBySource(c.source);if(d)return;const u=s.findFreeSendRecvEntry(c.type,!1);d=new Jg(u.mid,c.type),d.setDirection("sendrecv"),u.recvEntry=d,s.setEntrySource(d,c.sourceGroups||c.source)}),this.createDataChannelEntry();const r=this.offerSent;this.offerSent=!1;const o=s.entries.map(c=>c.mid),l={type:r?"answer":"offer",sdp:s.generateSdp({bundle:o,entries:s.entries.filter(c=>o.includes(c.mid)),isAnswer:!r})};this.log("[sdp] remote",l.sdp),await t.setRemoteDescription(l),await this.tryToReleaseCandidates(),r||await this.doTheMagic();break}case"Candidates":{for(const i of e.candidates){const n=eO.generateCandidate(i);n.sdpMLineIndex=0;const r=new RTCIceCandidate(n);this.candidates.push(r)}await this.tryToReleaseCandidates();break}default:this.log.error("unrecognized signaling data",e)}}async tryToReleaseCandidates(){const{connectionInstance:e}=this;if(!e)return;const{connection:t}=e;if(t.remoteDescription){const s=this.candidates.map(i=>this.addIceCandidate(t,i));this.candidates.length=0,await Promise.all(s)}else this.log("[candidates] postpone")}async addIceCandidate(e,t){this.log("[candidate] start",t);try{await e.addIceCandidate(t),this.log("[candidate] add",t)}catch(s){this.log.error("[candidate] error",t,s)}}async processDecryptQueue(){const{encryptor:e}=this;if(!e){this.log.warn("got encrypted signaling data before the encryption key");return}if(!this.decryptQueue.length)return;const s=this.decryptQueue.slice();this.decryptQueue.length=0;for(const i of s){const n=await e.decryptRawPacket(i);if(!n)continue;const r=new TextDecoder().decode(n);try{const o=JSON.parse(r);this.log("[update] updateNewCallSignalingData",o),this.applyCallSignalingData(o)}catch{this.log.error("wrong signaling data",r),this.hangUp("phoneCallDiscardReasonDisconnect"),Un.dispatchEvent("incompatible",this.interlocutorUserId)}}}onUpdatePhoneCallSignalingData(e){this.decryptQueue.push(e),this.processDecryptQueue()}}async function tO(a){const e=document.createElement("canvas");return e.width=a.videoWidth,e.height=a.videoHeight,e.getContext("2d").drawImage(a,0,0,e.width,e.height),new Promise((s,i)=>{e.toBlob(n=>{n?s(n):i(new Error("Failed to create blob"))})})}class sO extends ue{constructor(e){super("rtmp-output-popup",{overlayClosable:!0,title:!0,body:!0,buttons:[{langKey:"OK",callback:()=>{e.setSinkId(s)}}]}),this.video=e;const t=e.sinkId||"default";let s=t;this.title.append(P("Rtmp.OutputPopup.Title")),navigator.mediaDevices.enumerateDevices().then(i=>{const n=i.filter(o=>o.kind==="audiooutput"),r=vm(n.map(o=>({textElement:je(o.label),value:o.deviceId,checked:o.deviceId===t})),o=>{s=o});this._dispose=wi(()=>T(Du,{name:"fade",mode:"outin",get children(){return T(Js,{get when(){return n.length===0},fallback:r,get children(){return vm([{textElement:P("Rtmp.OutputPopup.Default"),value:"",checked:!0}],o=>{})}})}}),this.body)})}cleanup(){this._dispose()}}const iO="data:image/svg+xml,%3csvg%20width='168'%20height='64'%20viewBox='0%200%20168%2064'%20fill='none'%20xmlns='http://www.w3.org/2000/svg'%3e%3crect%20width='168'%20height='64'%20rx='10'%20fill='white'/%3e%3ccircle%20cx='35'%20cy='32'%20r='20'%20fill='%234E8EE5'/%3e%3cpath%20fill-rule='evenodd'%20clip-rule='evenodd'%20d='M35%2022C32.7909%2022%2031%2023.7909%2031%2026V31C31%2033.2091%2032.7909%2035%2035%2035C37.2091%2035%2039%2033.2091%2039%2031V26C39%2023.7909%2037.2091%2022%2035%2022ZM27.5%2030C28.0523%2030%2028.5%2030.4477%2028.5%2031C28.5%2034.5899%2031.4101%2037.5%2035%2037.5C38.5899%2037.5%2041.5%2034.5899%2041.5%2031C41.5%2030.4477%2041.9477%2030%2042.5%2030C43.0523%2030%2043.5%2030.4477%2043.5%2031C43.5%2035.3561%2040.2232%2038.9469%2036%2039.4418V41.5C36%2042.0523%2035.5523%2042.5%2035%2042.5C34.4477%2042.5%2034%2042.0523%2034%2041.5V39.4418C29.7768%2038.9469%2026.5%2035.3561%2026.5%2031C26.5%2030.4477%2026.9477%2030%2027.5%2030Z'%20fill='white'/%3e%3cpath%20d='M70%2026V36'%20stroke='%234E8EE5'%20stroke-width='4'%20stroke-linecap='round'/%3e%3cpath%20d='M77%2021V41'%20stroke='%234E8EE5'%20stroke-width='4'%20stroke-linecap='round'/%3e%3cpath%20d='M84%2024V38'%20stroke='%234E8EE5'%20stroke-width='4'%20stroke-linecap='round'/%3e%3cpath%20d='M91%2026V36'%20stroke='%234E8EE5'%20stroke-width='4'%20stroke-linecap='round'/%3e%3cpath%20d='M98%2021V41'%20stroke='%234E8EE5'%20stroke-width='4'%20stroke-linecap='round'/%3e%3cpath%20d='M105%2024V38'%20stroke='%234E8EE5'%20stroke-width='4'%20stroke-linecap='round'/%3e%3cpath%20d='M112%2026V36'%20stroke='%234E8EE5'%20stroke-width='4'%20stroke-linecap='round'/%3e%3cpath%20d='M119%2021V41'%20stroke='%234E8EE5'%20stroke-width='4'%20stroke-linecap='round'/%3e%3cpath%20d='M126%2024V38'%20stroke='%234E8EE5'%20stroke-width='4'%20stroke-linecap='round'/%3e%3cpath%20d='M133%2026V36'%20stroke='%234E8EE5'%20stroke-width='4'%20stroke-linecap='round'/%3e%3cpath%20d='M140%2021V41'%20stroke='%234E8EE5'%20stroke-width='4'%20stroke-linecap='round'/%3e%3cpath%20d='M147%2024V38'%20stroke='%234E8EE5'%20stroke-width='4'%20stroke-linecap='round'/%3e%3cpath%20d='M154%2026V36'%20stroke='%234E8EE5'%20stroke-width='4'%20stroke-linecap='round'/%3e%3c/svg%3e",nO=""+new URL("videoVertical-DfKAjRLf.svg",import.meta.url).href,aO=""+new URL("videoHorizontal-DFE8hxwc.svg",import.meta.url).href,rO=Y("<div><img><div>"),oO=Y("<div><div><img><img></div><div>"),lO=Y("<button>"),cO=Y("<div><div><div><br><br></div></div><div><div></div></div><div>"),Hi=(a="")=>`rtmp-record-popup${a}`;class dO extends ue{constructor(){super(Hi(),{overlayClosable:!0,closable:!0,title:!0,body:!0});ro(this,"_onSubmit",t=>{this.forceHide(),this.managers.appGroupCallsManager.startRecording(cs.currentCall.inputCall,t).catch(()=>{$e({langPackKey:"Rtmp.RecordPopup.Failed"})})});this.title.append(P("Rtmp.RecordPopup.Title")),this._dispose=wi(()=>{const t=this;return T(hO,{get onSubmit(){return t._onSubmit}})},this.body)}cleanup(){super.cleanup(),this._dispose()}}const LC=40,hO=a=>{const[e,t]=K(""),[s,i]=K(!1),[n,r]=K(!0),o=new _t({toggle:!0});o.input.addEventListener("change",()=>{i(o.checked)});const l=()=>{a.onSubmit({name:e(),recordVideo:s(),videoHorizontal:n()})};return(()=>{const c=cO(),d=c.firstChild,u=d.firstChild,h=u.firstChild;h.nextSibling;const p=d.nextSibling,m=p.firstChild,g=p.nextSibling;return k(d,T(Yy,{get class(){return Hi("-config-name")},get value(){return e()},onRawInput:t,get labelText(){return P("Rtmp.RecordPopup.RecordingTitle").innerText},maxLength:LC}),u),k(u,()=>P("Rtmp.RecordPopup.RecordingQuestion"),h),k(u,()=>P("Rtmp.RecordPopup.RecordingHint"),null),k(d,T(qk,{icon:"videocamera",get title(){return P("Rtmp.RecordPopup.AlsoRecordVideo")},checkboxField:o}),null),k(p,T(Du,{name:"fade",mode:"outin",get children(){return[T(Js,{get when(){return!s()},get children(){const f=rO(),v=f.firstChild,y=v.nextSibling;return Es(v,"src",iO),k(y,()=>P("Rtmp.RecordPopup.RecordAudioHint")),Me(w=>{const b=Hi("-preview-wrap"),S=P("Rtmp.RecordPopup.RecordAudio").innerText,_=Ge(Hi("-preview-img"),Hi("-preview-img_audio")),M=Hi("-preview-title");return b!==w._v$&&be(f,w._v$=b),S!==w._v$2&&Es(v,"alt",w._v$2=S),_!==w._v$3&&be(v,w._v$3=_),M!==w._v$4&&be(y,w._v$4=M),w},{_v$:void 0,_v$2:void 0,_v$3:void 0,_v$4:void 0}),f}}),T(Js,{get when(){return s()},get children(){const f=oO(),v=f.firstChild,y=v.firstChild,w=y.nextSibling,b=v.nextSibling;return y.$$click=()=>r(!0),Es(y,"src",aO),w.$$click=()=>r(!1),Es(w,"src",nO),k(b,()=>P("Rtmp.RecordPopup.RecordVideoHint")),Me(S=>{const _=Hi("-preview-wrap"),M=Hi("-preview-images"),C=P("Rtmp.RecordPopup.Horizontal").innerText,L={[Hi("-preview-img")]:!0,[Hi("-preview-img_videoH")]:!0,[Hi("-preview-img_active")]:n()},E=P("Rtmp.RecordPopup.Vertical").innerText,x={[Hi("-preview-img")]:!0,[Hi("-preview-img_videoV")]:!0,[Hi("-preview-img_active")]:!n()},R=Hi("-preview-title");return _!==S._v$5&&be(f,S._v$5=_),M!==S._v$6&&be(v,S._v$6=M),C!==S._v$7&&Es(y,"alt",S._v$7=C),S._v$8=er(y,L,S._v$8),E!==S._v$9&&Es(w,"alt",S._v$9=E),S._v$10=er(w,x,S._v$10),R!==S._v$11&&be(b,S._v$11=R),S},{_v$5:void 0,_v$6:void 0,_v$7:void 0,_v$8:void 0,_v$9:void 0,_v$10:void 0,_v$11:void 0}),f}})]}}),null),k(g,T(Ku,{get children(){const f=lO();return f.$$click=l,k(f,()=>P("Rtmp.RecordPopup.ButtonRecord")),Me(v=>{const y=e().length>LC,w=Hi("-button");return y!==v._v$12&&(f.disabled=v._v$12=y),w!==v._v$13&&be(f,v._v$13=w),v},{_v$12:void 0,_v$13:void 0}),f}})),Me(f=>{const v=Hi("-content"),y=Hi("-config"),w=Hi("-config-text"),b=Hi("-preview"),S=Hi("-preview-shadow");return v!==f._v$14&&be(c,f._v$14=v),y!==f._v$15&&be(d,f._v$15=y),w!==f._v$16&&be(u,f._v$16=w),b!==f._v$17&&be(p,f._v$17=b),S!==f._v$18&&be(m,f._v$18=S),f},{_v$14:void 0,_v$15:void 0,_v$16:void 0,_v$17:void 0,_v$18:void 0}),c})()};Fs(["click"]);const uO=Y('<div><div><div><svg xmlns=http://www.w3.org/2000/svg width=18 height=18 viewBox="0 0 18 18"fill=none><path d="M9.83591 16.9562C14.23 16.4944 17.4177 12.5579 16.9559 8.16382C16.494 3.76974 12.5575 0.582034 8.16345 1.04387C3.76938 1.50571 0.58167 5.4422 1.04351 9.83627"stroke=white stroke-width=2 stroke-linecap=round></path></svg><div></div></div><div>'),dc=(a="")=>`rtmp-player${a}`,pO=({peerId:a})=>{const[e,t]=K(""),[s,i]=K(""),[n,r]=K(!0);return Jt(()=>{I.managers.appGroupCallsManager.fetchRtmpUrl(a).then(async o=>{t(o.url),i(o.key),r(!1)}).catch(()=>{$e({langPackKey:"Error.AnError"})})}),(()=>{const o=uO(),l=o.firstChild,c=l.firstChild,d=c.firstChild,u=d.nextSibling,h=c.nextSibling;return k(u,()=>P("Rtmp.MediaViewer.Failed.Title")),k(h,()=>P("Rtmp.MediaViewer.Failed.Description")),k(l,T(AP,{get key(){return s()},get url(){return e()},get loading(){return n()},contrast:!0}),null),Me(p=>{const m=dc("-empty"),g=dc("-empty-text"),f=dc("-empty-header"),v=dc("-empty-loader"),y=dc("-empty-title"),w=dc("-empty-text-inner");return m!==p._v$&&be(o,p._v$=m),g!==p._v$2&&be(l,p._v$2=g),f!==p._v$3&&be(c,p._v$3=f),v!==p._v$4&&Es(d,"class",p._v$4=v),y!==p._v$5&&be(u,p._v$5=y),w!==p._v$6&&be(h,p._v$6=w),p},{_v$:void 0,_v$2:void 0,_v$3:void 0,_v$4:void 0,_v$5:void 0,_v$6:void 0}),o})()},EC=15e3,ia=class ia extends yw{constructor(e){super(new Ag({loadMore:async()=>({count:0,items:[]})}),e?["forward"]:[]),this.shareUrl=e,this.listenerSetter=new $t,this.onForward=async()=>{Rs.createSharingPicker({onSelect:async t=>{const s=await _r.prepareStarsForPayment({messageCount:1,peerId:t});if(s===Fn)throw new Error;I.managers.appMessagesManager.sendText({peerId:t,text:this.shareUrl,confirmedPaymentResult:s}),$e({langPackKey:"InviteLinkSentSingle",langPackArguments:[await qe({peerId:t,dialog:!0})]})}})},this.rejoin=()=>{cs.currentCall&&cs.rejoinCall().catch(t=>{this.log.error("rejoinCall",t)}).then(()=>{this.rejoinInterval=window.setTimeout(this.rejoin,EC)})},this.showLoader=()=>{this.videoPlayer.video.parentElement.classList.add("is-buffering"),this.preloaderTemplate.parentElement||this.content.mover.querySelector("canvas.canvas-thumbnail, .thumbnail-avatar").after(this.preloaderTemplate,this.adminPanel),this.preloaderRtmp.attach(this.preloaderTemplate,!0),this.content.mover.querySelector(".controls-live").classList.remove("is-not-buffering"),cs.currentCall.state=qn.BUFFERING},this.preloaderRtmp=new Kn({cancelable:!1,rtmp:!0}),this.preloaderRtmp.construct(),this.preloaderTemplate=document.createElement("div"),this.preloaderTemplate.classList.add("preloader-template"),this.retryTempId=0,this.shareUrl&&this.setBtnMenuToggle([{icon:"forward",text:"Forward",onClick:this.onForward}]),this.buttons.download.classList.add("hide"),this.buttons.zoomin.classList.add("hide"),this.wholeDiv.classList.add("live"),this.setListeners()}setListeners(){super.setListeners(),J(this.buttons.forward,this.onForward,{listenerSetter:this.listenerSetter}),this.listenerSetter.add(Ae.serviceMessagePort)("rtmpStreamDestroyed",e=>{cs.currentCall?.call.id===e&&this.retryLoadStream(this.videoPlayer.video,"was destroyed")})}async openMedia(e){const t=e.peerId.toChatId();(!cs.currentCall||cs.currentCall.peerId!==e.peerId)&&(cs.currentCall&&await cs.leaveCall(),await cs.joinCall(t)),ia.activeInstance=this,this.peerId=e.peerId;const s=Ae.getChat(t);if(ji(s)[0])this.shareUrl=dC(this.peerId);else{const i=await this.managers.appProfileManager.getChatFull(t);this.shareUrl=i.exported_invite?.link}await this._openMedia({media:cs.currentCall.inputCall,mediaThumbnail:e.peerId===ia.previousPeerId?ia.previousCapture:void 0,timestamp:0,fromId:e.peerId,fromRight:0,setupPlayer:(i,n)=>{const r=i.video,o=()=>cs.currentCall;i.updateLiveViewersCount(o().call.participants_count),(!dn||e.isAdmin)&&i.setupLiveMenu([{icon:"volume_up",text:"Rtmp.MediaViewer.Menu.OutputDevice",onClick:()=>ue.createPopup(sO,i.video).show(),verify:()=>typeof navigator.mediaDevices?.enumerateDevices=="function"&&!dn},{icon:"radioon",text:"Rtmp.MediaViewer.Menu.StartRecording",verify:()=>o()?.admin&&!o().call.pFlags.record_video_active,onClick:()=>ue.createPopup(dO).show()},{icon:"radiooff",text:"Rtmp.MediaViewer.Menu.StopRecording",verify:()=>o()?.admin&&o().call.pFlags.record_video_active,onClick:()=>{this.managers.appGroupCallsManager.stopRecording(o().inputCall).catch(()=>{$e({langPackKey:"Error.AnError"})})}},{icon:"settings",text:"Rtmp.MediaViewer.Menu.StreamSettings",verify:()=>o()?.admin,onClick:()=>{ue.createPopup(RP,{peerId:this.peerId,active:!0,onEndStream:()=>this.close(void 0,!0)}).show()}},{icon:"crossround",text:"Rtmp.MediaViewer.Menu.EndLiveStream",danger:!0,verify:()=>o()?.admin,onClick:()=>this.close(void 0,!0)}]);const l=()=>{!r.error&&!r.ended&&Sn(r)};this.listenerSetter.add(r)("pause",l);const d=this.content.mover.querySelector("canvas.canvas-thumbnail, .thumbnail-avatar");r.after(d);const u=d.tagName==="CANVAS"?d:this.content.mover.querySelector("img");i.emptyPipVideoSource=u,n.then(()=>{i.dimBackground()})},onMoverSet:()=>{if(!e.isAdmin)return;const i=document.createElement("div");i.classList.add("admin-popup-container"),this.adminPanel=i,this.adminPanel.classList.add("admin-hidden"),this.disposeSolid=wi(()=>pO({peerId:e.peerId}),this.adminPanel)},onCanPlay:()=>{const i=this.content.mover.querySelector("canvas.canvas-thumbnail, .thumbnail-avatar");this.streamEnded||this.preloaderRtmp.detach(),this.videoPlayer.liveEl.classList.add("is-not-buffering"),e.isAdmin&&Dt({element:this.adminPanel,className:"is-not-buffering",forwards:!0,duration:300}),Dt({element:i,className:"hide-thumbnail",forwards:!0,duration:300}),cs.currentCall.state=qn.PLAYING},onBuffering:this.showLoader}),this.listenerSetter.add(cs)("currentCallChanged",i=>{if(!i){this.close(void 0,!0);return}this.videoPlayer?.updateLiveViewersCount(i.call.participants_count)}),this.rejoinInterval=window.setTimeout(this.rejoin,EC)}toggleAdminPanel(e){e&&this.videoPlayer&&(this.videoPlayer.cancelFullScreen(),this.videoPlayer.inPip&&document.exitPictureInPicture()),this.videoPlayer?.lockControls(e?!0:void 0),Dt({element:this.adminPanel,className:"admin-hidden",forwards:!e,duration:300})}retryLoadStream(e,t){const s=++this.retryTempId,i=this.log.bindPrefix(`retryLoadStream-${s}-${t}`),n=cs.currentCall?.call.id;if(!n){this.close(void 0,!0);return}let r=!0,o=!0,l=0;const c=()=>s===this.retryTempId,d=()=>{c()&&(clearTimeout(this.retryTimeout),cs.isCurrentCallDead(o).then(u=>{if(cs.currentCall?.call.id!==n||!c())return;if(i("empty",u,r,o),o=u==="dying",u==="dead"||u==="dying"){r&&(this.showLoader(),cs.currentCall?.admin&&this.toggleAdminPanel(!0),dn&&Ae.serviceMessagePort.invokeVoid("leaveRtmpCall",[cs.currentCall.call.id,!1])),r=!1,this.retryTimeout=window.setTimeout(d,1e3);return}cs.currentCall?.admin&&this.toggleAdminPanel(!1);const h=cM(cs.currentCall.inputCall);e.getAttribute("src")!==h&&(e.src=h,e.load(),Sn(e))}).catch(u=>{cs.currentCall?.call.id!==n||!c()||(++l>5?(i.error(u),$e({langPackKey:"Error.AnError"}),this.close(void 0,!0)):this.retryTimeout=window.setTimeout(d,1e3))}))};d()}async leaveCall(e=!1){cs.leaveCall(e).catch(()=>{$e({langPackKey:"Error.AnError"})})}async close(e,t=!1){const s=this.videoPlayer?.inPip;if(clearTimeout(this.retryTimeout),clearTimeout(this.rejoinInterval),++this.retryTempId,this.videoPlayer)try{const i=await tO(this.videoPlayer.video);ia.previousCapture&&URL.revokeObjectURL(ia.previousCapture),ia.previousCapture=URL.createObjectURL(i),ia.previousPeerId=this.peerId}catch{}super.close(e),ia.activeInstance=void 0,cs.currentCall&&this.leaveCall(t),this.listenerSetter.removeAll(),s&&document.exitPictureInPicture()}static closeActivePip(e=!1){ia.activeInstance&&ia.activeInstance.videoPlayer?.inPip&&document.exitPictureInPicture()}static async getShareUrl(e){const t=Ae.getChat(e);return ji(t)[0]?dC(e.toPeerId(!0)):(await I.managers.appProfileManager.getChatFull(e)).exported_invite?.link}};ia.previousPeerId=Wt;let $c=ia;class mO{constructor(e,t){this.appendTo=e,this.appendLiveTo=t,this.descriptionIntl=new Ne.IntlElement({key:"VoiceChat.Status.Connecting"}),this.descriptionIntl.element.classList.add("rtmp-description"),this.liveTextElement=P("Rtmp.MediaViewer.Live")}detach(){this.descriptionIntl.element.remove(),this.liveTextElement.remove()}update(e){let t,s;e.state!==qn.PLAYING?t="VoiceChat.Status.Connecting":(t="Rtmp.Watching",s=[hb(e.call.participants_count)]);const{descriptionIntl:i}=this;i.compareAndUpdate({key:t,args:s}),this.descriptionIntl.element.parentElement||this.appendTo.append(this.descriptionIntl.element),this.liveTextElement.parentElement||this.appendLiveTo.append(this.liveTextElement)}}function gO(a,e){switch(a){case ds.CLOSING:case ds.CLOSED:return qs.CLOSED;case ds.CONNECTED:return e?qs.MUTED:qs.UNMUTED;default:return qs.CONNECTING}}function fO(a){switch(a){case qn.CLOSED:return qs.CLOSED;case qn.CONNECTING:case qn.BUFFERING:return qs.CONNECTING;default:return qs.MUTED_BY_ADMIN}}const jd="topbar-call";class vO{constructor(e){this.managers=e,this.onState=()=>{this.updateInstance(this.instance)};const t=this.listenerSetter=new $t;t.add(Un)("instance",({instance:s})=>{this.instance||this.updateInstance(s)}),t.add(Un)("accepting",s=>{this.instance!==s&&this.updateInstance(s)}),t.add(Wa)("instance",s=>{this.updateInstance(s)}),t.add(I)("group_call_update",s=>{const i=Wa.groupCall;i?.id===s.id&&this.updateInstance(i)}),t.add(cs)("currentCallChanged",s=>{this.updateInstance(s)}),t.add(Ol.ANALYSER_LISTENER)("amplitude",({amplitudes:s,type:i})=>{const{weave:n}=this;if(!s.length||!n)return;let r=0;for(let o=0;o<s.length;++o){const{type:l,value:c}=s[o];r=c>r?c:r}n.setAmplitude(r)})}clearCurrentInstance(){this.instance&&(this.center.replaceChildren(),this.currentDescription&&(this.currentDescription.detach(),this.currentDescription=void 0),this.instance=void 0,this.instanceListenerSetter.removeAll())}updateInstance(e){this.construct&&(this.construct(),this.construct=void 0);const t=[["group-call",cl],["call",am],["rtmp",Na]],s=this.instance!==e;s&&(this.clearCurrentInstance(),this.instance=e,this.instanceListenerSetter=new $t,e&&(this.instanceListenerSetter.add(e)("state",this.onState),e instanceof cl?this.currentDescription=this.groupCallDescription:e instanceof am?(this.currentDescription=this.callDescription,this.instanceListenerSetter.add(e)("muted",this.onState)):e instanceof Na&&(this.currentDescription=this.rtmpDescription),t.forEach(([l,c])=>{const d=e instanceof c;this.container.classList.toggle(`is-${l}`,d),d&&document.documentElement.style.setProperty("--topbar-call-height",`var(--topbar-call-${l}-height)`)})));const i=e instanceof Na?void 0:!e||this.instance.isMuted;let n;e?e instanceof cl?n=e.state:e instanceof Na?n=fO(e.state):n=gO(e.connectionState,i):n=qs.CLOSED;const{weave:r}=this;r.componentDidMount();const o=n===qs.CLOSED;if((!document.body.classList.contains("is-calling")||s||o)&&(o&&r.setAmplitude(0),Dt({element:document.body,className:"is-calling",forwards:!o,duration:250,onTransitionEnd:o?()=>{r.componentWillUnmount(),this.clearCurrentInstance()}:void 0})),o){this.toggleActivity(!1);return}this.currentActivityName=e?.constructor?.name,this.toggleActivity(!0),r.setCurrentState(e instanceof Na?"rtmp":"group",e instanceof Na?e.state:n,!0),this.setTitle(e),this.setDescription(e),this.muteButton.classList.toggle("hide",i===void 0),i!==void 0&&this.groupCallMicrophoneIconMini.setState(!i),this.endButton.classList.toggle("hide",e instanceof Na)}setDescription(e){return this.currentDescription.update(e)}setTitle(e){if(e instanceof Na)St(this.center,new Xt({peerId:e.peerId}).element);else{if(e instanceof cl)return this.groupCallTitle.update(e);St(this.center,new Xt({peerId:e.interlocutorUserId.toPeerId()}).element)}}construct(){const{listenerSetter:e}=this,t=this.container=document.createElement("div");t.classList.add("sidebar-header",jd+"-container");const s=document.createElement("div");s.classList.add(jd+"-left");const i=this.groupCallMicrophoneIconMini=new Ty,n=this.muteButton=yt();n.append(i.container),s.append(n);const r=fa(()=>{this.instance.toggleMuted()},600,!0);J(n,h=>{_e(h),r()},{listenerSetter:e});const o=this.center=document.createElement("div");o.classList.add(jd+"-center"),this.groupCallTitle=new TM(o),this.groupCallDescription=new ky(s),this.callDescription=new RM(s),this.rtmpDescription=new mO(o,s);const l=document.createElement("div");l.classList.add(jd+"-right");const c=this.endButton=yt("endcall_filled");l.append(c),J(c,h=>{_e(h);const{instance:p}=this;p&&(p instanceof Na?cs.leaveCall():p instanceof cl?p.hangUp():p.hangUp("phoneCallDiscardReasonHangup"))},{listenerSetter:e}),J(t,()=>{if(this.instance instanceof Na)$c.closeActivePip();else if(this.instance instanceof cl){if(ue.getPopups(ng).length)return;ue.createPopup(ng).show()}else if(this.instance instanceof am){if(ue.getPopups(xy).find(p=>p.getCallInstance()===this.instance))return;ue.createPopup(xy,this.instance).show()}},{listenerSetter:e}),t.append(s,o,l);const d=this.weave=new FN,u=d.render(jd+"-weave");t.prepend(u),document.getElementById("column-center").prepend(t),d.componentDidMount()}toggleActivity(e){this.currentActivityName&&Ae.invoke("toggleUninteruptableActivity",{activity:this.currentActivityName,active:e})}}async function kC(a,e=!1){const t=[],s=async(i,n)=>{if(i.isDirectory){const r=i.createReader();await new Promise((o,l)=>{r.readEntries(async c=>{for(const d of c)await s(d,n);o()})})}else if(i)if(e)t.push(i.type);else{const r=n.getAsFile(),o=i instanceof File?i:i instanceof DataTransferItem?i.getAsFile():await new Promise((l,c)=>i.file(l,d=>l(r)));if(!o)return;t.push(o)}};if(a instanceof DragEvent&&a.dataTransfer.files&&!a.dataTransfer.items)for(let i=0;i<a.dataTransfer.files.length;i++){const n=a.dataTransfer.files[i];t.push(e?n.type:n)}else{const i=(a.dataTransfer||a.clipboardData||a.originalEvent.clipboardData).items,n=[];for(let r=0;r<i.length;++r){const o=i[r];if(o.kind==="file"){const l=(e?o:o.webkitGetAsEntry())||o.getAsFile();n.push(s(l,o))}}await Promise.all(n)}return t}const mo="popup-gift-premium";class yO extends ue{constructor(e,t){super(mo,{closable:!0,overlayClosable:!0,body:!0,scrollable:!0}),this.peerId=e,this.giftOptions=t,this.construct()}async construct(){const{peerId:e,giftOptions:t}=this,s=vs({middleware:this.middlewareHelper.get(),size:100,peerId:e});s.node.classList.add(mo+"-avatar");const i=document.createElement("span");ks(i,"GiftTelegramPremiumTitle"),i.classList.add(mo+"-title");const n=P("GiftTelegramPremiumDescription",[await qe({peerId:e})]);n.classList.add(mo+"-subtitle");const r=this.giftOptions.slice().sort((p,m)=>p.months-m.months)[0],o=p=>qi(p,r.currency,!1,!0,!0),l=this.giftOptions.map((p,m)=>{let g=P("PricePerMonth",[o(+p.amount/p.months)]);if(p!==r){const w=document.createElement("span"),b=document.createElement("span");b.classList.add(mo+"-discount");const S=+r.amount*p.months/r.months,_=Math.round((1-+p.amount/S)*100);b.textContent="-"+_+"%",w.append(b,g),g=w}const f=!(p.months%12),v=new _t({checked:m===0,round:!0,name:"gift-months",asRadio:!0}),y=new Fe({title:P(f?"Years":"Months",[f?p.months/12:p.months]),checkboxField:v,clickable:!0,subtitle:g,rightTextContent:o(p.amount)});return y.container.classList.add(mo+"-option"),y}),c=document.createElement("form");c.classList.add(mo+"-options"),c.append(...l.map(p=>p.container));const d=new Ne.IntlElement({key:"GiftSubscriptionFor",args:[o(t[0].amount)]}),u=()=>t[l.findIndex(p=>p.checkboxField.checked)];this.listenerSetter.add(c)("change",()=>{d.compareAndUpdate({args:[o(u().amount)]})});const h=ot(`btn-primary ${mo}-confirm shimmer`);h.append(d.element),J(h,async()=>{const p=u();Ln.create({inputInvoice:{_:"inputInvoicePremiumGiftCode",option:p,purpose:{_:"inputStorePaymentPremiumGiftCode",amount:p.amount,currency:p.currency,users:[await this.managers.appUsersManager.getUserInput(e.toUserId())]}}}),this.hide()},{listenerSetter:this.listenerSetter}),this.scrollable.append(s.node,i,n,c,h),this.show()}}const bO=["allow-scripts","allow-same-origin","allow-popups","allow-forms","allow-modals","allow-storage-access-by-user-activation"].join(" ");class NM{constructor(e){if(this.onBackClick=()=>(this.telegramWebView.dispatchWebViewEvent("back_button_pressed",void 0),!1),this.isConfirmationNeededOnClose=()=>{if(this.isCloseConfirmationNeeded)return Rt({descriptionLangKey:"BotWebViewChangesMayNotBeSaved",button:{isDanger:!0,langKey:"BotWebViewCloseAnyway"}})},this.sendTheme=()=>{this.telegramWebView.dispatchWebViewEvent("theme_changed",{theme_params:this.getThemeParams()})},this.setHeaderColor=(t=this.lastHeaderColor)=>{this.lastHeaderColor=t;let s;const i=t.color;if(i){const n=Pa(i),r=AE(n),o=xE(r),l=kE(r,2.5),c=TE([...o,l],n);s=i,this.title.style.color=`rgb(${o.join(",")})`,this.header.style.setProperty("--secondary-text-color",`rgb(${c.join(", ")})`),this.header.style.setProperty("--light-secondary-text-color",`rgba(${o.join(", ")}, ${.08})`),this.header.style.setProperty("--border-color",`rgba(${o.join(", ")}, ${.08})`)}else s=this.getThemeParams()[t.color_key],this.title.style.color="",this.header.style.removeProperty("--secondary-text-color"),this.header.style.removeProperty("--light-secondary-text-color"),this.header.style.removeProperty("--border-color");this.header.style.backgroundColor=s},this.setBodyColor=t=>{this.body.style.backgroundColor=t},this.switchInlineQuery=async({query:t,chat_types:s})=>{if((await this.managers.appUsersManager.getUser(this.webViewOptions.botId)).bot_inline_placeholder===void 0)return;this.forceHide();const n=Ce.chat;let r=n.peerId,o=n.threadId;if(s?.length){const l=await Rs.createPicker(s,["send_inline"]);r!==l&&(r=l,o=void 0,await Ce.setInnerPeer({peerId:r}))}this.managers.appInlineBotsManager.switchInlineQuery(r,o,this.webViewOptions.botId,t)},this.setupMainButton=({is_visible:t,is_active:s,is_progress_visible:i,color:n,text:r,text_color:o})=>{t=t&&!!r?.trim(),r&&this.mainButton.replaceChildren(je(r)),n&&Ls.applyAppColor({name:"primary-color",element:this.mainButton,hex:n,darkenAlpha:.04}),o&&(this.mainButton.style.color=o),this.footer.classList.toggle("is-visible",t)},this.setupBackButton=({is_visible:t})=>{this.onBackStatus(t)},this.setupSettingsButton=({is_visible:t})=>{this.showSettingsButton=t},this.openPopup=async({title:t,message:s,buttons:i})=>{const n={cancel:"Cancel",close:"Close",ok:"OK"};let r;const o=ue.createPopup(mi,"popup-confirmation",{title:t?je(t):void 0,description:je(s),buttons:i.map(({type:c,text:d,id:u})=>{const h=n[c];return{langKey:h,text:h?void 0:je(d),isCancel:!0,isDanger:c==="destructive",callback:()=>{r=u}}})}),l=new Promise(c=>{o.addEventListener("close",()=>{this.telegramWebView.dispatchWebViewEvent("popup_closed",{...r!==void 0?{button_id:r}:{}}),c()})});return o.show(),l},Nt(this,e),this.listenerSetter=new $t,this.managers=I.managers,this.title.classList.add("web-app-title"),this.header.classList.add("web-app-header"),this.body.classList.add("web-app-body"),this.footer.classList.add("web-app-footer"),this.mainButton=ot("btn-primary btn-color-primary web-app-button",{noRipple:!0}),this.footer.append(this.mainButton),this.body.after(this.footer),J(this.mainButton,()=>{this.telegramWebView.dispatchWebViewEvent("main_button_pressed",void 0)},{listenerSetter:this.listenerSetter}),this.listenerSetter.add(I)("theme_changed",()=>{this.setHeaderColor(),this.sendTheme()}),this.listenerSetter.add(I)("attach_menu_bot",t=>{this.webViewOptions.botId===t.bot_id&&(this.attachMenuBot=t)}),this.webViewResultUrl._==="webViewResultUrl"){const t=this.webViewResultUrl.query_id;this.listenerSetter.add(I)("web_view_result_sent",s=>{t===s&&this.forceHide()})}}getMenuButtons(){const e=this.webViewOptions.botId,t=e.toPeerId();return[{icon:"settings",text:"BotSettings",onClick:()=>{this.telegramWebView.dispatchWebViewEvent("settings_button_pressed",void 0)},verify:()=>this.showSettingsButton},{icon:"bots",text:"BotWebViewOpenBot",onClick:()=>{this.forceHide(),Ce.setInnerPeer({peerId:t})},verify:()=>this.webViewOptions.peerId!==t},{icon:"rotate_left",text:"BotWebViewReloadPage",onClick:()=>{const s=()=>{const i=this.telegramWebView,n=this.createWebView();i.iframe.replaceWith(n.iframe),i.destroy(),n.onMount()};if(!this.readyResult?.reload_supported){s();return}this.reloadTimeout=window.setTimeout(()=>{this.reloadTimeout=void 0,s()},300),this.telegramWebView.dispatchWebViewEvent("reload_iframe",void 0)},verify:()=>!0},{icon:"delete",className:"danger",text:"BotWebViewDeleteBot",onClick:()=>{Ce.toggleBotInAttachMenu(e,!1).then(async s=>{this.attachMenuBot=s,this.forceHide()})},verify:()=>this.attachMenuBot&&!this.attachMenuBot.pFlags.inactive,separator:!0}]}getThemeParams(){return Ls.getThemeParamsForWebView()}destroy(){this.destroyed=!0,this.telegramWebView.destroy(),this.listenerSetter.removeAll()}debouncePopupMethod(e,t,s){let i=!1,n=!1;return async(...r)=>{if(i)return;const{lastDispatchedWebViewEvent:o}=this.telegramWebView;if(!n&&o?.type===t&&o.count>=3&&(n=!0,setTimeout(()=>{this.telegramWebView.lastDispatchedWebViewEvent===o&&(this.telegramWebView.lastDispatchedWebViewEvent.count=0),n=!1},3e3)),n){this.telegramWebView.dispatchWebViewEvent(t,s);return}i=!0;try{await e(...r)}finally{i=!1}}}createWebView(){const e=this.telegramWebView=new T1({url:this.webViewResultUrl.url,sandbox:bO,allow:"camera; microphone; geolocation;",onLoad:()=>{this.iconElement&&(this.iconElement.style.opacity="0"),e.iframe.style.opacity="1",e.iframe.classList.remove("disable-hover")}});return e.iframe.style.opacity="0",e.iframe.classList.add("disable-hover"),e.iframe.allowFullscreen=!0,e.addMultipleEventsListeners({iframe_ready:t=>{this.readyResult=t},iframe_will_reload:()=>{this.reloadTimeout&&(clearTimeout(this.reloadTimeout),this.reloadTimeout=void 0)},web_app_data_send:({data:t})=>{!this.webViewOptions.isSimpleWebView||this.webViewOptions.fromSwitchWebView||(this.forceHide(),this.managers.appAttachMenuBotsManager.sendWebViewData(this.webViewOptions.botId,this.webViewOptions.buttonText,t))},web_app_close:()=>{this.forceHide()},web_app_open_link:({url:t})=>{Ul(t)},web_app_open_tg_link:({path_full:t})=>{Ce.openUrl("https://t.me"+t)},web_app_open_invoice:({slug:t})=>{const s={_:Ct.INVOICE,slug:t};Yu.processInvoiceLink(s).then(i=>{i.addEventListener("finish",n=>{e.dispatchWebViewEvent("invoice_closed",{slug:t,status:n})})})},web_app_request_theme:this.sendTheme,web_app_set_background_color:({color:t})=>this.setBodyColor(t),web_app_set_header_color:this.setHeaderColor,web_app_switch_inline_query:this.switchInlineQuery,web_app_setup_main_button:this.setupMainButton,web_app_setup_back_button:this.setupBackButton,web_app_setup_settings_button:this.setupSettingsButton,web_app_setup_closing_behavior:({need_confirmation:t})=>this.isCloseConfirmationNeeded=!!t,web_app_open_popup:this.debouncePopupMethod(this.openPopup,"popup_closed",{}),web_app_open_scan_qr_popup:()=>e.dispatchWebViewEvent("scan_qr_popup_closed",{}),web_app_read_text_from_clipboard:async({req_id:t})=>{const s={req_id:t};let i;if(this.attachMenuBot&&!this.attachMenuBot.pFlags.inactive)try{(await navigator.permissions.query({name:"clipboard-read"})).state==="granted"&&(i=await navigator.clipboard.readText())}catch(n){console.error("clipboard read error",n)}i!==void 0&&(s.data=i),e.dispatchWebViewEvent("clipboard_text_received",s)},web_app_request_write_access:this.debouncePopupMethod(async()=>{const t=this.webViewOptions.botId,s=await this.managers.appBotsManager.canSendMessage(t),i={status:"allowed"};if(!s)try{await Rt({titleLangKey:"WebApp.WriteAccess.Title",descriptionLangKey:"WebApp.WriteAccess.Description",descriptionLangArgs:[await qe({peerId:t.toPeerId(!1)})],button:{langKey:"OK"}}),await this.managers.appBotsManager.allowSendMessage(t)}catch{i.status="cancelled"}e.dispatchWebViewEvent("write_access_requested",i)},"write_access_requested",{status:"cancelled"}),web_app_request_phone:this.debouncePopupMethod(async()=>{const t={status:"sent"};try{const s=this.webViewOptions.botId;await this.managers.appMessagesManager.unblockBot(s),await Ce.requestPhone(s.toPeerId(!1))}catch{t.status="cancelled"}e.dispatchWebViewEvent("phone_requested",t)},"phone_requested",{status:"cancelled"}),web_app_invoke_custom_method:async({req_id:t,method:s,params:i})=>{let n,r;try{n=await this.managers.appAttachMenuBotsManager.invokeWebViewCustomMethod(this.webViewOptions.botId,s,i)}catch(o){r=o}e.dispatchWebViewEvent("custom_method_invoked",{req_id:t,result:n&&JSON.parse(n.data),error:r?.type})}}),e.iframe.classList.add("payment-verification"),e}getPeerId(){return this.attachMenuBot?this.attachMenuBot.bot_id.toPeerId(!1):this.webViewOptions.botId.toPeerId(!1)}async getTitle(e){if(this.attachMenuBot)return e?this.attachMenuBot.short_name:je(this.attachMenuBot.short_name);{const t=this.getPeerId();return e?Gr({peerId:t,plainText:!0}):qe({peerId:t})}}async init(e){this.attachMenuBot||this.title.append(await this.getTitle(!1));let t=!1;this.iconElement=document.createElement("span");try{const i=this.attachMenuBot??await this.managers.appAttachMenuBotsManager.getAttachMenuBot(this.webViewOptions.botId),n=hw(i);n&&(await G_({element:this.iconElement,doc:n.icon,size:80,textColor:()=>"secondary-text-color",strokeWidth:()=>.5}),t=!0)}catch{}t?this.iconElement.classList.add("web-app-icon"):this.iconElement=void 0;const s=this.createWebView();this.setBodyColor(this.getThemeParams().bg_color),this.setHeaderColor({color_key:"bg_color"}),this.body.prepend(...[this.iconElement,s.iframe].filter(Boolean)),Promise.resolve(e()).then(()=>{s.onMount(),!this.webViewOptions.isSimpleWebView&&this.webViewResultUrl.query_id&&setTimeout(()=>this.prolongWebView(),5e4)})}prolongWebView(){this.managers.appAttachMenuBotsManager.prolongWebView({queryId:this.webViewResultUrl.query_id,...this.webViewOptions}).then(()=>{this.destroyed||setTimeout(()=>{this.destroyed||this.prolongWebView()},5e4)},e=>{this.destroyed||(e.type==="QUERY_ID_INVALID"?this.forceHide():console.error("web app prolong error",e))})}}class wO extends ue{constructor(e){super("popup-payment popup-payment-verification popup-web-app",{closable:!0,overlayClosable:!0,body:!0,footer:!0,title:!0,onBackClick:()=>this.webApp.onBackClick(),isConfirmationNeededOnClose:()=>this.webApp.isConfirmationNeededOnClose()}),Nt(this,e),this.webApp=new NM({...e,header:this.header,title:this.title,body:this.body,footer:this.footer,forceHide:this.forceHide,onBackStatus:s=>this.btnCloseAnimatedIcon.classList.toggle("state-back",s)});const t=ki({listenerSetter:this.listenerSetter,buttons:this.webApp.getMenuButtons(),direction:"bottom-left"});this.title.after(t),this.webApp.init(()=>{this.show()})}destroy(){return this.webApp.destroy(),super.destroy()}}function SO(){const a=[],e=window.getSelection();for(let t=0;t<e.rangeCount;++t){const s=e.getRangeAt(t);let{startContainer:i,endContainer:n}=s;for(n.nodeType!==n.TEXT_NODE&&(n=n.firstChild);i&&i!==n;)a.push(i.nodeType===n.TEXT_NODE?i:i.firstChild),i=i.nextSibling;a[a.length-1]!==n&&a.push(n)}return a.filter(t=>!!t)}const CO="_Browser_m63td_41",_O="_BrowserHeader_m63td_55",IO="_BrowserHeaderButton_m63td_65",PO="_BrowserHeaderTabs_m63td_72",MO="_BrowserHeaderTabsScrollable_m63td_81",LO="_BrowserHeaderTab_m63td_72",EO="_first_m63td_96",kO="_BrowserHeaderTabTitle_m63td_102",TO="_BrowserHeaderTabIcon_m63td_111",xO="_BrowserHeaderTabIconInner_m63td_117",AO="_BrowserHeaderTabMore_m63td_126",RO="_BrowserHeaderTabClose_m63td_141",FO="_BrowserHeaderTabMask_m63td_149",BO="_active_m63td_157",DO="_BrowserHeaderTabHover_m63td_163",$O="_BrowserHeaderSelector_m63td_174",NO="_BrowserHeaderSelectorTail_m63td_188",OO="_left_m63td_192",UO="_right_m63td_195",HO="_BrowserHeaderCollapsedTitle_m63td_199",GO="_BrowserHeaderNewButton_m63td_214",VO="_BrowserBody_m63td_220",zO="_BrowserPage_m63td_228",WO="_collapsed_m63td_238",KO="_BrowserCatalogue_m63td_252",jO="_BrowserCatalogueSearch_m63td_255",qO="_BrowserCatalogueList_m63td_260",YO="_folded_m63td_268",ms={Browser:CO,BrowserHeader:_O,BrowserHeaderButton:IO,BrowserHeaderTabs:PO,BrowserHeaderTabsScrollable:MO,BrowserHeaderTab:LO,first:EO,BrowserHeaderTabTitle:kO,BrowserHeaderTabIcon:TO,BrowserHeaderTabIconInner:xO,BrowserHeaderTabMore:AO,BrowserHeaderTabClose:RO,BrowserHeaderTabMask:FO,active:BO,BrowserHeaderTabHover:DO,BrowserHeaderSelector:$O,BrowserHeaderSelectorTail:NO,left:OO,right:UO,BrowserHeaderCollapsedTitle:HO,BrowserHeaderNewButton:GO,BrowserBody:VO,BrowserPage:zO,collapsed:WO,BrowserCatalogue:KO,BrowserCatalogueSearch:jO,BrowserCatalogueList:qO,folded:YO},QO=Y('<svg xmlns=http://www.w3.org/2000/svg width=16 height=16 viewBox="0 0 16 16"fill=none><path fill-rule=evenodd clip-rule=evenodd d="M16 16V0C16 8.83656 8.83656 16 0 16H16Z"fill=var(--surface-color)>'),Ew=Y("<span>"),XO=Y("<div><div></div><div>"),Th=Y("<div>"),Ry=Y("<div><div>");function TC(a){return(()=>{const e=QO();return Me(()=>Es(e,"class",Ge(ms.BrowserHeaderSelectorTail,a.left?ms.left:ms.right))),e})()}function rm(a){return T(Pi,ni(a,{get class(){return Ge(ms.BrowserHeaderButton,a.class)},noRipple:!0}))}function ZO(a){const[e,t]=us(af),s=V(()=>!e.collapsed&&e.page===a.page),i=V(()=>{if(!e.collapsed)return"";const n=a.index();let r=-20+Math.min(2,n)*-26;return n>2&&(r+=(n-2)*-40),`translateX(${r}px)`});return(()=>{const n=XO(),r=n.firstChild,o=r.nextSibling;n.$$click=()=>t.select(a.page);const l=a.ref;return typeof l=="function"?Ue(l,n):a.ref=n,k(n,T(rm,{get class(){return ms.BrowserHeaderTabIcon},get children(){return[(()=>{const c=Ew();return k(c,()=>a.page.icon),Me(()=>be(c,ms.BrowserHeaderTabIconInner)),c})(),T(hs,{icon:"more",get class(){return Ge(ms.BrowserHeaderTabHover,ms.BrowserHeaderTabMore)},get onClick(){return a.openPageMenu}})]}}),r),k(r,()=>kl(je(a.page.title))),k(n,T(Pi,{icon:"close",get class(){return Ge(ms.BrowserHeaderTabHover,ms.BrowserHeaderTabClose)},noRipple:!0,onClick:c=>{c.stopPropagation(),t.close(a.page)}}),null),Me(c=>{const d=Ge(ms.BrowserHeaderTab,s()&&ms.active,e.pages.indexOf(a.page)===0&&ms.first),u=a.page.titleWidth+26+"px",h=Math.max(1,4-a.index()),p=i(),m=ms.BrowserHeaderTabTitle,g=Ge(ms.BrowserHeaderTabHover,ms.BrowserHeaderTabMask);return d!==c._v$&&be(n,c._v$=d),u!==c._v$2&&((c._v$2=u)!=null?n.style.setProperty("--text-width",u):n.style.removeProperty("--text-width")),h!==c._v$3&&((c._v$3=h)!=null?n.style.setProperty("z-index",h):n.style.removeProperty("z-index")),p!==c._v$4&&((c._v$4=p)!=null?n.style.setProperty("transform",p):n.style.removeProperty("transform")),m!==c._v$5&&be(r,c._v$5=m),g!==c._v$6&&be(o,c._v$6=g),c},{_v$:void 0,_v$2:void 0,_v$3:void 0,_v$4:void 0,_v$5:void 0,_v$6:void 0}),n})()}function JO(a){const[e,t]=us(af),s=V(()=>!!e.page.needBackButton),i=new Map;le(()=>{const l=e.page,c=e.page?.scrollFromPage;c&&Bu({container:o,element:i.get(l.id),position:"center",axis:"x",forceDuration:200,getNormalSize:({rect:d})=>{const u=c.titleWidth-l.titleWidth;return d.width+u}})});const n=async l=>{const c=ne(l.target,ms.BrowserHeaderTab);if(!c)return;l instanceof MouseEvent&&l.preventDefault(),l instanceof MouseEvent&&(l.cancelBubble=!0);const d=e.pages.find(m=>i.get(m.id)===c);if(!d?.menuButtons)return;const u=new $t,h=(await a1(kn(d.menuButtons))).map(m=>(m.options={listenerSetter:u},m)),p=xa({buttons:h,listenerSetter:u});p.classList.add("contextmenu"),document.getElementById("page-chats").append(p),Ql(l,p),Li.openBtnMenu(p,()=>{setTimeout(()=>{p.remove(),u.removeAll()},1e3)})};Jt(()=>{const l=new $t;Er({element:o,callback:n,listenerSetter:l}),ze(()=>{l.removeAll()})});const r=V(()=>{const l=d=>d.map(u=>je(u.title)),c=e.pages;return c.length===1?P("MiniApps.Collapsed.One",l([c[0]])):c.length===2?P("MiniApps.Collapsed.Two",l(c.slice(0,2))):P("MiniApps.Collapsed.Many",[...l([c[0]]),c.length-1])});let o;return(()=>{const l=Ry(),c=l.firstChild;return k(l,T(rm,{onClick:()=>{s()?e.page.onBackClick():t.close(e.page)},get children(){const d=Th();return Me(()=>be(d,Ge("animated-close-icon",s()&&"state-back"))),d}}),c),k(l,T(od,{get class(){return Ge(ms.BrowserHeaderTabsScrollable,e.collapsed&&"disable-hover")},axis:"x",ref(d){const u=o;typeof u=="function"?u(d):o=d},withBorders:"manual",get children(){const d=Ry(),u=d.firstChild;return k(u,T(TC,{left:!0}),null),k(u,T(TC,{right:!0}),null),k(d,T(Yo,{type:"grow-width",mode:"add-remove",get children(){return T(Cs,{get each(){return e.pages},children:(h,p)=>T(ZO,{page:h,openPageMenu:n,ref:m=>i.set(h.id,m),index:p})})}}),null),k(d,T(rm,{get class(){return Ge(ms.BrowserHeaderTabIcon,ms.BrowserHeaderNewButton)},onClick:()=>iU(),get children(){const h=Ew();return k(h,T(hs,{icon:"plus"})),Me(()=>be(h,ms.BrowserHeaderTabIconInner)),h}}),null),Me(h=>{const p=ms.BrowserHeaderTabs,m=ms.BrowserHeaderSelector,g=`translateX(${e.index*40+7+(e.index>=1?16:0)}px)`,f=e.page.titleWidth+16*2+34+"px";return p!==h._v$7&&be(d,h._v$7=p),m!==h._v$8&&be(u,h._v$8=m),g!==h._v$9&&((h._v$9=g)!=null?u.style.setProperty("transform",g):u.style.removeProperty("transform")),f!==h._v$10&&((h._v$10=f)!=null?u.style.setProperty("width",f):u.style.removeProperty("width")),h},{_v$7:void 0,_v$8:void 0,_v$9:void 0,_v$10:void 0}),d}}),c),k(c,r),k(l,T(rm,{get icon(){return e.collapsed?"app_expand":"app_shrink"},onClick:()=>t.toggleCollapsed()}),null),Me(d=>{const u=ms.BrowserHeader,h=ms.BrowserHeaderCollapsedTitle,p=Math.max(0,3-e.pages.length)*-14+"px";return u!==d._v$11&&be(l,d._v$11=u),h!==d._v$12&&be(c,d._v$12=h),p!==d._v$13&&((d._v$13=p)!=null?c.style.setProperty("--translateX",p):c.style.removeProperty("--translateX")),d},{_v$11:void 0,_v$12:void 0,_v$13:void 0}),l})()}function eU(a){const e={pages:[],index:0,get page(){return t.pages[t.index]},destroyed:!1,collapsed:!1},[t,s]=Qr(e),i=ZP({add:n=>{n=xC(n),s("pages",r=>[...r,n]),i.select(t.pages.length-1)},select:n=>{let r;typeof n=="number"?n<0||n>=t.pages.length?r=-1:r=n:r=t.pages.indexOf(n),r!==-1&&pi(()=>{const o=t.page,l=t.pages[r];s("index",r),s("pages",r,"scrollFromPage",o),queueMicrotask(()=>{const c=t.pages.indexOf(l);s("pages",c,"scrollFromPage",void 0)})})},close:async n=>{const r=t.pages.findIndex(c=>c.id===n.id);if(r===-1)return;if(await n.isConfirmationNeededOnClose?.(),t.pages.length===1){i.destroy();return}const o=t.pages.slice();o.splice(r,1);let l;r<t.index?l=t.index-1:r===t.index&&(l=Math.min(t.index,o.length-1)),s({pages:o,...l!==void 0&&{index:l}}),n.dispose()},destroy:()=>{t.destroyed||s("destroyed",!0)},toggleCollapsed:()=>{s("collapsed",n=>!n)},replace:(n,r)=>{n.id=r.id,n=xC(n),r.dispose(),s("pages",t.pages.findIndex(o=>o.id===r.id),Ec(n))}});return a.pages.forEach(i.add),s("index",0),ze(()=>{t.pages.forEach(n=>n.dispose())}),[t,i]}const af=fd();function tU(a){const r=485.33333333333337,[o,l]=Ia=us(af),[c,d]=K({width:480,height:688});Jt(()=>{const g=new $t,f=new Pw({listenerSetter:g,movableOptions:{minWidth:328,minHeight:r,element:u,verifyTouchTarget:(v,y)=>{const w=v.target;return!(y==="move"&&(!ne(w,ms.BrowserHeader)||ne(w,ms.BrowserHeaderButton)||ne(w,ms.BrowserHeaderTab)))},aspectRatio:.75,resetTransition:!0},onResize:v=>{o.collapsed||d(v)},previousState:c()});le(()=>{const{movable:v}=f,{collapsed:y}=o,w=328,b=48;v.toggleResizable(!y),v.setMinValues(y?w:328,y?b:r);const S=Ot(c);v.state=y?{...S,width:w,height:b}:{...v.state,width:S.width,height:S.height}}),ze(()=>{g.removeAll(),f.destroy()})});let u;const h=(()=>{const g=Ry(),f=g.firstChild,v=u;return typeof v=="function"?Ue(v,g):u=g,k(g,T(JO,{}),f),k(f,T(Cs,{get each(){return o.pages},children:y=>(()=>{const w=Th();return k(w,()=>y.content),Me(()=>be(w,Ge(ms.BrowserPage,o.page!==y&&"hide"))),w})()})),Me(y=>{const w=Ge(ms.Browser,o.collapsed&&ms.collapsed,"movable-element"),b=ms.BrowserBody,S=c().width+"px",_=c().height-48+"px";return w!==y._v$14&&be(g,y._v$14=w),b!==y._v$15&&be(f,y._v$15=b),S!==y._v$16&&((y._v$16=S)!=null?f.style.setProperty("width",S):f.style.removeProperty("width")),_!==y._v$17&&((y._v$17=_)!=null?f.style.setProperty("height",_):f.style.removeProperty("height")),y},{_v$14:void 0,_v$15:void 0,_v$16:void 0,_v$17:void 0}),g})(),p=T(Yo,{type:"cross-fade",mode:"add-remove",appear:!0,get children(){return!o.destroyed&&h}}),m=sb(()=>p);return le(()=>{m()||a.onExit()}),T(gd,{children:p})}function xC(a){return a.titleWidth??(a.titleWidth=Dl(a.title,$h)),a.id??(a.id=Math.random().toString(36).slice(2)),a.menuButtons??(a.menuButtons=[]),a.menuButtons.push({icon:"close",text:"Close",onClick:()=>{Ia[1].close(a)}}),a}let Ia;function OM(a){if(Ia){Ia[1].add(a);return}Ft(e=>{const s=eU({pages:[a].filter(Boolean)});return T(af.Provider,{value:s,get children(){return T(tU,{onExit:()=>{Ia=void 0,e()}})}})})}async function sU(a){if(Ia&&a.cacheKey){const d=Ia[0].pages.find(u=>u.cacheKey===a.cacheKey);if(d){Ia[1].select(d);return}}const e=Mt(),[t,s]=K(!1),[i,n]=K(!1),r=new NM({...a,header:document.createElement("div"),title:document.createElement("div"),body:document.createElement("div"),footer:document.createElement("div"),forceHide:()=>n(!0),onBackStatus:s}),o=await r.getTitle(!0);r.init(()=>e);const l=Ht(),c=vs({peerId:r.getPeerId(),size:24,middleware:l.get()});return await c.readyThumbPromise,Ft(d=>{const u={title:o,icon:c.node,menuButtons:r.getMenuButtons(),dispose:d,isConfirmationNeededOnClose:r.isConfirmationNeededOnClose,content:[V(()=>r.body),V(()=>r.footer)],get needBackButton(){return t()},onBackClick:r.onBackClick,cacheKey:r.cacheKey};ze(()=>r.destroy()),le(()=>{i()&&Ia[1].close(u)}),queueMicrotask(()=>e.resolve());const h=Ia?.[0];h&&h?.page.isCatalogue?Ia[1].replace(u,Ia[0].page):OM(u)})}async function iU(){return Ft(a=>{const[e,t]=K(!0),[s,i]=K(""),n=new WeakMap,r=new rw({ignoreCase:!0}),o=new jo({placeholder:"MiniApps.Search",onChange:m=>{m=m.trim(),i(m)},debounceTime:200,oldStyle:!0});o.container.classList.add(ms.BrowserCatalogueSearch);const l=(m,g)=>{const f=[],v=m.map(y=>T(_I,{ref:w=>n.set(w,y),get peerId(){return y.toPeerId(!1)},promises:f,avatarSize:64}));return Promise.all(f).then(g),v},c=(m,g)=>(()=>{const f=Th();return k(f,m),Me(()=>be(f,Ge(ms.BrowserCatalogueList,g?.()&&ms.folded))),f})(),d=m=>(Ot(()=>{m.forEach(g=>{const f=tS(g);r.indexObjectArray(g,[f.first_name,f.last_name,...ji(f)].filter(Boolean))})}),m),u=T(Ms,{name:"MiniApps.AppsSearch",noShadow:!0,get children(){return T(dv,{loader:()=>{const m=s();return async()=>[...r.search(m)]},render:l,children:c})}}),h=(()=>{const m=Th();return k(m,T(dv,{loader:()=>async()=>{const g=await I.managers.appUsersManager.getTopPeers("bots_app");return d(g.map(f=>f.id.toPeerId(!1)))},render:l,children:g=>{const f=yd(g).toArray,v=V(()=>f().length>7);return v()||t(!1),T(Ms,{name:"MiniApps.Apps",get nameRight(){return V(()=>!!v())()&&(()=>{const y=Ew();return y.$$click=()=>t(w=>!w),k(y,()=>P(e()?"MiniApps.AppsMore":"MiniApps.AppsLess")),y})()},noShadow:!0,get children(){return c(g,e)}})}}),null),k(m,T(dv,{loader:()=>{let g="";return async()=>{const f=await I.managers.appAttachMenuBotsManager.getPopularAppBots(g,50);return g=f.nextOffset,d(f.userIds)}},render:l,children:g=>g()&&T(Ms,{name:"MiniApps.Popular",noShadow:!0,get children(){return c(g)}})}),null),m})(),p={title:"Open App",icon:hs({icon:"plus"}),dispose:a,content:T(od,{get class(){return ms.BrowserCatalogueScrollable},get children(){const m=Th();return m.$$click=g=>{const f=ne(g.target,"similar-channels-channel");if(!f)return;const v=n.get(f);Yu.processWebAppLink({_:Ct.WEB_APP,appname:"",domain:ji(tS(v))[0]})},k(m,()=>o.container,null),k(m,T(Yo,{type:"cross-fade",get children(){return s()?u:h}}),null),Me(()=>be(m,ms.BrowserCatalogue)),m}}),isCatalogue:!0};OM(p)})}function dv(a){const e=V(a.loader),[t,s]=K(!1),[i,n]=K(void 0,{equals:!1}),r=o=>{const l=e(),[c,d]=K();l().then(d),Or(()=>{const u=()=>{n(m=>[p]),a.onReady?.(),s(!0)};let h=!1;const p=a.render(c(),()=>{h?u():h=!0});h?u():h=!0})(c)};return le(Vt(e,()=>r())),V((()=>{const o=V(()=>!!t());return()=>o()&&a.children(i)})())}Fs(["click"]);const nU=()=>{const[a,e]=K(mm.getIsLocked()),[t,{mutate:s}]=ma(()=>I.managers.appStateManager.getState().then(c=>c.settings?.passcode?.enabled||!1)),[i,{mutate:n}]=ma(()=>I.managers.appStateManager.getState().then(c=>c?.settings?.passcode?.lockShortcutEnabled||!1)),[r,{mutate:o}]=ma(()=>I.managers.appStateManager.getState().then(c=>c?.settings?.passcode?.lockShortcut||[])),l=new $t;l.add(I)("settings_updated",({key:c,value:d})=>{c===ci("settings","passcode","enabled")?s(d):c===ci("settings","passcode","lockShortcut")?o(d):c===ci("settings","passcode","lockShortcutEnabled")&&n(d)}),l.add(I)("toggle_locked",c=>{e(c)}),ze(()=>{l.removeAll()}),le(()=>{if(a()||!t()||!i()||!r()?.length)return;const c=[...r(),"KeyL"].join("+"),d=c==="Shift+KeyL";Ce.isShiftLockShortcut=d;const u=zm([c],(h,p)=>{const m=document.activeElement;d&&m&&(m.isContentEditable||["INPUT","TEXTAREA"].includes(m.tagName))||(p.preventDefault(),mm.lock(!0,()=>{I.dispatchEvent("toggle_locked",!0)}))},!1);ze(()=>{u(),Ce.isShiftLockShortcut=!1})})},aU=()=>{let a;return Ft(e=>{a=e,nU()}),{dispose:a}};var pd=(a=>(a[a.CHATLIST=0]="CHATLIST",a[a.CHAT=1]="CHAT",a[a.PROFILE=2]="PROFILE",a))(pd||{});class rU extends pn{constructor(){super(...arguments),this.columnEl=document.getElementById("column-center"),this.offline=!1,this.updateStatusInterval=0,this.setPeerPromise=null,this.chats=[],this.cacheStorage=new RE("cachedFiles"),this.isShiftLockShortcut=!1,this.onHashChange=e=>{try{this.onHashChangeUnsafe(e)}catch(t){this.log.error("hash change error",t)}},this.onHashChangeUnsafe=e=>{const t=location.hash;e||Pt.replaceState();const s=t.split("?"),i=QC(t,s);if(this.log("hashchange",t,s[0],i),!!t){if(i.tgaddr){Pt.replaceState(),this.openUrl(i.tgaddr);return}switch(s[0]){default:i.p=s[0].slice(1);case"#/im":{if(!Object.keys(i).length)break;const n=i.p,r=i.post!==void 0?+i.post:void 0,o=r||(i.message!==void 0?+i.message:void 0),l=i.thread!==void 0?+i.thread:void 0;switch(n[0]){case"@":{this.openUsername({userName:n,lastMsgId:o,threadId:l});break}default:{const c=r?n.toPeerId(!0):n.toPeerId();this.managers.appPeersManager.getPeer(c).then(d=>{this.op({peer:d,lastMsgId:o,threadId:l,call:i.call})});break}}}}}},this.onSponsoredBoxClick=e=>{const t=e.sponsoredMessage,s=Bo(t.url);this.clickIfSponsoredMessage(e),s.onclick?this.chat.appImManager.openUrl(t.url):Ul(s.url)},this.setSettings=()=>{const{messagesTextSize:e}=I.settings;this.customEmojiSize=ii(e+4,e+4),document.documentElement.style.setProperty("--messages-text-size",e+"px"),!this.customEmojiSize||(document.querySelectorAll("middle-ellipsis-element").forEach(l=>{l.disconnectedCallback(),l.dataset.fontSize=""+e,l.title&&(l.textContent=l.title),l.connectedCallback()}),document.querySelectorAll(".chat custom-emoji-renderer-element").forEach(l=>{l.forceRenderAfterSize=!0})),document.body.classList.toggle("animation-level-0",!wt.isAvailable("animations")),document.body.classList.toggle("animation-level-1",!1),document.body.classList.toggle("animation-level-2",wt.isAvailable("animations")),this.chatsSelectTabDebounced=$i(()=>{this.chat.topbar.pinnedMessage?.setCorrectIndex(0),this.managers.apiFileManager.setQueueId(this.chat.bubbles.lazyLoadQueue.queueId)},wt.isAvailable("animations")?250:0,!1,!0);const s=["stickers_chat","stickers_panel"],i=Ut.setLoop(I.settings.stickers.loop),n=!!s.filter(r=>Ut.setAutoplay(wt.isAvailable(r),r)).length;(i||n)&&Ut.checkAnimations2(!1);for(const r of this.chats)r.setAutoDownloadMedia();Ne.setTimeFormat(I.settings.timeFormat),this.toggleChatGradientAnimation(this.chat)},this.onDocumentPaste=async(e,t)=>{const s=au();if(e instanceof DragEvent){const n=e.dataTransfer.types;(n.contains?n.contains("Files"):n.indexOf("Files")>=0)&&_e(e)}const i=await kC(e);if(!(!await this.canDrag()&&!s)&&i.length){if(s){s.addFiles(i);return}const n=this.chat.input;n.willAttachType=t||(Wr.has(i[0].type)?"media":"document"),ue.createPopup(Ao,this.chat,i,n.willAttachType)}},this.onEmojiStickerClick=async({event:e,container:t,managers:s,peerId:i,middleware:n})=>{_e(e);const r=ne(t,"bubble"),o=t.dataset.stickerEmoji,l=t.classList.contains("custom-emoji")?void 0:Ns.getAnimation(t);if(l?.paused){const f=await s.appStickersManager.getAnimatedEmojiSoundDocument(o);if(f){const v=document.createElement("audio");v.style.display="none",t.parentElement.append(v);try{const y=await fs.downloadMediaURL({media:f});v.src=y,Sn(v),await ua(v,void 0,!0),v.addEventListener("ended",()=>{v.src="",v.remove()},{once:!0})}catch{}}l.autoplay=!0,l.restart()}if(!i.isUser()||!wt.isAvailable("effects_emoji"))return!1;const c=t.activeAnimations??(t.activeAnimations=new Set);if(c.size>=3)return!0;const d=await s.appStickersManager.getAnimatedEmojiSticker(o,!0);if(!d)return!1;const u=t.emojiData??(t.emojiData={a:[],v:1}),h=t.sendInteractionThrottled??(t.sendInteractionThrottled=fa(()=>{if(!u.a.length)return;const v=u.a[0].t;u.a.forEach(S=>{S.t=(S.t-v)/1e3});const{peerId:y,threadId:w}=this.chat,b=ne(t,"bubble");s.appMessagesManager.setTyping(y,{_:"sendMessageEmojiInteraction",msg_id:An(+b.dataset.mid),emoticon:o,interaction:{_:"dataJSON",data:JSON.stringify(u)}},!0,w),u.a.length=0},1e3,!1)),p={};c.add(p);const m=r?r.classList.contains("is-out"):void 0,{animationDiv:g}=Dh({doc:d,middleware:n,side:m?"right":"left",size:360,target:t,play:!0,withRandomOffset:!0,onUnmount:()=>{c.delete(p)},scrollable:this.chat.bubbles.scrollable});return m!==void 0&&!m&&g.classList.add("reflect-x"),e.isTrusted&&(u.a.push({i:1,t:Date.now()}),h()),!0}}get myId(){return I.myId}get chat(){return this.chats[this.chats.length-1]}construct(e){this.managers=e,Yu.construct(e),hd.constructAndStartAll(),rt.construct(e),this.log=Ni("IM",Rn.Log|Rn.Warn|Rn.Debug|Rn.Error),this.backgroundPromises={},wl.themes.forEach(r=>{const o=r.settings;if(!o)return;const{wallpaper:l}=o,c=l.slug;if(!c)return;const d="assets/img/"+c+".svg"+(jc?"?1":"");kc.setBackgroundUrlToCache({slug:c,url:d})}),this.selectTab(0),qr.addEventListener("change",r=>{this.offline=r,this.updateStatus(),r?clearInterval(this.updateStatusInterval):this.updateStatusInterval=window.setInterval(()=>this.updateStatus(),5e4)}),this.chatsContainer=document.createElement("div"),this.chatsContainer.classList.add("chats-container","tabs-container"),this.chatsContainer.dataset.animation="navigation",this.appendEmojiAnimationContainer(st.activeScreen),this.columnEl.append(this.chatsContainer),this.createNewChat(),this.chatsSelectTab(this.chat.container),Pt.onHashChange=this.onHashChange,this.setSettings(),I.addEventListener("settings_updated",this.setSettings);const t=r=>{document.body.classList.contains("is-premium")!==r&&(document.body.classList.toggle("is-premium",r),this.dispatchEvent("premium_toggle",r))};I.addEventListener("premium_toggle",t),I.addEventListener("background_change",()=>{this.applyCurrentTheme({noSetTheme:!0})}),t(I.premium),this.managers.rootScope.getPremium().then(t),yg(()=>{Ut.setOnlyOnePlayableGroup("lock"),Ut.checkAnimations2(!0)},()=>{Ut.setOnlyOnePlayableGroup(),Ut.checkAnimations2(!1)}),Ls.AppBackgroundTab=Dc,jc&&Ae.oldVersion&&FE(Ae.oldVersion,"1.4.3")===-1?this.deleteFilesIterative(r=>r.headers.get("Content-Type")==="image/svg+xml").then(()=>{this.applyCurrentTheme({noSetTheme:!0})}):this.applyCurrentTheme({noSetTheme:!0}),st.addEventListener("changeScreen",(r,o)=>{document.body.classList.contains(kh)&&document.body.classList.contains(Lh)&&Gs.toggleSidebar(!1),this.appendEmojiAnimationContainer(o)}),st.addEventListener("resize",()=>{this.adjustChatPatternBackground()});const s=r=>{this.saveChatPosition(r)},i=()=>{this.addEventListener("peer_changing",s,{once:!0})};this.addEventListener("peer_changed",i),this.addEventListener("peer_changed",()=>{this.managers.appReactionsManager.getPaidReactionPrivacy()},{once:!0}),I.addEventListener("theme_changed",()=>{this.applyCurrentTheme({broadcastEvent:!0,noSetTheme:!0,skipAnimation:!0})}),I.addEventListener("choosing_sticker",r=>{this.setChoosingStickerTyping(!r)}),I.addEventListener("peer_title_edit",({peerId:r,threadId:o})=>{this.chat?.peerId===r&&!o&&this.tabId!==void 0&&this.overrideHash(r)}),I.addEventListener("peer_typings",({peerId:r,typings:o})=>{const l=this.chat;if(!l||l.peerId!==r||vn.isOverlayActive||st.activeScreen===fn.mobile&&this.tabId!==1)return;const c=o.find(d=>d.action._==="sendMessageEmojiInteraction");if(c?.action?._==="sendMessageEmojiInteraction"){const d=c.action,u=l.bubbles.getBubble(r,c.action.msg_id);if(u&&u.classList.contains("emoji-big")&&Ko(u,l.bubbles.scrollable.container)){const h=u.querySelector(".media-sticker-wrapper:not(.bubble-hover-reaction-sticker):not(.reaction-sticker)");JSON.parse(d.interaction.data).a.forEach(m=>{setTimeout(()=>{Xs(h)},m.t*1e3)}),this.managers.appMessagesManager.setTyping(r,{_:"sendMessageEmojiInteractionSeen",emoticon:d.emoticon})}}}),I.addEventListener("message_error",({peerId:r,error:o})=>{if(o.type.includes("SLOWMODE_WAIT")){const l=+o.type.split("_").pop();Rt({titleLangKey:"Slowmode",peerId:r,descriptionLangKey:"SlowModeHint",descriptionLangArgs:[S_(l)],button:{langKey:"OK",isCancel:!0}})}}),I.addEventListener("file_speed_limited",({increaseTimes:r,isUpload:o})=>{const{hide:l}=Gu({icon:"premium_speed",title:P(o?"UploadSpeedLimited":"DownloadSpeedLimited"),textElement:P(o?"Chat.UploadLimit.Text":"Chat.DownloadLimit.Text",[xi(()=>{l(),rs.show({feature:"faster_download"})}),r]),appendTo:this.chat.bubbles.container,from:"top",duration:1e4})}),this.addEventListener("chat_changing",({to:r})=>{this.toggleChatGradientAnimation(r)}),I.addEventListener("service_notification",r=>{Rt({button:{langKey:"OK",isCancel:!0},description:jt(r.message)})}),I.addEventListener("payment_sent",async({peerId:r,mid:o,receiptMessage:l})=>{const c=await this.managers.appMessagesManager.getMessageByPeer(r,o);if(!c)return;const d=l.action;$e({langPackKey:"PaymentInfoHint",langPackArguments:[qi(d.total_amount,d.currency),je(c.media.title)]})}),I.addEventListener("toggle_locked",r=>{r&&h_.reload(!1)}),aU(),window.onSpoilerClick=r=>{const o=ne(r.target,"spoiler"),l=ne(o,"spoilers-container")||o.parentElement;if(l.querySelector(".message-spoiler-overlay"))return;const c="is-spoiler-visible",d=l.classList.contains(c);d||(_e(r),Eo!=="click"&&window.addEventListener("click",_e,{capture:!0,once:!0}));const u=400/2,h=5e3,p=d?0:2;p&&l.classList.add("will-change");const m=l.dataset.spoilerTimeout;m!==null&&(clearTimeout(+m),delete l.dataset.spoilerTimeout),Dt({element:l,className:c,forwards:!0,duration:u,onTransitionEnd:()=>{l.dataset.spoilerTimeout=""+window.setTimeout(()=>{Dt({element:l,className:c,forwards:!1,duration:u,onTransitionEnd:()=>{l.classList.remove("will-change"),delete l.dataset.spoilerTimeout}})},h)},useRafs:p})},document.addEventListener("mousemove",r=>{const o=ne(r.target,"media-sticker-wrapper");if(!o||o.classList.contains("custom-emoji")||ne(r.target,"emoji-big"))return;Ut.getAnimations(o)?.forEach(c=>{const{liteModeKey:d,animation:u}=c;!d||!u?.paused||wt.isAvailable(d)||(u instanceof Up?u.playOrRestart():u.play())})}),I.addEventListener("sticker_updated",({type:r,faved:o})=>{r==="faved"?$e({langPackKey:o?"AddedToFavorites":"RemovedFromFavorites"}):o||$e({langPackKey:"RemovedFromRecent"})}),I.addEventListener("gif_updated",({saved:r})=>{$e({langPackKey:r?"GifSavedHint":"RemovedGIFFromFavorites"})}),Ae.addEventListener("notificationBuild",async r=>{const{accountNumber:o}=r,c=await pm(o).appPeersManager.isForum(r.message.peerId),d=yr(r.message,c);this.chat.peerId===r.message.peerId&&this.chat.threadId===d&&!qr.isIdle||hd.byAccount[o]?.buildNotificationQueue(r)}),this.addEventListener("peer_changed",async({peerId:r})=>{document.body.classList.toggle("has-chat",!!r),mf.textContent="",this.overrideHash(r),Ae.updateTabState("chatPeerIds",this.chats.map(o=>o.peerId).filter(Boolean))}),this.chatPositions={},(Gh||Uh)&&(this.topbarCall=new vO(e)),Gh&&(Un.addEventListener("instance",({instance:r})=>{const o=ue.createPopup(xy,r);r.addEventListener("acceptCallOverride",()=>this.discardCurrentCall(r.interlocutorUserId.toPeerId(),"Call",void 0,r).then(()=>(Un.dispatchEvent("accepting",r),!0)).catch(()=>!1)),o.addEventListener("close",()=>{const l=Un.currentCall;l&&l!==r&&!r.wasTryingToJoin&&r.hangUp("phoneCallDiscardReasonBusy")},{once:!0}),o.show()}),Un.addEventListener("incompatible",async r=>{$e({langPackKey:"VoipPeerIncompatible",langPackArguments:[await qe({peerId:r.toPeerId()})]})})),cm.activateInstance();const n=()=>{$E.setAuthorized(!0)};BE&&document.addEventListener("visibilitychange",()=>{if(document.hidden)return;Array.from(document.querySelectorAll("canvas")).forEach(o=>{const l=o.getContext("2d");if(!l)return;const c=l.fillStyle;l.fillStyle="transparent",l.fillRect(0,0,1,1),l.fillStyle=c})}),setInterval(n,$y),n(),this.managers.appReactionsManager.getSavedReactionTags().then(r=>{su.splice(0,su.length,...r)}),this.onHashChange(!0),this.attachKeydownListener(),this.attachCopyListener(),this.handleAutologinDomains(),this.handlePeerColors(),this.checkForShare(),this.init()}adjustChatPatternBackground(){m_.resizeInstancesOf(this.chatsContainer)}checkForShare(){const e=Ae.share;e&&(Ae.share=void 0,ue.createPopup(kr,void 0,async(t,s)=>{if(await this.setPeer({peerId:t,threadId:s}),e.files?.length){const i=e.files.some(n=>Wr.has(n.type));ue.createPopup(Ao,this.chat,e.files,i?"media":"document")}else{const i=await _r.prepareStarsForPayment({messageCount:1,peerId:t});if(i===Fn)throw new Error;this.managers.appMessagesManager.sendText({peerId:t,text:e.text,confirmedPaymentResult:i})}}))}async confirmBotWebViewInner({botId:e,requestWriteAccess:t,showDisclaimer:s}){const i=e.toPeerId();if(s){const n={text:"WebApp.Disclaimer.Check",textArgs:[jt(Ne.format("WebAppDisclaimerUrl",!0))]};return Rt({titleLangKey:"TermsOfUse",descriptionLangKey:"BotWebAppDisclaimerSubtitle",checkbox:n,button:{langKey:"Continue",onlyWithCheckbox:n}})}return Rt({title:await qe({peerId:i}),descriptionLangKey:"BotWebViewStartPermission",checkbox:t?{text:"OpenUrlOption2",textArgs:[await qe({peerId:i})],checked:!0}:void 0,button:{langKey:"BotWebAppInstantViewOpen"},peerId:i})}async pushBotIdAsConfirmed(e){const t=await Ae.getState();t.confirmedWebViews.push(e),await this.managers.appStateManager.pushToState("confirmedWebViews",t.confirmedWebViews)}async confirmBotWebView(e){const t=await Ae.getState();if(e.ignoreConfirmedState||e.showDisclaimer||!t.confirmedWebViews.includes(e.botId)){const s=await this.confirmBotWebViewInner(e);return await this.pushBotIdAsConfirmed(e.botId),s}}async toggleBotInAttachMenu(e,t,s){return s??(s=await this.managers.appAttachMenuBotsManager.getAttachMenuBot(e)),!!s.pFlags.inactive==!t||(s.pFlags.inactive?(await this.confirmBotWebViewInner({botId:e,showDisclaimer:!0}),await this.pushBotIdAsConfirmed(e),await this.managers.appAttachMenuBotsManager.toggleBotInAttachMenu(e,!0,!0),delete s.pFlags.inactive,$e({langPackKey:s.pFlags.show_in_attach_menu&&s.pFlags.show_in_side_menu?"BotAttachMenuShortcatAddedAttachAndSide":s.pFlags.show_in_attach_menu?"BotAttachMenuShortcatAddedAttach":"BotAttachMenuShortcatAddedSide",langPackArguments:[je(s.short_name)]})):(await this.managers.appAttachMenuBotsManager.toggleBotInAttachMenu(e,!1),s.pFlags.inactive=!0,$e({langPackKey:s.pFlags.show_in_attach_menu&&s.pFlags.show_in_side_menu?"WebApp.AttachRemove.SuccessAll":s.pFlags.show_in_attach_menu?"WebApp.AttachRemove.Success":"WebApp.AttachRemove.SuccessSide",langPackArguments:[je(s.short_name)]}))),s}async openWebApp(e){if(e.botId??(e.botId=e.attachMenuBot?.bot_id),e.themeParams??(e.themeParams={_:"dataJSON",data:JSON.stringify(Ls.getThemeParamsForWebView())}),!e.attachMenuBot)try{e.attachMenuBot=await this.managers.appAttachMenuBotsManager.getAttachMenuBot(e.botId)}catch{}if(!e.noConfirmation){const t=e.attachMenuBot;let s;e.fromSideMenu?t?.pFlags?.side_menu_disclaimer_needed?s=!0:await this.pushBotIdAsConfirmed(e.botId):s=Ae.getUser(e.botId).pFlags.bot_attach_menu&&t?.pFlags?.inactive,s?await this.toggleBotInAttachMenu(e.botId,!0,t):await this.confirmBotWebView({botId:e.botId})}try{const t=[e.botId,e.startParam];(e.fromBotMenu||e.fromSideMenu||e.main)&&t.push("main");const s=t.join("-"),n={webViewResultUrl:await this.managers.appAttachMenuBotsManager.requestWebView(e),webViewOptions:e,attachMenuBot:e.attachMenuBot,cacheKey:s};pt?ue.createPopup(wO,n):sU(n)}catch(t){t.type==="PEER_ID_INVALID"&&e.attachMenuBot&&$e({langPackKey:"BotAlreadyAddedToAttachMenu"})}}handleUrlAuth(e){const{peerId:t,mid:s,buttonId:i,url:n}=e,r=c=>{window.open(c,"_blank")},o=c=>{r(c.url)},l=async c=>{if(c._==="urlAuthResultRequest"){const d=document.createElement("b");d.append(c.domain);const u=await qe({peerId:I.myId}),h=await qe({peerId:c.bot.id.toPeerId()}),p={text:"OpenUrlOption1",textArgs:[d.cloneNode(!0),u],checked:!0},m=c.pFlags.request_write_access?{text:"OpenUrlOption2",textArgs:[h],checked:!0}:void 0,f=Rt({titleLangKey:"OpenUrlTitle",button:{langKey:"Open"},descriptionLangKey:"OpenUrlAlert2",descriptionLangArgs:[d],checkboxes:[p,m].filter(Boolean)});m&&p.checkboxField.input.addEventListener("change",()=>{const b=!p.checkboxField.checked;m.checkboxField.toggleDisability(b),b&&(m.checkboxField.checked=!1)});const[v,y]=await f;if(!v){r(n);return}const w=await this.managers.appSeamlessLoginManager.acceptUrlAuth(n,t,s,i,y);return l(w)}else c._==="urlAuthResultAccepted"?o(c):r(n)};return this.managers.appSeamlessLoginManager.requestUrlAuth(n,t,s,i).then(c=>{l(c)})}handleAutologinDomains(){let e,t;I.addEventListener("app_config",n=>e=n),I.addEventListener("config",n=>t=n),this.managers.apiManager.getAppConfig().then(n=>e=n),this.managers.apiManager.getConfig().then(n=>t=n);const s=n=>{var c;if(!e)return;const r=new URL(n.href);if(e.url_auth_domains?.includes(r.hostname)){this.handleUrlAuth({url:n.href}),_e();return}const o=t.autologin_token;if(!o||!e.autologin_domains)return;const l=(c=n.dataset).originalUrl??(c.originalUrl=n.href);e.autologin_domains.includes(r.hostname)&&(r.searchParams.set("autologin_token",o),n.href=r.toString(),setTimeout(()=>{n.href=l,delete n.dataset.originalUrl},0))},i=n=>{const r=ne(n,"bubble");if(!r)return;const o=r.message;this.clickIfSponsoredMessage(o)};document.addEventListener("click",async n=>{const r=Mn(n.target,"A");r?.href&&s(r),r&&i(r);const o=Wh(n.target);o&&o.classList.contains("has-stories")&&!ne(n.target,"stories-list")&&this.openStoriesFromAvatar(o)})}handlePeerColors(){let e;const t=(n=e)=>{const r=Ae.getUser(I.myId.toUserId());NE(n.colors,r),e=n};I.addEventListener("theme_changed",()=>t()),this.managers.apiManager.getPeerColors().then(t);const[s,i]=dM();this.managers.apiManager.getPeerProfileColors().then(n=>{i(n.colors)})}clickIfSponsoredMessage(e){const t=e?.sponsoredMessage;t&&this.managers.appMessagesManager.clickSponsoredMessage(t.random_id)}async openStoriesFromAvatar(e){const t=+e.dataset.storyId;Fo({target:()=>e,peerId:e.dataset.peerId.toPeerId(),id:t||void 0})}getStackFromElement(e){let t=ne(e,"bubble");if(!t){const l=ne(e,"bubbles-group");l&&(t=l.querySelector(".bubble"))}if(!t)return;const s=ne(t,"chat"),n=(s&&this.chats.find(l=>l.container===s))?.peerId,r=+t.dataset.mid,o=t.message||n&&Ae.getMessageByPeer(n,r);return{peerId:n,mid:r,message:o,isOut:o?!!o.pFlags.out:void 0}}deleteFilesIterative(e){return this.cacheStorage.timeoutOperation(t=>{const s=performance.now();return t.keys().then(i=>{const n=i.map(r=>t.match(r).then(o=>e(o)));return Promise.all(n).then(r=>(r.map((o,l)=>{if(!o)return;const c=i[l];return t.delete(c)}),Promise.all(r.filter(Boolean))))}).then(()=>{this.log("deleted files",performance.now()-s)})})}toggleChatGradientAnimation(e){}appendEmojiAnimationContainer(e){const t=e===fn.mobile?this.columnEl:document.body;mf.parentElement!==t&&t.append(mf)}attachKeydownListener(){const e=new Set(["PageUp","PageDown","Meta","Control"]),t=s=>{const i=s.key,n=document.getSelection().isCollapsed;if(vn.isOverlayActive||e.has(i))return;const r=s.target,o=r.tagName==="INPUT"&&!["checkbox","radio"].includes(r.type)||r.isContentEditable,l=this.chat;if(!(this.isShiftLockShortcut&&s.shiftKey)&&!((i.startsWith("Arrow")||s.shiftKey&&i==="Shift")&&!n)){{if(s.code==="KeyC"&&(s.ctrlKey||s.metaKey)&&!o)return;if(s.altKey&&(i==="ArrowUp"||i==="ArrowDown"))_e(s),this.managers.dialogsStorage.getNextDialog(this.chat.peerId,i==="ArrowDown",nt.filterId).then(c=>{c&&this.setPeer({peerId:c.peerId})});else if(i==="ArrowUp"&&this.chat.type!==we.Scheduled)if(!l.input.editMsgId&&l.input.isInputEmpty())this.managers.appMessagesManager.getFirstMessageToEdit(l.peerId,l.threadId).then(c=>{c&&(l.input.initMessageEditing(c.mid),_e(s))});else return;else if(i==="ArrowDown")return}l?.input?.messageInput&&r!==l.input.messageInput&&!o&&!pt&&(!st.isMobile||this.tabId===1)&&!l.selection.isSelecting&&!l.input.recording&&l.input.messageInput.isContentEditable&&f_(l.input.messageInput,s)}};document.body.addEventListener("keydown",t)}attachCopyListener(){document.addEventListener("copy",e=>{SO().some(s=>{let i=s;if(s.nodeType!==s.ELEMENT_NODE&&(i=s.parentElement),!ne(i,"no-forwards"))return!1;const n=ne(i,"bubble");if(!n)return!1;e.preventDefault();const r=n.dataset.peerId.toPeerId(),o=Ae.getChat(r.toChatId());return $e({langPackKey:o.pFlags.broadcast?"CopyRestricted.Channel":"CopyRestricted.Group"}),!0})})}openUrl(e,t){const{url:s,onclick:i}=Bo(e);if(!i){t&&Ul(s);return}const n=document.createElement("a");return n.href=s,window[i](n)}async open(e){return this.op({...e,peer:await this.managers.appPeersManager.getPeer(e.peerId)})}async op(e){if(!e.peer)return;const t=e.peer._==="user",s=e.peer._==="channel";let i=e.peer.id.toPeerId(!t);const n=["commentId","lastMsgId","threadId"],r=s?e.peer.id:void 0,o=!!e.peer.pFlags.forum;await Promise.all(n.map(async h=>{e[h]&&(e[h]=await this.managers.appMessagesIdsManager.generateMessageId(e[h],r))}));const l=e.peer.migrated_to;if(l){const h=l.channel_id;e.peer=await this.managers.appChatsManager.getChat(h),i=h.toPeerId(!0)}let{commentId:c,threadId:d,lastMsgId:u}=e;if(!c&&!d&&!u&&o){nt.toggleForumTabByPeerId(i,!0,!0);return}if(o&&u&&!d){const h=await this.managers.appMessagesManager.reloadMessages(i,u);h?d=e.threadId=yr(h,o):(d=e.threadId=u,u=e.lastMsgId=void 0)}if(e.call){const h=await I.managers.appCallsManager.getCall(e.call);I.dispatchEvent("call_update",h)}return d?this.openThread({...e,peerId:i}):c?this.openComment({peerId:i,msgId:u,commentId:c}):this.setInnerPeer({...e,peerId:i})}openPremiumBot(){return this.managers.apiManager.getAppConfig().then(e=>this.openUsername({userName:e.premium_bot_username}))}openUsername(e){const{userName:t}=e;return this.managers.appUsersManager.resolveUsername(t).then(s=>this.op({peer:s,...e}),s=>{s.type==="USERNAME_NOT_OCCUPIED"?$e({langPackKey:"NoUsernameFound"}):s.type==="USERNAME_INVALID"&&$e({langPackKey:"Alert.UserDoesntExists"})})}async openThread(e){return await this.managers.appChatsManager.isForum(e.peerId.toChatId())?(await this.managers.dialogsStorage.getForumTopicOrReload(e.peerId,e.threadId),this.setInnerPeer(e)):this.managers.appMessagesManager.reloadMessages(e.peerId,e.threadId).then(async t=>(t||(e.lastMsgId=void 0),this.setInnerPeer({...e,type:we.Discussion})))}openComment(e){return this.managers.appMessagesManager.getDiscussionMessage(e.peerId,e.msgId).then(t=>this.openThread({peerId:t.peerId,lastMsgId:e.commentId,threadId:t.mid}))}async callUser(e,t){if(Un.getCallByUserId(e))return;if((await this.managers.appProfileManager.getProfile(e)).pFlags.phone_calls_private){qe({peerId:e.toPeerId()}).then(n=>Rt({descriptionLangKey:"Call.PrivacyErrorMessage",descriptionLangArgs:[n],button:{langKey:"OK",isCancel:!0}}));return}await this.discardCurrentCall(e.toPeerId(),"Call"),Un.startCallInternal(e,t==="video")}discardCurrentCall(e,t,s,i,n){return Wa.groupCall&&Wa.groupCall!==s?this.discardGroupCallConfirmation(e,t):Un.currentCall&&Un.currentCall!==i?this.discardCallConfirmation(e,t):cs.currentCall&&cs.currentCall!==n?this.discardLiveConfirmation(e,t):Promise.resolve()}async discardAnyCallConfirmation(e,t,s,i){await Promise.all([qe({peerId:e}),qe({peerId:t})]).then(([n,r])=>Rt({titleLangKey:`Call.Confirm.Discard.${s}.Header`,descriptionLangKey:`Call.Confirm.Discard.${s}.To${i}.Text`,descriptionLangArgs:[n,r],button:{langKey:"OK"}}))}async discardGroupCallConfirmation(e,t){const s=Wa.groupCall;s&&(await this.discardAnyCallConfirmation(s.chatId.toPeerId(!0),e,"Voice",t),Wa.groupCall===s&&await s.hangUp())}async discardCallConfirmation(e,t){const s=Un.currentCall;s&&(await this.discardAnyCallConfirmation(s.interlocutorUserId.toPeerId(!1),e,"Call",t),s.isClosing||await s.hangUp("phoneCallDiscardReasonDisconnect"))}async discardLiveConfirmation(e,t){const s=cs.currentCall;s&&(await this.discardAnyCallConfirmation(s.chatId.toPeerId(!0),e,"Live",t),cs.currentCall===s&&await cs.leaveCall())}async joinGroupCall(e,t){const s=e.toChatId(),i=this.managers.appChatsManager.hasRights(s,"manage_call"),n=async()=>{const r=await this.managers.appProfileManager.getChatFull(s);let o;if(r.call)o=r.call;else{if(!i)return;o=await this.managers.appGroupCallsManager.createGroupCall(s)}Wa.joinGroupCall(s,o.id,!0,!1)};if(t&&(await this.managers.appGroupCallsManager.getGroupCallFull(t))._==="groupCallDiscarded"){if(!i){$e({langPackKey:"VoiceChat.Chat.Ended"});return}await Rt({descriptionLangKey:"VoiceChat.Chat.StartNew",button:{langKey:"VoiceChat.Chat.StartNew.OK"}})}await this.discardCurrentCall(e,"Voice"),n()}async joinLiveStream(e){await this.discardCurrentCall(e,"Live"),await cs.joinCall(e.toChatId()).catch(t=>{console.error(t),$e({langPackKey:"Error.AnError"})}),this.openLiveStreamPlayer(e)}async openLiveStreamPlayer(e){if($c.activeInstance)return;const t=await $c.getShareUrl(e.toChatId());new $c(t).openMedia({peerId:e,isAdmin:cs.currentCall.admin})}setCurrentBackground(e=!1,t){const s=Ls.getTheme(),i=s.settings?.wallpaper?.slug;if(i){const n=wl.themes.find(r=>r.name===s.name);return Promise.resolve(kc.getBackground({slug:i,managers:this.managers,appDownloadManager:fs})).then(r=>this.setBackground(r,e,t),()=>(s.settings=kn(n.settings),this.setCurrentBackground(!0)))}return this.setBackground("",e,t)}setBackground(e,t=!0,s){this.lastBackgroundUrl=e;const i=this.chats.map(n=>n.setBackgroundIfNotSet({url:e,skipAnimation:s}));return Promise.resolve(i[i.length-1]).then(()=>{t&&I.dispatchEvent("background_change")})}saveChatPosition(e){if(![we.Chat,we.Discussion,we.Saved].includes(e.type)||!e.peerId)return;const t=e.bubbles,s=e.peerId+(e.threadId?"_"+e.threadId:""),i=this.chatPositions;if(!(t.scrollable.getDistanceToEnd()<=16&&t.scrollable.loadedAll.bottom)&&t.getRenderedLength()&&!e.savedReaction&&t.getViewportSlice().invisibleBottom.length){t.sliceViewport(!0);const n=t.scrollable.scrollPosition,r={mids:t.getRenderedHistory("desc",!0).map(o=>ti(o).mid),top:n};i[s]=r,this.log("saved chat position:",r)}else delete i[s],this.log("deleted chat position");this.chatPositions=i}getChatSavedPosition(e){if(![we.Chat,we.Discussion,we.Saved].includes(e.type)||!e.peerId)return;const t=e.peerId+(e.threadId?"_"+e.threadId:"");return this.chatPositions[t]}applyCurrentTheme({slug:e,backgroundUrl:t,broadcastEvent:s,noSetTheme:i,skipAnimation:n}={}){return t&&kc.setBackgroundUrlToCache({slug:e,url:t}),!i&&Ls.setTheme(),this.setCurrentBackground(s===void 0?!!e:s,n)}chatsSelectTab(e,t){if(this.prevTab!==e){if(t===!1&&this.prevTab&&vC([e,this.prevTab].filter(Boolean)),this.prevTab){this.prevTab.classList.remove("active"),this.chatsSelectTabDebounced(),wt.isAvailable("animations")&&t!==!1&&Al(ns(400),400);const s=Bn(this.prevTab);Bn(e)>s&&Pt.pushItem({type:"chat",onPop:n=>{this.setPeer({},n),Fa()}})}e.classList.add("active"),this.prevTab=e}}init(){document.addEventListener("paste",this.onDocumentPaste,!0),pt||this.attachDragAndDropListeners(),Ld.getInstance().handleSelection()}attachDragAndDropListeners(){const e=[],t=[];let s=!1;const i=async(l,c)=>{if(c===s)return;const d=l.dataTransfer.types,u=d.contains?d.contains("Files"):d.indexOf("Files")>=0,h=au(),p=await kC(l,!0);if(!u||!await this.canDrag()&&!h){n=0;return}const m=await Ao.canSend({...this.chat.getMessageSendingParams(),onlyVisible:!0}),g=h?o:r,f=h?t:e;if(c&&!f.length){const v=u&&!p.length,[y,w]=qc(p,_=>Wr.has(_)),[b,S]=qc(y,_=>um.has(_));if(m.send_docs?w.push(...y):w.length=0,m.send_photos||(b.forEach(_=>Vs(y,_)),b.length=0),m.send_videos||(S.forEach(_=>Vs(y,_)),S.length=0),this.log("drag files",p,y,w,b,S),h){h.appendDrops(g);const _=(m.send_docs?[w]:[b,S]).reduce((M,C)=>M+C.length,0);(_||v)&&f.push(new rv(g,{header:"Preview.Dragging.AddItems",headerArgs:[_],onDrop:M=>{i(M,!1),this.log("drop",M),this.onDocumentPaste(M,"document")}}))}else(w.length||v)&&f.push(new rv(g,{icon:"dragfiles",header:"Chat.DropTitle",subtitle:"Chat.DropAsFilesDesc",onDrop:_=>{i(_,!1),this.log("drop",_),this.onDocumentPaste(_,"document")}})),(y.length||v)&&f.push(new rv(g,{icon:"dragmedia",header:"Chat.DropTitle",subtitle:"Chat.DropQuickDesc",onDrop:_=>{i(_,!1),this.log("drop",_),this.onDocumentPaste(_,"media")}})),this.chat.container.append(g)}Dt({element:g,className:"is-visible",forwards:c,duration:200,onTransitionEnd:()=>{c||(f.forEach(v=>{v.destroy()}),f.length=0)}}),c?f.forEach(v=>{v.setPath()}):n=0,document.body.classList.toggle("is-dragging",c),s=c};let n=0;document.body.addEventListener("dragenter",l=>{++n}),document.body.addEventListener("dragover",l=>{i(l,!0),_e(l)}),document.body.addEventListener("dragleave",l=>{--n===0&&i(l,!1)});const r=document.createElement("div");r.classList.add("drops-container");const o=r.cloneNode(!0)}async canDrag(){const e=this.chat,s=!(!e?.peerId||vn.isOverlayActive||!await e.canSend("send_media"));return s&&await this.chat.input.showSlowModeTooltipIfNeeded({element:this.chat.input.attachMenu})?!1:s}async overrideHash(e){let t;if(e){const s=await this.managers.appPeersManager.getPeerUsername(e);t=s?"@"+s:""+e}Pt.overrideHash(t)}selectTab(e,t){t===!1&&vC([Ri.sidebarEl,this.columnEl,Gs.sidebarEl]),document.body.classList.toggle(kh,e===0);const s=this.tabId;s!==void 0&&(this.overrideHash(e>0?this.chat?.peerId:void 0),this.dispatchEvent("tab_changing",e)),this.log("selectTab",e,s);let i=wt.isAvailable("animations")?hi():Promise.resolve();if(s!==void 0&&s!==e&&wt.isAvailable("animations")&&t!==!1&&st.activeScreen!==fn.large){const r=(st.isMobile?250:200)+100;i=ns(r),Al(i,r)}this.tabId=e,Fa(),st.isMobile&&s===2&&e<2&&Gs.hide(),s!==void 0&&e>s&&(e<2||!Pt.findItemByType("im"))&&Pt.pushItem({type:"im",onPop:r=>{this.setPeer({},r)}});const n=window.onImTabChange;return n?.(e),i}updateStatus(){return this.managers.appUsersManager.updateMyOnlineStatus(this.offline)}goOffline(){this.offline=!0,this.updateStatus()}createNewChat(){const e=new NP(this,this.managers,!0);return this.chatsContainer.append(e.container),this.chats.push(e),e}spliceChats(e,t=!0,s,i){if(e>=this.chats.length)return;const n=this.chat;this.chats.length>1&&t&&this.dispatchEvent("peer_changing",this.chat),i||(i=this.chats.splice(e,this.chats.length-e));const r=this.chat;this.dispatchEvent("chat_changing",{from:n,to:r});for(let o=0;o<i.length-1;++o)Pt.removeByType("chat",!0);i.length>1&&i.slice(0,-1).forEach(o=>{o.container.remove()}),this.chatsSelectTab(r.container,s),t&&(this.dispatchEvent("peer_changed",r),Gs.getTab(FP)?.close(),Gs.replaceSharedMediaTab(r.sharedMediaTab)),i.forEach(o=>{o.beforeDestroy()}),setTimeout(()=>{i.forEach(o=>{o.destroy()})},350)}async setPeer(e={},t){e.peerId??(e.peerId=Wt),e.peerId=await this.managers.appPeersManager.getPeerMigratedTo(e.peerId)||e.peerId;const{peerId:s,lastMsgId:i,threadId:n}=e;if(s&&e.stack){const c=Ae.getPeer(s),d=c&&c.pFlags.min;d&&s.isUser()?await this.managers.appUsersManager.getApiUsers([{_:"inputUserFromMessage",msg_id:An(e.stack.mid),peer:await this.managers.appPeersManager.getInputPeerById(e.stack.peerId),user_id:s.toUserId()}]):d&&await this.managers.appChatsManager.resolveChannel({_:"inputChannelFromMessage",msg_id:An(e.stack.mid),peer:await this.managers.appPeersManager.getInputPeerById(e.stack.peerId),channel_id:s.toChatId()})}const r=this.chat,o=this.chats.indexOf(r),l=this.isSamePeer(r,e);if(s){if(o>0&&r.peerId&&!l){const c=this.chats.splice(1,this.chats.length-1);if(this.chat.peerId===s){this.spliceChats(0,!0,!0,c);return}else{const d=this.setPeer(e);return this.spliceChats(0,!1,!1,c),d}}}else{if(e.isDeleting){await this.selectTab(0,t),await r.setPeer(e);return}if(o>0){this.spliceChats(o,void 0,t);return}else if(st.isFloatingLeftSidebar){this.selectTab(+!this.tabId,t);return}}if(l&&st.activeScreen<=fn.medium&&document.body.classList.contains(kh))return this.selectTab(1,t),!1;if(s||st.activeScreen!==fn.mobile){const c=await r.setPeer(e),d=c?.cached?c.promise:Promise.resolve();s&&Promise.all([d,r.setBackgroundPromise]).then(()=>{setTimeout(()=>{setTimeout(()=>{this.chatsSelectTab(this.chat.container)},0),this.selectTab(1,t)},0)})}if(!s)return this.selectTab(0,t),!1}async setInnerPeer(e){let{peerId:t}=e;if(t===Wt||!t)return;t=e.peerId=await this.managers.appPeersManager.getPeerMigratedTo(t)||t,e.type||(e.threadId&&(e.peerId===I.myId?e.type=we.Saved:Ae.isForum(e.peerId)||(e.type=we.Discussion)),e.type??(e.type=we.Chat));const s=this.chats.findIndex(r=>this.isSamePeer(r,e)||st.activeScreen===fn.mobile&&this.tabId===0);if(s!==-1)return this.spliceChats(s+1),this.setPeer(e);const i=this.chat;let n=i;return i.inited&&(n=this.createNewChat()),this.dispatchEvent("chat_changing",{from:i,to:n}),this.setPeer(e)}openScheduled(e){this.setInnerPeer({peerId:e,type:we.Scheduled})}async toggleViewAsMessages(e,t){e===I.myId?DE("settings","savedAsForum",!t):await this.managers.appChatsManager.toggleViewForumAsMessages(e.toChatId(),t),this.selectTab(0),nt.toggleForumTabByPeerId(e,!t,!1)}getTypingElement(e){const t=document.createElement("span");let s="peer-typing";switch(t.classList.add(s),t.dataset.action=e._,e._){case"sendMessageTypingAction":{s+="-text";for(let i=0;i<3;++i){const n=s+"-dot",r=document.createElement("span");r.className=n+(i===0?" "+n+"-first":i===2?" "+n+"-last":""),t.append(r)}break}case"sendMessageUploadAudioAction":case"sendMessageUploadDocumentAction":case"sendMessageUploadRoundAction":case"sendMessageUploadVideoAction":case"sendMessageUploadPhotoAction":{s+="-upload";break}case"sendMessageRecordAudioAction":case"sendMessageRecordRoundAction":case"sendMessageRecordVideoAction":{s+="-record";break}case"sendMessageEmojiInteractionSeen":case"sendMessageChooseStickerAction":{s+="-choosing-sticker";for(let i=0;i<2;++i){const n=document.createElement("div");n.className=s+"-eye",t.append(n)}break}}return t.classList.add(s),t}async getPeerTyping(e,t,s){const i=e.isUser();if(i&&await this.managers.appUsersManager.isBot(e))return;const n=await this.managers.appProfileManager.getPeerTypings(e,s);if(!n?.length)return;const r=n[0],o={private:{sendMessageTypingAction:"Peer.Activity.User.TypingText",sendMessageUploadAudioAction:"Peer.Activity.User.SendingFile",sendMessageUploadDocumentAction:"Peer.Activity.User.SendingFile",sendMessageUploadPhotoAction:"Peer.Activity.User.SendingPhoto",sendMessageUploadVideoAction:"Peer.Activity.User.SendingVideo",sendMessageUploadRoundAction:"Peer.Activity.User.SendingVideo",sendMessageRecordVideoAction:"Peer.Activity.User.RecordingVideo",sendMessageRecordAudioAction:"Peer.Activity.User.RecordingAudio",sendMessageRecordRoundAction:"Peer.Activity.User.RecordingVideo",sendMessageGamePlayAction:"Peer.Activity.User.PlayingGame",sendMessageChooseStickerAction:"Peer.Activity.User.ChoosingSticker",sendMessageEmojiInteractionSeen:"Peer.Activity.User.EnjoyingAnimations"},chat:{sendMessageTypingAction:"Peer.Activity.Chat.TypingText",sendMessageUploadAudioAction:"Peer.Activity.Chat.SendingFile",sendMessageUploadDocumentAction:"Peer.Activity.Chat.SendingFile",sendMessageUploadPhotoAction:"Peer.Activity.Chat.SendingPhoto",sendMessageUploadVideoAction:"Peer.Activity.Chat.SendingVideo",sendMessageUploadRoundAction:"Peer.Activity.Chat.SendingVideo",sendMessageRecordVideoAction:"Peer.Activity.Chat.RecordingVideo",sendMessageRecordAudioAction:"Peer.Activity.Chat.RecordingAudio",sendMessageRecordRoundAction:"Peer.Activity.Chat.RecordingVideo",sendMessageGamePlayAction:"Peer.Activity.Chat.PlayingGame",sendMessageChooseStickerAction:"Peer.Activity.Chat.ChoosingSticker",sendMessageEmojiInteractionSeen:"Peer.Activity.Chat.EnjoyingAnimations"},multi:{sendMessageTypingAction:"Peer.Activity.Chat.Multi.TypingText1",sendMessageUploadAudioAction:"Peer.Activity.Chat.Multi.SendingFile1",sendMessageUploadDocumentAction:"Peer.Activity.Chat.Multi.SendingFile1",sendMessageUploadPhotoAction:"Peer.Activity.Chat.Multi.SendingPhoto1",sendMessageUploadVideoAction:"Peer.Activity.Chat.Multi.SendingVideo1",sendMessageUploadRoundAction:"Peer.Activity.Chat.Multi.SendingVideo1",sendMessageRecordVideoAction:"Peer.Activity.Chat.Multi.RecordingVideo1",sendMessageRecordAudioAction:"Peer.Activity.Chat.Multi.RecordingAudio1",sendMessageRecordRoundAction:"Peer.Activity.Chat.Multi.RecordingVideo1",sendMessageGamePlayAction:"Peer.Activity.Chat.Multi.PlayingGame1",sendMessageChooseStickerAction:"Peer.Activity.Chat.Multi.ChoosingSticker1"}},l=i?o.private:n.length>1?o.multi:o.chat;let c=r.action;if(n.length>1){const g={};n.forEach(f=>{const v=f.action._;g[v]===void 0&&(g[v]=0),++g[v]}),Object.keys(g).length>1&&(c={_:"sendMessageTypingAction"})}const d=l[c._];if(!d)return;let u,h;if(e.isAnyChat()){const g=new Xt;u=g.update({peerId:r.userId.toPeerId(!1),onlyFirstName:!0}),h=[g.element,n.length-1],await u}t||(t=document.createElement("span"),t.classList.add("online","peer-typing-container")),t.classList.toggle("peer-typing-flex",c._==="sendMessageChooseStickerAction"||c._==="sendMessageEmojiInteractionSeen");let p=t.firstElementChild;if(p?p.dataset.action!==c._&&p.replaceWith(this.getTypingElement(c)):(p=this.getTypingElement(c),t.prepend(p)),c._==="sendMessageEmojiInteractionSeen"){h?h.pop():h=[];const g=nb(je(c.emoticon));h.push(g)}const m=P(d,h);return m.classList.add("peer-typing-description"),t.childElementCount>1?t.lastElementChild.replaceWith(m):t.append(m),t}async getChatStatus(e,t){const s=t?void 0:await this.getPeerTyping(e.toPeerId(!0));if(s)return{cached:!0,result:Promise.resolve(s)};const i=await this.managers.acknowledged.appProfileManager.getChatFull(e),n=async o=>{let[l,c]=await Promise.all([ja(e,void 0,void 0,void 0,o),this.managers.acknowledged.appProfileManager.getOnlines(e)]);return{cached:c.cached,result:c.result.then(d=>{if(d>1){const u=document.createElement("span");u.append(...Yi([l,P("OnlineCount",[ln(d)])],!1)),l=u}return l})}},r=i.result.then(n);return{cached:i.cached?(await r).cached:i.cached,result:r.then(o=>o.result)}}async getUserStatus(e,t){const s={cached:!0,result:Promise.resolve(void 0)},i=await this.managers.appUsersManager.getUser(e);if(!i||i.pFlags.self&&!t)return s;const n=qo(i);if(!i.pFlags.bot&&!i.pFlags.support){let r=await this.getPeerTyping(e.toPeerId());if(!r&&i.status?._==="userStatusOnline"&&(r=document.createElement("span"),r.classList.add("online"),r.append(n)),r)return s.result=Promise.resolve(r),s}return s.result=Promise.resolve(n),s}async getPeerStatus(e,t,s){if(!e)return;let i;return e.isAnyChat()?i=this.getChatStatus(e.toChatId(),s):i=this.getUserStatus(e.toUserId(),t),i}async setPeerStatus(e){const{peerId:t,element:s,needClear:i,useWhitespace:n,middleware:r,ignoreSelf:o,noTyping:l}=e;if(!i){const h=s.querySelector(".peer-typing-container");if(h&&await this.getPeerTyping(t,h))return}const c=await this.getPeerStatus(t,o,l);if(!r())return;const d=async()=>{const h=c&&await c.result;if(r())return()=>St(s,h||u)},u=n?Ab:"";if(!c||c.cached||i===void 0)return d();if(i)return()=>(s.textContent=u,d().then(h=>h?.()))}setChoosingStickerTyping(e){this.managers.appMessagesManager.setTyping(this.chat.peerId,{_:e?"sendMessageCancelAction":"sendMessageChooseStickerAction"},void 0,this.chat.threadId)}isSamePeer(e,t){return e.peerId===t.peerId&&e.threadId===t.threadId&&(typeof e.type!=typeof t.type||e.type===t.type)}giftPremium(e){this.managers.appPaymentsManager.getPremiumGiftCodeOptions().then(t=>{ue.createPopup(yO,e,t.filter(s=>s.users===1&&s.currency!==Mo))})}requestPhone(e){return Rt({titleLangKey:"ShareYouPhoneNumberTitle",button:{langKey:"OK"},descriptionLangKey:"AreYouSureShareMyContactInfoBot"}).then(()=>this.managers.appMessagesManager.sendContact(e,I.myId))}setPeerColorToElement({peerId:e,element:t,messageHighlighting:s,colorAsOut:i,color:n}){const r="--peer-color-rgb",o="--peer-border-background",l=Ae.getPeer(e);let c,d;if(s||i){const h=jC(l).length,p=s?"message-empty":"message-out";c=`var(--${p}-primary-color-rgb)`,d=`var(--${p}-peer-${Math.max(1,h)}-border-background)`}else{const u=n?.color??i_(l);if(u===-1){t.style.removeProperty(r),t.style.removeProperty(o);return}c=`var(--peer-${u}-color-rgb)`,d=`var(--peer-${u}-border-background)`}t.style.setProperty(r,c),t.style.setProperty(o,d)}async initGifting(){const e=await this.managers.apiManager.getAppConfig(),s=(await this.managers.appUsersManager.resolveUsername(e.premium_bot_username)).id.toPeerId(!1);this.managers.appMessagesManager.sendText({peerId:s,text:"/gift"}),this.setInnerPeer({peerId:s})}}const UM=new rU;Di&&(Di.appImManager=UM);const Ce=UM,tp=(a,e)=>{const t=Mn(e.target,"A");if(!t||t.classList.contains("timestamp"))return;const s=ne(e.target,"spoiler");if(t instanceof HTMLAnchorElement&&(!s||a.classList.contains("is-spoiler-visible"))){const i=t.getAttribute("onclick");return!i||i.includes("showMaskedAlert")?void 0:(_e(e),()=>{t.click()})}};class zl extends yw{constructor(e,t){super(new Rg({processItem:o=>{const l=this.searchContext.inputFilter._==="inputMessagesFilterDocument",{mid:c,peerId:d}=o,u=Vi(o,!0);if(u&&!(l&&!zl.isMediaCompatibleForDocumentViewer(u)))return{element:null,mid:c,peerId:d}}}),["delete","forward"],t?60:0),this.local=e,this.onPrevClick=async o=>{this.openMedia({message:this.local?o.message:await this.getMessageByPeer(o.peerId,o.mid),index:o.index,target:o.element,fromRight:-1})},this.onNextClick=async o=>{this.openMedia({message:this.local?o.message:await this.getMessageByPeer(o.peerId,o.mid),index:o.index,target:o.element,fromRight:1})},this.onDeleteClick=()=>{const o=this.target;ue.createPopup(Md,o.peerId,[o.mid],we.Chat,()=>{this.target={element:this.content.media},this.close()})},this.onForwardClick=()=>{const o=this.target;o.mid&&ue.createPopup(kr,{[o.peerId]:[o.mid]},()=>this.close())},this.onAuthorClick=async o=>{let{mid:l,peerId:c,message:d}=this.target;if(l&&l!==Number.MAX_SAFE_INTEGER){const u=this.searchContext.threadId;d||(d=await this.getMessageByPeer(c,l)),this.close(o).then(async()=>{if(st.isMobile){const h=Gs.getTab(Vl);h&&h.close()}Ce.setInnerPeer({peerId:d.peerId,lastMsgId:l,threadId:u})})}},this.onDownloadClick=async(o,l)=>{if(l){const h=await this.managers.appDocsManager.getDoc(l);fs.downloadToDisc({media:h,queueId:Ce.chat.bubbles.lazyLoadQueue.queueId});return}const{message:c,index:d}=this.target,u=Vi(c,!0,d);u&&fs.downloadToDisc({media:u,queueId:Ce.chat.bubbles.lazyLoadQueue.queueId})},this.listLoader.onEmptied=()=>{this.close()},this.content.caption=document.createElement("div"),this.content.caption.classList.add(_i+"-caption","spoilers-container");let s;const i=()=>{s&&clearTimeout(s),s=window.setTimeout(()=>{s=void 0,this.content.caption.classList.remove("is-focused")},800)};this.content.caption.addEventListener("touchstart",()=>{st.isMobile&&(this.content.caption.classList.add("is-focused"),s&&(clearTimeout(s),s=void 0),document.addEventListener("touchend",i,{once:!0}))});const n=new tn(this.content.caption);n.onAdditionalScroll=i,this.wholeDiv.append(this.content.caption),J(this.buttons.delete,this.onDeleteClick);const r=[this.btnMenuForward={icon:"forward",text:"Forward",onClick:this.onForwardClick},this.btnMenuDownload={icon:"download",text:"MediaViewer.Context.Download",onClick:this.onDownloadClick},this.btnMenuDelete={icon:"delete",className:"danger",text:"Delete",onClick:this.onDeleteClick}];this.setBtnMenuToggle(r),this.setListeners()}get searchContext(){return this.listLoader.searchContext}setListeners(){super.setListeners(),J(this.buttons.forward,this.onForwardClick),J(this.author.container,this.onAuthorClick);const e=t=>{const s=tp(this.content.caption,t);if(s)return this.close().then(()=>{this.content.caption.removeEventListener("click",e,{capture:!0}),s()}),!1};this.content.caption.addEventListener("click",e,{capture:!0})}getMessageByPeer(e,t){return this.searchContext.isScheduled?this.managers.appMessagesManager.getScheduledMessageByPeer(e,t):this.managers.appMessagesManager.getMessageByPeer(e,t)}setCaption(e){const t=!!e.pFlags.sponsored;t&&this.author.nameEl.append(P("SponsoredMessageAd"));const s=Vi(e,!0),i=[],n={maxMediaTimestamp:s?.type==="video"&&s.duration||void 0,textColor:"white",loadPromises:i};let r,o;if(t){const l=e.sponsoredMessage,c=e.media.webpage;o=document.createElement("div"),r=!0;const d=document.createElement("b");d.append(je(l.title)),o.append(d,`
- `,Db(c,{...n,entities:c.entities},!0));const u=ot("btn-primary media-viewer-caption-button",{noRipple:!0});u.append(je(l.button_text)),this.content.caption.append(u),this.content.caption.classList.add("has-button"),J(u,()=>{this.close().then(()=>{Ce.onSponsoredBoxClick(e)})})}else(r=!!e.message)&&(o=Nu({peerId:e.peerId,message:e,middleware:this.content.mover.middlewareHelper.get(),richTextOptions:n}),this.saveTimestamps(o,i));Qt(this.content.caption.firstElementChild,o),this.content.caption.classList.toggle("hide",!r)}removeTimestamps(){this.videoTimestamps=[]}async saveTimestamps(e,t){t&&await Promise.all(t);const s=Array.from(e.querySelectorAll(".timestamp[data-timestamp]"));this.videoTimestamps=s.map(i=>({time:+i.dataset.timestamp,text:this.extractTimestampText(i)}))}extractTimestampText(e){const t=[];let s=e.nextSibling;for(;s&&!(s instanceof HTMLElement&&s.classList.contains("timestamp"));){const i=s.textContent,n=i.includes(`
- `);if(t.push(i.split(`
- `)[0].trim()),n)break;s=s.nextSibling}return t.filter(Boolean).join(" ")}setSearchContext(e){return this.listLoader.setSearchContext(e),this}async openMedia({message:e,index:t,target:s,fromRight:i=0,reverse:n=!1,prevTargets:r=[],nextTargets:o=[],mediaTimestamp:l}){if(this.setMoverPromise)return this.setMoverPromise;const c=e.mid,d=e.fwd_from&&!e.fromId?Aa(e.fwd_from):e.fromId,u=Vi(e,!0,t),h=!!e.pFlags.sponsored,p=h,m=await this.managers.appPeersManager.noForwards(e.peerId),g=e._==="messageService",f=g||p||!await this.managers.appMessagesManager.canForward(e),v=(g?m:f&&!h)||!UP(e);[[[this.buttons.forward,this.btnMenuForward],f],[[this.buttons.download,this.btnMenuDownload],v],[[this.buttons.delete,this.btnMenuDelete],!await this.managers.appMessagesManager.canDeleteMessage(e)]].forEach(([b,S])=>{b.forEach(_=>{_ instanceof HTMLElement?_.classList.toggle("hide",S):_.verify=()=>!S})}),this.wholeDiv.classList.toggle("no-forwards",v),this.removeTimestamps(),this.setCaption(e);const w=super._openMedia({media:u,timestamp:e.date,fromId:d,fromRight:i,target:s,reverse:n,prevTargets:r,nextTargets:o,message:e,mediaTimestamp:l,noAuthor:p});return this.target.mid=c,this.target.peerId=e.peerId,this.target.message=e,this.target.index=t,w}static isMediaCompatibleForDocumentViewer(e){return e._==="photo"||Wr.has(e.mime_type)&&e.size<=yv}}function HM({periodOptions:a,onOption:e,checked:t=0,users:s=1,discountInTitle:i}){const n=a[0]._==="premiumGiftCodeOption",r=a.slice().sort((h,p)=>h.months-p.months)[0],o=h=>qi(h,r.currency,!1,!0,!0),l=n?void 0:{12:"PremiumTierAnnual",6:"PremiumTierSemiannual",1:"PremiumTierMonthly"},c=a.map((h,p)=>{const m=+h.amount/(n?h.users:1);let g=l?P(l[h.months]||"Months",[h.months]):Zr(h.months,!1),f;if(n?f=P("Multiplier",[o(m),s]):h!==r&&(f=P("PricePerMonth",[o(+h.amount/h.months)])),h!==r){const w=document.createElement("span"),b=document.createElement("span");b.classList.add("popup-gift-premium-discount");const S=+r.amount*h.months/r.months,_=Math.round((1-+h.amount/S)*100);b.textContent="-"+_+"%",w.append(b,i?g:f),i?g=w:f=w}const v=new _t({checked:p===t,round:!0,name:"premium-period",asRadio:!0}),y=new Fe({title:g,checkboxField:v,clickable:!0,subtitle:f,rightTextContent:o(n?m*s:h.amount)});return y.container.classList.add("popup-gift-premium-option"),y}),d=document.createElement("form");d.classList.add("popup-gift-premium-options"),d.append(...c.map(h=>h.container));const u=()=>a[c.findIndex(h=>h.checkboxField.checked)];return d.addEventListener("change",()=>{e(u())}),e(u()),d}function GM(a){const e=a.gift;if(!e)return;let t,s;e._==="payments.checkedGiftCode"?t=it(e.from_id)||a.peerId:t=a.isOut?I.myId:a.peerId,s=a.isOut?a.peerId:I.myId,s||(s=I.myId);const i=s!==I.myId,n=e._!=="payments.checkedGiftCode"||!e.used_date;return{fromPeerId:t,toPeerId:s,isOutbound:i,isUnclaimed:n,gift:e}}class oU{constructor(e){this.options=e,this.onTabScroll=()=>{const{tab:t,options:s}=this,{scrollTop:i,scrollHeight:n}=t;s.header.classList.toggle("is-visible",i>100),s.header.classList.toggle("not-top",i>0),t.classList.toggle("not-bottom",n-i>t.offsetHeight)},this.initPremiumTab(e)}async initPremiumTab(e){const t=this.tab=document.createElement("div");t.append(e.header,e.body),t.classList.add("premium-promo-tab","not-bottom","scrollable","scrollable-y"),t.addEventListener("scroll",this.onTabScroll),e.body.append(...[this.createImageContainer(),await this.createHeading(),e.type==="premium"&&!e.isPremiumActive&&this.createOptionsForm(),this.createFeaturesContainer()].filter(Boolean)),e.container.classList.add("fixed-size")}async createHeading(){const e=document.createElement("div");e.classList.add("popup-premium-heading-text-container");const t=document.createElement("div");t.classList.add("popup-premium-heading-text-title");const s=document.createElement("div");s.classList.add("popup-premium-heading-text-description");const i={onlyFirstName:!0};let n,r;const o=GM(this.options);if(o){t.classList.add("smaller-text");const{fromPeerId:l,toPeerId:c,isOutbound:d,isUnclaimed:u,gift:h}=o,p=P("GiftMonths",[h.months]);if(d?n=P("GiftModal.Title.You",[await qe({...i,peerId:c}),p]):n=P(l?"TelegramPremiumUserGiftedPremiumDialogTitleWithPlural":"TelegramPremiumUserGiftedPremiumDialogTitleWithPluralSomeone",[l&&await qe({...i,peerId:l}),p].filter(Boolean)),d)r=P("TelegramPremiumUserGiftedPremiumOutboundDialogSubtitle",[await qe({...i,peerId:c})]);else if(h._==="messageActionGiftPremium")r=P("TelegramPremiumUserGiftedPremiumDialogSubtitle");else{const m="https://t.me/giftcode/"+h.slug,g=new Uu({button:!1,listenerSetter:this.options.listenerSetter,url:m});let f;u?f=P("GiftCode.ShareReceived",[xi(async()=>{this.close(),Ir.shareGiftLink(m)})]):f=P("BoostingLinkUsed"),r=document.createElement("div"),r.append(f,g.container)}}else n=this.options.isPremiumActive?P("TelegramPremiumSubscribedTitle"):P("Premium.Boarding.Title"),r=this.options.isPremiumActive?P("TelegramPremiumSubscribedSubtitle"):P("Premium.Boarding.Info");return t.append(n),s.append(r),e.append(t,s),e}createFeaturesContainer(){const e=document.createElement("div");return e.classList.add("popup-premium-features-container"),e.append(...[...this.createFeatures(this.options.features,this.options.order),this.options.type==="premium"&&this.options.premiumPromo.status_text&&this.createStatusText()].filter(Boolean)),e}createImageContainer(){const e=document.createElement("div");e.classList.add("popup-premium-header-image-container");const t=document.createElement("img");return t.src=`assets/img/premium-star${window.devicePixelRatio>1?"@2x":""}.png`,t.classList.add("popup-premium-header-image"),e.append(t),e}createStatusText(){const e=document.createElement("div");e.classList.add("popup-premium-status-text");const t=jt(this.options.premiumPromo.status_text,{entities:this.options.premiumPromo.status_entities});Qt(e,t);const s=i=>{const n=tp(e,i);n&&this.close(()=>{e.removeEventListener("click",s,{capture:!0}),n()})};return e.addEventListener("click",s,{capture:!0}),e}createOptionsForm(){return HM({periodOptions:this.options.premiumPromo.period_options,onOption:e=>{this.selectPeriod?.(e)}})}createFeatures(e,t){return t.map((s,i)=>{const n=e.find(l=>l.feature===s),r=new Fe({titleLangKey:n.titleLangKey,titleLangArgs:n.titleLangArgs,subtitleLangKey:n.subtitleLangKey,subtitleLangArgs:n.subtitleLangArgs,clickable:async()=>{this.transition(1),await this.selectFeature(n.feature)}}),o=r.createMedia("small");if(o.classList.add("premium-promo-tab-icon"),o.append(Be(n.icon)),o.style.backgroundColor=pS[i],n.new){const l=P("New");l.classList.add("row-title-badge"),r.title.append(l),l.style.backgroundColor=pS[i]}return r.container})}}class lU{async construct(e){this.limits=document.createElement("div"),this.limits.classList.add("limits-list");const t=e.limits.map(async(i,n)=>{const[r,o]=i.limitType?await Promise.all([e.managers.apiManager.getLimit(i.limitType,!1),e.managers.apiManager.getLimit(i.limitType,!0)]):[],l=document.createElement("div");l.classList.add("limit-text-container"),n||l.classList.add("no-margin");const c=document.createElement("div");c.classList.add("limit");const d=document.createElement("div");d.classList.add("limit-title"),ks(d,i.titleLangKey,i.titleLangArgs);const u=document.createElement("div");u.classList.add("limit-subtitle"),ks(u,i.subtitleLangKey,i.subtitleLangArgs);const h=new xg({limitFree:r??i.free,limitPremium:o??i.premium,color:i.backgroundColor});return l.append(d,u),c.append(l,h.container),c}),s=await Promise.all(t);return this.limits.append(...s),this.limits}}class cU{constructor(e){this.avatar=vs({middleware:e.middleware,size:84,isBig:!0,withStories:!0,peerId:e.premiumPromo.users[0].id.toPeerId(!1)});const t=document.createElement("div");t.classList.add("story-features-list"),this.features=t,e.features.forEach(s=>{const i=document.createElement("div");i.classList.add("story-feature");const n=new Fe({titleLangKey:s.titleLangKey,titleLangArgs:s.titleLangArgs,subtitleLangKey:s.subtitleLangKey,subtitleLangArgs:s.subtitleLangArgs,icon:s.icon,iconClasses:["row-icon-custom-color"],clickable:!1});n.container.style.setProperty("--custom-icon-color",s.iconColor),i.append(n.container),t.append(i)})}}class dU{constructor(e){this.initStickersCarousel(e)}cleanup(){this.destroyed=!0}assignVisibility(e,t){this.container.children[e].classList.add("visible"),this.container.children[this.activeStickerIndex].classList.add("active"),this.container.children[t].classList.add("visible")}runStickerAnimation(){Dh({doc:this.stickers[this.activeStickerIndex],middleware:this.stickersMiddlewareHelper.get(),side:"left",size:200*KC,target:this.container.children[this.activeStickerIndex],play:!0,fullThumb:ql(this.stickers[this.activeStickerIndex]),relativeEffect:!0,loopEffect:!1,onUnmount:()=>{if(this.ignoreUnmount){this.ignoreUnmount=void 0;return}this.destroyed||this.previousSticker()}})}previousSticker(){const e=this.stickers.length;this.stickersMiddlewareHelper.clean(),Array.from(this.container.children).forEach(i=>i.classList.remove("top-sibling","active","bottom-sibling","visible")),this.activeStickerIndex-1<0?this.activeStickerIndex=e-1:--this.activeStickerIndex;const t=this.activeStickerIndex===0?e-1:this.activeStickerIndex-1,s=this.activeStickerIndex===e-1?0:this.activeStickerIndex+1;this.assignVisibility(t,s),this.assignSiblings(),this.runStickerAnimation()}nextSticker(){const e=this.stickers.length;this.stickersMiddlewareHelper.clean(),Array.from(this.container.children).forEach(i=>i.classList.remove("top-sibling","active","bottom-sibling","visible")),this.activeStickerIndex+1===e?this.activeStickerIndex=0:++this.activeStickerIndex;const t=this.activeStickerIndex-1<0?e-1:this.activeStickerIndex-1,s=this.activeStickerIndex===e-1?0:this.activeStickerIndex+1;this.assignVisibility(t,s),this.assignSiblings(),this.runStickerAnimation()}assignSiblings(){for(let t=-3;t<=3;++t){const s=(this.activeStickerIndex+t+this.stickers.length)%this.stickers.length,i=this.container.children[s];t<0?i.classList.add("top-sibling"):t>0&&i.classList.add("bottom-sibling")}}async initStickersCarousel(e){e.topSection.classList.add("no-padding");const t=await e.managers.appStickersManager.getPromoPremiumStickers();this.stickersMiddlewareHelper=Ht(),this.lazyLoadQueue=new sr,this.superStickerRenderer=new Id({regularLazyLoadQueue:this.lazyLoadQueue,group:"none",managers:e.managers,visibleRenderOptions:{withLock:!1,width:200,height:200}}),this.stickers=t,this.container=document.createElement("div"),this.container.classList.add("premium-stickers-carousel"),this.activeStickerIndex=Math.round(this.stickers.length/2),t.forEach((s,i)=>{const n=document.createElement("div");n.classList.add("premium-stickers-carousel-item");const r=this.superStickerRenderer.renderSticker(s);n.append(r),n.addEventListener("click",o=>{o.stopPropagation(),i!==this.activeStickerIndex&&(this.ignoreUnmount=!0,n.classList.contains("bottom-sibling")&&this.nextSticker(),n.classList.contains("top-sibling")&&this.previousSticker())}),this.container.append(n)}),this.assignVisibility(this.activeStickerIndex-1,this.activeStickerIndex+1),this.assignSiblings(),this.runStickerAnimation(),e.topSection.addEventListener("click",s=>{s.stopPropagation()}),e.topSection.append(this.container)}}class hU{constructor(e){this.scrollListener=t=>{const s=t.target,{scrollTop:i,scrollHeight:n}=s;s.classList.toggle("top-border",i>0),s.classList.toggle("bottom-border",n-i>s.clientHeight)},this.middleware=e.middleware,this.header=e.header,this.managers=e.managers,this.premiumPromo=e.premiumPromo,this.features=e.features,this.container=document.createElement("div"),this.container.classList.add("carousel-container"),this.carouselItems=this.features.map(t=>{const s=document.createElement("div");if(s.classList.add("carousel-item","tabs-tab"),t.videoPosition||t.type==="premium-stickers"){const i=document.createElement("div");i.classList.add("carousel-item-content-title");const n=document.createElement("div");n.classList.add("carousel-item-content-subtitle");const r=document.createElement("div");r.classList.add("carousel-item-content-bottom-section"),i.append(P(t.titleLangKey,t.titleLangArgs)),n.append(P(t.subtitleLangKey,t.subtitleLangArgs)),r.append(i),r.append(n),s.append(r)}return s}),this.header.classList.add("absolute"),this.carouselItemsContainer=document.createElement("div"),this.carouselItemsContainer.classList.add("carousel-items-container","tabs-container"),this.selectTab=Sr({content:this.carouselItemsContainer,type:"premiumTabs",transitionTime:250,animateFirst:!1}),this.carouselItemsContainer.append(...this.carouselItems),this.container.append(this.carouselItemsContainer),this.features.forEach((t,s)=>{let i=this.carouselItems[s].querySelector(".carousel-item-content-top-section");if(i||(i=document.createElement("div"),i.classList.add("carousel-item-content-top-section"),this.carouselItems[s].prepend(i)),t.videoPosition){this.downloadVideo(s);let n=i.querySelector(".device-frame");if(!n){const r=document.createElement("img");r.classList.add("device-frame-image"),n=document.createElement("div"),n.classList.add("device-frame"),n.append(r),Ka(r,"assets/img/android-device.svg"),n.classList.toggle("bottom",t.videoPosition!=="top"),i.append(n)}}}),this.initCarouselControls(e)}cleanup(){this.premiumStickersCarousel?.cleanup()}ready(e){this.outerLayoutUpdater=e}async buildSlide(e){const t=this.features[e],s=this.carouselItems[e].querySelector(".carousel-item-content-top-section");if(s.removeEventListener("scroll",this.scrollListener),s.removeAttribute("style"),t.videoPosition)await this.appendVideo(e,this.carouselItems[e].querySelector(".device-frame"));else switch(t.type!=="premium-stickers"&&s.addEventListener("scroll",this.scrollListener),t.type){case"limits":{if(!!!s.querySelector(".limits-list")){const n=new lU,r=n.construct({limits:t.content,managers:this.managers}),o=n.limits;s.append(o),s.classList.add("scrollable","scrollable-y","no-scrollbar","bottom-border","top-margin"),await r}break}case"upgraded-stories":{if(!!!s.querySelector(".story-features-list")){const n=new cU({middleware:this.middleware,features:t.content,premiumPromo:this.premiumPromo}),r=document.createElement("div");r.classList.add("above-top-section"),r.prepend(n.avatar.node);const o=P(t.titleLangKey);o.classList.add("above-top-section-title"),r.append(o),this.carouselItems[e].prepend(r),this.carouselItems[e].classList.add("upgraded-stories"),s.append(n.features)}s.style.position="relative",s.classList.add("scrollable","scrollable-y","no-scrollbar","bottom-border");break}case"premium-stickers":{!!s.querySelector(".premium-stickers-carousel")||(this.premiumStickersCarousel=new dU({topSection:s,managers:this.managers}));break}}}async processSlideContent(e){let t=this.header.querySelector(".popup-title");const s=this.header.querySelector(".back-button"),i=!!this.features[e].headerLangKey;i&&(t.remove(),t=document.createElement("div"),t.classList.add("popup-title"),t.append(P(this.features[e].headerLangKey)),this.header.append(t)),this.header.classList.toggle("is-visible",!!i),i||this.header.classList.remove("not-top"),this.features[e].videoPosition||this.features[e].type==="premium-stickers"?(s.style.color="#ffffff",this.carouselItems[e].classList.remove("feature-background"),this.carouselItemsContainer.classList.remove("full")):(s.style.color="var(--secondary-text-color)",this.carouselItems[e].classList.add("feature-background"),this.carouselItemsContainer.classList.add("full")),await this.buildSlide(e)}async selectSlide(e){this.selectedFeature=e;const t=this.features.findIndex(i=>i.feature===e);await this.processSlideContent(t);const s=this.slideIndex;this.slideIndex=t,this.outerLayoutUpdater?.(this.features.find(i=>i.feature===e)),this.dots(e,t),this.selectTab(t,s!==void 0)}dots(e,t){const s=this.dotsContainer.querySelectorAll(".popup-premium-controls-dot");s.forEach(c=>{c.classList.remove("active"),c.style.transform=""}),this.dotsContainer.querySelector(`[data-feature=${e}]`)?.classList.add("active");const n=t/2-1<1?0:Math.ceil(t/2),r=this.features.length,o=r-1,l=Math.ceil(r/2)-1;if(n<1){const c=s[o-l+n];s[o-l+n-1].style.transform="scale(.75)",c&&(c.style.transform="scale(.5)")}else if(n>=1&&n<l){const c=s[o-l+n];s[n+1].style.transform="scale(.75)",s[n].style.transform="scale(.5)",s[o-l+n-1].style.transform="scale(.75)",c&&(c.style.transform="scale(.5)")}else s[n+1].style.transform="scale(.75)",s[n].style.transform="scale(.5)";this.dotsContainer.style.setProperty("--amount",""+r),this.dotsContainer.style.setProperty("--start",""+n)}initCarouselControls(e){this.controlsContainer=document.createElement("div"),this.controlsContainer.classList.add("popup-premium-controls"),this.dotsContainer=document.createElement("div"),this.dotsContainer.classList.add("popup-premium-controls-dots"),this.controlsContainer.append(this.dotsContainer),this.features.forEach((t,s)=>this.dotsContainer.append(this.createFeatureDot(e,t.feature,s))),J(this.dotsContainer,t=>{t.stopPropagation()},{listenerSetter:e.listenerSetter}),J(this.container,t=>{const s=this.container.getBoundingClientRect(),i=this.features.findIndex(o=>o.feature===this.selectedFeature),n=s.left+s.width/2<t.clientX?1:-1,r=this.features[i+n];r&&this.selectSlide(r.feature)},{listenerSetter:e.listenerSetter})}createFeatureDot(e,t,s){const i=document.createElement("div");return i.classList.add("popup-premium-controls-dot"),t===this.selectedFeature&&i.classList.add("active"),i.dataset.feature=t,J(i,n=>{_e(n),t!==this.selectedFeature&&this.selectSlide(t)},{listenerSetter:e.listenerSetter}),i}async downloadVideo(e,t,s=!1){const i=this.features[e].video;if(!i)return{video:void 0,loadPromise:new Promise(()=>{})};const n=await Xa({doc:i,withoutPreloader:!0,noInfo:!0,noPlayButton:!0,middleware:this.middleware,...s&&{container:t}});return this.features[e].wrappedVideo=n}async appendVideo(e,t){if(this.features[e].builded)return;this.features[e].builded=!0;let s,i,n=this.features[e].wrappedVideo;n?.loaded||(s=document.createElement("div"),s.classList.add("shimmer"),i=Be("star","device-frame-preload-icon"),t.append(...[n?.thumb?.images?.thumb,s,i].filter(Boolean))),n?t.append(this.features[e].wrappedVideo.video):(n=await this.downloadVideo(e,t,!0),n.loadPromise.then(()=>{n.loaded=!0})),s&&n.loadPromise.then(()=>{s.remove(),i.remove()})}}class uU{constructor(e){this.backBtn=yt("left popup-close back-button",{noRipple:!0}),this.initFeaturesTab(e)}cleanup(){this.featureCarousel?.cleanup()}initFeaturesTab(e){const t=document.createElement("div");t.classList.add("premium-feature-tab"),e.header.querySelector(".popup-close").replaceWith(this.backBtn),t.append(e.header),this.featureCarousel=new hU({...e,header:e.header}),t.append(this.featureCarousel.container,this.featureCarousel.controlsContainer),this.tab=t,J(this.backBtn,()=>{this.featureCarousel.slideIndex=void 0,this.transition(0)},{listenerSetter:e.listenerSetter})}setCarouselSlide(e){return this.featureCarousel.selectSlide(e)}}class rs extends ue{constructor(e={}){super("popup-premium",{overlayClosable:!0,closable:!0,body:!0,title:"Premium.Boarding.Title"}),this.prepareArguments=async t=>{const[s,i]=await Promise.all([t._titleLangArgs,t._subtitleLangArgs].map(n=>n&&n(this.managers)));return{titleLangArgs:s,subtitleLangArgs:i}},this.selectFeature=async t=>{this.selectedFeature=this.props.features.find(s=>s.feature===t),await this.featureSlideTab.setCarouselSlide(t),this.updateActionLayout(this.selectedFeature)},this.updateActionLayout=t=>{if(!this.actionButtonText)return;if(this.props.type==="gift"){const{isOutbound:n,isUnclaimed:r}=this.giftDetails;!n&&r&&this.actionButtonText.compareAndUpdate({key:"GiftPremiumActivateForFree"});return}if(this.props.isPremiumActive)return;this.actionButtonText.compareAndUpdate({key:t?.actionTitleLangKey||"Premium.Boarding.Subscribe",args:[this.wrapCurrency(+this.option.amount/this.option.months)]});const s=this.actionButton.querySelector(".tgico"),i=t?.actionIcon&&Be(t.actionIcon,"row-icon","action-button-icon");i?s?s?.replaceWith(i):this.actionButton.append(i):s?.remove()},this.close=t=>{t&&this.addEventListener("closeAfterTimeout",t),this.hide()},Nt(this,e),this.initTabs()}cleanup(){super.cleanup(),this.featureSlideTab.cleanup(),this.promoSlideTab.tab.remove()}filterOrder(e,t){return(t||[]).filter(s=>{const i=!!gS[s];if(!i){console.warn("premium feature is not implemented",s);const n=e.video_sections.indexOf(s);n!==-1&&(e.video_sections.splice(n,1),e.videos.splice(n,1))}return i})}async createFeatures(e,t){return Promise.all(t.map(async s=>{const i=gS[s];let n=i.content;n&&(n=await Promise.all(n.map(async l=>({...await this.prepareArguments(l),...l}))));const r=e.videos[e.video_sections.indexOf(s)],o={...await this.prepareArguments(i),...i,content:n,video:r};return r&&(o.videoPosition??(o.videoPosition="bottom")),o}))}async initTabs(){const[e,t]=await Promise.all([this.managers.appPaymentsManager.getPremiumPromo(),this.managers.apiManager.getAppConfig()]),s=this.filterOrder(e,t.premium_promo_order),i=I.premium;this.props={order:s,features:await this.createFeatures(e,s),premiumPromo:e,managers:this.managers,middleware:this.middlewareHelper.get(),appConfig:t,isPremiumActive:i,gift:this.gift,peerId:this.peerId||this.stack?.peerId,isOut:this.isOut||this.stack?.isOut,type:this.gift?"gift":"premium",stack:this.stack,listenerSetter:this.listenerSetter},this.giftDetails=GM(this.props);const n=this.tabsContainer=document.createElement("div");n.classList.add("tabs-container","premium-tabs"),this.option=this.props.premiumPromo.period_options[0];const r=this.props.premiumPromo.period_options.slice().sort((c,d)=>c.months-d.months)[0];this.wrapCurrency=c=>qi(c,r.currency,!1,!0,!0);const o=document.createElement("div");o.classList.add("popup-header-background"),this.header.prepend(o),this.createTransitionSlider(),this.createActionButton(),this.createPromoSlideTab(),this.createFeatureSlideTab();const l=[this.promoSlideTab.tab,this.featureSlideTab.tab].filter(Boolean);l.forEach(c=>{c.classList.add("tabs-tab","premium-tab")}),n.append(...l),this.container.append(...[n,this.actionButtonContainer].filter(Boolean)),this.actionButtonContainer||this.container.classList.add("no-button"),this.feature&&await this.selectFeature(this.feature),this.transition(this.feature?1:0),this.show()}createTransitionSlider(){this.transition=Sr({content:this.tabsContainer,type:"navigation",transitionTime:150,animateFirst:!1,onTransitionEnd:e=>{this.selectedTab=e,e?this.featureSlideTab.featureCarousel.ready(this.updateActionLayout):this.updateActionLayout()}})}createActionButton(){if(this.props.type==="gift"&&(this.giftDetails.isOutbound||!this.giftDetails.isUnclaimed))return;this.actionButtonText=new Ne.IntlElement({key:"OK"}),this.actionButtonContainer=document.createElement("div"),this.actionButtonContainer.classList.add("action-button-container"),this.actionButton=ot("btn-primary popup-gift-premium-confirm action-button shimmer"),this.actionButton.append(this.actionButtonText.element);let e;this.props.type==="gift"?e=()=>{const t=this.props.gift;Ir.applyGiftCode(t.slug,this.actionButton,this)}:e=()=>{if(this.props.isPremiumActive){this.hide();return}this.buyPremium()},J(this.actionButton,e,{listenerSetter:this.listenerSetter,once:!0}),this.actionButtonContainer.append(this.actionButton)}createPromoSlideTab(){this.promoSlideTab=new oU({container:this.tabsContainer,header:this.header,body:this.body,...this.props}),this.promoSlideTab.transition=this.transition,this.promoSlideTab.selectFeature=this.selectFeature,this.promoSlideTab.selectPeriod=e=>{this.option=e,this.updateActionLayout()},this.promoSlideTab.close=this.close}createFeatureSlideTab(){this.featureSlideTab=new uU({header:this.header.cloneNode(!0),actionButtonContainer:this.actionButtonContainer,...this.props}),this.featureSlideTab.transition=this.transition}buyPremium(){this.close(()=>{Ce.openUrl(this.option.bot_url)})}static show(...e){ue.createPopup(rs,...e)}}const pU={pin:{title:"LimitReached",description:"LimitReachedPinDialogs",descriptionPremium:"LimitReachedPinDialogsPremium",descriptionLocked:"LimitReachedPinDialogsLocked",icon:"limit_pin"},folders:{title:"LimitReached",description:"LimitReachedFolders",descriptionPremium:"LimitReachedFoldersPremium",descriptionLocked:"LimitReachedFoldersLocked",icon:"limit_folders"},folderPeers:{title:"LimitReached",description:"LimitReachedChatInFolders",descriptionPremium:"LimitReachedChatInFoldersPremium",descriptionLocked:"LimitReachedChatInFoldersLocked",icon:"limit_folders"},chatlistInvites:{title:"LimitReached",description:"LimitReachedSharedFolderInvites",descriptionPremium:"LimitReachedSharedFolderInvitesPremium",descriptionLocked:"LimitReachedSharedFolderInvitesLocked",icon:"limit_link"},savedPin:{title:"LimitReached",description:"LimitReachedPinDialogs",descriptionPremium:"LimitReachedPinDialogsPremium",descriptionLocked:"LimitReachedPinDialogsLocked",icon:"limit_pin"}};class mU extends mi{constructor(e,t){super("popup-limit",{buttons:e.isPremium===void 0?[{langKey:"LimitReached.Ok",isCancel:!0}]:e.isPremium?[{langKey:"OK",isCancel:!0}]:[{langKey:"IncreaseLimit",callback:()=>{rs.show({feature:e.feature})},iconRight:"premium_double"},{langKey:"Cancel",isCancel:!0}],descriptionLangKey:e.isPremium===void 0?t.descriptionLocked:e.isPremium?t.descriptionPremium:t.description,descriptionLangArgs:e.isPremium?[e.limitPremium]:[e.limit,e.limitPremium],titleLangKey:t.title});const s=new xg({limitPremium:e.limitPremium,hint:{icon:t.icon,content:""+(e.isPremium?e.limitPremium:e.limit)}});e.isPremium!==void 0?s.setProgress(e.isPremium?1:.5):s.container.querySelector(".limit-line")?.remove(),this.description.before(s.container),s._setHintActive()}}async function Ja(a){const e="double_limits",t=pU[a],[s,i,n]=await Promise.all([I.managers.apiManager.getAppConfig(),...[!1,!0].map(o=>I.managers.apiManager.getLimit(a,o))]),r=s.premium_purchase_blocked;new mU({isPremium:r?void 0:I.premium,limit:i,limitPremium:n,feature:e},t).show()}class gU{constructor(e){this.managers=e,this.onArchiveClick=async()=>{const t=await this.managers.appMessagesManager.getDialogOnly(this.peerId);t&&this.managers.appMessagesManager.editPeerFolders([t.peerId],+!t.folder_id)},this.onHideTopicClick=()=>{this.managers.appChatsManager.editForumTopic({chatId:this.peerId.toChatId(),topicId:this.threadId,hidden:!0})},this.onToggleTopicClick=()=>{this.managers.appChatsManager.editForumTopic({chatId:this.peerId.toChatId(),topicId:this.threadId,closed:!this.dialog.pFlags.closed})},this.onPinClick=()=>{const{peerId:t,filterId:s,threadId:i,dialog:n}=this,r=pr(n);this.managers.appMessagesManager.toggleDialogPin({peerId:t,filterId:s,topicOrSavedId:i}).catch(async o=>{(o.type==="PINNED_DIALOGS_TOO_MUCH"||o.type==="PINNED_TOO_MUCH")&&(r?Ja("savedPin"):i?this.managers.apiManager.getLimit("topicPin").then(l=>{$e({langPackKey:"LimitReachedPinnedTopics",langPackArguments:[l]})}):oa.has(s)?Ja("pin"):$e({langPackKey:"PinFolderLimitReached"}))})},this.onUnmuteClick=()=>{this.managers.appMessagesManager.togglePeerMute({peerId:this.peerId,mute:!1,threadId:this.threadId})},this.onMuteClick=()=>{ue.createPopup(K_,this.peerId,this.threadId)},this.onUnreadClick=async()=>{const{peerId:t,dialog:s}=this;s.unread_count?this.threadId?this.managers.appMessagesManager.readHistory(t,s.top_message,this.threadId):this.managers.appMessagesManager.markDialogUnread(t,!0):this.threadId||this.managers.appMessagesManager.markDialogUnread(t)},this.onDeleteClick=()=>{ue.createPopup(kg,this.peerId,void 0,void 0,this.threadId)}}attach(e){Dn({listenTo:e,buttons:this.getButtons(),appendTo:document.getElementById("page-chats"),onOpen:async(t,s)=>{this.li=s,s.classList.add("menu-open"),this.peerId=s.dataset.peerId.toPeerId(),this.threadId=+s.dataset.threadId||void 0,this.dialog=await this.managers.dialogsStorage.getAnyDialog(this.peerId,this.threadId),this.filterId=this.threadId?void 0:nt.filterId,this.canManageTopics=Yr(this.dialog)?await this.managers.dialogsStorage.canManageTopic(this.dialog):void 0},onOpenBefore:async()=>{const t=this.threadId?"Delete":await this.managers.appPeersManager.getDeleteButtonText(this.peerId),s=this.buttons[this.buttons.length-1];s?.element&&s.element.lastChild.replaceWith(P(t))},onClose:()=>{this.li.classList.remove("menu-open"),this.li=this.peerId=this.dialog=this.filterId=this.threadId=this.canManageTopics=void 0},findElement:t=>Mn(t.target,tc)})}getButtons(){return this.buttons??(this.buttons=[{icon:"newtab",text:"OpenInNewTab",onClick:e=>{nt.openDialogInNewTab(this.li),_e(e)},verify:()=>OE},{icon:"topics",text:"TopicViewAsTopics",onClick:()=>{Ce.toggleViewAsMessages(this.peerId,!1)},verify:()=>!!(this.dialog&&this.dialog.pFlags.view_forum_as_messages)},{icon:"topics",text:"SavedViewAsChats",onClick:()=>{Ce.toggleViewAsMessages(this.peerId,!1)},verify:()=>this.peerId===I.myId&&!I.settings.savedAsForum&&!this.threadId},{icon:"message",text:"SavedViewAsMessages",onClick:()=>{Ce.toggleViewAsMessages(this.peerId,!0)},verify:()=>this.peerId===I.myId&&I.settings.savedAsForum&&!this.threadId},{icon:"unread",text:"MarkAsUnread",onClick:this.onUnreadClick,verify:async()=>!this.threadId&&!await this.managers.appMessagesManager.isDialogUnread(this.dialog)},{icon:"readchats",text:"MarkAsRead",onClick:this.onUnreadClick,verify:()=>this.managers.appMessagesManager.isDialogUnread(this.dialog)},{icon:"pin",text:"ChatList.Context.Pin",onClick:this.onPinClick,verify:async()=>pr(this.dialog)?!this.dialog.pFlags.pinned:this.threadId&&!this.canManageTopics?!1:!(this.filterId!==void 0&&this.filterId>1?(await this.managers.appMessagesManager.getFilter(this.filterId)).pinnedPeerIds.includes(this.dialog.peerId):!!this.dialog.pFlags?.pinned)},{icon:"unpin",text:"ChatList.Context.Unpin",onClick:this.onPinClick,verify:async()=>pr(this.dialog)?!!this.dialog.pFlags.pinned:this.threadId&&!this.canManageTopics?!1:this.filterId!==void 0&&this.filterId>1?(await this.managers.appMessagesManager.getFilter(this.filterId)).pinnedPeerIds.includes(this.dialog.peerId):!!this.dialog.pFlags?.pinned},{icon:"mute",text:"ChatList.Context.Mute",onClick:this.onMuteClick,verify:async()=>this.peerId!==I.myId&&!await this.managers.appNotificationsManager.isPeerLocalMuted({peerId:this.dialog.peerId,threadId:this.threadId})},{icon:"unmute",text:"ChatList.Context.Unmute",onClick:this.onUnmuteClick,verify:()=>this.peerId!==I.myId&&this.managers.appNotificationsManager.isPeerLocalMuted({peerId:this.dialog.peerId,threadId:this.threadId})},{icon:"archive",text:"Archive",onClick:this.onArchiveClick,verify:()=>!this.threadId&&this.dialog.folder_id!==yn&&this.peerId!==I.myId},{icon:"unarchive",text:"Unarchive",onClick:this.onArchiveClick,verify:()=>this.filterId===yn&&this.peerId!==I.myId},void 0,{icon:"lock",text:"CloseTopic",onClick:this.onToggleTopicClick,verify:()=>this.canManageTopics&&!this.dialog.pFlags.closed},{icon:"lockoff",text:"RestartTopic",onClick:this.onToggleTopicClick,verify:()=>this.canManageTopics&&!!this.dialog.pFlags.closed},{icon:"delete",className:"danger",text:"Delete",onClick:this.onDeleteClick,verify:()=>this.threadId?pr(this.dialog)?!0:this.canManageTopics?this.dialog.id!==Tu:!1:!0}]),this.buttons=this.buttons.filter(Boolean)}}function fU(a,e,t){let s;if(typeof e=="string"?s=e:e?.pFlags.out&&(e.error?s="sendingerror":e.pFlags.is_outgoing?s="sending":e.pFlags.unread?s="check":s="checks"),!s){a.textContent="",a.classList.add("hide");return}const i=a.lastElementChild;if(i&&i.classList.contains(zr(s)))return;const n=Be(s,"sending-status-icon","sending-status-icon-"+s);a.append(n),a.classList.remove("hide"),i?.remove()}const sp=window.devicePixelRatio,qd=20*sp,AC=2.5*sp,hv=2*sp,vU=1*sp,uv=3,RC=4,yU=12,FC=1e3;function bU(a=!1){const e=document.createElement("canvas");e.width=e.height=qd;const t=e.getContext("2d"),s=uv*hv+(uv-1)*AC,i=(qd-s)/2,n=Date.now();let r=!1;const o=()=>{if(e.isConnected)r||(r=e.isConnected);else if(r)return!1;const l=Date.now(),c=j_((l-n)%FC,0,1,FC);t.clearRect(0,0,qd,qd),t.fillStyle=a&&!st.isMobile?yi.getProperty("primary-color"):"#fff";for(let d=0;d<uv;++d){const u=i+d*hv+d*AC;let h;c>=.5?h=d%2?2-c*2:(c-.5)*2:h=d%2?c*2:1-c*2;let p=RC+h*(yU-RC);p*=sp;const m=(qd-p)/2;Wp(t,u,m,hv,p,vU)}return!0};return{canvas:e,startAnimation:()=>{No(o),o()},setActive:l=>{a=l,o()}}}const tc="A";function BC(a,e){a[e]?.reject();const s=a[e]=Mt();s.catch(()=>{}).finally(()=>{a[e]===s&&delete a[e]});const i=Bl(()=>a[e]===s);return{deferred:s,middleware:i}}const Yd=22,ag=250;class rf extends Bg{constructor(e){super({getIndex:t=>this.managers.dialogsStorage.getDialogIndex(this.virtualFilterId??t.id,this.indexKey,this.virtualFilterId?t.id:void 0),onDelete:t=>{t.dialogElement.remove(),this.onListLengthChange?.()},onSort:(t,s)=>{const i=t.dom.listEl.parentElement!==this.list;di(t.dom.listEl,this.list,s),i&&this.onListLengthChange?.()},onElementCreate:async t=>{const s=[],i=Zs.addListDialog({peerId:this.virtualFilterId??t.id,loadPromises:s,isBatch:!0,threadId:this.virtualFilterId?t.id:void 0,isMainList:this.indexKey==="index_0",controlled:!0,wrapOptions:void 0});return t.dom=i.dom,t.dialogElement=i,await Promise.all(s),t},updateElementWith:u_,log:e.log}),Nt(this,e),this.isSavedDialogs=this.virtualFilterId===I.myId}clear(){this.list.replaceChildren(),this.elements.forEach(e=>{e.dialogElement.destroy()}),super.clear()}}const wU={bigger:54,abitbigger:42,small:32},Rw=class Rw extends Fe{constructor({peerId:e,rippleEnabled:t=!0,onlyFirstName:s=!1,meAsSaved:i=!0,avatarSize:n="bigger",autonomous:r,loadPromises:o,fromName:l,noIcons:c,threadId:d,wrapOptions:u={},isMainList:h,withStories:p,controlled:m}){super({clickable:!0,noRipple:!t,havePadding:!d,title:!0,titleRightSecondary:!0,subtitle:!0,subtitleRight:!0,noWrap:!0,asLink:!0}),this.subtitleRight.remove();const g=u?.middleware;this.middlewareHelper=g?u.middleware.create():m?Ht():void 0;const f={...u};this.middlewareHelper&&(f.middleware=this.middlewareHelper.get());const v=!!d&&e===I.myId,y=!!d&&!v,w=v?d:e,b=y?void 0:vs({middleware:this.middlewareHelper.get(),size:wU[n],lazyLoadQueue:f.lazyLoadQueue,isDialog:!!i,peerId:l?Wt:w,peerTitle:l,withStories:p,wrapOptions:f,meAsNotes:v});o?.push(b?.readyThumbPromise);const S=b?.node;S&&(S.classList.add("dialog-avatar"),this.applyMediaElement(S,n));const _=this.container,M=this.title;M.classList.add("user-title"),this.titleRow.classList.add("dialog-title");const C=!r&&Ce.chat&&Ce.isSamePeer(Ce.chat,{peerId:e,threadId:d,type:v?we.Saved:we.Chat}),L=new Xt,E=L.update({peerId:w,fromName:l,dialog:i,onlyFirstName:s,withIcons:!c,threadId:v?void 0:d,wrapOptions:{textColor:Zs.getPrimaryColor(C),...f},meAsNotes:v});o?.push(E),M.append(L.element);const x=this.subtitle,R=this.container;R.classList.add("chatlist-chat","chatlist-chat-"+n),r||(R.href="#"+e),n==="bigger"?this.container.classList.add("row-big"):n==="small"&&this.container.classList.add("row-small"),R.dataset.peerId=""+e,d&&(R.dataset.threadId=""+d);const B=document.createElement("span");B.classList.add("message-status","sending-status");const N=document.createElement("span");N.classList.add("message-time");const G=this.titleRight;G.classList.add("dialog-title-details"),G.append(B,N),this.subtitleRow.classList.add("dialog-subtitle","has-multiple-badges");const O=this.dom={avatarEl:b,captionDiv:_,titleSpan:L.element,titleSpanContainer:M,statusSpan:B,lastTimeSpan:N,lastMessageSpan:x,containerEl:R,listEl:R,subtitleEl:this.subtitleRow};r||(R.dialogDom=O,h&&Zs.forumTab?.peerId===e&&!d&&R.classList.add("is-forum-open")),C&&Zs.setDialogActive(R,!0)}destroy(){this.middlewareHelper?.destroy()}remove(){this.destroy(),this.dom.listEl.remove()}createPinnedBadge(){if(this.dom.pinnedBadge)return;const e=this.dom.pinnedBadge=document.createElement("div");e.className=`dialog-subtitle-badge badge badge-icon badge-${Yd} dialog-subtitle-badge-pinned`,e.append(Be("chatspinned")),this.dom.subtitleEl.append(e)}createUnreadBadge(){if(this.dom.unreadBadge)return;const e=this.dom.unreadBadge=document.createElement("div");e.className=`dialog-subtitle-badge badge badge-${Yd} dialog-subtitle-badge-unread`,this.dom.subtitleEl.append(e)}createUnreadAvatarBadge(){if(this.dom.unreadAvatarBadge)return;const e=this.dom.unreadAvatarBadge=document.createElement("div");e.className=`dialog-subtitle-badge badge badge-${Yd} avatar-badge`,this.dom.listEl.append(e)}createMentionsBadge(){if(this.dom.mentionsBadge)return;const e=this.dom.mentionsBadge=document.createElement("div");e.className=`dialog-subtitle-badge badge badge-${Yd} mention mention-badge dialog-subtitle-badge-mention`,e.innerText="@",this.dom.subtitleEl.append(e)}createReactionsBadge(){if(this.dom.reactionsBadge)return;const e=this.dom.reactionsBadge=document.createElement("div");e.className=`dialog-subtitle-badge badge badge-${Yd} reaction-badge dialog-subtitle-badge-reaction`,e.append(Be("reactions_filled")),this.dom.subtitleEl.append(e)}toggleBadgeByKey(e,t,s,i){Dt({element:this.dom[e],className:"is-visible",forwards:t,duration:i?0:ag,onTransitionEnd:t?void 0:()=>{this.dom[e].remove(),delete this.dom[e]},useRafs:!s||!mr(this.dom[e])?2:0})}};Rw.BADGE_ORDER=["reactionsBadge","mentionsBadge","unreadBadge","pinnedBadge"];let rg=Rw;class pv extends Bs{constructor(){super(...arguments),this._close=()=>{this.slider?this.close():Zs.toggleForumTab(void 0,this)},this.viewAsMessages=async()=>{const e=Ce.chat,t=this.peerId;this._close(),await this.managers.appChatsManager.toggleViewForumAsMessages(t.toChatId(),!0),Ce[e?.peerId===t?"setPeer":"setInnerPeer"](this.getOptionsForMessages())}}async toggle(e){this.init2&&await this.init2(),Dt({element:this.container,className:"is-visible",forwards:e,duration:300,onTransitionEnd:e?void 0:()=>{this.onCloseAfterTimeout()},useRafs:this.firstTime?(this.firstTime=void 0,2):void 0})}init(e){Nt(this,e),this.log=Ni("FORUM"),this.firstTime=!0,this.container.classList.add("topics-container");const t=!this.slider;t&&(this.closeBtn.replaceChildren(Be("close")),this.container.classList.add("active","is-floating"),J(this.closeBtn,this._close,{listenerSetter:this.listenerSetter})),this.rows=document.createElement("div"),this.rows.classList.add("sidebar-header__rows"),this.subtitle=document.createElement("div"),this.subtitle.classList.add("sidebar-header__subtitle"),this.title.replaceWith(this.rows),this.rows.append(this.title,this.subtitle);const s=Zs.createChatList();Zs.setListClickListener({list:s,onFound:null,withContext:!0}),this.scrollable.append(s),this.xd=new SU(this.peerId,t?80:0),this.xd.scrollable=this.scrollable,this.xd.sortedList=new rf({managers:this.managers,log:this.log,list:s,indexKey:"index_0",virtualFilterId:this.peerId}),this.xd.bindScrollable();const i=ki({listenerSetter:this.listenerSetter,direction:"bottom-left",buttons:[{icon:"add",text:"ForumTopic.Context.New",onClick:()=>{Ri.createTab(Py).open(this.peerId)},separatorDown:!0,verify:()=>this.managers.appChatsManager.hasRights(this.peerId.toChatId(),"manage_topics")},{icon:"info",text:"ForumTopic.Context.Info",onClick:()=>{Vl.open(Ri,this.peerId)}},{icon:"message",text:"ForumTopic.Context.ShowAsMessages",onClick:this.viewAsMessages,verify:()=>{const n=Ce.chat;return!n||!Ce.isSamePeer(n,this.getOptionsForMessages())}},{icon:"adduser",text:"ForumTopic.Context.AddMember",onClick:()=>{},verify:()=>!1},{icon:"logout",danger:!0,text:"LeaveMegaMenu",onClick:()=>{ue.createPopup(kg,this.peerId,void 0,n=>{this._close()})},separator:!0,verify:async()=>!!await this.managers.appMessagesManager.getDialogOnly(this.peerId)}]});if(this.listenerSetter.add(I)("history_reload",n=>{this.peerId===n&&this.xd.fullReset()}),this.listenerSetter.add(I)("chat_update",n=>{if(this.peerId!==n.toPeerId(!0))return;Ae.getChat(n).pFlags.forum||Zs.toggleForumTab(void 0,this)}),pt&&bw({element:this.container,onSwipe:()=>{Zs.toggleForumTab(void 0,this)},middleware:this.middlewareHelper.get()}),this.header.append(i),!t)return this.init2()}async init2(){this.init2=void 0;const e=this.middlewareHelper.get(),t=this.peerId;this.managers.apiUpdatesManager.subscribeToChannelUpdates(this.peerId.toChatId()),e.onDestroy(()=>{this.managers.apiUpdatesManager.unsubscribeFromChannelUpdates(this.peerId.toChatId())});const s=qe({peerId:t,dialog:!0,wrapOptions:{middleware:e}}),i=Ce.setPeerStatus({peerId:t,element:this.subtitle,needClear:!0,useWhitespace:!1,middleware:e,noTyping:!0});return Promise.all([s,i,this.xd.onChatsScroll().then(n=>n.cached?n.renderPromise:void 0)]).then(([n,r,o])=>{e()&&(this.title.append(n),r?.())})}onCloseAfterTimeout(){super.onCloseAfterTimeout(),this.xd.destroy()}getOptionsForMessages(){return{peerId:this.peerId,type:we.Chat}}}const Qd=new Error("not implemented");class kw{constructor(){this.onChatsRegularScroll=()=>{this.sliceTimeout&&clearTimeout(this.sliceTimeout),this.sliceTimeout=window.setTimeout(()=>{this.sliceTimeout=void 0,!(!this.sortedList.list.childElementCount||Zs.processContact)&&u_(()=>{const e=".chatlist-chat",t=n_({overflowElement:this.scrollable.container,selector:e,extraMinLength:10}),s=t.visible,i=s[0],n=s[s.length-1],r=i?.element,o=n?.element;if(!r||!o)return;t.invisibleTop.length&&(this.scrollable.loadedAll.top=!1),t.invisibleBottom.length&&(this.scrollable.loadedAll.bottom=!1);const l=new Hg(this.scrollable,e,!!t.invisibleTop.length);l.save(),[...t.invisibleTop,...t.invisibleBottom].forEach(({element:c})=>{this.deleteDialogByKey(this.getDialogKeyFromElement(c))}),l.restore(),this.setOffsets()})},200)},this.log=Ni("CL"),this.offsets={top:0,bottom:0},this.managers=I.managers,this.listenerSetter=new $t}getOffsetIndex(e){return{index:this.scrollable.loadedAll[e]?0:this.offsets[e]}}isDialogMustBeInViewport(e){const t=this.getOffsetIndex("top"),s=this.getOffsetIndex("bottom");if(!t.index&&!s.index)return!0;const i=da(e,this.indexKey);return(!t.index||i<=t.index)&&(!s.index||i>=s.index)}setIndexKey(e){this.indexKey=e,this.sortedList.indexKey=e}deleteDialogByKey(e){this.sortedList.delete(e)}deleteDialog(e){return this.deleteDialogByKey(this.getDialogKey(e))}updateDialog(e){const t=this.getDialogKey(e);if(this.isDialogMustBeInViewport(e)){if(!this.sortedList.has(t)&&this.loadedDialogsAtLeastOnce){this.sortedList.add(t);return}}else{this.deleteDialog(e);return}const s=this.getDialogElement(t);s&&(Zs.setLastMessageN({dialog:e,dialogElement:s,setUnread:!0}),this.sortedList.update(t))}onChatsScrollTop(){return this.onChatsScroll("top")}onChatsScroll(e="bottom"){return this.loadDialogs(e)}createPlaceholder(){const e=this.placeholder=new i1(this.placeholderOptions),t=this.getRectFromForPlaceholder();return e.attach({container:this.sortedList.list.parentElement,getRectFrom:t,onRemove:()=>{this.placeholder===e&&(this.placeholder=void 0)},blockScrollable:this.scrollable}),e}loadDialogs(e){const t=this.log.bindPrefix("load-"+fg(1e3,9999));if(t("try",e),this.loadDialogsPromise||this.loadDialogsRenderPromise)return this.loadDialogsPromise;if(this.scrollable.loadedAll[e])return Promise.resolve({cached:!0,renderPromise:Promise.resolve()});t.warn("start",e);const s=Vo("MIDDLEWARE"),i=Mt(),n=new Promise(async(o,l)=>{const c=this.sortedList.list;let d=this.placeholder;try{const h=await this.loadDialogsInner(e);if(!c.childElementCount&&!d&&(!this.loadedDialogsAtLeastOnce&&this.needPlaceholderAtFirstTime||!h.cached)){if(this.loadDialogsRenderPromise!==n)throw s;d=this.createPlaceholder(),i.resolve(!1)}const p=await h.result;if(this.loadDialogsRenderPromise!==n)throw s;i.resolve(h.cached),e==="bottom"?p.isEnd&&(this.scrollable.loadedAll[e]=!0):p.isTopEnd&&(this.scrollable.loadedAll[e]=!0);const m=p.dialogs.length;if(t(`will render ${m} dialogs`),m){const v=(e==="top"?p.dialogs.slice().reverse():p.dialogs).map(y=>this.sortedList.add(this.getDialogKey(y)));if(await Promise.all(v).catch(),this.loadDialogsRenderPromise!==n)throw s}const g=p.dialogs[e==="top"?0:m-1];g&&(this.offsets[e]=da(g,this.indexKey)),this.loadedDialogsAtLeastOnce=!0,Zs.onListLengthChange(),t("getDialogs",p,c.childElementCount),setTimeout(()=>{this.scrollable.onScroll()},0),d&&d.detach(c.childElementCount)}catch(u){u?.type!=="MIDDLEWARE"&&t.error(u),l(u),i.reject(u);return}o()}).finally(()=>{this.loadDialogsRenderPromise===n?(t("end"),this.loadDialogsRenderPromise=void 0):t("has been cleared")});this.loadDialogsRenderPromise=n;const r=this.loadDialogsPromise=i.then(o=>({cached:o,renderPromise:n})).finally(()=>{this.loadDialogsPromise===r&&(this.loadDialogsPromise=void 0)});return r}async setOffsets(){const e=this.sortedList.list,[t,s]=await Promise.all([this.getDialogFromElement(e.firstElementChild),this.getDialogFromElement(e.lastElementChild)]),{indexKey:i}=this;this.offsets.top=da(t,i),this.offsets.bottom=da(s,i)}getDialogKey(e){throw Qd}getDialogKeyFromElement(e){throw Qd}getRectFromForPlaceholder(){throw Qd}getDialogFromElement(e){throw Qd}loadDialogsInner(e){throw Qd}async setTyping(e){const t=this.getDialogKey(e),s=this.getDialogDom(t);if(!s)return;const i=s.lastMessageSpan.querySelector(".peer-typing-container"),n=await Ce.getPeerTyping(e.peerId,i,Yr(e)?e.id:void 0);!i&&n&&(St(s.lastMessageSpan,n),s.lastMessageSpan.classList.add("user-typing"))}unsetTyping(e){const t=this.getDialogKey(e),s=this.getDialogElement(t);s&&(s.dom.lastMessageSpan.classList.remove("user-typing"),Zs.setLastMessageN({dialog:e,lastMessage:null,dialogElement:s,setUnread:null}))}getDialogDom(e){return this.sortedList.get(e)?.dom}getDialogElement(e){return this.sortedList.get(e)?.dialogElement}bindScrollable(){this.scrollable.container.addEventListener("scroll",this.onChatsRegularScroll),this.scrollable.onScrolledTop=this.onChatsScrollTop.bind(this),this.scrollable.onScrolledBottom=this.onChatsScroll.bind(this)}clear(){this.sortedList.clear(),this.placeholder?.remove()}reset(){this.scrollable.loadedAll.top=!0,this.scrollable.loadedAll.bottom=!1,this.offsets.top=this.offsets.bottom=0,this.loadDialogsRenderPromise=void 0,this.loadDialogsPromise=void 0}fullReset(){return this.reset(),this.clear(),this.onChatsScroll()}destroy(){this.clear(),this.scrollable.destroy(),this.listenerSetter.removeAll()}}class SU extends kw{constructor(e,t){super(),this.peerId=e,this.paddingX=t,this.placeholderOptions={avatarSize:0,marginVertical:5,totalHeight:64},this.listenerSetter.add(I)("peer_typings",async({peerId:s,threadId:i,typings:n})=>{if(!i||this.peerId!==s)return;const r=await this.managers.dialogsStorage.getForumTopic(s,i);r&&(n.length?this.setTyping(r):this.unsetTyping(r))}),this.listenerSetter.add(I)("dialogs_multiupdate",s=>{for(const[i,{dialog:n,topics:r}]of s)i!==this.peerId||!r?.size||r.forEach(o=>{this.updateDialog(o)})}),this.listenerSetter.add(I)("dialog_unread",({dialog:s})=>{!Yr(s)||s.peerId!==this.peerId||Zs.setUnreadMessagesN({dialog:s,dialogElement:this.getDialogElement(this.getDialogKey(s))})}),this.listenerSetter.add(I)("dialog_notify_settings",async s=>{if(s.peerId===this.peerId){if(Po(s)){const n=[...this.sortedList.getAll().entries()],r=n.map(([l])=>this.managers.dialogsStorage.getForumTopic(this.peerId,l)),o=await Promise.all(r);n.forEach(([l,c],d)=>{Zs.setUnreadMessagesN({dialog:o[d],dialogElement:c.dialogElement})});return}Zs.setUnreadMessagesN({dialog:s,dialogElement:this.getDialogElement(this.getDialogKey(s))})}}),this.listenerSetter.add(I)("dialog_drop",s=>{!Yr(s)||s.peerId!==this.peerId||this.deleteDialogByKey(this.getDialogKey(s))}),this.listenerSetter.add(I)("dialog_draft",({dialog:s,drop:i,peerId:n})=>{!Yr(s)||s.peerId!==this.peerId||(i?this.deleteDialog(s):this.updateDialog(s))})}isDialogMustBeInViewport(e){return e.pFlags.hidden?!1:super.isDialogMustBeInViewport(e)}getDialogKey(e){return e.id}getDialogKeyFromElement(e){return+e.dataset.threadId}getRectFromForPlaceholder(){return()=>{const e=Ri.rect,t=56;return{top:t,right:e.right,bottom:0,left:this.paddingX,width:e.width-this.paddingX,height:e.height-t}}}getDialogFromElement(e){return this.managers.dialogsStorage.getForumTopic(+e.dataset.peerId,+e.dataset.threadId)}async loadDialogsInner(e){const{indexKey:t}=this;let s=It.height/64*1.25|0,i=0;const n=this.peerId,{index:r}=this.getOffsetIndex(e);if(i=r,r)if(e==="top"){const o=await this.managers.dialogsStorage.getFolderDialogs(n,!0),l=o.findIndex(d=>da(d,t)<=r),c=Math.max(0,l-s);s=l-c,i=da(o[c],t)+1}else i=r;return this.managers.acknowledged.dialogsStorage.getDialogs({offsetIndex:i,limit:s,filterId:n,skipMigrated:!!HE})}}class CU extends kw{constructor(e){super(),this.filterId=e,this.needPlaceholderAtFirstTime=!0,this.listenerSetter.add(I)("peer_typings",async({peerId:t,typings:s})=>{const[i,n]=await Promise.all([this.managers.appMessagesManager.getDialogOnly(t),this.managers.appPeersManager.isForum(t)]);!i||n||(s.length?this.setTyping(i):this.unsetTyping(i))}),this.listenerSetter.add(I)("user_update",async t=>{if(!this.isActive)return;const s=t.toPeerId(),i=this.getDialogDom(s);if(!i)return;const r=(await this.managers.appUsersManager.getUserStatus(t))?._==="userStatusOnline";this.setOnlineStatus(i.avatarEl.node,r)}),this.listenerSetter.add(I)("chat_update",async t=>{const s=t.toPeerId(!0);this.processDialogForCallStatus(s)}),this.listenerSetter.add(I)("dialog_flush",({dialog:t})=>{!this.isActive||!t||this.updateDialog(t)}),this.listenerSetter.add(I)("dialogs_multiupdate",t=>{if(this.isActive)for(const[s,{dialog:i,topics:n}]of t)Po(i)&&(this.updateDialog(i),Zs.processContact?.(s.toPeerId()))}),this.listenerSetter.add(I)("dialog_drop",t=>{!this.isActive||!Po(t)||(this.deleteDialogByKey(this.getDialogKey(t)),Zs.processContact?.(t.peerId))}),this.listenerSetter.add(I)("dialog_unread",({dialog:t})=>{!this.isActive||!Po(t)||this.updateDialog(t)}),this.listenerSetter.add(I)("dialog_notify_settings",t=>{!this.isActive||!Po(t)||this.updateDialog(t)}),this.listenerSetter.add(I)("dialog_draft",({dialog:t,drop:s,peerId:i})=>{!this.isActive||Yr(t)||(s?this.deleteDialog(t):this.updateDialog(t),Zs.processContact?.(i))}),this.listenerSetter.add(I)("filter_update",async t=>{if(this.isActive&&t.id===this.filterId&&!oa.has(t.id)){const s=await this.managers.dialogsStorage.getCachedDialogs(!0);await this.validateListForFilter();for(let i=0,n=s.length;i<n;++i){const r=s[i];this.updateDialog(r)}Zs.filterId===this.filterId&&Zs.fetchChatlistUpdates?.()}})}get isActive(){return Zs.xd===this}getRectFromForPlaceholder(){return this.filterId===yn?Zs.chatsContainer:Zs.folders.container}async loadDialogsInner(e){const{filterId:t,indexKey:s}=this;let i=It.height/72*1.25|0,n=0;const r=Zs.doNotRenderChatList,{index:o}=this.getOffsetIndex(e);if(o)if(e==="top"){const d=await this.managers.dialogsStorage.getFolderDialogs(t,!0),u=d.findIndex(p=>da(p,s)<=o),h=Math.max(0,u-i);i=u-h,n=da(d[h],s)+1}else n=o;const c=await this.managers.acknowledged.dialogsStorage.getDialogs({offsetIndex:n,limit:i,filterId:t,skipMigrated:!0});return r&&(c.result=Promise.reject(Vo("MIDDLEWARE"))),c}setOnlineStatus(e,t){const s="is-online",i=e.classList.contains(s);!i&&t&&e.classList.add(s),Dt({element:e,className:"is-visible",forwards:t,duration:250,onTransitionEnd:t?void 0:()=>{e.classList.remove(s)},useRafs:t&&!i?2:0})}generateScrollable(e,t){const s=t.id,i=new tn(null,"CL",500);i.container.dataset.filterId=""+s;const n=t1(t.localId),r=new rf({managers:I.managers,log:this.log,list:e,indexKey:n,onListLengthChange:()=>{i.onSizeChange(),Zs.onListLengthChange?.()}});return this.scrollable=i,this.sortedList=r,this.setIndexKey(n),this.bindScrollable(),i}testDialogForFilter(e){return!(oa.has(this.filterId)?this.filterId!==e.folder_id:da(e,this.indexKey)===void 0)}isDialogMustBeInViewport(e){return e.migratedTo!==void 0||!this.testDialogForFilter(e)?!1:super.isDialogMustBeInViewport(e)}async validateListForFilter(){this.sortedList.getAll().forEach(async e=>{const t=await I.managers.appMessagesManager.getDialogOnly(e.id);this.testDialogForFilter(t)||this.deleteDialog(t)})}updateDialog(e){if(!this.testDialogForFilter(e)){this.getDialogElement(e.peerId)&&this.deleteDialog(e);return}return super.updateDialog(e)}setCallStatus(e,t){let{callIcon:s,listEl:i}=e;if(!s&&t){const{canvas:n,startAnimation:r}=e.callIcon=s=bU(i.classList.contains("active"));n.classList.add("dialog-group-call-icon"),i.append(n),r()}s&&Dt({element:e.callIcon.canvas,className:"is-visible",forwards:t,duration:ag,onTransitionEnd:t?void 0:()=>{e.callIcon.canvas.remove(),e.callIcon=void 0},useRafs:t?2:0})}processDialogForCallStatus(e,t){if(!Uh||(t||(t=this.getDialogDom(e)),!t))return;const s=Ae.getChat(e.toChatId());this.setCallStatus(t,!!(s.pFlags.call_active&&s.pFlags.call_not_empty))}onChatsScroll(e="bottom"){return this.scrollable.loadedAll[e]&&Zs.loadContacts?.(),this.log("onChatsScroll",e),super.onChatsScroll(e)}toggleAvatarUnreadBadges(e,t){if(!e){this.sortedList.getAll().forEach(i=>{const{dom:n,dialogElement:r}=i;n.unreadAvatarBadge&&r.toggleBadgeByKey("unreadAvatarBadge",!1,!1,!1)});return}const s=["unread","mention"];this.sortedList.getAll().forEach(i=>{const{dom:n,dialogElement:r}=i,o=n.unreadBadge?.textContent;if(!o||n.unreadBadge.classList.contains("backwards")||n.unreadBadge.classList.contains("dialog-pinned-icon"))return;const l=!!n.unreadAvatarBadge;r.createUnreadAvatarBadge(),r.toggleBadgeByKey("unreadAvatarBadge",!0,l),n.unreadAvatarBadge.textContent=o;const c=n.unreadAvatarBadge.classList,d=n.unreadBadge.classList;s.forEach(u=>{c.toggle(u,d.contains(u))})})}getDialogKey(e){return e.peerId}getDialogKeyFromElement(e){return+e.dataset.peerId}getDialogFromElement(e){return I.managers.appMessagesManager.getDialogOnly(e.dataset.peerId.toPeerId())}}class VM extends kw{constructor(){super(),this.listenerSetter.add(I)("dialogs_multiupdate",e=>{let t=!1;for(const[s,{saved:i}]of e)i?.forEach(n=>{t=!0,this.updateDialog(n)});t&&this.onAnyUpdate?.()}),this.listenerSetter.add(I)("dialog_drop",e=>{pr(e)&&(this.deleteDialogByKey(this.getDialogKey(e)),this.onAnyUpdate?.())})}getRectFromForPlaceholder(){return Zs.chatsContainer}async loadDialogsInner(e){const{indexKey:t}=this;let s=It.height/72*1.25|0,i=0;const n=I.myId,{index:r}=this.getOffsetIndex(e);if(i=r,r)if(e==="top"){const o=await this.managers.dialogsStorage.getFolderDialogs(n),l=o.findIndex(d=>da(d,t)<=r),c=Math.max(0,l-s);s=l-c,i=da(o[c],t)+1}else i=r;return this.managers.acknowledged.dialogsStorage.getDialogs({offsetIndex:i,limit:s,filterId:n,skipMigrated:!0})}getDialogKey(e){return e.savedPeerId}getDialogKeyFromElement(e){return+e.dataset.peerId}getDialogFromElement(e){return I.managers.dialogsStorage.getAnyDialog(e.dataset.peerId.toPeerId(),e.dataset.threadId.toPeerId())}}const _U=void 0;class zM{constructor(){this.chatsContainer=document.getElementById("chatlist-container"),this.log=Ni("DIALOGS",Rn.Log|Rn.Error|Rn.Warn|Rn.Debug),this.folders={menu:document.getElementById("folders-tabs"),menuScrollContainer:null,container:document.getElementById("folders-container")},this.filtersRendered={},this.lastActiveElements=new Set,this.initedListeners=!1,this.xds={},this.onTabChange=()=>{const{filterId:e}=this;this.xd=this.xds[e],this.xd.reset(),this.cancelChatlistUpdatesFetching?.(),this.cancelChatlistUpdatesFetching=void 0,this.fetchChatlistUpdates=void 0;const t=this.xd.onChatsScroll();return oa.has(e)||Promise.all([this.managers.filtersStorage.getFilter(e),this.managers.apiManager.getAppConfig(),t.then(({renderPromise:s})=>s).catch(()=>{})]).then(([s,i])=>{if(s?._!=="dialogFilterChatlist"||this.filterId!==e)return;const n=(i.chatlist_update_period??3600)*1e3,r=this.filtersRendered[e];let o=r.topNotification&&!_U&&s.updatedTime||0,l=!1;this.fetchChatlistUpdates=()=>{if(o=Date.now(),l)return;l=!0,this.managers.filtersStorage.getChatlistUpdates(e).catch(()=>{}).then(d=>{if(this.filterId!==e||this.filtersRendered[e]!==r)return;const u=d?d.missing_peers.length:0;if(u){this.createTopNotification(r),r.topNotificationData={_:"chatlistUpdates",chatlistUpdates:d};const h=r.topNotification,p=P("ChatsNew",[u]);p.classList.add("primary");const m=P("ChatList.SharedFolder.Title",[p]);h.title.replaceChildren(m),h.subtitle.replaceChildren(P("ChatList.SharedFolder.Subtitle"))}this.toggleTopNotification(r,!!u)}).finally(()=>{l=!1})},this.cancelChatlistUpdatesFetching=Bb(this.fetchChatlistUpdates,()=>{const c=Date.now()-o;return n-c},!1)}),t},this._onListLengthChange=()=>{if(!this.xd.loadedDialogsAtLeastOnce||(this.checkIfPlaceholderNeeded(),this.filterId!==Fi))return;const e=this.chatList,t=e.childElementCount,s=e.parentElement.parentElement,i=e.parentElement.nextElementSibling,n=!!i.childElementCount;if(t>=10){n&&this.removeContactsPlaceholder();return}else if(n||!this.xd.scrollable.loadedAll.bottom)return;s.classList.add("with-contacts");const r=new Oe({name:"Contacts",noDelimiter:!0,fakeGradientDelimiter:!0});r.container.classList.add("sidebar-left-contacts-section","hide"),this.managers.appUsersManager.getContactsPeerIds(void 0,void 0,"online").then(o=>{let l=!1;const c=()=>{l&&r.container.classList.toggle("hide",!d.list.childElementCount),this.updateContactsLength(!0)},d=new qh({avatarSize:"abitbigger",createChatListOptions:{dialogSize:48,new:!0},autonomous:!1,onListLengthChange:c,managers:this.managers,middleware:void 0});this.loadContacts=()=>{const h=It.height/60|0;zn(o.splice(0,h),this.verifyPeerIdForContacts).then(m=>{m.forEach(g=>{d.add(g)})}),o.length||(this.loadContacts=void 0)},this.loadContacts(),this.processContact=async h=>{if(h.isAnyChat())return;const p=await this.verifyPeerIdForContacts(h),m=d.has(h);!m&&p?d.add(h):m&&!p&&d.delete(h)};const u=d.list;u.classList.add("chatlist-new"),this.setListClickListener({list:u}),r.content.append(u),l=!0,c()}),i.append(r.container)},this.verifyPeerIdForContacts=async e=>{const[t,s]=await Promise.all([this.managers.appPeersManager.isContact(e),this.managers.appMessagesManager.getDialogOnly(e)]);return t&&!s}}start(){const e=this.managers=UE();this.contextMenu=new gU(e),this.stateMiddlewareHelper=Ht(),this.folders.menuScrollContainer=this.folders.menu.parentElement,this.onListLengthChange=$i(this._onListLengthChange,100,!1,!0);const t=this.bottomPart=document.createElement("div");t.classList.add("connection-status-bottom"),t.append(this.folders.container),(this.storiesListContainer=document.createElement("div")).classList.add("stories-list"),this.forumsTabs=new Map,this.forumsSlider=document.createElement("div"),this.forumsSlider.classList.add("topics-slider"),this.chatsContainer.parentElement.parentElement.append(this.forumsSlider),pt&&bw({element:this.folders.container,onSwipe:r=>{const o=n.prevId();n(r<0?o+1:o-1)},verifyTouchTarget:()=>!this.forumTab}),this.allChatsIntlElement=new Ne.IntlElement({key:"FilterAllChatsShort"}),I.addEventListener("premium_toggle",async r=>{if(r)return;await this.managers.filtersStorage.isFilterIdAvailable(this.filterId)||n(Bn(this.filtersRendered[Fi].menu),!1)}),I.addEventListener("state_cleared",()=>{const r=oa.has(this.filterId);Ae.getState().then(async o=>{this.xd.loadedDialogsAtLeastOnce=!1,this.showFiltersPromise=void 0,r&&(this.xd.clear(),this.onTabChange()),this.onStateLoaded(o)})}),this.setFilterId(Fi),this.addFilter({id:Fi,title:{_:"textWithEntities",text:"",entities:[]},localId:Fi});const i=new io(this.folders.menuScrollContainer);t.prepend(this.folders.menuScrollContainer);const n=this.selectTab=vd(this.folders.menu,this.folders.container,async(r,o)=>{const l=r;if(r=+o.dataset.filterId||Fi,I.dispatchEventSingle("changing_folder_from_chatlist",r),!(this.filterId===-1||oa.has(r)||await this.managers.filtersStorage.isFilterIdAvailable(r)))return Ja("folders"),!1;const d=this.filterId;if(wr||(l?this.filtersNavigationItem||(this.filtersNavigationItem={type:"filters",onPop:()=>{n(0),this.filtersNavigationItem=void 0}},Pt.spliceItems(1,0,this.filtersNavigationItem)):this.filtersNavigationItem&&(Pt.removeItem(this.filtersNavigationItem),this.filtersNavigationItem=void 0)),d===r)return;this.xds[r].clear();const u=this.setFilterIdAndChangeTab(r).then(({cached:h,renderPromise:p})=>{if(h)return p});if(d!==-1)return u},()=>{for(const r in this.xds)+r!==this.filterId&&this.xds[r].clear()},void 0,i);_M({appSidebarLeft:Ri,AppChatFoldersTab:Cd,AppEditFolderTab:vr,managers:this.managers,className:"menu-horizontal-div-item",listenTo:this.folders.menu}),Ae.getState().then(r=>{const[o,l]=Ho();return rt.setPlaybackParams(o.playbackParams),rt.addEventListener("playbackParams",c=>{l("playbackParams",c)}),this.onStateLoaded(r)}),st.addEventListener("resize",()=>{this.changeFiltersAllChatsKey()}),this.chatsContainer.append(t),setTimeout(()=>{Ns.loadLottieWorkers()},200),ue.MANAGERS=I.managers=e,fs.construct(e),Ri.construct(e),Gs.construct(e),Wa.construct(e),Un.construct(e),Ce.construct(e),Cv&&cs.construct(e),new jh().construct(e,this.chatsContainer,Ri.inputSearch),this.xd=this.xds[this.filterId],Ri.onCollapsedChange()}_renderStories(){return this.chatsContainer.parentElement.parentElement.firstElementChild.after(this.storiesListContainer),aM({foldInto:document.querySelector(".item-main .input-search input"),setScrolledOn:this.chatsContainer,getScrollable:()=>this.xd.scrollable.container,listenWheelOn:this.bottomPart,offsetX:-1,resizeCallback:e=>{this.resizeStoriesList=e}})}renderStories(){this.disposeStories=wi(()=>this._renderStories(),this.storiesListContainer)}get chatList(){return this.xd.sortedList.list}setFilterId(e){this.filterId=e}async setFilterIdAndChangeTab(e){return this.setFilterId(e),this.onTabChange()}initListeners(){I.addEventListener("dialog_flush",({dialog:e})=>{e&&this.setFiltersUnreadCount()}),I.addEventListener("folder_unread",async e=>{if(e.id<0){const t=this.xd.getDialogElement(e.id);if(!t)return;this.setUnreadMessagesN({dialog:await this.managers.dialogsStorage.getDialogOnly(e.id),dialogElement:t})}else this.setFilterUnreadCount(e.id)}),I.addEventListener("contacts_update",e=>{this.processContact?.(e.toPeerId())}),Ce.addEventListener("peer_changed",({peerId:e,threadId:t,isForum:s})=>{const i={peerId:e,threadId:s||I.myId?t:void 0};for(const r of this.lastActiveElements){const o=+r.dataset.threadId||void 0,l=r.dataset.peerId.toPeerId();Ce.isSamePeer({peerId:l,threadId:o},i)||this.setDialogActive(r,!1)}Array.from(document.querySelectorAll(`[data-autonomous="0"] .chatlist-chat[data-peer-id="${e}"]`)).forEach(r=>{const o=+r.dataset.threadId||void 0;Ce.isSamePeer({peerId:e,threadId:o},i)&&this.setDialogActive(r,!0)})}),I.addEventListener("filter_update",async e=>{if(oa.has(e.id))return;if(!this.filtersRendered[e.id]){this.addFilter(e);return}const t=this.filtersRendered[e.id];Qt(t.title,await fr(e.title,t.middlewareHelper.get()))}),I.addEventListener("filter_delete",e=>{const t=this.filtersRendered[e.id];t&&(t.container.remove(),t.menu.remove(),t.middlewareHelper.destroy(),this.xds[e.id].destroy(),delete this.xds[e.id],delete this.filtersRendered[e.id],this.onFiltersLengthChange(),this.filterId===e.id&&this.selectTab(0,!1))}),I.addEventListener("filter_order",async e=>{e=e.slice(),Vs(e,yn);const t=this.folders.menu,s=await Promise.all(e.map(async i=>{const[n,r]=await Promise.all([this.managers.dialogsStorage.getDialogIndexKeyByFilterId(i),this.managers.filtersStorage.getFilter(i)]);return{indexKey:n,filter:r}}));e.forEach((i,n)=>{const{indexKey:r,filter:o}=s[n],l=this.filtersRendered[i];this.xds[i].setIndexKey(r),di(l.menu,t,o.localId),di(l.container,this.folders.container,o.localId)})}),I.addEventListener("filter_joined",e=>{const t=this.filtersRendered[e.id];this.selectTab(t.menu)}),I.addEventListener("changing_folder_from_sidebar",({id:e,dontAnimate:t})=>{const s=this.filtersRendered[e];this.selectTab(s.menu,!t)})}getTextColor(e){return e?"white":"secondary-text-color"}getPrimaryColor(e){return e?"white":"primary-color"}setDialogActiveStatus(e,t){e.classList.toggle("active",t),e.querySelectorAll(".custom-emoji-renderer").forEach(i=>{i.textColor=this.getTextColor(t)}),D_(e,this.getPrimaryColor(t))}setDialogActive(e,t){const s=e.dialogDom;this.setDialogActiveStatus(e,t),e.classList.toggle("is-forum-open",this.forumTab?.peerId===e.dataset.peerId.toPeerId()&&!e.dataset.threadId),t?this.lastActiveElements.add(e):this.lastActiveElements.delete(e),s?.callIcon&&s.callIcon.setActive(t)}async onStateLoaded(e){this.stateMiddlewareHelper.clean();const t=this.stateMiddlewareHelper.get(),s=e.filtersArr,i=s.length>oa.size;this.disposeStories?.(),this.disposeStories=this.resizeStoriesList=void 0;const n=c=>{for(const d of c)this.addFilter(d)};let r;i?n(s):r=this.managers.filtersStorage.getDialogFilters().then(n),this.doNotRenderChatList=!0;const o=this.xd.onChatsScroll(),l=Bl(t);try{await l(o)}catch{}i||this.selectTab(0,!1),r&&await l(r),this.renderStories(),this.doNotRenderChatList=void 0,this.filterId=-1,this.selectTab(0,!1),this.initedListeners||(this.initListeners(),this.initedListeners=!0),i&&this.showFiltersPromise&&await l(this.showFiltersPromise),this.managers.appNotificationsManager.getNotifyPeerTypeSettings(),await(await l(o)).renderPromise.catch(as),this.managers.appMessagesManager.fillConversations()}async setFilterUnreadCount(e){const t=this.filtersRendered[e]?.unread;if(!t)return;const{unreadUnmutedCount:s,unreadCount:i}=await this.managers.dialogsStorage.getFolderUnreadCount(e);t.classList.toggle("badge-gray",!s);const n=e===Fi?s:i;Ro(t,n?""+n:"")}setFiltersUnreadCount(){for(const e in this.filtersRendered)this.setFilterUnreadCount(+e)}l(e){const t=this.createChatList(),s=this.xds[e.id]=new CU(e.id),i=s.generateScrollable(t,e);return this.setListClickListener({list:t,onFound:null,withContext:!0}),{ul:t,xd:s,scrollable:i}}createTopNotification(e){if(e.topNotification)return;const t=e.topNotificationContainer=document.createElement("div");t.classList.add("chatlist-top-notification-container");const s=e.topNotification=new Fe({title:!0,subtitle:!0,clickable:async()=>{const i=e.topNotificationData;i._==="chatlistUpdates"&&ue.createPopup(Sb,{chatlistInvite:{...i.chatlistUpdates,already_peers:[],_:"chatlists.chatlistInviteAlready",filter_id:e.id},updating:!0})},contextMenu:{buttons:[{icon:"hide",text:"HideAboveTheList",onClick:()=>{this.managers.filtersStorage.hideChatlistUpdates(e.id).then(()=>{this.filterId===e.id&&this.fetchChatlistUpdates?.()})},verify:()=>e.topNotificationData?._==="chatlistUpdates"}]},icon:"next"});s.container.classList.add("chatlist-top-notification"),t.append(s.container)}toggleTopNotification(e,t){if(!t&&!e.topNotification)return;let s=!0;t&&(s=!!e.topNotificationContainer.parentElement,s||e.scrollable.prepend(e.topNotificationContainer)),Dt({element:e.topNotificationContainer,className:"is-visible",duration:250,forwards:t,useRafs:s?0:2,onTransitionEnd:t?void 0:()=>{e.topNotificationContainer.remove(),e.topNotification=e.topNotificationContainer=e.topNotificationData=void 0}})}addFilter(e){const{id:t}=e;if(t===yn)return;const s=this.folders.menu,i=this.filtersRendered[t];if(i){di(i.menu,s,e.localId),di(i.container,this.folders.container,e.localId);return}const n=Ht(),r=document.createElement("div");r.classList.add("menu-horizontal-div-item");const o=document.createElement("span");o.classList.add("menu-horizontal-div-item-span");const l=document.createElement("span");l.classList.add("text-super"),t===Fi?l.append(this.allChatsIntlElement.element):Qt(l,fr(e.title,n.get(),!0));const c=xo("div",20,"primary"),d=document.createElement("i");o.append(l,c,d),Ei(r),r.append(o),r.dataset.filterId=""+t,di(r,s,e.localId);const{ul:u,scrollable:h}=this.l(e);h.container.classList.add("tabs-tab","chatlist-parts");const p=document.createElement("div");p.classList.add("chatlist-top");const m=document.createElement("div");m.classList.add("chatlist-bottom"),p.append(u),h.append(p,m);const g=h.container;di(h.container,this.folders.container,e.localId),this.filtersRendered[t]={id:t,menu:r,container:g,unread:c,title:l,scrollable:h,middlewareHelper:n},this.onFiltersLengthChange()}changeFiltersAllChatsKey(){const e=this.folders.menuScrollContainer.firstElementChild,t=e.scrollWidth>e.clientWidth?"FilterAllChatsShort":"FilterAllChats";this.allChatsIntlElement.compareAndUpdate({key:t})}onFiltersLengthChange(){let e=this.showFiltersPromise;return e??(e=this.showFiltersPromise=ns(0).then(()=>{if(this.showFiltersPromise!==e)return;const s=Object.keys(this.filtersRendered).length>1,i=!this.folders.menuScrollContainer.classList.contains("hide");s!==i&&(this.folders.menuScrollContainer.classList.toggle("hide",!s),s&&!i&&this.setFiltersUnreadCount(),this.chatsContainer.classList.toggle("has-filters",s)),this.changeFiltersAllChatsKey(),this.showFiltersPromise=void 0}))}generateEmptyPlaceholder(e){const t="empty-placeholder",s=document.createElement("div");s.classList.add(t,t+"-"+e.classNameType);const i=document.createElement("div");i.classList.add(t+"-header"),ks(i,e.title);const n=document.createElement("div");return n.classList.add(t+"-subtitle"),e.subtitle&&ks(n,e.subtitle,e.subtitleArgs),s.append(i,n),{container:s,header:i,subtitle:n}}checkIfPlaceholderNeeded(){if(this.filterId===yn)return;const e=this.chatList,t=e.parentElement;let s=Array.from(t.children).find(o=>o.matches(".empty-placeholder"));const i=this.xd.scrollable.loadedAll.bottom&&!e.childElementCount;if(i&&s)return;if(!i){s&&(t.classList.remove("with-placeholder"),s.remove());return}let n,r;if(this.filterId){n=this.generateEmptyPlaceholder({title:"FilterNoChatsToDisplay",subtitle:"FilterNoChatsToDisplayInfo",classNameType:r="folder"}),s=n.container;const o=document.createElement("div"),l="📂",c=128;Xo({div:o,emoji:l,width:c,height:c}),s.prepend(o);const d=ot("btn-primary btn-color-primary btn-control",{text:"FilterHeaderEdit",icon:"settings"});J(d,async()=>{const u=Ri.createTab(vr);u.setInitFilter(await this.managers.filtersStorage.getFilter(this.filterId)),u.open()}),s.append(d)}else{n=this.generateEmptyPlaceholder({title:"ChatList.Main.EmptyPlaceholder.Title",classNameType:r="dialogs"}),s=n.container;const o=document.createElement("img");o.classList.add("empty-placeholder-dialogs-icon"),this.emptyDialogsPlaceholderSubtitle=new Ne.IntlElement({element:n.subtitle}),Promise.all([this.updateContactsLength(!1),Vn(o,"assets/img/EmptyChats.svg"),Sv()]).then(([l])=>{s.classList.add("visible"),t.classList.toggle("has-contacts",!!l)}),s.prepend(o)}t.append(s),t.classList.add("with-placeholder"),t.dataset.placeholderType=r}updateContactsLength(e){return this.updateContactsLengthPromise??(this.updateContactsLengthPromise=this.managers.appUsersManager.getContacts().then(t=>{const s=this.emptyDialogsPlaceholderSubtitle;if(s){let i,n;t.length?(i="ChatList.Main.EmptyPlaceholder.Subtitle",n=[P("Contacts.Count",[t.length])]):(i="ChatList.Main.EmptyPlaceholder.SubtitleNoContacts",n=[]),s.compareAndUpdate({key:i,args:n})}return e&&this.chatList.parentElement.classList.toggle("has-contacts",!!t.length),this.updateContactsLengthPromise=void 0,t.length}))}removeContactsPlaceholder(){const e=this.chatList,t=e.parentElement.parentElement,s=e.parentElement.nextElementSibling;t.classList.remove("with-contacts"),s.replaceChildren(),this.loadContacts=void 0,this.processContact=void 0}async toggleForumTab(e,t=this.forumTab){if(!t&&!e)return;if(t){const l=this.xd.getDialogElement(t.peerId);l&&l.dom.listEl.classList.remove("is-forum-open")}t===e&&(e=void 0),t?.toggle(!1);const s=e?.toggle(!0);if(t===this.forumTab&&(this.forumTab=e,this.onForumTabToggle?.()),e){const l=this.xd.getDialogElement(e.peerId);l&&l.dom.listEl.classList.add("is-forum-open"),Ce.selectTab(pd.CHATLIST)}s&&await s,e&&!this.forumNavigationItem?(this.forumNavigationItem={type:"forum",onPop:()=>{this.forumNavigationItem=void 0,this.toggleForumTab()}},Pt.pushItem(this.forumNavigationItem)):!e&&this.forumNavigationItem&&(Pt.removeItem(this.forumNavigationItem),this.forumNavigationItem=void 0);const i=!!e,n=s?2:void 0;this.xd.toggleAvatarUnreadBadges(i,n);const r=Mt(),o=300;Dt({element:this.forumsSlider.parentElement,className:"is-forum-visible",duration:o,forwards:i,useRafs:n,onTransitionEnd:()=>{r.resolve()}}),Al(r,o).then(()=>r.resolve())}async toggleForumTabByPeerId(e,t,s){if(e===I.myId){const u=Ri.getTab(Vl);t===!0||t===void 0&&!u?Vl.open(Ri,e,!0):(u?.peerId===e&&u.close(),Ce.setPeer({peerId:e}));return}const{managers:i}=this,n=Ri.getHistory(),r=n[n.length-1],o=await i.dialogsStorage.getDialogOnly(e);if(o&&!!o.pFlags.view_forum_as_messages){const u=Ce.chat?.peerId===e;Ce[u||!s?"setPeer":"setInnerPeer"]({type:we.Chat,peerId:e});return}let c;if(r){if(r instanceof pv&&r.peerId===e&&t){to(r.container);return}c=Ri.createTab(pv),c.open({peerId:e,managers:i});return}c=this.forumsTabs.get(e);const d=this.forumTab&&this.forumTab===c;if(t??(t=!d),t===d){t&&to(c.container);return}return t&&!c&&(c=new pv(void 0),c.init({peerId:e,managers:i}),this.forumsTabs.set(e,c),this.forumsSlider.append(c.container),c.managers=this.managers,c.eventListener.addEventListener("destroy",()=>{this.forumsTabs.delete(e)})),this.toggleForumTab(c)}openDialogInNewTab(e){const t=e.dataset.peerId.toPeerId(),s=+e.dataset.mid||void 0,i=+e.dataset.threadId||void 0,n=new URLSearchParams;n.set("p",""+t),s&&n.set("message",""+s),i&&n.set("thread",""+i);const r=`#/im?${n.toString()}`;window.open(r,"_blank")}setListClickListener({list:e,onFound:t,withContext:s=!1,autonomous:i=!1,openInner:n=!1}){let r;const o=(n?Ce.setInnerPeer:Ce.setPeer).bind(Ce),l=d=>d.closest(".avatar.has-stories"),c=()=>Ri.isCollapsed()&&!Ri.hasSomethingOpenInside();e.dataset.autonomous=""+ +i,e.addEventListener("mousedown",d=>{if(d.button!==0||!c()&&l(d.target))return;this.log("dialogs click list");const u=d.target,h=Mn(u,tc);if(!h)return;const p=h.dataset.peerId.toPeerId(),m=+h.dataset.mid||void 0,g=+h.dataset.threadId||void 0;if(t?.(h)===!1)return;if(!!h.querySelector(".is-forum")&&!d.shiftKey&&!m){this.toggleForumTabByPeerId(p,void 0,!1);return}if(d.ctrlKey||d.metaKey){this.openDialogInNewTab(h),_e(d);return}i&&(r&&!(r===h)&&this.setDialogActiveStatus(r,!1),h&&(this.setDialogActiveStatus(h,!0),r=h,this.lastActiveElements.add(h))),(!g||m)&&this.xd.sortedList.list===e&&this.xd!==this.xds[yn]&&this.toggleForumTab(),o({peerId:p,lastMsgId:m,threadId:g})},{capture:!0}),e.addEventListener("click",d=>{if(d.button===0&&_e(d),c())return;const u=l(d.target);u&&Ce.openStoriesFromAvatar(u)},{capture:!0}),s&&this.contextMenu.attach(e)}createChatList(e={}){const t=document.createElement("ul");return t.classList.add("chatlist"),e.new&&t.classList.add("chatlist-new"),e.dialogSize&&t.classList.add("chatlist-"+e.dialogSize),t}setLastMessageN(e){return this.setLastMessage(e).catch(s=>{s?.type!=="MIDDLEWARE"&&this.log.error("set last message error",s)})}getLastMessageForDialog(e,t){let s;const{peerId:i,draft:n}=e;if(!t&&(n?._==="draftMessage"&&(!i.isAnyChat()||Yr(e)||!Ae.isForum(i))&&(s=n),t=e.topMessage,t?.mid!==e.top_message)){const r=Ae.getMessageByPeer(i,e.top_message);r&&r.action?._!=="messageActionChannelJoined"&&(t=r)}return{lastMessage:t,draftMessage:s}}async setLastMessage({dialog:e,lastMessage:t,dialogElement:s,highlightWord:i,isBatch:n=!1,setUnread:r=!1,noForwardIcon:o}){if(!s&&(s=this.xd.getDialogElement(e.peerId),!s))return;const{dom:l}=s,{peerId:c}=e,d=pr(e),{deferred:u,middleware:h}=BC(l,"setLastMessagePromise"),{draftMessage:p,lastMessage:m}=this.getLastMessageForDialog(e,t),g=r!==null&&!r;if(g||this.setUnreadMessagesN({dialog:e,dialogElement:s,isBatch:n,setLastMessagePromise:u}),!m&&!p){l.lastMessageSpan.replaceChildren(),l.lastTimeSpan.replaceChildren(),delete l.listEl.dataset.mid,u.resolve();return}g&&m&&(l.listEl.dataset.mid=""+m.mid,m.reply_to?.pFlags?.forum_topic&&(l.listEl.dataset.threadId=""+yr(m)));const f=!!m&&P_(m);{let v,y=[],w;if(p||(m?.fwdFromId&&!d&&!o?w="forward_filled":m?.reply_to?._==="messageReplyStoryHeader"&&(w="storyreply")),w){const L=Be(w,"dialog-subtitle-ico","dialog-subtitle-ico-"+w);y.push(L)}if(m&&!p&&!f){const L=Vi(m,!0),E=new Set(["video","gif","round"]);if(L&&(L._==="photo"||E.has(L.type))){const x=ha(L,20,20);if(x._!=="photoSizeEmpty"&&(v=document.createElement("div"),v.classList.add("dialog-subtitle-media"),L.type==="round"&&v.classList.add("is-round"),y.push(Bi({photo:L,message:m,container:v,withoutPreloader:!0,size:x}).then(()=>v)),E.has(L.type))){const R=Be("play","dialog-subtitle-media-play");v.append(R)}}}if(p){const L=document.createElement("span");L.classList.add("danger"),L.append(P("Draft"),": "),y.unshift(L)}else if(c.isAnyChat()&&c!==m.fromId&&!m.action){const L=document.createElement("span");if(L.classList.add("primary-text"),m.fromId===I.myId)L.append(P("FromYou")),y.unshift(L);else{const E=h(qe({peerId:m.fromId,onlyFirstName:!0})).then(x=>(L.prepend(x),L),as);y.unshift(E)}L.append(": ")}const b=!!v&&!!m?.message,S={textColor:this.getTextColor(l.listEl.classList.contains("active"))};let _,M;i&&m?.message?M=To({...S,message:m,highlightWord:i,withoutMediaType:b}):p?M=To({...S,message:p}):m?M=To({...S,message:m,withoutMediaType:b}):_=document.createDocumentFragment(),M&&(_=await h(M)),y.length&&(y=await h(Promise.all(y))),l.lastMessageSpan.classList.toggle("dialog-subtitle-flex",!0);{const L=[...y,_].map((E,x,R)=>{const B=document.createElement("span");return B.classList.add("dialog-subtitle-span"),B.classList.add("dialog-subtitle-span-overflow"),x===R.length-1&&(B.classList.add("dialog-subtitle-span-last"),B.dir="auto"),B.append(E),B});l.lastMessageSpan.replaceChildren(...L)}}if(m||p){const v=p?Math.max(p.date,m?.date||0):m.date;St(l.lastTimeSpan,Au(new Date(v*1e3)))}else l.lastTimeSpan.textContent="";u.resolve()}setUnreadMessagesN(e){return this.setUnreadMessages(e).catch(()=>{})}async setUnreadMessages({dialog:e,dialogElement:t,isBatch:s=!1,setLastMessagePromise:i}){const{dom:n}=t;if(!n)return;const r=Yr(e),o=pr(e),{deferred:l,middleware:c}=BC(n,"setUnreadMessagePromise"),{peerId:d}=e,u=Promise.all([this.managers.appNotificationsManager.isPeerLocalMuted({peerId:d,respectType:!0,threadId:r?e.id:void 0}),o?void 0:this.getLastMessageForDialog(e),r||o?!!e.pFlags.pinned:this.managers.dialogsStorage.isDialogPinned(d,this.filterId),this.managers.appMessagesManager.isDialogUnread(e),d.isAnyChat()&&!r?this.managers.acknowledged.dialogsStorage.getForumUnreadCount(d,!0).then(z=>z.cached?z.result:(z.result.then(()=>{this.setUnreadMessagesN({dialog:e,dialogElement:t})}),{count:0,hasUnmuted:!1})).catch(()=>{}):void 0]);let[h,p,m,g,f]=await c(u);const v=n.listEl.classList.contains("is-muted")&&!n.listEl.classList.contains("backwards"),{count:y,hasUnmuted:w}=f||{},{draftMessage:b,lastMessage:S}=p||{};let _;!b&&S&&S.pFlags.out&&S.peerId!==I.myId&&(_=S);const M=y??(o?0:e.unread_count);if(y!==void 0&&(g=!!M),r&&!g&&(g=!An(e.read_inbox_max_id)),i)try{await c(i)}catch{return}const C=s?0:ag;n.listEl.classList.toggle("no-unmuted-topic",!h&&w!==void 0&&!w),h!==v&&(h&&!n.mutedIcon&&(n.mutedIcon=Be("nosound","dialog-muted-icon"),n.titleSpanContainer.append(n.mutedIcon)),Dt({element:n.listEl,className:"is-muted",forwards:h,duration:C,onTransitionEnd:h?void 0:()=>{n.mutedIcon.remove(),delete n.mutedIcon}})),fU(n.statusSpan,r&&e.pFlags.closed?"premium_lock":_);const L=m,E=!!n.pinnedBadge;L&&t.createPinnedBadge();const x=g,R=!!n.unreadBadge;x&&t.createUnreadBadge();const B=this.xd!==this.xds[yn]&&!r&&(!!this.forumTab||Ri.isCollapsed())&&this.xd.getDialogElement(d)===t&&g,N=!!n.unreadAvatarBadge;B&&t.createUnreadAvatarBadge();const G=o?!1:e.unread_mentions_count&&(e.unread_mentions_count>1||e.unread_count>1),O=!!n.mentionsBadge;G&&t.createMentionsBadge();const $=o?!1:!!e.unread_reactions_count,H=!!n.reactionsBadge;$&&t.createReactionsBadge();const D=[L,x,G,$].filter(Boolean).length;if(Dt({element:t.subtitleRow,className:"has-only-pinned-badge",forwards:L&&D===1,duration:s?0:ag}),[["pinnedBadge",L,E],["unreadBadge",x,R],["unreadAvatarBadge",B,N],["mentionsBadge",G,O],["reactionsBadge",$,H]].forEach(([z,Z,de])=>{n[z]&&t.toggleBadgeByKey(z,Z,de,s)}),!x){l.resolve();return}let j=!0,q=!1,W;if(!o&&e.unread_mentions_count&&M===1?(W="@",q=!0):g?W=""+(M?un(M,1):" "):(W="",j=!1),r){const z=g&&W===" ";n.unreadBadge.classList.toggle("not-visited",z)}[n.unreadBadge&&[n.unreadBadge,W],n.unreadAvatarBadge&&[n.unreadAvatarBadge,W||void 0]].filter(Boolean).forEach(([z,Z])=>{Z!==void 0&&(z.innerText=W),z.classList.toggle("unread",j),z.classList.toggle("mention",q)}),l.resolve()}async getDialog(e,t){if(typeof e!="object"){let s;if(t){if(e===I.myId){if(s=await this.managers.dialogsStorage.getAnyDialog(e,t),!s)return{peerId:e||Wt,pFlags:{}}}else if(s=await this.managers.dialogsStorage.getForumTopic(e,t),!s)return{peerId:e||Wt,pFlags:{}}}else if(s=await this.managers.appMessagesManager.getDialogOnly(e),!s){const i=e||Wt;return{peerId:i,peer:await this.managers.appPeersManager.getOutputPeer(i),pFlags:{}}}return s}return e}addListDialog(e){e.autonomous=!1,e.withStories=!0;const t=this.addDialogNew(e);if(t){const{peerId:s}=e,n=this.getDialog(s,e.threadId).then(r=>{const o=[],l=s.isUser();return!l&&Po(r)&&o.push(this.xd.processDialogForCallStatus(s,t.dom)),s!==I.myId&&l&&o.push(this.managers.appUsersManager.getUserStatus(s.toUserId()).then(c=>{c?._==="userStatusOnline"&&this.xd.setOnlineStatus(t.dom.avatarEl.node,!0)})),o.push(this.setLastMessageN({dialog:r,dialogElement:t,isBatch:e.isBatch,setUnread:!0})),Promise.all(o)});e.loadPromises?.push(n)}return t}addDialogAndSetLastMessage(e){const{peerId:t,message:s,query:i}=e,n=this.addDialogNew({...e,...d1(s),peerId:t});return this.setLastMessageN({dialog:{_:"dialog",peerId:t},lastMessage:s,dialogElement:n,highlightWord:i}),s.peerId!==t&&(n.dom.listEl.dataset.peerId=""+s.peerId),n}addDialogNew(e){const t=new rg({autonomous:!!e.container,avatarSize:"bigger",...e});if(t.container.dialogElement=t,e.container){const s=e.append===!1?"prepend":"append";e.container[s](t.container)}return t}}const Zs=new zM;Di.appDialogsManager=Zs;const nt=Zs,OU=Object.freeze(Object.defineProperty({__proto__:null,AppDialogsManager:zM,DIALOG_LIST_ELEMENT_TAG:tc,DialogElement:rg,Some4:VM,SortedDialogList:rf,default:nt},Symbol.toStringTag,{value:"Module"}));export{hs as I,uI as L,cy as P,En as R,Ms as S,NU as a,xi as b,Rt as c,Uo as d,Rm as e,OU as f,no as h,Jr as n,$e as t,$U as u};
- //# sourceMappingURL=appDialogsManager-B7M3PQZv.js.map
|