const __vite__fileDeps=["./chart-BIax9IsQ.js","./chart-CQQX2xOH.css"],__vite__mapDeps=i=>i.map(i=>__vite__fileDeps[i]); var YI=Object.defineProperty;var XI=(o,e,t)=>e in o?YI(o,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):o[e]=t;var Lr=(o,e,t)=>(XI(o,typeof e!="symbol"?e+"":e,t),t),dy=(o,e,t)=>{if(!e.has(o))throw TypeError("Cannot "+t)};var Bt=(o,e,t)=>(dy(o,e,"read from private field"),t?t.call(o):e.get(o)),ds=(o,e,t)=>{if(e.has(o))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(o):e.set(o,t)},Ft=(o,e,t,s)=>(dy(o,e,"write to private field"),s?s.call(o,t):e.set(o,t),t);import{i as D,c as Ce,b as pa,s as Ti,u as wt,d as uo,t as ce,P as ee,e as fr,B as it,a as yb,f as Eu,g as ZI,h as wn,r as Sg,j as kc,D as Cg,k as Ui,l as Hi,m as _u,n as zi,o as Pl,p as JI,q as eL}from"./avatar-QMf5nvPE.js";import{a as N,i as ca,h as Ig,f as Ns,C as Go,s as Sd,b as Ba,T as Na,w as Ri,g as As,c as ll,d as fs,F as Rh,e as vb,j as Lg,k as Ml,u as Pg,l as Xr,m as Mg,n as tL}from"./page-NWzulROZ.js";import{I as Le,s as Dh,r as Ni,B as ze,a as po,g as bb}from"./button-DUmZNV0E.js";import{S as vi,a as yr}from"./scrollable-C20Fr3mN.js";import{a as I,b as fe,f as ke,d as Zt,m as $e,q as sL,t as pi,i as M,u as Eg,v as _g,N as Tt,w as iL,T as ac,x as kg,y as cl,z as Tg,B as wh,C as K,j as Pt,F as Et,G as oa,H as Jt,J as ye,K as $s,L as El,O as ut,P as ne,Q as wb,R as Cd,U as pm,V as kt,W as Bh,X as xg,Y as Ag,Z as us,$ as Oa,a0 as Id,a1 as It,a2 as Fg,a3 as as,a4 as _n,a5 as Sb,k as st,e as oe,n as bs,a6 as Rg,a7 as vs,a8 as nL,a9 as aL,aa as Wt,ab as U,ac as j,ad as Ve,ae as an,af as Ai,ag as Tc,ah as cr,ai as Ls,aj as ei,E as Si,I as Je,ak as Ua,al as ft,am as Li,an as Oi,ao as Zr,ap as Cb,aq as Ms,ar as Qn,as as Kt,g as mm,D as $i,at as ir,au as ri,A as rc,av as Ib,aw as Nh,ax as mo,ay as Ld,p as Hs,az as Gi,aA as Oh,aB as Lb,aC as lt,s as Jr,r as Pd,aD as Wi,aE as Di,aF as ws,M as Ws,aG as Pi,aH as gm,aI as rL,aJ as Pb,aK as oL,aL as Mb,aM as dl,aN as Md,aO as _a,aP as Dg,aQ as hi,aR as lL,aS as ma,aT as cL,aU as Eb,aV as ti,aW as zo,h as Dn,aX as dL,aY as Mp,aZ as fm,a_ as ka,a$ as yn,b0 as hL,b1 as _b,b2 as Xn,b3 as xc,b4 as Vr,_ as uL,b5 as oc,b6 as vr,b7 as eo,b8 as Ac,b9 as pL,ba as ku,bb as Fc,o as ym,bc as xa,bd as mL,be as kb,bf as Tb,bg as xb,bh as Uh,bi as gL,bj as fL,bk as yL,bl as vm,bm as Ci,bn as Hh,bo as $h,bp as bm,bq as Ja,br as vL,bs as hy,bt as bL,bu as Vh,bv as Sh,bw as wL,bx as Ab,by as SL,bz as CL,bA as IL,bB as wm,bC as Xd,bD as LL,bE as PL,bF as uy,bG as ML,bH as EL,bI as Rc,bJ as Tu,bK as Ao,bL as Gs,bM as _L,bN as di,bO as Qi,bP as kL,bQ as Sm,bR as No,bS as TL,bT as xL,bU as AL,S as Gr,bV as FL,bW as Fb,bX as ra,bY as Vi,bZ as RL,b_ as py,b$ as DL,c0 as Cm,c1 as BL,c2 as NL,c3 as pn,c4 as Rb,c5 as OL,c6 as UL,c7 as HL,c8 as $L,c9 as VL,ca as GL,c as Zd,cb as zL,cc as KL,cd as WL,ce as jL,cf as qL,cg as Db,ch as QL,ci as YL}from"./index-CbCftUfG.js";import{w as _e,a as Rs,e as XL,b as ZL,c as Yt,d as Ko,m as Qr,g as xt,s as my,r as dt,l as _s,f as Ki,h as Im,i as Bb,j as Sn,k as hl,n as cs,o as Nb,q as JL,u as Kn,t as jt,L as Ut,v as bi,I as _t,x as gn,p as Zs,y as Ch,z as ga,A as Bi,B as go,C as yi,D as gt,E as Wn,F as wi,G as e0,H as Ob,J as Bg,K as fo,R as Ih,M as Ng,S as Ub,N as Ga,O as Hb,V as xu,P as Og,Q as Ug,T as gy,U as $b,W as Hg,X as t0,Y as Vb,Z as Dc,_ as s0,$ as Gb,a0 as Lm,a1 as i0,a2 as zb,a3 as Gh,a4 as n0,a5 as a0,a6 as fn,a7 as Au,a8 as r0,a9 as Pm,aa as o0,ab as l0,ac as c0,ad as d0,ae as h0,af as Kb,ag as u0,ah as Ep}from"./wrapEmojiText-CZyOyt8f.js";import{s as $g,p as rn}from"./putPreloader-YG6jLs1E.js";import{h as Vg,b as p0,P as Gg,a as m0}from"./htmlToSpan-D4DA0RUe.js";import{a as pt,g as g0,C as f0,f as _l,T as Wb,b as y0}from"./countryInputField-Dm2t4SUk.js";import{t as v0,b as b0}from"./textToSvgURL-Cnw_Q8Rw.js";import w0 from"./fastBlur-Co-79rP4.js";import{C as S0,T as C0}from"./codeInputField-4BUMrXlT.js";function Aa(o,e,t=e+10){return o=o.trim(),o.length>t&&(o=o.slice(0,e)+"..."),o}function ui(o){if(!o)return[];const e=o.usernames;return e?e.filter(t=>t.pFlags.active).map(t=>t.username):o.username?[o.username]:[]}async function ar(o){const{peerId:e=I.myId,plainText:t,onlyFirstName:s,limitSymbols:i,managers:n=I.managers,threadId:a}=o;let r="";if(e.isUser()){const l=fe.getUser(e.toUserId());l&&(l.first_name&&(r+=l.first_name),l.last_name&&(!s||!r)&&(r+=" "+l.last_name)),r?r=r.trim():r=!l||l.pFlags.deleted?ke.format(s?"Deleted":"HiddenName",!0):ui(l)[0]||""}else a&&(r=(await n.dialogsStorage.getForumTopic(e,a))?.title||""),r||(r=fe.getChat(e.toChatId())?.title||""),s&&(r=r.split(" ")[0]);return i!==void 0&&(r=Aa(r,i,i)),t?r:_e(r)}function jb(o){const e=document.createElement("span");return e.classList.add("badge-fake"),Zt(e,o?"ScamMessage":"FakeMessage"),e}function I0(){return Le("star","premium-icon")}function L0(){const o=document.createElement("span");o.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),o.append(t),o}async function qb({wrapOptions:o,emojiStatus:e,size:t=$e.active.emojiStatus}){const{middleware:s,animationGroup:i,textColor:n}=o,a=document.createElement("span");a.classList.add("emoji-status");const r=await I.managers.acknowledged.appEmojiManager.getCustomEmojiDocument(e.document_id),l=async d=>{if(!s())return;const h=[],u=d.attributes.find(p=>p._==="documentAttributeCustomEmoji");u&&u.pFlags.text_color&&a.classList.add("emoji-status-text-color"),await Rs({doc:d,div:a,width:t.width,height:t.height,loop:2,play:!0,group:i||"EMOJI-STATUS",loadPromises:h,middleware:s,static:d.mime_type==="video/webm"&&!sL,textColor:n||"primary-color"}),s()&&await Promise.all(h)};if(!s())return a;const c=r.result.then(l);return r.cached&&await c,a}async function Mm({peerId:o,noVerifiedIcon:e,noFakeIcon:t,noPremiumIcon:s,peer:i,wrapOptions:n}){i??(i=fe.getPeer(o));const a=[];if(!i)return a;if((i.pFlags.fake||i.pFlags.scam)&&!t&&a.push(jb(i.pFlags.scam)),!s&&n?.middleware){const r=i.emoji_status,l=await fe.isPremiumFeaturesHidden();if(r&&r._!=="emojiStatusEmpty"&&!l){const{middleware:c}=n,d=await qb({emojiStatus:r,wrapOptions:n});if(!c())return a;a.push(d)}else i.pFlags.premium&&!l&&a.push(I0())}return i.pFlags.verified&&!e&&a.push(L0()),a}var Xi=(o=>(o[o.Seconds=0]="Seconds",o[o.Minutes=1]="Minutes",o[o.Hours=2]="Hours",o[o.Days=3]="Days",o[o.Weeks=4]="Weeks",o[o.Months=5]="Months",o[o.Years=6]="Years",o))(Xi||{});function yo(o,e=2){o||(o=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((r,l)=>{if(n=Math.round(n*r.m),o=0;--r)a[r].duration===0&&a.splice(r,1);return a}function Fi(o,e=!1){const t=parseInt(o+"",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 fy={[Xi.Seconds]:"Seconds",[Xi.Minutes]:"Minutes",[Xi.Hours]:"Hours",[Xi.Days]:"Days",[Xi.Weeks]:"Weeks",[Xi.Months]:"Months",[Xi.Years]:"Years"};function kl(o,e){if(e){const i=o.map(n=>ke.format(fy[n.type],!0,[n.duration]));return pi(i,!1,e)}const t=o.map(i=>M(fy[i.type],[i.duration])),s=document.createElement("span");return s.append(...pi(t,!1)),s}function Lh(o,e){return kl(yo(o,2),e)}function Qb(o){const e=yo(o,3);return e[0].type<=Xi.Hours?Fi(o,!0):(e.splice(1,1/0),kl(e))}function Yb(o){const e=yo(o,3);return e[0].type===Xi.Seconds?kl(e):Fi(o,!0)}const Xb={AED:{code:"AED",title:"United Arab Emirates Dirham",symbol:"AED",native:"د.إ.‏",thousands_sep:",",decimal_sep:".",symbol_left:!0,space_between:!0,exp:2,min_amount:"367",max_amount:"3673030"},AFN:{code:"AFN",title:"Afghan Afghani",symbol:"AFN",native:"؋",thousands_sep:",",decimal_sep:".",symbol_left:!0,space_between:!1,exp:2,min_amount:"8729",max_amount:"87299487"},ALL:{code:"ALL",title:"Albanian Lek",symbol:"ALL",native:"Lek",thousands_sep:".",decimal_sep:",",symbol_left:!1,space_between:!1,exp:2,min_amount:"11842",max_amount:"118421187"},AMD:{code:"AMD",title:"Armenian Dram",symbol:"AMD",native:"դր.",thousands_sep:",",decimal_sep:".",symbol_left:!1,space_between:!0,exp:2,min_amount:"40943",max_amount:"409436718"},ARS:{code:"ARS",title:"Argentine Peso",symbol:"ARS",native:"$",thousands_sep:".",decimal_sep:",",symbol_left:!0,space_between:!0,exp:2,min_amount:"14705",max_amount:"147059002"},AUD:{code:"AUD",title:"Australian Dollar",symbol:"AU$",native:"$",thousands_sep:",",decimal_sep:".",symbol_left:!0,space_between:!1,exp:2,min_amount:"153",max_amount:"1536825"},AZN:{code:"AZN",title:"Azerbaijani Manat",symbol:"AZN",native:"ман.",thousands_sep:" ",decimal_sep:",",symbol_left:!1,space_between:!0,exp:2,min_amount:"169",max_amount:"1699858"},BAM:{code:"BAM",title:"Bosnia & Herzegovina Convertible Mark",symbol:"BAM",native:"KM",thousands_sep:".",decimal_sep:",",symbol_left:!1,space_between:!0,exp:2,min_amount:"199",max_amount:"1990677"},BDT:{code:"BDT",title:"Bangladeshi Taka",symbol:"BDT",native:"৳",thousands_sep:",",decimal_sep:".",symbol_left:!0,space_between:!0,exp:2,min_amount:"10009",max_amount:"100094046"},BGN:{code:"BGN",title:"Bulgarian Lev",symbol:"BGN",native:"лв.",thousands_sep:" ",decimal_sep:",",symbol_left:!1,space_between:!0,exp:2,min_amount:"199",max_amount:"1993315"},BND:{code:"BND",title:"Brunei Dollar",symbol:"BND",native:"$",thousands_sep:".",decimal_sep:",",symbol_left:!0,space_between:!1,exp:2,min_amount:"142",max_amount:"1421883"},BOB:{code:"BOB",title:"Bolivian Boliviano",symbol:"BOB",native:"Bs",thousands_sep:".",decimal_sep:",",symbol_left:!0,space_between:!0,exp:2,min_amount:"683",max_amount:"6832607"},BRL:{code:"BRL",title:"Brazilian Real",symbol:"R$",native:"R$",thousands_sep:".",decimal_sep:",",symbol_left:!0,space_between:!0,exp:2,min_amount:"539",max_amount:"5397799"},BYN:{code:"BYN",title:"Belarusian ruble",symbol:"BYN",native:"BYN",thousands_sep:" ",decimal_sep:",",symbol_left:!1,space_between:!0,exp:2,min_amount:"249",max_amount:"2495801"},CAD:{code:"CAD",title:"Canadian Dollar",symbol:"CA$",native:"$",thousands_sep:",",decimal_sep:".",symbol_left:!0,space_between:!1,exp:2,min_amount:"136",max_amount:"1366860"},CHF:{code:"CHF",title:"Swiss Franc",symbol:"CHF",native:"CHF",thousands_sep:"'",decimal_sep:".",symbol_left:!1,space_between:!0,exp:2,min_amount:"97",max_amount:"976705"},CLP:{code:"CLP",title:"Chilean Peso",symbol:"CLP",native:"$",thousands_sep:".",decimal_sep:",",symbol_left:!0,space_between:!0,exp:0,min_amount:"963",max_amount:"9637495"},CNY:{code:"CNY",title:"Chinese Renminbi Yuan",symbol:"CN¥",native:"CN¥",thousands_sep:",",decimal_sep:".",symbol_left:!0,space_between:!1,exp:2,min_amount:"709",max_amount:"7094102"},COP:{code:"COP",title:"Colombian Peso",symbol:"COP",native:"$",thousands_sep:".",decimal_sep:",",symbol_left:!0,space_between:!0,exp:2,min_amount:"452870",max_amount:"4528700000"},CRC:{code:"CRC",title:"Costa Rican Colón",symbol:"CRC",native:"₡",thousands_sep:".",decimal_sep:",",symbol_left:!0,space_between:!1,exp:2,min_amount:"62506",max_amount:"625061070"},CZK:{code:"CZK",title:"Czech Koruna",symbol:"CZK",native:"Kč",thousands_sep:" ",decimal_sep:",",symbol_left:!1,space_between:!0,exp:2,min_amount:"2497",max_amount:"24975029"},DKK:{code:"DKK",title:"Danish Krone",symbol:"DKK",native:"kr",thousands_sep:"",decimal_sep:",",symbol_left:!1,space_between:!0,exp:2,min_amount:"755",max_amount:"7555990"},DOP:{code:"DOP",title:"Dominican Peso",symbol:"DOP",native:"$",thousands_sep:",",decimal_sep:".",symbol_left:!0,space_between:!1,exp:2,min_amount:"5275",max_amount:"52757308"},DZD:{code:"DZD",title:"Algerian Dinar",symbol:"DZD",native:"د.ج.‏",thousands_sep:",",decimal_sep:".",symbol_left:!0,space_between:!0,exp:2,min_amount:"14035",max_amount:"140353307"},EGP:{code:"EGP",title:"Egyptian Pound",symbol:"EGP",native:"ج.م.‏",thousands_sep:",",decimal_sep:".",symbol_left:!0,space_between:!0,exp:2,min_amount:"1953",max_amount:"19537405"},ETB:{code:"ETB",title:"Ethiopian Birr",symbol:"ETB",native:"ብር",thousands_sep:",",decimal_sep:".",symbol_left:!0,space_between:!1,exp:2,min_amount:"5224",max_amount:"52247069"},EUR:{code:"EUR",title:"Euro",symbol:"€",native:"€",thousands_sep:" ",decimal_sep:",",symbol_left:!1,space_between:!0,exp:2,min_amount:"101",max_amount:"1016045"},GBP:{code:"GBP",title:"British Pound",symbol:"£",native:"£",thousands_sep:",",decimal_sep:".",symbol_left:!0,space_between:!1,exp:2,min_amount:"89",max_amount:"894445"},GEL:{code:"GEL",title:"Georgian Lari",symbol:"GEL",native:"GEL",thousands_sep:" ",decimal_sep:",",symbol_left:!1,space_between:!0,exp:2,min_amount:"283",max_amount:"2830234"},GTQ:{code:"GTQ",title:"Guatemalan Quetzal",symbol:"GTQ",native:"Q",thousands_sep:",",decimal_sep:".",symbol_left:!0,space_between:!1,exp:2,min_amount:"778",max_amount:"7781323"},HKD:{code:"HKD",title:"Hong Kong Dollar",symbol:"HK$",native:"$",thousands_sep:",",decimal_sep:".",symbol_left:!0,space_between:!1,exp:2,min_amount:"784",max_amount:"7849750"},HNL:{code:"HNL",title:"Honduran Lempira",symbol:"HNL",native:"L",thousands_sep:",",decimal_sep:".",symbol_left:!0,space_between:!0,exp:2,min_amount:"2441",max_amount:"24413729"},HRK:{code:"HRK",title:"Croatian Kuna",symbol:"HRK",native:"kn",thousands_sep:".",decimal_sep:",",symbol_left:!1,space_between:!0,exp:2,min_amount:"764",max_amount:"7648805"},HUF:{code:"HUF",title:"Hungarian Forint",symbol:"HUF",native:"Ft",thousands_sep:" ",decimal_sep:",",symbol_left:!1,space_between:!0,exp:2,min_amount:"42685",max_amount:"426850229"},IDR:{code:"IDR",title:"Indonesian Rupiah",symbol:"IDR",native:"Rp",thousands_sep:".",decimal_sep:",",symbol_left:!0,space_between:!1,exp:2,min_amount:"1523370",max_amount:"15233700000"},ILS:{code:"ILS",title:"Israeli New Sheqel",symbol:"₪",native:"₪",thousands_sep:",",decimal_sep:".",symbol_left:!0,space_between:!0,exp:2,min_amount:"354",max_amount:"3543350"},INR:{code:"INR",title:"Indian Rupee",symbol:"₹",native:"₹",thousands_sep:",",decimal_sep:".",symbol_left:!0,space_between:!1,exp:2,min_amount:"8155",max_amount:"81555550"},ISK:{code:"ISK",title:"Icelandic Króna",symbol:"ISK",native:"kr",thousands_sep:".",decimal_sep:",",symbol_left:!1,space_between:!0,exp:0,min_amount:"142",max_amount:"1425603"},JMD:{code:"JMD",title:"Jamaican Dollar",symbol:"JMD",native:"$",thousands_sep:",",decimal_sep:".",symbol_left:!0,space_between:!1,exp:2,min_amount:"15013",max_amount:"150131044"},JPY:{code:"JPY",title:"Japanese Yen",symbol:"¥",native:"¥",thousands_sep:",",decimal_sep:".",symbol_left:!0,space_between:!1,exp:0,min_amount:"144",max_amount:"1443065"},KES:{code:"KES",title:"Kenyan Shilling",symbol:"KES",native:"Ksh",thousands_sep:",",decimal_sep:".",symbol_left:!0,space_between:!1,exp:2,min_amount:"12075",max_amount:"120750271"},KGS:{code:"KGS",title:"Kyrgyzstani Som",symbol:"KGS",native:"KGS",thousands_sep:" ",decimal_sep:"-",symbol_left:!1,space_between:!0,exp:2,min_amount:"8018",max_amount:"80182898"},KRW:{code:"KRW",title:"South Korean Won",symbol:"₩",native:"₩",thousands_sep:",",decimal_sep:".",symbol_left:!0,space_between:!1,exp:0,min_amount:"1431",max_amount:"14315201"},KZT:{code:"KZT",title:"Kazakhstani Tenge",symbol:"KZT",native:"₸",thousands_sep:" ",decimal_sep:"-",symbol_left:!0,space_between:!1,exp:2,min_amount:"47186",max_amount:"471867112"},LBP:{code:"LBP",title:"Lebanese Pound",symbol:"LBP",native:"ل.ل.‏",thousands_sep:",",decimal_sep:".",symbol_left:!0,space_between:!0,exp:2,min_amount:"150999",max_amount:"1509998778"},LKR:{code:"LKR",title:"Sri Lankan Rupee",symbol:"LKR",native:"රු.",thousands_sep:",",decimal_sep:".",symbol_left:!0,space_between:!0,exp:2,min_amount:"35546",max_amount:"355469651"},MAD:{code:"MAD",title:"Moroccan Dirham",symbol:"MAD",native:"د.م.‏",thousands_sep:",",decimal_sep:".",symbol_left:!0,space_between:!0,exp:2,min_amount:"1093",max_amount:"10938136"},MDL:{code:"MDL",title:"Moldovan Leu",symbol:"MDL",native:"MDL",thousands_sep:",",decimal_sep:".",symbol_left:!1,space_between:!0,exp:2,min_amount:"1926",max_amount:"19264439"},MNT:{code:"MNT",title:"Mongolian Tögrög",symbol:"MNT",native:"MNT",thousands_sep:" ",decimal_sep:",",symbol_left:!0,space_between:!1,exp:2,min_amount:"322444",max_amount:"3224442056"},MUR:{code:"MUR",title:"Mauritian Rupee",symbol:"MUR",native:"MUR",thousands_sep:",",decimal_sep:".",symbol_left:!0,space_between:!1,exp:2,min_amount:"4453",max_amount:"44535174"},MVR:{code:"MVR",title:"Maldivian Rufiyaa",symbol:"MVR",native:"MVR",thousands_sep:",",decimal_sep:".",symbol_left:!1,space_between:!0,exp:2,min_amount:"1546",max_amount:"15460397"},MXN:{code:"MXN",title:"Mexican Peso",symbol:"MX$",native:"$",thousands_sep:",",decimal_sep:".",symbol_left:!0,space_between:!1,exp:2,min_amount:"2012",max_amount:"20122860"},MYR:{code:"MYR",title:"Malaysian Ringgit",symbol:"MYR",native:"RM",thousands_sep:",",decimal_sep:".",symbol_left:!0,space_between:!1,exp:2,min_amount:"463",max_amount:"4632502"},MZN:{code:"MZN",title:"Mozambican Metical",symbol:"MZN",native:"MTn",thousands_sep:",",decimal_sep:".",symbol_left:!0,space_between:!1,exp:2,min_amount:"6382",max_amount:"63829729"},NGN:{code:"NGN",title:"Nigerian Naira",symbol:"NGN",native:"₦",thousands_sep:",",decimal_sep:".",symbol_left:!0,space_between:!1,exp:2,min_amount:"43203",max_amount:"432039828"},NIO:{code:"NIO",title:"Nicaraguan Córdoba",symbol:"NIO",native:"C$",thousands_sep:",",decimal_sep:".",symbol_left:!0,space_between:!0,exp:2,min_amount:"3556",max_amount:"35566412"},NOK:{code:"NOK",title:"Norwegian Krone",symbol:"NOK",native:"kr",thousands_sep:" ",decimal_sep:",",symbol_left:!0,space_between:!0,exp:2,min_amount:"1069",max_amount:"10690975"},NPR:{code:"NPR",title:"Nepalese Rupee",symbol:"NPR",native:"नेरू",thousands_sep:",",decimal_sep:".",symbol_left:!0,space_between:!1,exp:2,min_amount:"12954",max_amount:"129546657"},NZD:{code:"NZD",title:"New Zealand Dollar",symbol:"NZ$",native:"$",thousands_sep:",",decimal_sep:".",symbol_left:!0,space_between:!1,exp:2,min_amount:"174",max_amount:"1746220"},PAB:{code:"PAB",title:"Panamanian Balboa",symbol:"PAB",native:"B/.",thousands_sep:",",decimal_sep:".",symbol_left:!0,space_between:!0,exp:2,min_amount:"98",max_amount:"988722"},PEN:{code:"PEN",title:"Peruvian Nuevo Sol",symbol:"PEN",native:"S/.",thousands_sep:",",decimal_sep:".",symbol_left:!0,space_between:!0,exp:2,min_amount:"390",max_amount:"3902208"},PHP:{code:"PHP",title:"Philippine Peso",symbol:"PHP",native:"₱",thousands_sep:",",decimal_sep:".",symbol_left:!0,space_between:!1,exp:2,min_amount:"5862",max_amount:"58627496"},PKR:{code:"PKR",title:"Pakistani Rupee",symbol:"PKR",native:"₨",thousands_sep:",",decimal_sep:".",symbol_left:!0,space_between:!1,exp:2,min_amount:"22642",max_amount:"226426805"},PLN:{code:"PLN",title:"Polish Złoty",symbol:"PLN",native:"zł",thousands_sep:" ",decimal_sep:",",symbol_left:!1,space_between:!0,exp:2,min_amount:"493",max_amount:"4932350"},PYG:{code:"PYG",title:"Paraguayan Guaraní",symbol:"PYG",native:"₲",thousands_sep:".",decimal_sep:",",symbol_left:!0,space_between:!0,exp:0,min_amount:"6977",max_amount:"69772317"},QAR:{code:"QAR",title:"Qatari Riyal",symbol:"QAR",native:"ر.ق.‏",thousands_sep:",",decimal_sep:".",symbol_left:!0,space_between:!0,exp:2,min_amount:"364",max_amount:"3640989"},RON:{code:"RON",title:"Romanian Leu",symbol:"RON",native:"RON",thousands_sep:".",decimal_sep:",",symbol_left:!1,space_between:!0,exp:2,min_amount:"502",max_amount:"5028645"},RSD:{code:"RSD",title:"Serbian Dinar",symbol:"RSD",native:"дин.",thousands_sep:".",decimal_sep:",",symbol_left:!1,space_between:!0,exp:2,min_amount:"11918",max_amount:"119184990"},RUB:{code:"RUB",title:"Russian Ruble",symbol:"RUB",native:"₽",thousands_sep:" ",decimal_sep:",",symbol_left:!1,space_between:!0,exp:2,min_amount:"7128",max_amount:"71281218"},SAR:{code:"SAR",title:"Saudi Riyal",symbol:"SAR",native:"ر.س.‏",thousands_sep:",",decimal_sep:".",symbol_left:!0,space_between:!0,exp:2,min_amount:"375",max_amount:"3756546"},SEK:{code:"SEK",title:"Swedish Krona",symbol:"SEK",native:"kr",thousands_sep:".",decimal_sep:",",symbol_left:!1,space_between:!0,exp:2,min_amount:"1109",max_amount:"11094972"},SGD:{code:"SGD",title:"Singapore Dollar",symbol:"SGD",native:"$",thousands_sep:",",decimal_sep:".",symbol_left:!0,space_between:!1,exp:2,min_amount:"143",max_amount:"1430495"},THB:{code:"THB",title:"Thai Baht",symbol:"฿",native:"฿",thousands_sep:",",decimal_sep:".",symbol_left:!0,space_between:!1,exp:2,min_amount:"3780",max_amount:"37800497"},TJS:{code:"TJS",title:"Tajikistani Somoni",symbol:"TJS",native:"TJS",thousands_sep:" ",decimal_sep:";",symbol_left:!1,space_between:!0,exp:2,min_amount:"975",max_amount:"9753854"},TRY:{code:"TRY",title:"Turkish Lira",symbol:"TRY",native:"TL",thousands_sep:".",decimal_sep:",",symbol_left:!1,space_between:!0,exp:2,min_amount:"1854",max_amount:"18543598"},TTD:{code:"TTD",title:"Trinidad and Tobago Dollar",symbol:"TTD",native:"$",thousands_sep:",",decimal_sep:".",symbol_left:!0,space_between:!1,exp:2,min_amount:"672",max_amount:"6722681"},TWD:{code:"TWD",title:"New Taiwan Dollar",symbol:"NT$",native:"NT$",thousands_sep:",",decimal_sep:".",symbol_left:!0,space_between:!1,exp:2,min_amount:"3173",max_amount:"31738502"},TZS:{code:"TZS",title:"Tanzanian Shilling",symbol:"TZS",native:"TSh",thousands_sep:",",decimal_sep:".",symbol_left:!0,space_between:!1,exp:2,min_amount:"233199",max_amount:"2331999890"},UAH:{code:"UAH",title:"Ukrainian Hryvnia",symbol:"UAH",native:"₴",thousands_sep:" ",decimal_sep:",",symbol_left:!1,space_between:!1,exp:2,min_amount:"3633",max_amount:"36338830"},UGX:{code:"UGX",title:"Ugandan Shilling",symbol:"UGX",native:"USh",thousands_sep:",",decimal_sep:".",symbol_left:!0,space_between:!1,exp:0,min_amount:"3816",max_amount:"38166726"},USD:{code:"USD",title:"United States Dollar",symbol:"$",native:"$",thousands_sep:",",decimal_sep:".",symbol_left:!0,space_between:!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,exp:2,min_amount:"4080",max_amount:"40801205"},UZS:{code:"UZS",title:"Uzbekistani Som",symbol:"UZS",native:"UZS",thousands_sep:" ",decimal_sep:",",symbol_left:!1,space_between:!0,exp:2,min_amount:"1089058",max_amount:"10890583014"},VND:{code:"VND",title:"Vietnamese Đồng",symbol:"₫",native:"₫",thousands_sep:".",decimal_sep:",",symbol_left:!1,space_between:!0,exp:0,min_amount:"23862",max_amount:"238625000"},YER:{code:"YER",title:"Yemeni Rial",symbol:"YER",native:"ر.ي.‏",thousands_sep:",",decimal_sep:".",symbol_left:!0,space_between:!0,exp:2,min_amount:"25030",max_amount:"250300677"},ZAR:{code:"ZAR",title:"South African Rand",symbol:"ZAR",native:"R",thousands_sep:",",decimal_sep:".",symbol_left:!0,space_between:!0,exp:2,min_amount:"1789",max_amount:"17894299"}};function P0(o,e,t,s){o=(o+"").replace(/[^0-9+\-Ee.]/g,"");var i=isFinite(+o)?+o:0,n=isFinite(+e)?Math.abs(e):0,a=typeof s>"u"?",":s,r=typeof t>"u"?".":t,l="",c=function(d,h){var u=Math.pow(10,h);return""+Math.round(d*u)/u};return l=(n?c(i,n):""+Math.round(i)).split("."),l[0].length>3&&(l[0]=l[0].replace(/\B(?=(?:\d{3})+(?!\d))/g,a)),(l[1]||"").length{t._==="messageEntitySpoiler"&&(o=XL(o,t).text)}),o}function zh(o){return{_:"messageEntityEmoji",offset:0,length:o.length,unicode:ZL(o).join("-").replace(/-?fe0f/g,"")}}const yy=new RegExp(`(^${iL})`);function zg(o,e=!1){const t=(o||"").trim().split(" ");if(!t[0])return{text:"",entities:[]};const s=[],i=t[0].match(yy),n=i?.[0]||t[0][0];i&&s.push(zh(n));const a=t.length;if(e||a===1)return{text:n,entities:s};const r=t[a-1].match(yy),l=r?.[0]||t[a-1][0];return r&&s.push({...zh(l),offset:n.length}),{text:n+l,entities:s}}function Fu(o,e){const{text:t,entities:s}=zg(o,e);return _e(t,void 0,s)}let Wa,Jd,vy;const by=new Map;function M0(o,e){if(!Wa){vy=document.getElementById("svg-defs");const a="http://www.w3.org/2000/svg";Wa=document.createElementNS(a,"svg"),Wa.setAttributeNS(null,"width","26"),Wa.setAttributeNS(null,"height","26"),Wa.setAttributeNS(null,"viewBox","0 0 26 26"),Wa.classList.add("topic-icon-svg");const r=document.createElementNS(a,"use");r.setAttributeNS(null,"href","#topic-icon"),Wa.append(r),Jd=document.createElement("span"),Jd.classList.add("topic-icon","avatar-like");const l=document.createElement("span");l.classList.add("topic-icon-content"),Jd.append(Wa,l)}o||(console.error("NO TOPIC ICON COLOR!"),o=ac[0]),e||(console.error("NO TOPIC NAME!"),e="");const t=o.toString(16),s=`topic-icon-gradient-${o}`;let i=by.get(o);if(!i){const{h:a,s:r,l,a:c}=kg("#"+t);vy.insertAdjacentHTML("beforeend",` `),by.set(o,i=`hsla(${a}, ${r}%, ${Math.max(0,l-40)}%, ${c})`)}const n=Jd.cloneNode(!0);return n.firstElementChild.style.fill=`url(#${s})`,n.firstElementChild.style.stroke=i,n.lastElementChild.append(Fu(e,!0)),n}function Kg({docIds:o,loadPromises:e,middleware:t,lazyLoadQueue:s,customEmojiSize:i,animationGroup:n}){const a=" ".repeat(o.length),r=[];return o.forEach((c,d)=>{r.push({_:"messageEntityCustomEmoji",offset:d,length:1,document_id:c})}),Yt(a,{entities:r,loadPromises:e,animationGroup:n,customEmojiSize:i,middleware:t,lazyLoadQueue:s})}function E0(o){const e=o.loadPromises??(o.loadPromises=[]),t=Kg(o);return Promise.all(e).then(()=>t)}function wy(o){const e=o.action,{onclick:t,url:s}=cl(`tg://voicechat?chat_id=${o.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 ul(o,e){const t=[],s=[];for(let i=0,n=o.length;i_0.has(e.platform)&&!k0.has(e.reason))}function Jb(o){return!!Zb(o)}function T0(o){return o.replace(/[|\\{}()[\]^$+*?.]/g,"\\$&").replace(/-/g,"\\x2d")}function ew(o){return!!(o.restriction_reason&&Jb(o.restriction_reason))}function Wg(o,e){return o=o.replace(/[\u2640\u2642\u2764](?!\ufe0f)/g,(t,s,i)=>{if(e){const n=t.length;s+=n,e.forEach(a=>{const r=a.offset+a.length;r===s?a.length+=n:r>s&&(a.offset+=n)})}return t+"️"}),o}function Em(o,e=[]){o=Wg(o,e);const t=Ko(o),s=Qr(e,t);return{message:o,entities:e,myEntities:t,totalEntities:s}}function Bc(o){const{message:e,entities:t,myEntities:s}=Em(o.text,o.entities),i=Qr(t,s.filter(n=>n._==="messageEntityCustomEmoji"||n._==="messageEntityEmoji"));return{_:"textWithEntities",text:e,entities:i}}async function x0(o){return{cached:o.cached,result:o.cached?await o.result:o.result}}function to(o){return o.then(x0)}const[A0,F0]=Tg({}),tw=o=>{I.managers.appProfileManager.getProfileByPeerId(o).then(e=>{F0(o,wh(e))})};I.addEventListener("peer_full_update",tw);function sw(o){return K(()=>{if(!o())return;const e=A0[o()];return e||tw(o()),e})}let eh,_p;function iw(o){eh||(eh=new Worker(new URL(""+new URL("tinyld.worker-sOiVgKBT.js",import.meta.url).href,import.meta.url),{type:"module"}),eh.addEventListener("message",t=>{const{lang:s}=t.data;_p.shift().resolve(s)}),_p=[]);const e=Pt();return _p.push(e),eh.postMessage({text:o}),e}const R0=8,D0=.65;let dr,aa,_m,Ru=()=>{Ru=void 0,[dr,aa]=Tg({}),Jt(()=>{const[o]=El();_m=K(()=>new Set(o.translations.doNotTranslate.concat(navigator.language.split("-")[0],ke.langCodeNormalized()))),ye($s(_m,e=>oa(()=>{for(const t in dr){const s=dr[t];if(!s)continue;let i=0;for(const n in s.languages)e.has(n)||(i+=s.languages[n]);aa(t.toPeerId(),"totalForeign",i)}}),{defer:!0}))})};function nw(){return{messages:{},languages:{},language:void 0,total:0,totalForeign:0}}function B0(o){Ru?.(),Et(()=>dr[o])||aa(o,nw()),aa(o,"isFull",!0)}async function N0(o,e){if(Ru?.(),dr[o]&&dr[o].messages[e])return;const s=fe.getMessageByPeer(o,e).message;if(!s)return;const i=await iw(s),n=!_m().has(i);oa(()=>{let a=Et(()=>dr[o]);if(!a)aa(o,a=nw());else if(a.messages[e])return;const r=(a.languages[i]??0)+1,l=a.total+1,c=a.totalForeign+(n?1:0);aa(o,"messages",e,i),aa(o,"languages",i,r),aa(o,"total",l),n&&aa(o,"totalForeign",c);const d=a.language;(a.languages[d]||0){const t=o();if(!t)return;Ru?.();const s=dr[t];if(!(s&&s.total{const t=o();let s=kp.get(t);return s||(s={count:0,factory:e},s.value=Jt(i=>(s.dispose=i,e())),kp.set(t,s)),++s.count,ut(()=>{--s.count||(s.dispose(),kp.delete(t))}),s.value})}const[U0,rw]=Jt(()=>ne(I.premium)),Sy=()=>{I.managers.rootScope.getPremium().then(rw)};I.addEventListener("premium_toggle",rw);I.myId?Sy():I.addEventListener("user_auth",Sy);function Du(){return U0}function H0(o){const[e,t]=El(),s=sw(()=>o),i=O0(()=>o),n=Du(),a=K(()=>{if(!(!n()||!s()||!i()||!e.translations.enabled))return!(s().pFlags.translations_disabled||e.translations.doNotTranslate.includes(i()))}),r={peerLanguage:i,language:()=>e.translations.peers[o]||ke.langCodeNormalized(),setLanguage:l=>t("translations","peers",o,l),enabled:K(()=>!!(n()&&e.translations.enabled&&e.translations.enabledPeers[o])&&a()),toggle:l=>t("translations","enabledPeers",o,l?!0:void 0),shouldShow:a};return ye(()=>{r.shouldShow()===!1&&r.enabled()&&r.toggle(!1)}),r}function pl(o){return aw(()=>pl.name+"-"+o,()=>H0(o))()}function Ys(){const o=xt();return ut(()=>o.destroy()),o}const $0=!1;function ow(o){const e=$0,[t,s]=ne(!e),i=K(f=>f||t()),[n,a]=ne(),r=pl(o.peerId),l=Pt();let c=o.textWithEntities,d=!0,h=!1;const u=o.enabled,p=o.container??document.createElement("span");p.classList.add("translatable-message"),o.message&&(N0(o.peerId,o.message.mid),c={_:"textWithEntities",text:o.message.message,entities:o.message.totalEntities}),o.richTextOptions?.loadPromises&&o.richTextOptions.loadPromises.push(l);const m=(f,y)=>to(I.managers.acknowledged.appTranslationsManager.translateText({...o.message?{peerId:o.message.peerId,mid:o.message.mid}:{text:o.textWithEntities},lang:f,onlyCache:y})),g=f=>{a(c),p.classList.toggle("text-loading",!!f)};if(o.observer&&o.observeElement&&e){const f=y=>{s(y.isIntersecting)};o.observer.observe(o.observeElement,f),ut(()=>{o.observer.unobserve(o.observeElement,f)})}return ye(async()=>{const f=Ys().get(),y=d;if(d=!1,!r.enabled()&&!o.enabled||!i()&&!y){g();return}const v=await m(r.language(),y&&e);if(!f())return;if(!v.cached)u?p.classList.add("text-loading"):g(!0);else if(!v.result){g();return}const w=await v.result;if(f()){if(!w){g();return}a(w)}}),ye(()=>{let f=n();if(!f)return;o.onTextWithEntities&&(f=o.onTextWithEntities(f)),(c!==f||!o.message)&&(f=Bc(f));const y=Ys().get(),v=[],w=Yt(f.text,{...o.richTextOptions||{},loadPromises:v,entities:f.entities});Promise.all(v).then(()=>{if(!y())return;const b=()=>{y()&&(l.resolve(),p.replaceChildren(w),(h||u)&&p.classList.remove("text-loading"),h=!0)};if(h&&o.onTranslation){o.onTranslation(b);return}b()})}),p}function _d(o){return Jt(e=>(o.middleware.onDestroy(e),ow(o)))}async function lw(o){try{return await V0(o)}catch(e){return console.error("wrapMessageActionTextNewUnsafe error:",e),o.plain?"":document.createElement("span")}}async function hr(o){o.text??(o.text=o.message.message),!o.plain&&o.highlightWord&&(o.highlightWord=o.highlightWord.trim());const{message:e,usingMids:t,plain:s,highlightWord:i,withoutMediaType:n}=o,a=[];let r=!1;const l=(m,g,f)=>{if(m){if(g===void 0&&r)return;g=s?ke.format(m,!0,f):M(m,f)}if(s)a.push(g);else{const y=document.createElement("span");typeof g=="string"?y.innerHTML=g:y.append(g),a.push(y)}},d=I.managers.appMessagesManager,h=ew(e),u={...o,noLinebreaks:!0,noLinks:!0,noTextFormat:!0};let p=e.totalEntities??e.entities;if(e.media&&!h){let m=!0;if(e.grouped_id){if(t){const y=await d.getMidsByMessage(e);if(t.length===y.length){for(const v of y)if(!t.includes(v)){m=!1;break}}else m=!1}if(m){const y=await d.getGroupedText(e.grouped_id);o.text=y?.message||"",p=y?.totalEntities||[],n||(l("AttachAlbum"),r=!0)}}else m=!1;let g=1;if(!m&&!n||!o.text){const y=e.media;switch(y?._){case"messageMediaPhoto":l("AttachPhoto");break;case"messageMediaDice":l(void 0,s?y.emoticon:_e(y.emoticon));break;case"messageMediaVenue":{o.text=y.title,l("AttachLocation");break}case"messageMediaGeo":l("AttachLocation");break;case"messageMediaGeoLive":l("AttachLiveLocation");break;case"messageMediaPoll":const v="📊 ";if(s){const w=v+y.poll.question.text;l(void 0,w)}else{const w=Bc(y.poll.question),b=Yt(w.text,{...u,entities:w.entities});b.prepend(_e(v)),l(void 0,b)}break;case"messageMediaContact":l("AttachContact");break;case"messageMediaGame":{const w="🎮 "+y.game.title;l(void 0,s?w:_e(w));break}case"messageMediaDocument":{const w=y.document;if(w.type==="video")l("AttachVideo");else if(w.type==="voice")l("AttachAudio");else if(w.type==="gif")l("AttachGif");else if(w.type==="round")l("AttachRound");else if(w.type==="sticker"){const b=a.length;if(w.stickerEmojiRaw){const C=w.stickerEmojiRaw+" ";l(void 0,s?C:_e(C))}l("AttachSticker");const S=a.splice(b,2);if(s)a.push(S[0]+(S[1]?S[1]:""));else{const C=window.document.createElement("span");C.append(...S),a.push(C)}o.text=""}else if(w.type==="audio"){const b=w.attributes.find(C=>C._==="documentAttributeAudio"&&(C.title||C.performer)),S="🎵 "+(b?[b.title,b.performer].filter(Boolean).join(" - "):w.file_name);l(void 0,s?S:_e(S))}else l(void 0,s?w.file_name:_e(w.file_name));break}case"messageMediaInvoice":{y.extended_media?._==="messageExtendedMediaPreview"?l(void 0,s?y.description:_e(y.description)):l(void 0,s?y.title:_e(y.title));break}case"messageMediaUnsupported":{l(pm);break}case"messageMediaStory":{if(y.pFlags.via_mention){const w=at(y.peer),b=w===I.myId;l(b?"StoryMentionYou":"StoryMention",void 0,[await Oe({peerId:b?e.peerId:w,plainText:s})])}else l("Story");break}case"inputMediaWebPage":case"messageMediaPhotoExternal":case"messageMediaDocumentExternal":case"messageMediaWebPage":break;case"messageMediaGiveaway":{const w=wb(new Date(y.until_date*1e3));l("Giveaway.ToBeSelectedFull",void 0,[M("Giveaway.ToBeSelected",[y.quantity,s?w.textContent:w])]);break}case"messageMediaGiveawayResults":{const{langPackKey:w,args:b}=dw(y,s);l(w,void 0,b);break}case"messageMediaPaidMedia":{const w=y.extended_media,[b,S]=ul(w,P=>P._==="messageExtendedMediaPreview"?P.video_duration===void 0:P.media._==="messageMediaPhoto");s||(g+=2,l(void 0,Le("star","xtr-icon")),l(void 0," "));const C=b.length+S.length;if(C<2){l(b.length?"AttachPhoto":"AttachVideo");break}l(b.length&&S.length?"Media":b.length?"Photos":"Videos",void 0,[C]);break}default:l(pm),o.text="";break}}const f=a.length;for(;g({...g,text:Aa(g.text,100)})}):(m=Yt(o.text,{...u,entities:p}),m=Ed(m)),a.push(m)}if(s)return a.join("");{const m=document.createDocumentFragment();return m.append(...a),m}}function Kh(o){return o._==="payments.checkedGiftCode"?!o.from_id:(o.amount||o.crypto_amount)!==void 0}async function Cy(o){const e=await hr(o);if(o.plain)return e;const t=document.createElement("i");return t.dataset.savedFrom=o.message.peerId+"_"+o.message.mid,t.append(e),Oa(t),t}function lc(o,e){return e?o:Vg(_e(o))}async function Bu(o){const e=o.topic;let t=e?.icon_emoji_id;return e?.id===Id&&(t="5390854796011906616"),t?o.plain?I.managers.appEmojiManager.getCustomEmojiDocument(t).then(s=>s.stickerEmojiRaw):E0({...o,docIds:[t]}).then(s=>(s.lastElementChild.classList.add("topic-icon"),s)):o.plain?"":M0(e?.icon_color,e?.title)}function cw(o){const e=o.message.action;return Bu({...o,topic:e})}async function Iy(o){const e=o.message.action,t=document.createElement("span");return t.classList.add("topic-name"),t.append(await cw(o),lc(e.title,o.plain)),t}function dw(o,e){let t="Giveaway.Results",s=[o.winners_count];const i=(n,a)=>{s=[e?ke.format(t,!0,s):M(t,s)],t="Giveaway.Results.Combined",s.push(e?ke.format(n,!0,a):M(n,a))};return o.winners_count?o.unclaimed_count&&i("Giveaway.Results.Unclaimed",[o.unclaimed_count]):(t="Giveaway.Results.NoWinners",s=[o.unclaimed_count]),{langPackKey:t,args:s}}async function V0(o){const{plain:e,message:t,noLinks:s}=o,i=e?void 0:document.createElement("span"),n="action"in t&&t.action;if(n.message){const a=n.message;return e?vo(a):(kt(i,Yt(a,{noLinebreaks:!0})),i)}else{let a=n._,r,l;const c=I.managers,d=(p,m)=>m?ar({peerId:p,plainText:m}):Oe({peerId:p}),h=async(p,m)=>{if(p.length===1)return d(p[0],m);const g=pi(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":{a+="."+n.type,l=[Lh(n.duration,e)];break}case"messageActionGroupCall":{a+="."+n.type,l=[],!a.endsWith("You")&&!t.pFlags.post&&l.push(d(t.fromId,e)),n.duration!==void 0?l.push(Lh(n.duration,e)):s?l.push(""):l.push(wy(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"),us(p,g),r=m,l=p.map(f=>d(f,e)),l.push(s?"":wy(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 y=await c.appPeersManager.isBroadcast(t.peerId);r=y?"ChatList.Service.VoiceChatScheduled.Channel":"ChatList.Service.VoiceChatScheduled",l=[];const v=I.myId;t.fromId===v?r+="You":y||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 ke.IntlDateElement({date:m,options:{day:"2-digit",month:"2-digit",year:"2-digit"}}).element)),b.push(Ag(m));const S=M(w,b);l.push(S);break}case"messageActionChatCreate":{const p=I.myId;t.fromId===p?a+="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(Cy({...o,message:m})):(r="ActionPinnedNoText",t.reply_to_mid&&c.appMessagesManager.fetchMessageReplyTo(t));break}case"messageActionChatJoinedByRequest":{const p=await c.appPeersManager.isBroadcast(t.peerId);t.pFlags.out?r=p?"RequestToJoinChannelApproved":"RequestToJoinGroupApproved":(r=p?"ChatService.UserJoinedChannelByRequest":"ChatService.UserJoinedGroupByRequest",l=[d(t.fromId,e)]);break}case"messageActionGiveawayLaunch":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(lc(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(h(m,e));break}case"messageActionBotAllowed":{if(n.pFlags?.attach_menu){r="ActionAttachMenuBotAllowed";break}else if(n.pFlags?.from_request){r="ActionBotAllowedRequest";break}else if(!n.domain)break;const p=Yt(n.domain,{entities:[{_:"messageEntityUrl",length:n.domain.length,offset:0}],noLinks:s});l=[Vg(p)];break}case"messageActionPaymentSent":{const p=n.pFlags.recurring_init,m=n.pFlags.recurring_used;if(r=m?"Chat.Service.PaymentSentRecurringUsedNoTitle":p?"Chat.Service.PaymentSentRecurringInitNoTitle":"Chat.Service.PaymentSent1NoTitle",l=[In(n.total_amount,n.currency,void 0,void 0,e),d(t.peerId,e)],t.reply_to_mid){const f=t.reply_to,y=await c.appMessagesManager.getMessageByPeer(f?.reply_to_peer_id?at(f.reply_to_peer_id):t.peerId,t.reply_to_mid);y?(r=m?"Chat.Service.PaymentSentRecurringUsed":p?"Chat.Service.PaymentSentRecurringInit":"Chat.Service.PaymentSent1",l.push(Cy({...o,message:y}).then(v=>(v instanceof HTMLElement&&v.classList.add("is-receipt-link"),v)))):c.appMessagesManager.fetchMessageReplyTo(t)}break}case"messageActionSetMessagesTTL":{l=[];const p=await c.appPeersManager.isBroadcast(t.peerId);if(n.period){p?r="ActionTTLChannelChanged":t.fromId===I.myId?r="ActionTTLYouChanged":(r="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/(xg*30)|0)),m=e?ke.format(g,!0,f):M(g,f)}else m=Lh(n.period,e);l.push(m)}else p?r="ActionTTLChannelDisabled":t.fromId===I.myId?r="ActionTTLYouDisabled":(r="ActionTTLDisabled",l.push(d(t.fromId,e)));break}case"messageActionTopicEdit":{let p,m,g;const f=!!t.pFlags.out,y=n.icon_emoji_id!==void 0,v=y&&!+n.icon_emoji_id,w=n.title!==void 0,b=n.hidden!==void 0;f||(g=d(t.fromId,e)),w&&(m=lc(n.title,e)),y&&!v&&(p=cw(o)),l=g?[g]:[],n.closed?r=f?"Chat.Service.Group.TopicEdited.You.Paused":"Chat.Service.Group.TopicEdited.Paused":n.closed===!1?r=f?"Chat.Service.Group.TopicEdited.You.Resumed":"Chat.Service.Group.TopicEdited.Resumed":v&&w?(r=f?"Chat.Service.TopicEdited.You.Mixed.IconRemoved":"Chat.Service.TopicEdited.Mixed.IconRemoved",l.push(m)):y&&w?(r=f?"Chat.Service.TopicEdited.You.Mixed":"Chat.Service.TopicEdited.Mixed",l.push(Iy(o))):v?r=f?"Chat.Service.Group.TopicEdited.You.Icon.Removed":"Chat.Service.Group.TopicEdited.Icon.Removed":w?(r=f?"Chat.Service.Group.TopicEdited.You.Title":"Chat.Service.Group.TopicEdited.Title",l.push(m)):y?(r=f?"Chat.Service.Group.TopicEdited.You.Icon":"Chat.Service.Group.TopicEdited.Icon",l.push(p)):b&&(r=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=[Iy(o)],r="TopicWasCreatedAction";break}case"messageActionSetChatTheme":{const p=!!t.pFlags.out;let m;p||(m=d(t.fromId,e)),l=m?[m]:[],n.emoticon?(l.push(lc(n.emoticon,e)),r=p?"ChatThemeChangedYou":"ChatThemeChangedTo"):r=p?"ChatThemeDisabledYou":"ChatThemeDisabled";break}case"messageActionGiftCode":case"messageActionGiftPremium":{const p=n._==="messageActionGiftCode";if(p&&!Kh(n)){r="BoostingReceivedGiftNoName",n.boost_peer&&(r="BoostingReceivedGiftFrom",l=[d(at(n.boost_peer),e)]);break}const m=!!t.pFlags.out&&!p;let g;m||(g=d(t.fromId,e)),l=g?[g]:[],l.push(In(n.amount,n.currency,!1,!0,e)),r=m?"ActionGiftOutbound":"ActionGiftInbound";break}case"messageActionWebViewDataSent":{r="ActionBotWebViewData",l=[lc(n.text,e)];break}case"messageActionRequestedPeer":{r="Chat.Service.PeerRequested",l=[h(n.peers.map(p=>at(p)),e),d(t.peerId,e)];break}case"messageActionGiveawayResults":{const p=dw(n,e);r=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?r=n.pFlags.for_both?"ActionSetWallpaperForThisChatSelfBoth":n.pFlags.same?"ActionSetSameWallpaperForThisChatSelf":"ActionSetWallpaperForThisChatSelf":r=n.pFlags.for_both?"ActionSetWallpaperForThisChatBoth":n.pFlags.same?"ActionSetSameWallpaperForThisChat":"ActionSetWallpaperForThisChat";break}if(await c.appPeersManager.isBroadcast(t.peerId)){r="ActionSetWallpaperForThisChannel";break}r=t.fromId===t.peerId?"ActionSetWallpaperForThisGroup":"ActionSetWallpaperForThisGroupByUser";break}default:r=Bh[a]||`[${n._}]`;break}r||(r=Bh[a],r===void 0&&(r="["+a+"]"));const u=l&&await Promise.all(l);return e?ke.format(r,!0,u):Zt(i,r,u)}}const hw=new WeakMap;I.addEventListener("peer_title_edit",({peerId:o,threadId:e})=>{let t=`.peer-title[data-peer-id="${o}"]`;e&&(t+=`[data-thread-id="${e}"]`),Array.from(document.querySelectorAll(t)).forEach(i=>{hw.get(i)?.update()})});class Rt{constructor(e){this.element=document.createElement("span"),this.element.classList.add("peer-title"),Oa(this.element),this.options={},e&&this.update(e),hw.set(this.element,this)}setOptions(e){if(e){It(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 a;this.setOptions(e);let t=this.options.fromName;if(t!==void 0){this.options.limitSymbols!==void 0&&(t=Aa(t,this.options.limitSymbols,this.options.limitSymbols)),kt(this.element,_e(t));return}(a=this.options).peerId??(a.peerId=Tt);let s;const{peerId:i,threadId:n}=this.options;if(i===I.myId&&this.options.dialog){let r;this.options.meAsNotes?r=M(this.options.onlyFirstName?"MyNotesShort":"MyNotes"):r=M(this.options.onlyFirstName?"Saved":"SavedMessages"),dt(this.element,r)}else if(i===Fg)dt(this.element,M(this.options.onlyFirstName?"AuthorHiddenShort":"AuthorHidden"));else{if(n){const[h,u]=await Promise.all([I.managers.dialogsStorage.getForumTopic(i,n),I.managers.appPeersManager.isForum(i)]);if(!h&&u){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}))}),kt(this.element,M("Loading")),this.setHasInner(!1);return}}const r=n&&this.options.withIcons?I.managers.dialogsStorage.getForumTopic(i,n).then(h=>Bu({...this.options.wrapOptions??{},topic:h})):void 0,[l,c,d]=await Promise.all([ar(this.options),this.options.withIcons&&Mm({peerId:i,wrapOptions:this.options.wrapOptions})||this.options.withPremiumIcon&&Mm({peerId:i,wrapOptions:this.options.wrapOptions,noVerifiedIcon:!0,noFakeIcon:!0}),r]);if(c?.length||d){const h=document.createElement("span");h.classList.add("peer-title-inner"),s=!0,kt(h,l);const u=document.createDocumentFragment();u.append(...[d,h,...c??[]].filter(Boolean)),kt(this.element,u)}else kt(this.element,l)}this.setHasInner(s)}}function uw(o,e){const t=o.querySelector(".emoji-status-text-color"),s=t&&_s.getAnimation(t);s&&s.setColor(e,!0)}async function Oe(o){const e=new Rt;return await e.update(o),e.element}const Nc=[["#CC5049"],["#D67722"],["#955CDB"],["#40A920"],["#309EBA"],["#368AD1"],["#C7508B"]],Tp=["red","orange","violet","green","cyan","blue","pink"],G0=Nc;function pw(o){return Math.abs(+o)%7}function km(o){let e=Nu(o);if(e===-1)return;let t=Tp[e];if(!t){const s=Nc[e];if(!s)return Tp[pw(o.id)];const n=kg(s[0]).h;n>=345||n<29?e=0:n<67?e=1:n<140?e=3:n<199?e=4:n<234?e=5:n<301?e=2:e=6,t=Tp[e]}return t}function Nu(o){return o?o.color?.color??pw(o.id):-1}function jg(o){const e=Nu(o);return Nc[e]??[]}function Ly(o,e,t){for(const s of e){const n=(t?s.dark_colors:s.colors)?.colors;if(!n?.length)continue;const a=n.map(r=>Sb(r));o[s.color_id]=a}return o}function Py(o,e){const t=o.length;return e||(e=5),t!==3&&(o=o.slice().reverse()),`repeating-linear-gradient(-45deg, ${o.map((i,n,a)=>{const r=n*e+"px",l=(n+1)*e+"px";return[`${i} ${r}`,`${i} ${l}`].join(", ")}).join(", ")})`}function z0(o,e){let t=Ly(G0.slice(),o);as.isNight()&&(t=Ly(t,o,!0)),Nc.splice(0,Nc.length,...t),t.forEach((n,a)=>{const r=`--peer-${a}`,l=`${r}-border-background`,c=`${r}-color-rgb`;if(document.documentElement.style.setProperty(c,_n(n[0]).join(",")),n.length>1){const d=Py(n);document.documentElement.style.setProperty(l,d)}else document.documentElement.style.removeProperty(l)});const s=jg(e);[["--peer-border-background","--primary-color",s.length],["--message-out-peer-border-background","--message-out-primary-color",s.length],["--message-out-peer-1-border-background","--message-out-primary-color",1],["--message-out-peer-2-border-background","--message-out-primary-color",2],["--message-out-peer-3-border-background","--message-out-primary-color",3],["--message-empty-peer-1-border-background","--message-empty-primary-color",1],["--message-empty-peer-2-border-background","--message-empty-primary-color",2],["--message-empty-peer-3-border-background","--message-empty-primary-color",3]].forEach(([n,a,r])=>{let l;if(r>1){const c=[`rgba(var(${a}-rgb), .4)`,`rgba(var(${a}-rgb), .2)`,`var(${a})`];r===2&&c.shift(),l=Py(c)}else l=`var(${a})`;document.documentElement.style.setProperty(n,l)})}function K0(o){const e=o?.restriction_reason;return!!(e&&o.pFlags.restricted&&Jb(e))}function W0(o){if(!(!o||K0(o)))return o?.photo}function j0(o){let e="";return o&&(e=o.title??[o.first_name,o.last_name].filter(Boolean).join(" ")),Fu(e)}function ot(...o){return o.filter(Boolean).join(" ")}function Wo(o){const e=new Array(o.childNodes.length);let t=o.firstChild,s=0;for(;t;)e[s++]=t.nodeType===t.TEXT_NODE?t.nodeValue:t,t=t.nextSibling;return e}class q0{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,a)=>n+a.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;nDh.mutateElement(o,()=>{i?.append(e),s?(r?.(),a.addEventListener("animationend",()=>{Dh.mutate(()=>{a.classList.remove("fade-in"),n?.remove(),o.classList.add("no-background"),l?.()})},{once:!0})):(n?.remove(),o.classList.add("no-background"),r?.(),l?.())}))}const th=Symbol("RAF"),xp=Symbol("TIMEOUT"),bt=o=>{const{element:e,className:t,forwards:s,duration:i,onTransitionEnd:n,onTransitionStart:a,useRafs:r}=o,l=t&&t.split(" "),c=e[xp],d=e[th];if(c!==void 0&&clearTimeout(+c),d!==void 0&&(window.cancelAnimationFrame(+d),r||delete e[th]),r&&st.isAvailable("animations")&&i){e[th]=""+window.requestAnimationFrame(()=>{delete e[th],bt({...o,useRafs:r-1})});return}s&&t&&e.classList.add(...l);const h=()=>{delete e[xp],!s&&t&&e.classList.remove("backwards",...l),e.classList.remove("animating"),n?.()};if(a?.(),!st.isAvailable("animations")||!i){e.classList.remove("animating","backwards"),h();return}e.classList.add("animating"),e.classList.toggle("backwards",!s),e[xp]=""+setTimeout(h,i)},Ap=200;class tn{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&&oe(t),this.preloader.classList.contains("manual")?this.loadFunc?.(t):this.promise?.cancel?.()},e&&It(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=`
`:this.preloader.innerHTML=`
`,this.streamable?this.totalLength=118.61124420166016:this.totalLength=149.82473754882812,this.cancelable?(this.preloader.innerHTML+=` `,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&&N(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 a=Date.now()-s;if(!n&&this.cancelable){this.setProgress(100);const r=Ap*.75;a{t===this.tempId&&this.detach()},r)}else this.tryAgainOnFail?(this.attach(this.preloader.parentElement),bs(()=>{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 a=n.done/n.total*100;this.setProgress(a)})}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=ca(this.preloader)?1:2,this.preloader.parentElement!==e&&e[this.attachMethod](this.preloader)),bt({element:this.preloader,className:"is-visible",forwards:!0,duration:Ap,useRafs:i}),this.cancelable&&t&&this.setProgress(0)}detach(){this.detached||(this.detached=!0,this.preloader?.parentElement&&bt({element:this.preloader,className:"is-visible",forwards:!1,duration:Ap,onTransitionEnd:()=>{this.preloader.remove()},useRafs:1}))}setProgress(e){if(!(!this.totalLength&&!ca(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 Oc({photo:o,cacheContext:e,useBlur:t,ignoreCache:s,onlyStripped:i}){const n=["video","gif"].includes(o.type);if(!e.downloaded||n||s){if(o._==="document"&&e.downloaded&&!s&&(!n||e.type!==Rg))return null;const a=o.sizes||o.thumbs,r=a?.length;if(!r)return null;let l=-1;if(!i)for(let d=r-1;d>=0;--d){const h=a[d];if(h.type===e.type)l=d;else if(l){const u=fe.getCacheContext(o,h.type);if(u.downloaded)return Im(o,h,!1,u.url)}}const c=a.find(d=>d._==="photoStrippedSize");if(c&&"bytes"in c)return Im(o,c,t)}return null}const Tm=320,Q0=120,Y0=200,X0=368;function jo({photo:o,element:e,boxWidth:t,boxHeight:s,noZoom:i=!0,message:n,pushDocumentSize:a,photoSize:r,size:l,canHaveVideoPlayer:c}){const d=Bb(o);!r&&!l&&(r=Sn(o,t,s,void 0,a));const h=o?._==="document";l||(h||d?l=vs(o.w||r.w||512,o.h||r.h||512):l=vs(r.w||100,r.h||100));let u=vs(t,s);u=l=l.aspect(u,i);let p=!0;if(!h||["video","gif"].includes(o.type)||d){const m=Y0;u.width{const re=A&&!c;return cs.downloadMediaURL({media:o,thumb:c,queueId:r&&r.queueId,onlyCache:re?void 0:B})},se=re=>mw({container:t,media:G,url:re,needFadeIn:z,aspecter:R,thumbImage:F,fadeInElement:w,onRender:b,onRenderFinish:S,useRenderCache:P}),Y=async re=>{if(!(l&&!l())){if(v&&(re=await v(re)),f){const ge=Nb(re,12);return ge.promise.then(()=>se(ge.canvas.toDataURL()))}return se(re)}};let Q;const he=!k&&c.w>=150&&c.h>=150||B,le=async()=>{B&&!d&&q&&(q.construct(),q.setManual());const re=$(),ge=fe.getCacheContext(o,c?.type);q&&!ge.downloaded&&!d&&he&&q.attach(t,!1,re),B=void 0;const be=re.then(Y);return be.catch(Wt),{download:re,render:be}};return q&&q.setDownloadFunction(le),H.downloaded?X=Q=(await le()).render:r?r.push({div:t,load:()=>le().then(({download:re})=>re)}):Q=(await le()).render,h&&X&&h.push(X),_.loadPromises.thumb=X,_.loadPromises.full=Q||Promise.resolve(),_.preloader=q,_}function sn(o){return(e,t,s)=>{o.addEventListener(e,t,s),ut(()=>{o.removeEventListener(e,t,s)})}}function Ou(){const[o,e]=ne(as.isNight());return sn(I)("theme_changed",()=>{e(as.isNight())}),o}const Z0=ce("
"),J0=ce("
"),eP=ce("
"),tP=ce("
"),sP=200,Oo=new Map,Po=new Map,Fp=new Set;function qg(o,e){return o+(e?"_"+e:"")}const gw=({peerId:o,threadId:e})=>{const t=qg(o,e),s=Oo.get(t);if(s?.size)for(const i of s)i.render()},Uu=({peerId:o})=>{const e=qg(o),t=Oo.get(e);if(t?.size)for(const s of t)s.updateStoriesSegments()};I.addEventListener("avatar_update",gw);I.addEventListener("peer_title_edit",async o=>{await I.managers.appAvatarsManager.isAvatarCached(o.peerId)||gw(o)});I.addEventListener("peer_stories",({peerId:o})=>{Uu({peerId:o})});I.addEventListener("stories_read",Uu);I.addEventListener("story_deleted",Uu);I.addEventListener("story_new",Uu);const My=async(o,e)=>{if(e){const s=[{length:1,type:await I.managers.appStoriesManager.getUnreadType(o,e)}];return{cached:!0,result:Promise.resolve(s)}}return I.managers.acknowledged.appStoriesManager.getPeerStoriesSegments(o)},iP=(o,e,t)=>{const s=o.createLinearGradient(e*.9156*t,e*-.05695821429*t,e*.1342364286*t,e*1.02370714286*t);return s.addColorStop(0,Ls.getProperty("avatar-color-story-unread-from")),s.addColorStop(1,Ls.getProperty("avatar-color-story-unread-to")),s},nP=(o,e,t)=>{const s=o.createLinearGradient(e*.5*t,e*0*t,e*.5*t,e*1*t);return s.addColorStop(0,Ls.getProperty("avatar-color-story-close-from")),s.addColorStop(1,Ls.getProperty("avatar-color-story-close-to")),s};function Uc(o){let e=U(o,"avatar");return e&&(e=U(e,"has-stories")||e),e}const aP=o=>{const e=Math.round(o*.8888888888888888),t=o*(1+2/54),s=o/54,i=2*s;return{size:o,willBeSize:e,totalSvgSize:t,multiplier:s,strokeWidth:i}};function fw(o,e,t=100,s){return Ks({container:o.node,message:null,photo:e,boxHeight:t,boxWidth:t,withoutPreloader:!0,size:s}).then(i=>(o.node.classList.replace("media-container","avatar-relative"),o.node.style.width=o.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 rP(o){const[e,t]=ne(),s=K(n=>{if(e()!==void 0)return n?.size===o.size?n:aP(o.size)}),i=K(()=>{const n=s();if(!n)return;let a;if(o.isStoryFolded!==void 0){const f=K(()=>{const y=e();return(y.find(b=>b.type==="close")||y.find(b=>b.type==="unread")||y[0]).type});a=(()=>{const y=Z0();return Ve(v=>pa(y,{["is-"+f()]:!0},v)),y})()}const r=(f,y)=>f.type==="read"?{color:o.colors?.read||Ls.getProperty("avatar-color-story-read"),length:f.length,lineWidth:n.strokeWidth/2}:f.type==="close"||y?{color:p??(p=nP(d,c.width,h)),length:f.length,lineWidth:n.strokeWidth}:{color:u??(u=iP(d,c.width,h)),length:f.length,lineWidth:n.strokeWidth},l=new q0,{canvas:c,context:d,dpr:h}=l;l.prepare({radius:n.size/2,gap:4*n.multiplier,width:n.totalSvgSize,height:n.totalSvgSize});let u,p;c.style.setProperty("--offset",`${(n.totalSvgSize-n.size)/-2}px`),c.classList.add("avatar-stories-svg");const m=()=>{const f=e(),y=f.find(b=>b.type==="close");let v=f.map(b=>r(b,!!y));const w=v.reduce((b,S)=>b+S.length,0);w>30&&(v=v.map(b=>({...b,length:Math.floor(b.length/w*30)})).filter(b=>b.length>0)),l.render(v)},g=Ou();return ye($s([g,e],()=>{u=p=void 0,m()})),a?[c,a]:c});return{setStoriesSegments:t,storyDimensions:s,storiesCircle:i}}const Fn=o=>{const[e,t]=ne(!1),[s,i]=ne(),[n,a]=ne(),[r,l]=ne(),[c,d]=ne(),[h,u]=ne(),[p,m]=ne(!1),[g,f]=ne(!1),{setStoriesSegments:y,storyDimensions:v,storiesCircle:w}=rP({size:o.size,colors:o.storyColors,isStoryFolded:o.isStoryFolded}),b=Pt(),S=Pt(),C=I.myId,P=I.managers,L=o.wrapOptions?.middleware?o.wrapOptions.middleware.create():xt();let E=!1,_;ut(()=>{_=void 0,L.destroy(),b.resolve(),T(),o.lazyLoadQueue?.delete({div:Q})});const k=re=>{a(re),t(!0),b.resolve(),S.resolve()},x=re=>{l(re),t(!0),S.resolve()},A=()=>qg(o.peerId,o.threadId),T=()=>{if(!H)return;const re=Po.get(H);re&&(re.delete(void 0),re.size||Po.delete(H));const ge=Oo.get(H);ge?.delete(le)&&(ge.size||Oo.delete(H))},B=async re=>{const ge=L.get(),{peerId:be,useCache:Z}=o,{photo:de,size:Ze}=re,Ne=fe.loadAvatar(be,de,Ze),pe=Ne,Be=!(Ne instanceof Promise),He=!Be&&st.isAvailable("animations");let De;const Ae=De=document.createElement("img");Ae.className=ot("avatar-photo",He&&"fade-in");let Ke,We,Fe,Ue;if(Be)We=()=>{ge()&&k(Ae)};else{if(Ze==="photo_big"){const Lt=await B({photo:de,size:"photo_small"});if(!ge())return;Ke=Lt.loadThumbPromise||Lt.loadPromise,Fe=Lt.thumbImage}else if(de.stripped_thumb){Ue=Fe=document.createElement("img"),Fe.className="avatar-photo avatar-photo-thumbnail";const Lt=JL(de.stripped_thumb);Ke=Ki(Fe,Lt,o.useCache,o.processImageOnLoad).then(()=>{n()||!ge()||x(Ue)})}We=()=>{ge()&&(k(Ae),He?setTimeout(()=>{De.classList.remove("fade-in"),l()},He?sP:0):l())}}const nt=ei(pe,Lt=>{const At=Kn(De,Lt,void 0,Z,o.processImageOnLoad);return ei(At,We),At instanceof Promise?At:Promise.resolve(At)});return{cached:Be,loadPromise:nt,loadThumbPromise:Be?nt:Ke||Promise.resolve(),thumbImage:Fe,thumbElement:Ue,image:De,element:Ae}},R=({abbreviature:re,icon:ge,color:be,isForum:Z,isTopic:de,storiesSegments:Ze})=>{l(),a(),i(ge),d(re),u(be),m(Z),f(de),y(Ze)},O=async()=>{if(!o.withStories||o.peerId===I.myId&&o.isDialog)return;const re=await(await My(o.peerId,o.storyId)).result;_&&await(await _)?.loadThumbPromise,y(re)},X=async re=>{const ge=L.get(),{isDialog:be,withStories:Z,storyId:de,isBig:Ze,peerTitle:Ne,threadId:pe,wrapOptions:Be}=o;let{peerId:He}=o;if(Ne!==void 0&&(He=Tt),He===C&&be){R({icon:o.meAsNotes?"mynotes":"saved",isForum:!o.meAsNotes&&Tc.settings.savedAsForum}),!o.meAsNotes&&Jt(Cs=>{ye($s(()=>Tc.settings.savedAsForum,m,{defer:!0})),ge.onDestroy(Cs)});return}const De=o.peer??fe.getPeer(He);if(Ne){const Cs=km(De),os=Fu(Ne);R({abbreviature:Wo(os),color:Cs});return}if(pe){const Cs=await P.dialogsStorage.getForumTopic(He,pe);return R({isTopic:!0}),Bu({...Be,middleware:ge,topic:Cs,lazyLoadQueue:!1}).then(os=>{k(os)})}if(!ge())return;if(He!==Tt&&He.isUser()&&De?.pFlags?.deleted){R({color:"archive",icon:"deletedaccount"});return}const Ae=!!De?.pFlags?.forum,Ke=Z&&(De?.stories_max_id||de)&&await My(He,de),We=Ke?.cached?await Ke.result:void 0;if(!ge())return;const Fe=Ze?"photo_big":"photo_small",Ue=W0(De),nt=!!Ue,Lt=nt&&!!n(),At=nt&&fe.isAvatarCached(He,Fe);if(!ge())return;let rs=!1;if(!Lt&&!At){let Cs;if(He&&(He!==C||!be)&&(Cs=km(De)),He===cr){R({color:Cs,icon:"reply_filled"});return}if(He===Fg){R({color:"violet",icon:"author_hidden"});return}const os=j0(De);R({abbreviature:Wo(os),color:Cs,isForum:Ae,storiesSegments:We}),rs=!0}if(Ke&&!Ke.cached&&O(),nt){const Cs=B({photo:Ue,size:Fe,onlyThumb:re});if(rs)return Cs;const os=!!We,js=Ae!==p();return Cs.then(({loadThumbPromise:mi})=>mi).then(()=>{ge()&&(os&&y(We),js&&m(Ae))}),Cs}},F=re=>(!re&&!g()&&k(),_=void 0,re);let H;const G=async re=>{const ge=A();if(ge!==H){T(),H=ge;let Ne=Oo.get(ge);Ne||Oo.set(ge,Ne=new Set),Ne.add(le)}re?.peerId!==void 0&&o.peerId!==re.peerId&&(Q.dataset.peerId=""+re.peerId),re&&Object.assign(o,re),L.clean();const be=L.get();if(o.lazyLoadQueue)if(Fp.has(o.peerId))E&&o.lazyLoadQueue.delete({div:Q});else{if(E)return;E=!0;const Ne=A();let pe=Po.get(Ne);pe||Po.set(Ne,pe=new Set),pe.add(le),o.lazyLoadQueue.push({div:Q,load:()=>(Fp.add(o.peerId),G())});const He=await(_=X(!0));return be()?F(He):void 0}Fp.add(o.peerId);const Z=_=X(),de=Po.get(ge);if(de){de.delete(le);const Ne=Array.from(de);Po.delete(ge);for(let pe=0,Be=Ne.length;pe{o.onStoriesStatus(!!v())});const z=()=>({"is-forum":p(),"is-topic":g(),"avatar-relative":!!r()}),q=()=>({...!w()&&z(),"has-stories":!!v()}),$=()=>{const re=v();return{padding:re?(re.size-re.willBeSize)/2+"px":void 0,"--size":g()&&o.wrapOptions.customEmojiSize.width?o.wrapOptions.customEmojiSize.width+"px":void 0}},se=[K((()=>{const re=K(()=>!!s());return()=>re()&&Le(s(),"avatar-icon","avatar-icon-"+s())})()),K(r),K(()=>[n(),c()].find(Boolean))],Y=j(an,{get when(){return v()},fallback:se,get children(){const re=J0(),ge=re.firstChild;return D(re,w,ge),D(re,(()=>{const be=K(()=>o.isStoryFolded!==void 0);return()=>be()&&eP()})(),ge),D(ge,se),Ve(be=>{const Z=`avatar avatar-like avatar-${v().willBeSize}`,de=z(),Ze=h();return Z!==be._v$&&Ce(ge,be._v$=Z),be._v$2=pa(ge,de,be._v$2),Ze!==be._v$3&&Ti(ge,"data-color",be._v$3=Ze),be},{_v$:void 0,_v$2:void 0,_v$3:void 0}),re}});let Q;const le={element:(()=>{const re=tP(),ge=Q;return typeof ge=="function"?wt(ge,re):Q=re,uo(re,Ai({get class(){return`avatar avatar-like avatar-${o.size}`},get classList(){return q()},get"data-color"(){return h()},get"data-peer-id"(){return o.peerId},get"data-story-id"(){return o.storyId},get style(){return $()}},()=>o.props||{}),!1,!0),D(re,Y),re})(),ready:e,readyPromise:b,readyThumbPromise:S,node:Q,render:G,setIcon:i,setStoriesSegments:y,updateStoriesSegments:O,set:R};return(o.peerId!==void 0||o.peerTitle!==void 0||o.peer!==void 0)&&G(),le};function es(o){return Jt(e=>(o.middleware.onDestroy(e),(o.wrapOptions??(o.wrapOptions={})).middleware=o.middleware,Fn(o)))}class Ss extends ee{constructor(e,t={}){if(super("popup-peer"+(e?" "+e:""),{overlayClosable:!0,...t,title:!0,buttons:t.buttons&&fr(t.buttons)}),this.className=e,t.peerId){const i=!!(t.peerId===I.myId&&t.threadId),{node:n}=es({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(M(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(M(t.descriptionLangKey,t.descriptionLangArgs)):t.description&&t.description!==!0?kt(i,t.description):t.descriptionRaw&&i.append(_e(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 pt(i);i.checkboxField=n,s.append(n.label)}),t.buttons.forEach(i=>{if(i.callback){const a=i.callback;i.callback=r=>{const l=new Set;t.checkboxes.forEach(c=>{c.checkboxField.checked&&l.add(c.text)}),a(r,l)}}const n=i.onlyWithCheckbox;if(n){const a=()=>{jt([i.element],!n.checkboxField.checked)};this.listenerSetter.add(n.checkboxField.input)("change",a),a()}})),t.inputField){const i=t.buttons.find(n=>!n.isCancel);this.listenerSetter.add(t.inputField.input)("input",()=>{jt([i.element],!t.inputField.isValid())})}this.header.after(s)}}class Hu{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),a=await Oe({peerId:n?i:e,threadId:n?void 0:i,meAsNotes:n}),r=ee.MANAGERS;t===void 0&&(t=await r.appPeersManager.getDialogType(e,i));const l=(f,y,v=g&&!!y.size)=>{let w=r.appChatsManager.leave(e.toChatId());v&&(w=w.then(()=>r.appMessagesManager.flushHistory(e))),s?.(w)},c=(f,y)=>{let v;if(n)v=r.appMessagesManager.flushHistory(e,!1,!0,i);else if(i)v=r.appMessagesManager.flushHistory(e,!1,!0,i);else if(e.isUser())v=r.appMessagesManager.flushHistory(e,!1,g?!!y.size:void 0);else if(y.size)v=r.appChatsManager.delete(e.toChatId());else return l(f,y);s?.(v)};let d,h,u,p,m,g;switch(t){case"channel":{await r.appChatsManager.hasRights(e.toChatId(),"delete_chat")?(d="ChannelDeleteMenu",u="AreYouSureDeleteAndExitChannel",m=[{langKey:"ChannelDeleteMenu",isDanger:!0,callback:c}],g=[{text:"DeleteChannelForAll"}]):(d="LeaveChannelMenu",u="ChannelLeaveAlertWithName",p=[a],m=[{langKey:"LeaveChannel",isDanger:!0,callback:l}]);break}case"chat":{d="DeleteChatUser",u="AreYouSureDeleteThisChatWithUser",p=[a],m=[{langKey:"DeleteChatUser",isDanger:!0,callback:c}],g=[{text:"DeleteMessagesOptionAlso",textArgs:[await Oe({peerId:e})]}];break}case"saved":{d="DeleteChatUser",u="AreYouSureDeleteThisChatSavedMessages",m=[{langKey:"DeleteChatUser",isDanger:!0,callback:c}];break}case"savedDialog":{d="DeleteChatUser",u="DeleteSavedDialogDescription",p=[a],m=[{langKey:"DeleteChatUser",isDanger:!0,callback:c}];break}case"megagroup":case"group":{i?(d="DeleteTopics",h=[1],u="DeleteSelectedTopic",p=[a],m=[{langKey:"Delete",isDanger:!0,callback:c}]):await r.appChatsManager.hasRights(e.toChatId(),"delete_chat")?(d="DeleteMegaMenu",u="AreYouSureDeleteAndExit",m=[{langKey:"DeleteMegaMenu",isDanger:!0,callback:c}],g=[{text:"DeleteChat.DeleteGroupForAll"}]):(d="LeaveMegaMenu",u="AreYouSureDeleteAndExitName",p=[a],m=[{langKey:"DeleteChatUser",isDanger:!0,callback:(f,y)=>l(f,y,!0)}]);break}}ee.createPopup(Ss,"popup-delete-chat",{peerId:e,threadId:i,titleLangKey:d,titleLangArgs:h,descriptionLangKey:u,descriptionLangArgs:p,buttons:m,checkboxes:g}).show()}}class $u extends Si{constructor(e,t){super(!1),this.navigationType=e,this.withOverlay=t,this.onClick=s=>{Ig(s)||this.element&&!(this.element===document.body)&&Ns(s.target,this.element)||(this.listenerOptions?.capture&&oe(s),this.close())},this.listenerOptions=t?{}:{capture:!0}}close(){this.element&&(this.overlay?.remove(),this.element=void 0,this.dispatchEvent("toggle",!1)),Je||window.removeEventListener("contextmenu",this.onClick,this.listenerOptions),document.removeEventListener(Go,this.onClick,this.listenerOptions),!Ua&&this.navigationType&&ft.removeByType(this.navigationType)}open(e=document.body){this.close(),!Ua&&this.navigationType&&ft.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(Go,s=>{oe(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)),Je||window.addEventListener("contextmenu",this.onClick,{...this.listenerOptions,once:!0}),document.addEventListener(Go,this.onClick,this.listenerOptions),this.dispatchEvent("toggle",!0)}}const Ph=document.createElement("div");Ph.classList.add("toasts-container");const Pa=document.createElement("div");Pa.classList.add("toast");let zr;const mc=new $u("toast");mc.addEventListener("toggle",o=>{o||bo()});function bo(){mc.close(),Pa.classList.remove("is-visible"),zr&&clearTimeout(+zr),zr=window.setTimeout(()=>{Pa.remove(),zr=void 0},200)}function zs(o,e){mc.close(),dt(Pa,o),Pa.parentElement||(Ph.parentNode||document.body.append(Ph),Ph.append(Pa),Pa.offsetLeft),Pa.classList.add("is-visible"),zr&&clearTimeout(+zr),mc.open(Pa),zr=window.setTimeout(bo,3e3),e&&mc.addEventListener("toggle",e,{once:!0})}function Ee(o){zs(M(o.langPackKey,o.langPackArguments),o.onClose)}class _i{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");s.type="radio",s.name="input-radio-"+e.name,e.value&&(s.value=e.value,e.stateKey&&(fe.getState().then(n=>{s.checked=g0(n,e.stateKey)===e.value}),s.addEventListener("change",()=>{I.managers.appStateManager.setByKey(e.stateKey,e.value)})));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&&Zt(i,e.langKey),t.append(s,i)}get checked(){return this.input.checked}set checked(e){this.setValueSilently(e),Sd(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=Le("premium_lock","radio-field-lock")),this.main.classList.add("is-locked"))}setValueSilently(e){this.input.checked=e}}function yw(o,e){const t=document.createElement("form");return o.forEach(s=>{const{container:i,input:n}=s;t.append(i),n.addEventListener("change",a=>{n.checked&&e(n.value,a)})}),t}function Ln(o){return o.reduce((e,t)=>(e.push(...t),e),[])}class oP extends $u{constructor(){super("menu",!0),this.onMouseMove=e=>{U(e.target,"btn-menu-item")?.inner;const s=this.element.getBoundingClientRect(),{clientX:i,clientY:n}=e,a=i>=s.right?i-s.right:s.left-i,r=n>=s.bottom?n-s.bottom:s.top-n;(a>=100||r>=100)&&this.close()},$e.addEventListener("resize",()=>{this.element&&this.close()})}isOpened(){return!!this.element}close(){if(this.element&&(this.element.classList.remove("active"),this.element.parentElement.classList.remove("menu-open"),this.element.classList.contains("night"))){const e=this.element;setTimeout(()=>{e.classList.contains("active")||e.classList.remove("night")},400)}super.close(),Je||window.removeEventListener("mousemove",this.onMouseMove)}openBtnMenu(e,t){Li.isDarkOverlayActive&&e.classList.add("night"),super.open(e),this.element.classList.add("active","was-open"),this.element.parentElement.classList.add("menu-open"),t&&this.addEventListener("toggle",t,{once:!0}),Je||window.addEventListener("mousemove",this.onMouseMove)}}const Js=new oP;let Ey=!1;function vw({doc:o,element:e,size:t,textColor:s,strokeWidth:i}){e.classList.add("is-external"),Ey||(Ey=!0,I.addEventListener("theme_changed",()=>{document.querySelectorAll(".is-external").forEach(l=>{const c=l.set;c?.(!0)})}));const n=async r=>{const l=e.svg,c=Ls.getProperty(s());l.querySelectorAll("path").forEach(h=>{h.setAttributeNS(null,"fill",c),h.style.stroke=c,h.style.strokeWidth=i()+"px"});const d=await v0(l.outerHTML);if(!r)return d;e.image.src=d},a=Ks({container:e,photo:o,boxWidth:t,boxHeight:t,withoutPreloader:!0,noFadeIn:!0,noBlur:!0,processUrl:async r=>{const l=await(await fetch(r)).text(),d=new DOMParser().parseFromString(l,"image/svg+xml").firstElementChild;return e.svg=d,e.set=n,n()}});return a.then(async r=>(e.style.width=e.style.height="",e.image=r.images.full,await r.loadPromises.thumb,a))}function lP(o){if(o.element)return[o.separator,o.element].filter(Boolean);const{icon:e,iconDoc:t,className:s,text:i,onClick:n,checkboxField:a,noCheckboxClickListener:r}=o,l=document.createElement("div"),c=e?.split(" ");l.className="btn-menu-item rp-overflow"+(c?.length>1?" "+c.slice(1).join(" "):"")+(s?" "+s:"")+(o.danger?" danger":""),Oi&&Ni(l),c&&l.append(Le(c[0],"btn-menu-item-icon"));let d=o.textElement;if(d||(d=o.textElement=i?M(i,o.textArgs):document.createElement("span"),o.regularText&&(kt(d,o.regularText),d.dir="")),t){const p=document.createElement("span");p.classList.add("btn-menu-item-icon"),l.append(p);const m=()=>document.documentElement.classList.contains("is-mobile");o.loadPromise=vw({doc:t,element:p,size:24,textColor:()=>m()?"secondary-text-color":"primary-text-color",strokeWidth:()=>m()?.625:.375})}if(d.classList.add("btn-menu-item-text"),l.append(d),o.new){const p=document.createElement("span");p.classList.add("btn-menu-item-badge"),Zt(p,"New"),l.append(p)}const h=!!a||!!o.keepOpen;n&&N(l,p=>{oe(p);const m=U(p.target,"btn-menu");m&&!m.classList.contains("active")||(n(p),o.checkForClose?.()!==!1&&(h||Js.close(),a&&!r&&(a.checked=a.input.type==="radio"?!0:!a.checked)))},o.options),a&&l.append(a.label),(o.separator===!0||o.separatorDown)&&(o.separator=document.createElement("hr")),o.secondary&&(l.classList.add("is-secondary"),o.multiline=!0),o.multiline&&l.classList.add("is-multiline"),o.inner&&(l.append(Le("next","btn-menu-item-icon","btn-menu-item-icon-right")),l.classList.add("has-inner"),l.inner=o.inner);const u=[o.element=l];return o.separator&&u[o.separatorDown?"push":"unshift"](o.separator),u.filter(Boolean)}function jn({listenerSetter:o,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 pt))}),o&&e.forEach(n=>{(n.options??(n.options={})).listenerSetter=o});const i=e.map(lP);return s.append(...Ln(i)),t&&t.forEach(n=>{const a=e.filter(c=>c.radioGroup===n.name),r=document.createElement("hr");a[0].element.replaceWith(r);const l=yw(a.map((c,d)=>{const h=c.checkboxField.input;return h.type="radio",h.name=n.name,h.value=""+ +(d===n.checked),h.checked=d===n.checked,{container:c.element,input:c.checkboxField.input}}),n.onChange);r.before(l),l.append(r)}),s}async function Qg(o){const e=jn(o);return await Promise.all(o.buttons.map(({loadPromise:t})=>t)),e}async function Zi(o,e){const t=o.map(async(s,i,n)=>{if(await e(s,i,n))return s});return(await Promise.all(t)).filter(Boolean)}const bw=8,cP=bw,ww=8,dP=ww;function Tl(o,e,t,s){o.touches&&(o=o.touches[0]);const{pageX:i,pageY:n}=o,a=Array.from(e.children).find(P=>P.classList.contains("btn-menu-items")||P.classList.contains("btn-menu-item")&&!P.classList.contains("hide"))||e;let{scrollWidth:r}=a;const{scrollHeight:l}=e,c=document.body.getBoundingClientRect(),d=c.width,h=c.height;r+=a.offsetLeft*2;let u=bw,p=dP,m=cP,g=ww;s&&(s.top&&(u+=s.top),s.right&&(p+=s.right),s.bottom&&(m+=s.bottom),s.left&&(g+=s.left)),ke.isRTL?t=$e.isMobile?"left":"right":t=$e.isMobile?"right":"left";let f="top";const y=h-l-m,v=d-r-p,w=g,S={x:{left:i,right:Math.min(v,i-r)},intermediateX:t==="right"?w:v,y:{top:n,bottom:n-l},intermediateY:y},C={x:{left:S.x.left+r+p<=d,right:S.x.right>=g},y:{top:S.y.top+l+m<=h,bottom:S.y.bottom-m>=m}};{const P=C.x[t]?S.x[t]:(t="center",S.intermediateX);e.style.left=P+"px"}{const P=C.y[f]?S.y[f]:(f="center",S.intermediateY);e.style.top=P+"px"}return e.className=e.className.replace(/(top|center|bottom)-(left|center|right)/g,""),e.classList.add((f==="center"?f:"bottom")+"-"+(t==="center"?t:(ke.isRTL?t==="right":t==="left")?"right":"left")),{width:r,height:l}}let xm=!1,sh=0;function Sw(){sh&&clearTimeout(sh),sh=window.setTimeout(()=>{sh=0,xm=!1},400),xm=!0}function za({element:o,callback:e,listenerSetter:t,listenerOptions:s}){const i=t?t.add(o):o.addEventListener.bind(o),n=t?t.removeManual.bind(t,o):o.removeEventListener.bind(o);if(Zr&&Je||s){let a;const r={...s||{},capture:!0},l=()=>{clearTimeout(a),n("touchmove",l,r),n("touchend",l,r),n("touchcancel",l,r)};i("touchstart",c=>{if(c.touches.length>1){l();return}i("touchmove",l,r),i("touchend",l,r),i("touchcancel",l,r),a=window.setTimeout(()=>{if(xm){l();return}e(c),l(),Js.isOpened()&&i("touchend",oe,{once:!0})},400)},s)}else i("contextmenu",Je?a=>{e(a),Js.isOpened()&&i("touchend",oe,{once:!0})}:e,s)}function ln({buttons:o,findElement:e,listenTo:t,appendTo:s,filterButtons:i,onOpen:n,onClose:a,onCloseAfter:r,onOpenBefore:l,listenerSetter:c,middleware:d,listenForClick:h}){s??(s=document.body),c??(c=new Ut);const u=new Ut,p=d?d.create():xt();let m;const g=w=>{const b=e?e(w):t;if(!b)return;let S=m;if((w instanceof MouseEvent||w.hasOwnProperty("preventDefault"))&&w.preventDefault(),S&&S.classList.contains("active"))return!1;(w instanceof MouseEvent||w.hasOwnProperty("cancelBubble"))&&(w.cancelBubble=!0),(async()=>{await n?.(w,b);const P=await v();if(!P){a?.();return}b.classList.add("menu-open"),S=P.element;const{cleanup:L,destroy:E}=P;Tl(w,S),Js.openBtnMenu(S,()=>{b.classList.remove("menu-open"),a?.(),L(),setTimeout(()=>{r?.(),E()},300)})})()};za({element:t,callback:g,listenerSetter:c});const f=()=>{u.removeAll(),p.clean()},y=()=>{f(),c.removeAll()},v=async()=>{f(),o.forEach(C=>C.element=void 0);const b=await(i||(C=>Zi(C,P=>P?.verify?ei(P.verify(),L=>L??!1):!0)))(o);if(!b.length)return;const S=m=await Qg({buttons:b,listenerSetter:u});return S.classList.add("contextmenu"),await l?.(),s.append(S),{element:S,cleanup:f,destroy:()=>{S.remove()}}};return d&&d.onDestroy(()=>{y()}),h&&N(t,g,{listenerSetter:c}),{element:m,destroy:y,open:g}}const ih=(o,e)=>{e===!0||(typeof e=="string"?kt(o,e):o.append(e))};class ve{constructor(e={}){this.freezed=!1,e.checkboxFieldOptions&&(e.checkboxField=new pt({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(M(e.subtitleLangKey,e.subtitleLangArgs)):ih(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"),ih(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[a,r]=e.checkboxKeys,l=()=>{dt(this.subtitle,M(this.checkboxField.checked?a:r))};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?ih(this.title,e.title):e.titleLangKey&&this.title.append(M(e.titleLangKey,e.titleLangArgs)),i.append(this.title),n){const a=this.titleRight=document.createElement("div");a.classList.add("row-title","row-title-right"),e.titleRightSecondary&&a.classList.add("row-title-right-secondary"),ih(a,n),i.append(a)}}if(e.icon&&(s=!0,e.iconClasses?.length?this.container.append(Le(e.icon,"row-icon",...e.iconClasses)):this.container.append(Le(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 a=e.navigationTab.constructor.getInitArgs;a&&(i=()=>a())}let n=e.navigationTab.args??i?.();e.clickable=async()=>{n instanceof Promise&&(n=await n);const a=e.navigationTab.slider.createTab(e.navigationTab.constructor);a.open(n);const r=a.eventListener;r&&i&&r.addEventListener("destroyAfter",l=>{n=l.then(()=>i())})}}if((e.clickable||e.radioField||e.checkboxField)&&(typeof e.clickable=="function"&&N(this.container,i=>{this.freezed||e.clickable(i)},{listenerSetter:e.listenerSetter}),this.container.classList.add("row-clickable","hover-effect"),e.noRipple||Ni(this.container,void 0,void 0,!0)),(e.buttonRight||e.buttonRightLangKey)&&(e.rightContent=this.buttonRight=e.buttonRight instanceof HTMLElement?e.buttonRight:ze("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}=ln({...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"),Oa(e),e}createSubtitle(){const e=document.createElement("div");return e.classList.add("row-subtitle"),Oa(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=Le("menu","row-sortable-icon");this.container.classList.add("row-sortable"),this.container.append(e)}toggleSorting(e){this.container.classList.toggle("cant-sort",!e)}}const hP=o=>new ve(o).container,rr=o=>new ve({checkboxField:o,listenerSetter:o.listenerSetter}),xl=(o,e)=>yw(o.map(t=>({container:t.container,input:t.radioField.input})),e),Wh=(o,e,t)=>{const s="name-"+(Math.random()*8388607|0);let i;const n=o.map(({langPackKey:r,value:l,checked:c,textElement:d})=>{const h=new ve({radioField:new _i({textElement:d,langKey:r,name:s,value:""+l})});return c&&(i=h.radioField),h}),a=xl(n,e);return i&&(t?i.checked=!0:i.setValueSilently(!0)),a},Wl=3600,uP=[{value:Wl,langPackKey:"ChatList.Mute.1Hour"},{value:Wl*4,langPackKey:"ChatList.Mute.4Hours"},{value:Wl*8,langPackKey:"ChatList.Mute.8Hours"},{value:Wl*24,langPackKey:"ChatList.Mute.1Day"},{value:Wl*24*3,langPackKey:"ChatList.Mute.3Days"},{value:-1,langPackKey:"ChatList.Mute.Forever",checked:!0}];class Cw extends Ss{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?Cb:Ms(!0)+s,threadId:t})}}],body:!0});let s;const i=Wh(uP,n=>{s=+n},!0);this.body.append(i),this.show()}}function Iw(o,e,t,s){return o>=s?e+t:Lw(o/s,t)+e}function Lw(o,e){return-e/2*(Math.cos(Math.PI*o)-1)}class Vu{constructor(e){this.setHintActive=()=>{this.hint.classList.add("active")};let t;if(e.hint){t=document.createElement("div"),t.classList.add("limit-line-container");const a=this.hint=document.createElement("div");a.classList.add("limit-line-hint","is-locked");const r=Le(e.hint.icon,"limit-line-hint-icon");a.append(r),e.hint.content&&a.append(e.hint.content),this.hintNoStartEnd=e.hint.noStartEnd,t.append(a)}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");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?Zt(i,"LimitFree"):i.append(M("LimitFree"),""+e.limitFree),e.color!==void 0&&n.style.setProperty("--limit-background",e.color),s.append(n),n.append(M("LimitPremium"),""+e.limitPremium)),s.append(i,n),this.container=t||s,t&&t.append(s)}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=a=>{this.container.style.setProperty("--limit-progress",a*100+"%"),this.hint&&(this.hintNoStartEnd?this.hint.style.setProperty("--limit-progress",Kt(a,.1,1-.1)*100+"%"):(this.hint.classList.toggle("is-start",a<=.1),this.hint.classList.toggle("is-end",a>=1-.1)))};if(i!==void 0&&st.isAvailable("animations")){const r=Date.now(),l=e-this.lastProgress;Ba(()=>{const c=(Date.now()-r)/200,d=i+Lw(l*c,1);return n(d),c<1},this.container)}else n(e);s&&this.setProgressElements(s),this.lastProgress=e}_setHintActive(){st.isAvailable("animations")?Qn().then(this.setHintActive):this.setHintActive()}}function Ta(o,e="auto"){if(o===0)return M("FileSize.B",[0]);const t=e==="auto",s=1024,i=Math.floor(Math.log(o)/Math.log(s)),n=e==="auto"?Math.max(0,i-1):e,a=Math.max(0,n),r=["FileSize.B","FileSize.KB","FileSize.MB","FileSize.GB"],l=(o/Math.pow(s,i)).toFixed(a);return M(r[i],[t?l:parseFloat(l)])}const _y=["#ef6922","#e95a2c","#e74e33","#e3433c","#db374b","#cb3e6d","#bc4395","#ab4ac4","#9b4fed","#8958ff","#676bff","#5b79ff","#4492ff","#429bd5","#41a6a5","#3eb26d","#3dbd4a"],pP={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"}]},Pr=o=>e=>e.apiManager.getLimit(o,!0).then(t=>[t]),mP={feature:"double_limits",icon:"premium_limits",titleLangKey:"Premium.Boarding.Double.Title",subtitleLangKey:"Premium.Boarding.Double.Info",headerLangKey:"Premium.Boarding.Double.Title",_subtitleLangArgs:o=>Promise.all(["channels","folders","pin","links"].map(e=>o.apiManager.getLimit(e,!0))),type:"limits",content:[{titleLangKey:"GroupsAndChannelsLimitTitle",subtitleLangKey:"GroupsAndChannelsLimitSubtitle",_subtitleLangArgs:Pr("channels"),limitType:"channels",backgroundColor:"#5B9FFF"},{titleLangKey:"PinChatsLimitTitle",subtitleLangKey:"PinChatsLimitSubtitle",_subtitleLangArgs:Pr("pin"),limitType:"pin",backgroundColor:"#7889FE"},{titleLangKey:"PublicLinksLimitTitle",subtitleLangKey:"PublicLinksLimitSubtitle",_subtitleLangArgs:Pr("links"),limitType:"links",backgroundColor:"#9376FF"},{titleLangKey:"SavedGifsLimitTitle",subtitleLangKey:"SavedGifsLimitSubtitle",_subtitleLangArgs:Pr("gifs"),limitType:"gifs",backgroundColor:"#AB63F2"},{titleLangKey:"FavoriteStickersLimitTitle",subtitleLangKey:"FavoriteStickersLimitSubtitle",_subtitleLangArgs:Pr("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:Pr("folders"),limitType:"folders",backgroundColor:"#DB496F"},{titleLangKey:"ChatPerFolderLimitTitle",subtitleLangKey:"ChatPerFolderLimitSubtitle",_subtitleLangArgs:Pr("folderPeers"),limitType:"folderPeers",backgroundColor:"#E85D43"},{titleLangKey:"ConnectedAccountsLimitTitle",subtitleLangKey:"ConnectedAccountsLimitSubtitle",subtitleLangArgs:[4],free:3,premium:4,backgroundColor:"#F1822A"}]},ky=o=>Ta(o*1.024*512*1024,0),Ty={stories:pP,double_limits:mP,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:o=>o.apiManager.getLimit("uploadFileParts",!0).then(e=>[ky(e)]),subtitleLangKey:"Premium.Boarding.FileSize.Info",_subtitleLangArgs:o=>Promise.all([!1,!0].map(async e=>{const t=await o.apiManager.getLimit("uploadFileParts",e);return ky(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 Pw(o){bi(o.messages,(e,t,s)=>{e.action.photo||(s.splice(t,1),o.count!==void 0&&--o.count)})}class Gu{constructor(e){this.previous=[],this.next=[],this.reverse=!1,this.loadCount=50,this.loadWhenLeft=20,this.loadedAllUp=!1,this.loadedAllDown=!1,It(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.length0),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{const c=this.processItem?this.processItem(l):l;c&&n.push(c)});const r=(await Promise.all(n)).filter(Boolean);(e?this.loadPromiseDown:this.loadPromiseUp)===t&&(e?this.reverse?this.previous.unshift(...r):this.next.push(...r):this.reverse?this.next.push(...r):this.previous.unshift(...r),this.onLoadedMore?.())},()=>{}).then(()=>{e?this.loadPromiseDown=null:this.loadPromiseUp=null}),e?this.loadPromiseDown=t:this.loadPromiseUp=t,t}}class zu extends Gu{constructor(e={}){super({...e,loadMore:async(t,s,i)=>{const n=s?0:i;let a=t?.mid??this.searchContext.maxId;s||(a=await this.managers.appMessagesIdsManager.incrementMessageId(a,1));const r=this.searchContext.peerId||t?.peerId;return this.managers.appMessagesManager.getHistory({...this.searchContext,peerId:r,offsetId:a,offsetPeerId:r?void 0:t?.peerId,limit:n?0:i,backLimit:n}).then(l=>(this.searchContext.inputFilter._==="inputMessagesFilterChatPhotos"&&Pw(l),l.nextRate&&(this.searchContext.nextRate=l.nextRate),l.messages||(l.messages=l.history.map(c=>fe.getMessageByPeer(r,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=a=>a.peerId===t&&s.has(a.mid),n=(a,r,l)=>{i(a)&&l.splice(r,1)};bi(this.previous,n),bi(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(r=>this.processItem(r)))).filter(Boolean);this.searchContext!==s||!n.length||this.previous.concat(this.next,this.current?[this.current]:[]).some(r=>r?.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 zu({...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 Rr{constructor(e,t,s=!0,i,n=!0,a=!0,r,l){this.name=e,this.type=t,this.clearable=s,this.autonomous=a,this.onFound=r,this.noIcons=l,this.list=Xe.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(M(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&&Xe.setListClickListener({list:this.list,onFound:r,withContext:void 0,autonomous:a})}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 gP{constructor(e,t,s,i,n,a,r){this.container=e,this.searchInput=t,this.searchGroups=s,this.onSearch=n,this.noIcons=a,this.fromSavedDialog=r,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 vi(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:a,history:r}=i;a||(a=i.messages=r.map(c=>fe.getMessageByPeer(this.peerId,c))),a.length&&a[0].mid===this.minMsgId&&a.shift();const l=this.searchGroups.messages;a.forEach(c=>{try{const d=this.peerId?c.fromId:c.peerId;Xe.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?at(c.saved_peer_id):I.myId:void 0})}catch(d){console.error("[appSearch] render search result",d)}}),l.toggle(),this.minMsgId=a.length&&a[a.length-1].mid,this.loadedCount===-1&&(this.loadedCount=0),this.loadedCount+=a.length,this.foundCount===-1&&(this.foundCount=n,l.nameEl&&dt(l.nameEl,M(n?"Chat.Search.MessagesFound":"Chat.Search.NoMessagesFound",[n])),this.onSearch?.(this.foundCount))}).catch(i=>{s()&&(console.error("search error",i),this.searchPromise=null)})}}var Am=(o=>(o[o.Connected=0]="Connected",o[o.Connecting=1]="Connecting",o[o.Closed=2]="Closed",o[o.TimedOut=3]="TimedOut",o))(Am||{});const Ur=class Ur{constructor(){this.hadConnect=!1,this.connecting=!1,this.timedOut=!1,this.updating=!1,this.setConnectionStatus=e=>{Promise.all([mm.get("dc"),I.managers.rootScope.getConnectionStatus()]).then(([t,s])=>{t||(t=rc.baseDcId),this.setFirstConnectionTimeout&&(clearTimeout(this.setFirstConnectionTimeout),this.setFirstConnectionTimeout=0);const i=s["NET-"+t],n=i&&(e??i.status)===Am.Connected;this.connecting&&n&&this.managers.apiUpdatesManager.forceGetDifference(),n&&!this.hadConnect&&(this.hadConnect=!0),this.timedOut=i&&(e??i.status)===Am.TimedOut,this.connecting=!n,this.retryAt=i&&i.retryAt,$i&&this.log("connecting",this.connecting),this.setState()})},this.wrapSetStatusText=(...e)=>()=>this.inputSearch.setPlaceholder(...e),this.setState=()=>{if(ir.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 a=Date.now();t.innerText=""+Math.max(0,Math.round((s-a)/1e3)),a>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");$i&&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,$i&&this.log("setState: isShown:",i)};t?s():this.setStateTimeout=window.setTimeout(s,Ur.CHANGE_STATE_DELAY)})}}construct(e,t,s){this.managers=e,this.inputSearch=s,this.log=ri("CS",void 0,void 0),this.inputSearch.setPlaceholder("Search"),I.addEventListener("connection_status_change",i=>{this.setConnectionStatus()}),I.addEventListener("state_synchronizing",()=>{this.updating=!0,$i&&this.log("updating",this.updating),this.setState()}),I.addEventListener("state_synchronized",()=>{$i&&this.log("state_synchronized"),this.updating=!1,$i&&this.log("updating",this.updating),this.setState()}),this.setFirstConnectionTimeout=window.setTimeout(this.setConnectionStatus,Ur.INITIAL_DELAY)}getA(e,t){const s=document.createElement("a");return s.classList.add("force-reconnect"),s.append(M(e)),N(s,i=>{oe(i),t()}),s}};Ur.CHANGE_STATE_DELAY=400,Ur.INITIAL_DELAY=2e3,Ur.ANIMATION_DURATION=250;let Hc=Ur;class wo{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),N(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,a)=>{if(this.currentLangPackKey===n)return;this.currentLangPackKey=n;const r=this.currentPlaceholder;r&&bt({element:r,className:"is-hiding",forwards:!0,duration:Hc.ANIMATION_DURATION,onTransitionEnd:()=>{r.remove()}}),this.currentPlaceholder=M(n,a),this.currentPlaceholder.classList.add("input-search-placeholder","will-animate"),this.container.append(this.currentPlaceholder)},this.onInput=()=>{if(!this.onChange)return;const{value:n,prevValue:a}=this;if(n!==a){if(this.prevValue=n,this.verifyDebounce?.(n,a)===!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 a=this.inputField.isEmpty();this.value="",this.onChange?.(""),this.onClear?.(n,a)},this.clearTimeout=n=>{clearTimeout(this.timeout),this.onDebounce?.(n)},this.inputField=new _t({plainText:!0,withBorder:!e.noBorder}),this.listenerSetter=new Ut,this.container=this.inputField.container,this.container.classList.remove("input-field"),this.container.classList.add("input-search"),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),N(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"),it(e+" "+t.join(" "),{noRipple:!0})}createIcon(e,...t){return Le(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 tn({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()),bt({element:this.container,className:"is-connecting",forwards:e,duration:Hc.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 Dt{constructor(e,t){this._constructor(e,t)}_constructor(e,t=!0){this.slider=e,this.middlewareHelper=e?e.getMiddleware().create():xt(),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=it("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 vi(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 Ut}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(M(e))}}class Xt extends Dt{constructor(e){super(e),this.eventListener=new Si}onClose(){this.eventListener.dispatchEvent("close")}onCloseAfterTimeout(){const e=this.eventListener.dispatchResultableEvent("destroy");return this.eventListener.dispatchEvent("destroyAfter",Promise.all(e).then(Wt,Wt)),this.eventListener.cleanup(),super.onCloseAfterTimeout()}}const Rp=250;class Mw{constructor(e){this.historyTabIds=[],this.canHideFirst=!1,this.onCloseBtnClick=()=>{ft.findItemByType(this.navigationType)?ft.back(this.navigationType):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 a=this.historyTabIds[this.historyTabIds.length-1];return this._selectTab(a!==void 0?a instanceof Dt?a.container:a:this.canHideFirst?-1:0,s),!0},It(this,e),this.tabs??(this.tabs=new Map),this.tabsContainer=this.sidebarEl.querySelector(".sidebar-slider"),this._selectTab=Na({content:this.tabsContainer,type:"navigation",transitionTime:Rp}),this.canHideFirst||this._selectTab(0),this.middlewareHelper=xt()}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(()=>{ft.removeItem(t),this.closeTab(void 0,void 0,!0)}),!1}return this.closeTab(void 0,s,!0),!0}};ft.pushItem(t)}async selectTab(e){if(this.historyTabIds[this.historyTabIds.length-1]===e)return!1;const t=e instanceof Dt?e:this.tabs.get(e);return this.onOpenTab&&await this.onOpenTab(),t&&(t.onOpen?.(),t.onOpenAfterTimeout&&setTimeout(()=>{t.onOpenAfterTimeout()},Rp)),this.pushNavigationItem(t),this.historyTabIds.push(e),this._selectTab(e instanceof Dt?e.container:e),!0}removeTabFromHistory(e){us(this.historyTabIds,e),this.onCloseTab(e,void 0)}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||ft.removeByType(this.navigationType,!0);const i=e instanceof Dt?e:this.tabs.get(e);if(i){try{i.onClose?.()}catch{console.error("tab onClose error",i)}i.onCloseAfterTimeout&&setTimeout(()=>{i.onCloseAfterTimeout()},Rp+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}}class Yg{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=Le("cameraadd","avatar-edit-icon"),this.container.append(this.canvas,this.icon),N(this.container,()=>{ee.createPopup(yb,t).open(this.canvas,e)})}clear(){this.canvas.getContext("2d").clearRect(0,0,this.canvas.width,this.canvas.height)}}const Ei=(o={})=>{const e=ze("btn-circle btn-corner z-depth-1"+(o.className?" "+o.className:""),o);return e.tabIndex=-1,e};function br(o){if(!o)return document.createElement("span");let e,t;switch(o.id){case cr.toUserId():e="Peer.RepliesNotifications";break;case Cd.toUserId():e="Peer.ServiceNotifications";break;default:{if(o.pFlags.bot){e="Bot";break}if(o.pFlags.support){e="SupportStatus";break}switch(o.status?._){case"userStatusRecently":{e="Lately";break}case"userStatusLastWeek":{e="WithinAWeek";break}case"userStatusLastMonth":{e="WithinAMonth";break}case"userStatusOffline":{const s=o.status.was_online,i=new Date,a=(i.getTime()/1e3|0)-s;if(a<60)e="Peer.Status.justNow";else if(a<3600)e="Peer.Status.minAgo",t=[a/60|0];else if(a<86400&&i.getDate()===new Date(s*1e3).getDate())e="LastSeen.HoursAgo",t=[a/3600|0];else{e="Peer.Status.LastSeenAt";const{dateEl:r,timeEl:l}=Ib(s);t=[r,l]}break}case"userStatusOnline":{e="Online";break}default:{e="ALongTimeAgo";break}}break}}return M(e,t)}const Ku=()=>{const o=document.createElement("div");return o.classList.add("gradient-delimiter"),o},jl="sidebar-left-section";class Pe{constructor(e={}){const t=this.container=document.createElement("div");t.classList.add(jl+"-container");const s=this.innerContainer=document.createElement("div");if(s.classList.add(jl),e.noShadow&&s.classList.add("no-shadow"),e.fakeGradientDelimiter)s.append(Ku()),s.classList.add("with-fake-delimiter");else if(e.noDelimiter)s.classList.add("no-delimiter");else{const a=document.createElement("hr");s.append(a)}const i=this.content=this.generateContentElement();if(e.name){const a=this.title=document.createElement("div");a.classList.add("sidebar-left-h2",jl+"-name"),typeof e.name=="string"?Nh({element:a,key:e.name,args:e.nameArgs}):a.append(e.name),i.append(a)}t.append(s);const n=e.caption??e.captionOld;if(n){const a=this.caption=this.generateContentElement();a.classList.add(jl+"-caption"),e.captionOld||t.append(a),n!==!0&&Nh({element:a,key:n,args:e.captionArgs})}}generateContentElement(){const e=document.createElement("div");return e.classList.add(jl+"-content"),this.innerContainer.append(e),e}}const ml=(o,e,t)=>{const s=new Pe({name:e,caption:t});return o.append(s.container),s.content};class Ew extends Dt{constructor(){super(...arguments),this.uploadAvatar=null,this.isGeoChat=!1}init({peerIds:e,isGeoChat:t=!1,onCreate:s,openAfter:i=!0,title:n,asChannel:a=!1}){this.isGeoChat=t,this.peerIds=e,this.container.classList.add("new-group-container"),this.setTitle("NewGroup"),this.avatarEdit=new Yg(g=>{this.uploadAvatar=g});const r=new Pe({}),l=document.createElement("div");l.classList.add("input-wrapper"),this.groupNameInputField=new _t({label:"CreateGroup.NameHolder",maxLength:128}),this.groupLocationInputField=new _t({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=Ei({icon:"arrow_next"}),N(this.nextBtn,()=>{const g=this.groupNameInputField.value,f=this.peerIds.map(v=>v.toUserId());let y;if(this.isGeoChat){if(!this.userLocationAddress||!this.userLocationCoords)return;y=this.managers.appChatsManager.createChannel({title:g,about:"",geo_point:{_:"inputGeoPoint",...this.userLocationCoords},address:this.userLocationAddress,megagroup:!0}).then(v=>(this.uploadAvatar&&this.uploadAvatar().then(w=>{this.managers.appChatsManager.editPhoto(v,w)}),this.peerIds.length&&this.managers.appChatsManager.inviteToChannel(v,this.peerIds),v))}else this.nextBtn.disabled=!0,a?(y=this.managers.appChatsManager.createChannel({megagroup:!0,title:g,about:""}),e.length&&(y=y.then(v=>this.managers.appChatsManager.inviteToChannel(v,f).then(()=>v)))):y=this.managers.appChatsManager.createChat(g,f),y=y.then(v=>(this.uploadAvatar&&this.uploadAvatar().then(w=>{this.managers.appChatsManager.editPhoto(v,w)}),v));y&&y.then(v=>{s?.(v),this.close(),i&&me.setInnerPeer({peerId:v.toPeerId(!0)})})},{listenerSetter:this.listenerSetter});const c=new Pe({name:"Members",nameArgs:[this.peerIds.length]});this.peerIds.length||c.container.classList.add("hide");const d=this.list=Xe.createChatList({new:!0});c.content.append(d),r.content.append(this.avatarEdit.container,l),this.content.append(this.nextBtn),this.scrollable.append(r.container,c.container),t?(this.setTitle("NearbyCreateGroup"),this.groupLocationInputField.container.classList.remove("hide"),this.groupLocationInputField.setValueSilently(ke.format("Loading",!0)),this.startLocating()):this.groupLocationInputField.container.classList.add("hide");const h=Promise.all(this.peerIds.map(g=>this.managers.appUsersManager.getUser(g.toUserId()))),u=this.managers.appUsersManager.getSelf(),p=h.then(g=>g.map(f=>{const{dom:y}=Xe.addDialogNew({peerId:f.id.toPeerId(!1),container:this.list,rippleEnabled:!1,avatarSize:"abitbigger",wrapOptions:{middleware:this.middlewareHelper.get()}});y.lastMessageSpan.append(br(f))}));let m;return n?this.groupNameInputField.setDraftValue(n):m=this.peerIds.length>0&&this.peerIds.length<5?Promise.all([h,u]).then(([g,f])=>{const y=g.map(w=>[w.first_name,w.last_name].filter(Boolean).join(" "));y.unshift(f.first_name);const v=mo(y,w=>w?", ":" & ").join("");this.groupNameInputField.setDraftValue(v)}):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 Ps(o,e,t,s){return s===void 0&&(s=o.parentElement===e?Ri(o):-1),s===t?!1:(s!==-1&&st?e.insertBefore(o,e.children[t]):e.append(o):e.prepend(o),!0)}function Yr(o,e,t,s,i){if(!t)t=r=>r;else if(typeof t!="function"){const r=t;t=l=>l[r]}i||(i=(r,l)=>r-l);const n=t(e);if(s??(s=o.indexOf(e)),s!==-1){const r=o[s-1],l=o[s+1];if((!r||i(t(r),n)>=0)&&(!l||i(t(l),n)<=0))return s;o.splice(s,1)}const a=o.length;if(!a||i(n,t(o[a-1]))<=0)return o.push(e)-1;if(i(n,t(o[0]))>=0)return o.unshift(e),0;for(let r=0;r0)return o.splice(r,0,e),r;return console.error("wtf",o,e),o.indexOf(e)}const fP=Ld("MIDDLEWARE");function so(o,e=fP){return t=>{if(!(t instanceof Promise)){if(t instanceof Error)throw t;return t}return t.then(s=>{if(!o())throw e;return s})}}let yP=0;class _w{constructor(e){It(this,e),this.queue=[],this.middlewareHelper??(this.middlewareHelper=xt());const t="BATCH-PROCESSOR-"+ ++yP,s=Gi.Log|Gi.Warn|Gi.Error;this.log?this.log=this.log.bindPrefix(t,s):this.log=ri(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=so(e,this.possibleError),i=async()=>{t("start",this.queue.length);const a=this.queue.splice(0,this.queue.length),r=performance.now(),l=a.map(d=>(d instanceof Promise&&d.then(h=>{t("render item time",performance.now()-r,h)}),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(Hs(0)).then(()=>i().catch(a=>{throw a!==this.possibleError&&t.error("process queue error",a),a}),a=>{throw t("pause has been cleared"),a}).finally(()=>{this.promise===n&&(this.promise=void 0)});return n}}class Wu{constructor(e){this.updateElementWith=t=>t(),this.updateListWith=t=>t(!0),It(this,e),this.elements=new Map,this.sorted=[],this.middlewareHelper=e.middleware?.create()||xt(),this.batchProcessor=new _w({log:this.log,process:async(t,s,i)=>{const a=t.map(r=>this.update(r.id,r));await s(Promise.all(a))}})}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(a=>(n=!0,a)),Hs(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=Yr(this.sorted,t,"index");this.onSort(t,s)}}function Ha(o,e=" "){if(o===void 0)return"";const t=o.toString().split(".");return t[0]=t[0].replace(/\B(?=(\d{3})+(?!\d))/g,e),t.join(".")}function Xg(o){return o===void 0?"":Ha(o,",")}function kw(o){return o.participants_count||o.participants?.participants?.length||1}function xy(o,e){let t;e?t=kw(e):t=o.participants_count||o.participants?.participants.length;const s=o.pFlags.broadcast;return t=t||1,M(s?"Peer.Status.Subscribers":"Peer.Status.Member",[Ha(t)])}function da(o,e=I.managers,t,s,i){if(t??(t=fe.getChat(o)),t._==="chatForbidden")return M("YouWereKicked");if(s)return xy(t,void 0);const n=i||e.appProfileManager.getCachedFullChat(o);return ei(n,a=>xy(t,a))}function Zg(o){return o.rank||(o._==="channelParticipantAdmin"||o._==="chatParticipantAdmin"?2:o._==="chatParticipantCreator"||o._==="channelParticipantCreator"?1:void 0)}function Tw(o){return typeof o=="object"&&(o=Zg(o)),typeof o=="number"?M(o?o===1?"Chat.OwnerBadge":"ChatAdmin":"Chat.ChannelBadge"):_e(o)}const Iu=class Iu extends Wu{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 da(s.id.toChatId(),this.managers);dt(s.dom.lastMessageSpan,i)}else{const i=br(await this.managers.appUsersManager.getUser(s.id));dt(s.dom.lastMessageSpan,i)}}),onSort:(s,i)=>{const n=s.dom.listEl.parentElement!==this.list;Ps(s.dom.listEl,this.list,i),n&&this.onListLengthChange&&this.onListLengthChange()},onElementCreate:s=>{const i=Xe.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(Tw(n)),s.dom=i.dom,s.dialogElement=i,s},updateElementWith:bs,updateListWith:async s=>{if(!Array.from(this.elements.values()).some(i=>i.id.isUser())||!ca(this.list)||(await As(),!ca(this.list)))return s(!1);s(!0)},middleware:e.middleware}),this.ranks=new Map,this.avatarSize="abitbigger",this.rippleEnabled=!0,this.autonomous=!0,It(this,e),this.list=Xe.createChatList(this.createChatListOptions);const t=()=>{window.setTimeout(()=>{this.updateList(s=>{s&&t()})},Iu.SORT_INTERVAL)};t()}};Iu.SORT_INTERVAL=3e4;let $c=Iu;class kd{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())},It(this,e),this.peerId||(this.peerId=Tt),this.nextBtn?this.nextBtn.classList.contains("btn-corner")||(this.handleChange=()=>{this.nextBtn.toggleAttribute("disabled",!this.isChanged()||this.disabled)}):this.nextBtn=Ei({icon:"check"}),e.withoutAvatar||(this.avatarElem=es({middleware:e.middleware,size:this.avatarSize,peerId:this.peerId}),this.avatarElem.node.classList.add("avatar-placeholder"),e.doNotEditAvatar||(this.avatarEdit=new Yg(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 Ay(o,e){const t=document.createElement(e?"div":"textarea");if(e?(t.tabIndex=0,t.contentEditable="true",t.innerHTML=e):t.value=o,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 Fs(o,e){if(!navigator.clipboard){Ay(o);return}try{if(!e){await navigator.clipboard.writeText(o);return}await navigator.clipboard.write([new ClipboardItem({"text/plain":new Blob([o],{type:"text/plain"}),"text/html":new Blob([e],{type:"text/html"})})])}catch(t){console.error("clipboard error",t),Ay(o,e)}}function ii(o,e,t=!0,s=!0){let i,n,a,r,l=!1;const c=h=>{const u=a,p=r;try{const m=o.apply(null,h);u(m)}catch(m){console.error("debounce error",m),p(m)}},d=(...h)=>{n||(n=new Promise((p,m)=>(a=p,r=m))),i?(clearTimeout(i),l=!0,r(),n=new Promise((p,m)=>(a=p,r=m))):t&&(c(h),l=!1);const u=Oh.setTimeout(()=>{s&&(!t||l)&&c(h),i===u&&(i=n=a=r=void 0,l=!1)},e);return i=u,n.catch(Wt),n};return d.clearTimeout=()=>{i&&(Oh.clearTimeout(i),r(),i=n=a=r=void 0,l=!1)},d.isDebounced=()=>!!i,d}function Fm(o){if(o.length<3||o.length>32||!/[a-zA-Z]/.test(o.charAt(0)))return!1;for(let e=0;e=3&&Fm(o)}class Jg extends _t{constructor(e,t){super(e),this.managers=t,this.checkUsernameDebounced=ii(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(gn.Neutral),this.options.onChange?.();return}else Fm(s)?this.setState(gn.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(gn.Valid,this.options.availableText):this.setError(this.options.takenText))},i=>{if(this.getValue()===e)switch(this.error=i,i.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()&&Fm(i)&&this.checkUsername(i)})}}const Fy=o=>"touches"in o?o.touches[0]:o;function Ry(o,e){return e?Math.hypot(e.pageX-o.pageX,e.pageY-o.pageY):0}function Dy(o,e){return{x:(o.pageX+e.pageX)/2,y:(o.pageY+e.pageY)/2}}const Mr=document;let xw=!1;Js.addEventListener("toggle",o=>{xw=o});const Dp={passive:!1},Bp=!1,bP={capture:!0,passive:!1};class So{constructor(e){this.reset=t=>{this.log("reset"),Je?this.listenerSetter.removeManual(Mr,"touchmove",this.handleMove,Dp):(this.listenerSetter.removeManual(Mr,"mousemove",this.handleMove,Bp),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 a=t.touches;a?.length===2&&(this.initialDistance=Ry(a[0],a[1]),this.initialTouchCenter=Dy(a[0],a[1]));return}const s=Fy(t);if(![0,1].includes(Math.max(0,s.button??0))||(s.button===1&&oe(t),Lb(t)))return;const i=++this.tempId,n=this.verifyTouchTarget?.(t);if(n!==void 0){let a;if(n instanceof Promise){if(a=await n,this.tempId!==i)return}else a=n;if(!a)return this.reset()}if(this.isMouseDown=!0,this.withDelay&&!Je){const a={...Bp,once:!0},r=Pt(),l=()=>r.resolve(),c=this.listenerSetter.add(Mr)("mousemove",l,a);if(await Promise.race([Hs(300),r]),r.resolve(),this.listenerSetter.remove(c),this.tempId!==i)return}this.xDown=s.clientX,this.yDown=s.clientY,this.eventUp=s,Je?this.listenerSetter.add(Mr)("touchmove",this.handleMove,Dp):this.listenerSetter.add(Mr)("mousemove",this.handleMove,Bp),this.onStart&&(this.onStart(),this.hadMove=!0,this.handleMove(s))},this.handleMove=t=>{if(this.xDown===void 0||this.yDown===void 0||xw){this.reset();return}if(this.cancelEvent&&oe(t),this.releaseWheelDrag?.isDebounced()||this.releaseWheelZoom?.isDebounced())return;this.log("move");const s=this.eventUp=Fy(t),i=s.clientX,n=s.clientY,a=i-this.xDown+this.xAdded,r=n-this.yDown+this.yAdded;if(!this.hadMove){if(!a&&!r)return;this.setHadMove(t)}const l=t.touches;if(this.onZoom&&this.initialDistance>0&&l.length===2){const c=Ry(l[0],l[1]),d=Dy(l[0],l[1]),h=d.x-this.initialTouchCenter.x,u=d.y-this.initialTouchCenter.y,m={zoomFactor:c/this.initialDistance,initialCenterX:this.initialTouchCenter.x,initialCenterY:this.initialTouchCenter.y,dragOffsetX:h,dragOffsetY:u,currentCenterX:d.x,currentCenterY:d.y};this.onZoom(m)}this.dispatchOnSwipe(a,r,t)},this.handleWheel=t=>{if(!this.hadMove&&this.verifyTouchTarget){const i=this.verifyTouchTarget(t);if(i!==void 0&&!i){this.reset(t);return}}if(oe(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,a)=>{this.isDragCanceled={x:n,y:a}})},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=Kt(t.deltaY,-25,25);this.wheelZoom-=n*.01;const a={zoomAdd:this.wheelZoom-1,initialCenterX:this.initialTouchCenter.x,initialCenterY:this.initialTouchCenter.y,dragOffsetX:s,dragOffsetY:i,currentCenterX:t.x,currentCenterY:t.y};this.onZoom(a),this.releaseWheelZoom(t)},It(this,e),this.log=ri("SWIPE-HANDLER"),this.cursor??(this.cursor="grabbing"),this.cancelEvent??(this.cancelEvent=!0),this.listenerOptions??(this.listenerOptions=Dp),this.setCursorTo??(this.setCursorTo=this.element),this.listenerSetter=new Ut,this.setListeners(),this.resetValues(),this.tempId=0,e.middleware?.onDestroy(()=>{this.reset(),this.removeListeners()}),this.releaseWheelDrag=ii(this.reset,150,!1),this.releaseWheelZoom=ii(this.reset,150,!1)}setListeners(){Je?(this.withDelay?za({element:this.element,callback:e=>{oe(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(Mr)("touchend",this.reset)):(this.listenerSetter.add(this.element)("mousedown",this.handleStart,this.listenerOptions),this.listenerSetter.add(Mr)("mouseup",this.reset),(this.onZoom||this.onDoubleClick)&&this.listenerSetter.add(this.element)("wheel",this.handleWheel,bP))}removeListeners(){this.log("remove listeners"),this.reset(),this.listenerSetter.removeAll()}setCursor(e=""){this.cursor=e,!Je&&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:lt.width/2,y:lt.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 ef{constructor(e){this.onSwipe=(t,s)=>{s=Kt(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 a=s<0?"previousElementSibling":"nextElementSibling";let r=this.element[a];for(let l=0;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,h=(c?this.elementRect.bottom:this.elementRect.top)+l-this.addScrollPos;let u=2;h+(c?0:this.elementRect.height)>=this.scrollableRect.bottom||(h-(c?this.elementRect.height:0)<=this.scrollableRect.top?u*=-1:u=void 0),u!==void 0&&(this.scrollable.scrollPosition+=u)}},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=Ri(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),Je||N(document.body,oe,{capture:!0,once:!0}),st.isAvailable("animations")&&await Hs(250),this.list.classList.remove("is-reordering"),this.element.classList.remove("is-dragging"),Ps(this.element,this.list,n,i),[this.element,...this.siblings].forEach(a=>{a.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)},It(this,e),this.swipeHandler=new So({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=Ns(e,this.list);return t&&t.classList.contains("cant-sort")&&(t=void 0),t}}function Ct(o){return new Promise((e,t)=>{const{button:s,checkbox:i}=o;s.callback=(l,c)=>{e(i||!c?c?!!c.size:void 0:o.checkboxes.map(d=>c.has(d.text)))};const n=fr(o.buttons||[s]),a=n.find(l=>l.isCancel);a.callback=()=>{t()},o.buttons=n,o.checkboxes??(o.checkboxes=i&&[i]);const r=ee.createPopup(Ss,"popup-confirmation",o);r.addEventListener("closeAfterTimeout",()=>{t()}),r.show()})}const Mh="usernames";class Aw extends ve{constructor(){super({title:!0,subtitle:!0,clickable:!0}),this.container.classList.add(Mh+"-username"),this.subtitle.classList.add(Mh+"-username-status");const e=this.createMedia("medium");e.classList.add(Mh+"-username-icon"),e.append(Le("link"))}}class tf extends Pe{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:a}=e,r=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,h=document.createElement("div");h.classList.add(Mh);let u;const p=new Wu({getIndex:f=>u.length-u.findIndex(y=>y.username===f.id),onDelete:f=>{f.row.container.remove()},onSort:(f,y)=>{Ps(f.row.container,h,y)},onElementCreate:f=>{const y=u.find(S=>S.username===f.id),v=new Aw;v.title.textContent="@"+y.username;const w=!!y.pFlags.editable,b=!!y.pFlags.active;return w&&(v.container.dataset.editable="1"),v.makeSortable(),m(v,b),f.row=v,f},middleware:a}),m=(f,y)=>{f.subtitle.replaceChildren(M(f.container.dataset.editable?c?"UsernameLinkBotUsername":"UsernameLinkEditable":y?"UsernameLinkActive":"UsernameLinkInactive")),f.container.classList.toggle("active",y),f.toggleSorting(y)},g=(f=[])=>{u=f,p.getAll().forEach(y=>{f.some(v=>v.username===y.id)||p.delete(y.id)}),f.forEach(y=>{if(!p.has(y.username))p.add(y.username);else{const v=p.get(y.username);p.update(y.username,v),m(v.row,!!y.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 y=await r.appPeersManager.getPeer(t);g(y.usernames)}),N(h,async f=>{const y=Ns(f.target,h);if(!y)return;if(y.dataset.editable){c||Zs(i.input,!0,!0);return}const v=y.dataset.username,w=y.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 Ct({titleLangKey:b,descriptionLangKey:S,button:{langKey:w?"Hide":"Show"}})}catch{return}const C=!w;r.appUsernamesManager.toggleUsername({peerId:t,username:v,active:C}).catch(L=>{L.type==="USERNAMES_ACTIVE_TOO_MUCH"?Ct({titleLangKey:"UsernameActivateErrorTitle",descriptionLangKey:"UsernameActivateErrorMessage",button:{langKey:"OK",isCancel:!0}}).catch(Wt):console.error("turn username error",L)})}),new ef({list:h,middleware:a,onSort:(f,y)=>{const v=u.splice(f,1)[0];u.splice(y,0,v),p.updateList();const w=u.filter(b=>b.pFlags.active).map(b=>b.username);r.appUsernamesManager.reorderUsernames({peerId:t,order:w})}}),d.content.append(h)}}function Vc(o){return o.username?o.username:o.usernames?.find(s=>s.pFlags.editable)?.username}function sf(){const o=document.createElement("div"),e="https://fragment.com/username/",t=Jr(document.createElement("a")),s=M("Username.Purchase",[t]);return s.classList.add("username-purchase-help"),o.append(s,document.createElement("br"),document.createElement("br")),o.classList.add("hide"),{element:o,setUsername:i=>{i&&(t.href=e+i),o.classList.toggle("hide",!i)}}}class jh extends Dt{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=jh.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 a=ml(this.scrollable,void 0,"Bio.Description"),r=document.createElement("div");r.classList.add("input-wrapper"),this.firstNameInputField=new _t({label:"EditProfile.FirstNameLabel",name:"first-name",maxLength:70}),this.lastNameInputField=new _t({label:"Login.Register.LastName.Placeholder",name:"last-name",maxLength:64}),this.bioInputField=new _t({label:"EditProfile.BioLabel",name:"bio",maxLength:s}),r.append(this.firstNameInputField.container,this.lastNameInputField.container,this.bioInputField.container),t.push(this.firstNameInputField,this.lastNameInputField,this.bioInputField),this.editPeer=new kd({peerId:I.myId,inputFields:t,listenerSetter:this.listenerSetter,middleware:this.middlewareHelper.get()}),this.content.append(this.editPeer.nextBtn),a.append(this.editPeer.avatarEdit.container,r)}{const a=new Pe({name:"EditAccount.Username",caption:!0}),r=document.createElement("div");r.classList.add("input-wrapper"),this.usernameInputField=new Jg({label:"EditProfile.Username.Label",name:"username",plainText:!0,listenerSetter:this.listenerSetter,onChange:()=>{this.editPeer.handleChange();const{error:h}=this.usernameInputField,u=h?.type==="USERNAME_PURCHASE_AVAILABLE";c(u?this.usernameInputField.value:void 0)},availableText:"EditProfile.Username.Available",takenText:"EditProfile.Username.Taken",invalidText:"EditProfile.Username.Invalid"},this.managers),r.append(this.usernameInputField.container);const l=a.caption,{setUsername:c,element:d}=sf();l.append(d,M("UsernameHelp")),t.push(this.usernameInputField),a.content.append(r),this.scrollable.append(a.container)}{const a=new tf({peerId:I.myId,peer:i,listenerSetter:this.listenerSetter,usernameInputField:this.usernameInputField,middleware:this.middlewareHelper.get()});this.scrollable.append(a.container)}N(this.editPeer.nextBtn,()=>{this.editPeer.nextBtn.disabled=!0;const a=[],r=this.managers.appProfileManager.updateProfile(this.firstNameInputField.value,this.lastNameInputField.value,this.bioInputField.value);a.push(r.then(()=>{this.close()},l=>{console.error("updateProfile error:",l)})),this.editPeer.uploadAvatar&&a.push(this.editPeer.uploadAvatar().then(l=>this.managers.appProfileManager.uploadProfilePhoto(l))),this.usernameInputField.isValidToChange()&&a.push(this.managers.appUsersManager.updateUsername(this.usernameInputField.value)),Promise.race(a).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(Vc(i),!0),this.editPeer.handleChange()}}class wP extends Xt{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 Pe({name:e?"ChannelType":"GroupType"}),i=Pd(),n=new ve({radioField:new _i({langKey:e?"ChannelPrivate":"MegaPrivate",name:i,value:"private"}),subtitleLangKey:e?"ChannelPrivateInfo":"MegaPrivateInfo"}),a=new ve({radioField:new _i({langKey:e?"ChannelPublic":"MegaPublic",name:i,value:"public"}),subtitleLangKey:e?"ChannelPublicInfo":"MegaPublicInfo"}),r=xl([n,a],H=>{const G=[[h.container],[E]];H==="public"&&G.reverse(),G[0].forEach(z=>z.classList.remove("hide")),G[1].forEach(z=>z.classList.add("hide")),b(),B&&!t&&B.container.classList.toggle("hide",H!=="public")});let l=fe.getChat(this.chatId);const c={basic:[]},d=(H,G="basic")=>{c[G].push(H)};this.listenerSetter.add(I)("chat_update",H=>{this.chatId===H&&(l=fe.getChat(this.chatId),c.basic.forEach(G=>G()))}),s.content.append(r);const h=new Pe({}),u=new ve({title:this.chatFull.exported_invite.link,subtitleLangKey:e?"ChannelPrivateLinkHelp":"MegaPrivateLinkHelp",clickable:()=>{Fs(this.chatFull.exported_invite.link),zs(ke.format("LinkCopied",!0))},listenerSetter:this.listenerSetter}),p=ze("btn-primary btn-transparent danger",{icon:"delete",text:"RevokeLink"});N(p,()=>{ee.createPopup(Ss,"revoke-link",{buttons:[{langKey:"RevokeButton",callback:()=>{const H=jt([p],!0);this.managers.appProfileManager.getChatInviteLink(this.chatId,!0).then(G=>{H(),u.title.textContent=G})}}],titleLangKey:"RevokeLink",descriptionLangKey:"RevokeAlert"}).show()},{listenerSetter:this.listenerSetter}),h.content.append(u.container,p);const m=new Pe({caption:!0,noDelimiter:!0}),g=document.createElement("div");g.classList.add("input-wrapper");const f="t.me/";let y,v,w;const b=()=>{y=n.radioField.checked&&_!==f||S.isValidToChange()&&S.input.classList.contains("valid"),v=!!R&&R.checkboxField.checked!==X,w=!!O&&O.checkboxField.checked!==F,k.classList.toggle("is-visible",y||v||w);const{error:H}=S,G=H?.type==="USERNAME_PURCHASE_AVAILABLE";C(G?S.getValue():void 0)},S=new Jg({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:C,element:P}=sf();m.caption.append(P,M(e?"Channel.UsernameAboutChannel":"Channel.UsernameAboutGroup"));const L=new tf({peerId:this.chatId.toPeerId(!0),peer:l,listenerSetter:this.listenerSetter,usernameInputField:S,middleware:this.middlewareHelper.get()}),E=document.createElement("div");E.append(m.container,L.container);const _=f+(Vc(l)||"");g.append(S.container),m.content.append(g);const k=Ei({icon:"check",className:"is-visible"});this.content.append(k);const x=()=>a.radioField.checked?S.getValue():"",A=async()=>{const H=x(),G=await this.managers.appChatsManager.migrateChat(this.chatId);return H?this.managers.appChatsManager.updateUsername(G,H):this.managers.appChatsManager.makeChannelPrivate(G)},T=async()=>{if(!x()){const G=fe.getChat(this.chatId),z=Vc(G);z&&await Ct({descriptionLangKey:e?"ChannelVisibility.Confirm.MakePrivate.Channel":"ChannelVisibility.Confirm.MakePrivate.Group",descriptionLangArgs:[z],button:{langKey:"OK"}})}};N(k,async()=>{y&&await T();const H=$g(k);try{y&&await A(),(v||w)&&await Promise.all([v&&this.managers.appChatsManager.toggleJoinToSend(this.chatId,R.checkboxField.checked),w&&this.managers.appChatsManager.toggleJoinRequest(this.chatId,O.checkboxField.checked)]),this.close()}catch{H()}},{listenerSetter:this.listenerSetter}),this.scrollable.append(s.container,h.container,E);let B,R,O,X,F;if(!e){const H=B=new Pe({name:"ChannelSettingsJoinTitle",caption:t?"ChannelSettingsJoinToSendInfo":"ChannelSettingsJoinRequestInfo"});R=new ve({titleLangKey:"ChannelSettingsJoinToSend",checkboxField:new pt({toggle:!0})}),O=new ve({titleLangKey:"ChannelSettingsJoinRequest",checkboxField:new pt({toggle:!0})});const G=()=>t?R.checkboxField.checked:!E.classList.contains("hide"),z=()=>{const $=G();O.container.classList.toggle("hide",!$),!$&&O.checkboxField.checked&&(O.checkboxField.checked=!1)},q=()=>{X=!!l.pFlags.join_to_send,F=!!l.pFlags.join_request,R.checkboxField.setValueSilently(X),O.checkboxField.setValueSilently(F),z(),b()};[R,O].forEach($=>{this.listenerSetter.add($.checkboxField.input)("change",()=>{R===$&&z(),b()})}),t||R.container.classList.add("hide"),d(q),q(),H.content.append(R.container,O.container),this.scrollable.append(H.container)}{const H=new Pe({name:"SavingContentTitle",caption:e?"RestrictSavingContentInfoChannel":"RestrictSavingContentInfoGroup"});let G;const z=new ve({titleLangKey:"RestrictSavingContent",checkboxField:G=new pt({toggle:!0})});this.listenerSetter.add(G.input)("change",()=>{const $=z.toggleDisability(!0);this.managers.appChatsManager.toggleNoForwards(this.chatId,G.checked).then(()=>{$()})});const q=()=>{G.setValueSilently(!!l.pFlags.noforwards)};d(q),q(),H.content.append(z.container),this.scrollable.append(H.container)}(_!==f||ui(l).length?a:n).radioField.checked=!0,S.setOriginalValue(_,!0)}}class nf{constructor(e){this.loading=!1,this.loaded=!1,It(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 SP(o,e){if(o.default_banned_rights){e=Wi(e);const t=o.default_banned_rights.pFlags;for(const s in t)e.pFlags[s]=t[s]}return e}function fa(o,e,t,s){if(!o||o.pFlags.deactivated&&e!=="view_messages")return!1;const i=t===void 0;if(o.pFlags.creator&&i)return!0;if(o._==="chatForbidden"||o._==="channelForbidden"||o.pFlags.left&&!o.pFlags.megagroup||!t&&(t=o.admin_rights||o.banned_rights||o.default_banned_rights,!t))return!1;let n={};t&&(n=t.pFlags);const a=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(!a&&n[e]||o._==="channel"&&!o.pFlags.megagroup&&!n.post_messages)return!1;break}case"delete_messages":case"manage_call":return!!n[e];case"pin_messages":return a?!!(n[e]||!o.pFlags.megagroup&&n.post_messages):!n[e];case"invite_links":return o._==="chat"?!1:a&&!!n.invite_users;case"change_type":case"delete_chat":return!1;case"change_info":case"invite_users":return a||o.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 a&&!!n[e];case"ban_users":case"change_permissions":return a&&!!n.ban_users;case"view_participants":return!!(o._==="chat"||!o.pFlags.broadcast||o.pFlags.creator||o.admin_rights);case"create_giveaway":return a&&!!n.post_messages;case"manage_topics":return a?!!n[e]:!n[e]}return!0}function $a(o){return[...new Set(o)]}function gl(o){return typeof o!="object"?o:o.peer?at(o.peer):o.user_id.toPeerId()}function CP(o){return!!(o&&!o.pFlags.deleted&&o.id.toPeerId()!==cr)}function Fw(o=0){return`index_${o}`}function bn(o,e=Fw(o.folder_id)){return o?.[e]}async function ju({container:o,emoji:e,width:t,height:s,assetName:i,middleware:n,managers:a=I.managers,loop:r=!1,autoplay:l=!0}){o||(o=document.createElement("div")),o.classList.add("media-sticker-wrapper");let c;if(i)c=_s.loadAnimationAsAsset({container:o,loop:r,autoplay:l,width:t,height:s,noCache:!0,middleware:n},i).then(d=>_s.waitForFirstFrame(d));else if(e){const d=await a.appStickersManager.getAnimatedEmojiSticker(e);d&&(c=Rs({doc:d,div:o,loop:r,play:l,width:t,height:s,emoji:e,managers:a,middleware:n}).then(h=>h.render))}return{container:o,promise:c}}const IP=ce("
"),LP=ce("
");async function Rw({middleware:o,title:e,description:t,hide:s,assetName:i="UtyanSearch",width:n=140,height:a=140,isFullSize:r}){const{container:l,promise:c}=await ju({width:n,height:a,assetName:i,middleware:o,loop:!0});if(!o()||(await c,!o()))return;l.classList.add("selector-empty-placeholder-sticker");let d;return Jt(h=>{o.onClean(h),d=(()=>{const u=IP(),p=u.firstChild;return u.classList.toggle("is-full",!!r),D(u,l,p),D(p,e),D(u,(()=>{const m=K(()=>!!t());return()=>m()&&(()=>{const g=LP();return D(g,t),g})()})(),null),Ve(()=>u.classList.toggle("hide",!!s())),u})()}),d}function Dw(o,e,t,s,i,n){const a=o.canvas.dpr;a&&(e*=a,t*=a,s*=a),o.beginPath(),o.arc(e,t,s,0,2*Math.PI,!1),o.closePath(),i&&o.fill()}function PP(o,e,t,s,i,n){return Dw(o,e+s,t+s,s,i)}function Eh(o,e,t,s,i,n,a,r){const l=o.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]}o.beginPath(),o.moveTo(e+n.tl,t),o.lineTo(e+s-n.tr,t),o.quadraticCurveTo(e+s,t,e+s,t+n.tr),o.lineTo(e+s,t+i-n.br),o.quadraticCurveTo(e+s,t+i,e+s-n.br,t+i),o.lineTo(e+n.bl,t+i),o.quadraticCurveTo(e,t+i,e,t+i-n.bl),o.lineTo(e,t+n.tl),o.quadraticCurveTo(e,t,e+n.tl,t),o.closePath(),o.fill()}class MP{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 a=i*(this.diffTime/16.666666666666668);return this.paused?Date.now()-this.pausedTime>n&&(s=t,this.cycleAnimation(),this.paused=!1):(s=parseInt(""+(s+a)),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=Kt(this.lightSource,0,1),s=Kt(this.lightSource-this.lightSpread,0,1),i=Kt(this.lightSource+this.lightSpread,0,1);const a=Ls.getProperty("background-color-true",this.night),r=Ls.getProperty("surface-color",this.night);return e.addColorStop(s,a),e.addColorStop(n,r),e.addColorStop(i,a),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 Bw{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 MP,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:a}=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(a)}detach(e){this.detachTime||(this.availableLength=e,this.detachTime=Date.now(),st.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(!st.isAvailable("animations")){this.remove();return}}else return;const{width:a}=e;t.globalCompositeOperation="destination-out";const r=150,l=15,c=Date.now()-s;let d=!0;for(let h=0;h=n?l*(n-1):l*h,p=c-u;if(p<=0){d=!1;continue}const m=Iw(p,0,1,r);t.beginPath(),t.rect(0,this.dialogHeight*h,a,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(),ll(()=>n()?(st.isAvailable("animations")&&this.renderFrame(),n()):!1),I.addEventListener("theme_changed",this.onThemeChange),$e.addEventListener("resize",this.onResize)}stopAnimation(){++this.tempId,I.removeEventListener("theme_changed",this.onThemeChange),$e.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=Ls.getProperty("surface-color",this.night),i.fillRect(0,0,s.width,s.height),i.fillStyle="#000",i.globalCompositeOperation="destination-out";const a=this.dialogHeight=this.totalHeight*n,r=this.gapVertical*n;let l=0;const c=this.length=Math.ceil(e.height/a);for(let d=0;d{e&&oe(s),o(s)},t}class Mi{constructor(e){this.container=document.createElement("div"),this.list=Xe.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 r in this.tempIds)++this.tempIds[r];const n=this.list;this.oldList=n,this.list=Xe.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 a=n.parentElement?.clientHeight??0;a&&(n.style.overflow="hidden",n.style.height=`${a}px`),a&&this.dialogsPlaceholder?.attach({container:this.section.content,blockScrollable:this.scrollable,getRectFrom:()=>{const r=this.scrollable.container.getBoundingClientRect();return{width:this.section.content.getBoundingClientRect().width,height:r.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=xt();const n=this.emptySearchPlaceholderMiddlewareHelper.get(),[a,r]=ne(this.query),[l,c]=ne(),[d,h]=ne(!1);return this.emptySearchPlaceholderQuerySetter=r,this.emptySearchPlaceholderHideSetter=h,Jt(u=>{n.onClean(u),ye(()=>{c(M("RequestJoin.List.SearchEmpty",[_e(a())]))})}),Rw({middleware:n,title:()=>M("SearchEmptyViewTitle"),description:l,hide:d}).then(u=>{n()&&this.section.content.prepend(u)})}},It(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 Bw(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:a}=this,r=this.middlewareHelperLoader.get();if(a&&(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 Zi(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}),!r())return}await t(i,n),this.promise||this.processPlaceholderOnResults(),this.chatRightsActions?.some(l=>l.startsWith("send_"))&&Zi(i,async l=>{const c=l.toUserId();return this.managers.appUsersManager.isPremiumRequiredToContact(c)}).then(l=>{for(const c of l){const d=this.getElementByPeerId(c.toPeerId(!1));if(!d)continue;const h=Le("premium_lock","selector-premium-lock");d.append(h),d.classList.add("is-premium-locked")}})},!this.noSearch){this.input=document.createElement("input"),this.input.classList.add("selector-search-input"),this.input.type="text",Zt(this.input,this.placeholder||"SendMessageTo",void 0,"placeholder");const i=ii(this.onInput,200,!1,!0);this.input.addEventListener("input",i)}if(this.headerSearch){const i=this.searchSection=new Pe({});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 vi(n),this.multiSelect&&N(this.selectedContainer,a=>{if(this.freezed)return;let r=a.target;if(r=U(r,"selector-user"),!r)return;const l=r.dataset.key,c=this.chatsContainer.querySelector('[data-peer-id="'+l+'"]');c?fs(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 Pe({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 vi(this.chatsContainer),N(this.chatsContainer,i=>{const n=Ch(i.target,"data-peer-id");if(!n||(oe(i),this.freezed))return;let a=n.dataset.peerId;if(a=a.isPeerId()?a.toPeerId():a,a.isPeerId()&&n.classList.contains("is-premium-locked")){Oe({peerId:a,onlyFirstName:!0}).then(c=>{Ee({langPackKey:"OnlyPremiumCanMessage",langPackArguments:[c,ni(()=>{bo(),Vt.show()})]})});return}if(this.onSelect){this.onSelect(a);return}if(!this.multiSelect){this.add({key:a});return}if(!(this.selected.has(a)?this.remove(a):this.add({key:a})))return;const l=n.querySelector("input");l.checked=!l.checked}),this.scrollable.onScrolledBottom=()=>{this.getMoreResults()},this.input&&!this.noDelimiter&&this.scrollable.prepend(Ku()),this.listenerSetter=new Ut,this.container.append(this.chatsContainer),this.appendTo.append(this.container),this.channelParticipantsUpdateFilter&&this.listenerSetter.add(I)("chat_participant",i=>{const n=i.new_participant,a=i.user_id.toPeerId(!1),r=this.channelParticipantsUpdateFilter(n);r?this.participants.set(a,n):this.participants.delete(a),r?this.renderResultsFunc([a],!1):this.deletePeerId(a)}),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=lt.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 a=bn(n[n.length-1])||0;if(n=n.slice(),ga(n,r=>r.peerId===I.myId),this.chatRightsActions&&(n=await Zi(n,r=>this.filterByRights(r.peerId)),!t())||(await this.renderSaved(),!t()))return;this.offsetIndex=a}if(await this.renderResultsFunc(n.map(a=>a.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.sizefa(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[a,r]=await n;if(!i())return;if(r){let l=e?r.my_results.concat(r.results):r.my_results;if(this.chatRightsActions&&(l=await Zi(l,c=>this.filterByRights(c)),!i()))return;this.peerType.includes("dialogs")||(l=l.filter(c=>c.isUser())),this.cachedContacts=$a(a.concat(l))}else this.cachedContacts=a.slice();us(this.cachedContacts,I.myId)}const t=lt.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:a}=n,r=a.map(c=>{const d=gl(c);return this.participants.set(d,c),d});this.exceptSelf&&us(r,I.myId),await this.renderResultsFunc(r);const l=n.count??a.length;(this.list.childElementCount>=l||a.length{e()&&(this.loadedWhat.custom=!0)});const s=await t;if(!e())return;const{result:i,isEnd:n}=s;this.exceptSelf&&us(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(r=>r),a=this.list.childElementCount;if(n&&!a)return this.dialogsPlaceholder?.detach(a),this.processPlaceholderOnResults();(a||n)&&(this.dialogsPlaceholder?.detach(a),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 Zi(e,i=>this.managers.appUsersManager.isNonContactUser(i)));const s=e.map(async i=>{const n=Xe.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:a}=n;if(this.multiSelect){const l=this.selected.has(i);a.containerEl.prepend(this.checkbox(l))}let r;this.getSubtitleForElement&&(r=await this.getSubtitleForElement(i)),r||(r=await this.wrapSubtitle(i)),a.lastMessageSpan.append(r),this.processElementAfter&&await this.processElementAfter(i,n)});return Promise.all(s)}async wrapSubtitle(e){let t;return e.isAnyChat()?t=await da(e.toChatId()):e===I.myId&&this.meAsSaved?t=M(this.selfPresence):t=br(await this.managers.appUsersManager.getUser(e.toUserId())),t}checkbox(e){const t=new pt({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:a=!0}){const r=document.createElement("div");r.classList.add("selector-user"),r.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(Le("close"));const d=es({middleware:r.middlewareHelper.get(),size:i,isDialog:a});d.node.classList.add("selector-user-avatar"),l.append(d.node,c),r.dataset.key=""+e;const h=[];if(e.isPeerId()){if(s===void 0){const u=new Rt;h.push(u.update({peerId:e.toPeerId(),dialog:a})),s=u.element}d.render({peerId:e}),h.push(d.readyThumbPromise)}else n&&d.setIcon(n);if(s){const u=document.createElement("div");u.classList.add("selector-user-title"),typeof s=="string"?u.innerHTML=s:(dt(u,s),u.append(s)),r.append(u)}return r.insertAdjacentElement("afterbegin",l),{element:r,avatar:d,promises:h}}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 a=Mi.renderEntity({key:e,middleware:this.middlewareHelper.get(),title:t,avatarSize:32,fallbackIcon:n}),{element:r}=a;return s&&r.classList.add("scale-in"),this.selectedContainer.insertBefore(r,this.input),i&&this.onChange?.(this.selected.size),s&&this.selectedScrollable.scrollIntoViewNew({element:this.input,position:"center"}),a}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 st.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:Rh.Static})}))}}async function EP({topic:o,middleware:e}){const t=vs(32,32),s=new ve({title:_e(o.title),clickable:!0});s.container.dataset.peerId=""+o.id,s.container.classList.add("selector-forum-topic");const i=s.createMedia("abitbigger"),n=es({peerId:o.peerId,threadId:o.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 Es extends ee{constructor(e){super("popup-forward",{closable:!0,overlayClosable:!0,onBackClick:()=>{this.forumSelector.input.replaceWith(this.selector.input),this.transition(this.selector.container),this.forumNavigationItem&&(ft.removeItem(this.forumNavigationItem),this.forumNavigationItem=void 0)},body:!0,title:e.titleLangKey??!0});const t=!!e.onMultiSelect;let s;const i=async(a,r)=>{if(s)return;if(e.useTopics&&!Array.isArray(a)&&!r&&await this.managers.appPeersManager.isForum(a)){s=!0,await this.createForumSelector({tabsContainer:n,peerId:a,placeholder:e.placeholder,onSelect:i}),s=void 0;return}const l=e.onSelect||e.onMultiSelect;if(l){const c=l(a,r);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 Mi({...e,middleware:this.middlewareHelper.get(),appendTo:n,onChange:t?a=>{this.btnConfirm.classList.toggle("is-visible",!!a)}:void 0,onSelect:t?void 0:i,onFirstRender:()=>{this.show(),this.selector.checkForTriggers(),Je||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=Ei({icon:"check"}),this.body.append(this.btnConfirm),N(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(M(e.headerLangPackKey)):this.title.append(this.selector.input),this.attachScrollableListeners(),this.transition=Na({content:n,type:"navigation",transitionTime:150,animateFirst:!1,onTransitionEnd:a=>{a?this.selector.clearInput():Array.from(n.children).forEach(r=>{r!==this.selector.container&&(r.middlewareHelper.destroy(),r.remove())})}}),this.transition(this.selector.container))}async createForumSelector({tabsContainer:e,peerId:t,placeholder:s,onSelect:i}){const n=this.middlewareHelper.get().create(),a=n.get(),r=Pt();let l,c;const d=this.forumSelector=new Mi({middleware:a,appendTo:e,managers:this.managers,rippleEnabled:!1,night:this.night,multiSelect:!1,headerSearch:!1,placeholder:s,peerType:["custom"],getMoreCustom:async(u,p)=>{c!==u&&(l=void 0,c=u);const m=await this.managers.dialogsStorage.getDialogs({query:u,filterId:t,limit:20,skipMigrated:!0,offsetIndex:l});if(p())return l=bn(m.dialogs[m.dialogs.length-1]),{result:m.dialogs.map(g=>g.id),isEnd:m.isEnd}},renderResultsFunc:async(u,p)=>{const m=u.map(async f=>{const y=await this.managers.dialogsStorage.getForumTopic(t,f);return EP({topic:y,middleware:a})}),g=await Promise.all(m);d.list[p?"prepend":"append"](...g)},onSelect:u=>{i(t,u)},placeholderSizes:{avatarSize:32,avatarMarginRight:23,marginVertical:8,marginLeft:17,lineMarginVertical:11,gapVertical:0,totalHeight:48,statusWidth:0,noSecondLine:!0,night:this.night},onFirstRender:()=>{r.resolve()}});d.container.classList.add("tabs-tab"),d.scrollable.attachBorderListeners(),d.container.middlewareHelper=n,await r,this.btnCloseAnimatedIcon.classList.add("state-back"),this.selector.input.replaceWith(d.input),this.transition(d.container);const h=this.forumNavigationItem={type:"popup",onPop:()=>{fs(this.btnClose)}};ft.pushItem(this.forumNavigationItem),this.addEventListener("close",()=>{ft.removeItem(h)})}destroy(){super.destroy(),this.selector?.destroy(),this.selector=void 0}static async createPicker2({peerType:e,filterPeerTypeBy:t,chatRightsActions:s,multiSelect:i,limit:n,limitCallback:a,titleLangKey:r}){return new Promise((l,c)=>{let d=!1;const h=ee.createPopup(Es,{peerType:e,placeholder:"SelectChat",onSelect:i?void 0:u=>{l(u),d=!0},onMultiSelect:i?u=>{l(u),d=!0}:void 0,filterPeerTypeBy:t,chatRightsActions:s,titleLangKey:r});n&&h.selector.setLimit(n,a),h.addEventListener("close",()=>{d||c()},{once:!0})})}static async createPicker(e=["users","bots","groups","channels"],t){Array.isArray(e)||(e=[]);const s=Mi.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"),ee.createPopup(Es,{...e,peerType:["dialogs","contacts"]})}static createSharingPicker2(e){return new Promise((t,s)=>{let i=!1;Es.createSharingPicker({...e||{},onSelect:a=>{i=!0,t(a)}}).addEventListener("close",()=>{i||s()})})}static createReplyPicker(){return this.createSharingPicker2({placeholder:"ReplyToDialog",selfPresence:"SavedMessagesInfoQuote"})}}function gc(o,e,t){const s=e?._==="channelParticipantCreator",i=e?.promoted_by;return!!o.pFlags.creator||!s&&(!i||i===t)}const Lu=class Lu extends Xt{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",a=gc(t,this.participant,I.myId);let r;this.isAdmin?r=["channelParticipantAdmin","channelParticipantCreator"]:r=["channelParticipantBanned"];{const c=new Pe({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 h=Xe.createChatList({new:!0});d.append(h);const{dom:u}=Xe.addDialogNew({peerId:this.userId.toPeerId(!1),container:h,rippleEnabled:!0,avatarSize:"abitbigger",meAsSaved:!1,wrapOptions:{middleware:this.middlewareHelper.get()}});u.lastMessageSpan.append(br(await this.managers.appUsersManager.getUser(this.userId)));const p={chatId:this.chatId,listenerSetter:this.listenerSetter,appendTo:c.content,participant:r.includes(this.participant._)?this.participant:void 0,chat:t,canEdit:a},m=r.includes(this.participant._)?(this.isAdmin?this.participant.admin_rights:this.participant.banned_rights).pFlags:void 0;if(this.isAdmin){const g=new _P(p),f=g.fields.find(v=>v.flags[0]==="add_admins"),y=()=>{c.caption.replaceChildren(M(a?f.checkboxField.checked?"Channel.Admin.AdminAccess":"Channel.Admin.AdminRestricted":"EditAdminCantEdit"))};y(),this.listenerSetter.add(f.checkboxField.input)("change",y),e=()=>{if(!gc)return;const v=g.takeOut();m&&Di(m,v.pFlags)||this.managers.appChatsManager.editAdmin(this.chatId,this.participant,v,l?.value)}}else{const g=new af(p,this.managers);e=()=>{const f=g.takeOut();m&&Di(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 Pe({name:"EditAdminRank",caption:"EditAdminRankInfo",captionArgs:[M(c)]}),h=document.createElement("div");h.classList.add("input-wrapper");const u=l=new _t({name:"rank",placeholder:c,maxLength:16,canBeEdited:a}),p=this.participant.rank;p&&u.setOriginalValue(p,!0),h.append(u.container),d.content.append(h),this.scrollable.append(d.container)}if(this.isAdmin){const c=new Pe({});if(!n&&gc){const d=ze("btn-primary btn-transparent danger",{icon:"deleteuser",text:"Channel.Admin.Dismiss"});N(d,async()=>{const h=jt([d],!0);try{await this.managers.appChatsManager.editAdmin(this.chatId,this.participant,{_:"chatAdminRights",pFlags:{}},"")}catch{h();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 Pe({});if(this.participant._==="channelParticipantBanned"){const h=ze("btn-primary btn-transparent danger",{icon:"delete",text:"GroupPermission.Delete"});N(h,()=>{const u=jt([h],!0);this.managers.appChatsManager.clearChannelParticipantBannedRights(this.chatId,this.participant).then(()=>{this.eventListener.removeEventListener("destroy",e),this.close()},()=>{u()})},{listenerSetter:this.listenerSetter}),c.content.append(h)}const d=ze("btn-primary btn-transparent danger",{icon:"deleteuser",text:"UserRestrictionsBlock"});N(d,async()=>{const h=jt([d],!0);try{const u=this.userId.toPeerId();await Ct({peerId:this.chatId.toPeerId(!0),descriptionLangKey:"Permissions.RemoveFromGroup",descriptionLangArgs:[await Oe({peerId:u})],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{h();return}this.eventListener.removeEventListener("destroy",e),this.close()},{listenerSetter:this.listenerSetter}),c.content.append(d),this.scrollable.append(c.container)}}};Lu.openTab=(e,t,s,i)=>{const n=e.createTab(Lu);n.participant=s,n.chatId=t,n.userId=gl(s).toUserId(),n.isAdmin=i,n.open()};let Gc=Lu;class qu{constructor(e){It(this,e)}createField(e,t){if(e.nestedTo&&!t)return;const s=t&&!this.round,i=Le("down","accordion-icon");let n;this.round&&!s&&e.nested&&(n=document.createElement("div"),n.classList.add("accordion-right-button"));const a=e.row=new ve({titleLangKey:s?void 0:e.text,titleLangArgs:s?void 0:e.textArgs,checkboxField:e.checkboxField=new pt({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?!Ns(d.target,n)&&d.target!==n:Ns(d.target,a.checkboxField.label)){if(a.checkboxField.input.disabled){const h=a.checkboxField.checked;e.nested.forEach(u=>{u.checkboxField.checked=!h})}else a.checkboxField.checked=!a.checkboxField.checked;return}oe(d),a.container.classList.toggle("accordion-toggler-expanded"),l.classList.toggle("is-expanded"),this.onExpand?.(e)}:void 0,rightContent:n});if(a.container.classList.add("accordion-row"),e.restrictionText){if(!e.nestedTo){const d=e.checkboxField.label.lastElementChild.firstElementChild;d.classList.add("with-lock"),d.append(Le("premium_lock","checkbox-caption-lock"))}e.checkboxField.input.disabled=!0,e.nested||N(e.row.container,d=>{zs(ke.format(e.restrictionText,!0))},{listenerSetter:this.listenerSetter})}const r=[a.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 h=e;e.nested.forEach(u=>{u.nestedTo??(u.nestedTo=h),d.append(...this.createField(u,!0).nodes)}),r.push(d),c=e.nestedCounter=document.createElement("b"),c.classList.add("accordion-counter"),this.setNestedCounter(e),a.container.classList.add("accordion-toggler"),this.round?(n.append(Le(this.rightButtonIcon)," ",c," ",i),a.container.classList.add("accordion-toggler-round")):(a.title.append(" ",c," ",i),a.titleRow.classList.add("with-delimiter")),a.checkboxField.input.disabled=!0,a.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?u=>{const{toggleWith:p,nested:m}=u,g=u.checkboxField.checked,f=g?p.checked:p.unchecked;if(!f)return;this.fields.filter(v=>f.includes(v)).forEach(v=>{v.restrictionText||(v.checkboxField.setValueSilently(g),v.nestedTo&&!m&&this.setNestedCounter(v.nestedTo),v.toggleWith&&d(v))}),u.nested&&this.setNestedCounter(u)}:void 0,h=e.nestedTo?()=>{const u=this.getNestedCheckedLength(e.nestedTo);e.nestedTo.checkboxField.setValueSilently(u===e.nestedTo.nested.length),this.setNestedCounter(e.nestedTo,u)}:void 0;this.listenerSetter.add(e.checkboxField.input)("change",()=>{d?.(e),h?.(),this.onAnyChange?.()})}else this.onAnyChange&&!e.nested&&this.listenerSetter.add(e.checkboxField.input)("change",()=>{this.onAnyChange()});return this.onRowCreation?.(a,e),{row:a,nodes:r}}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}`}}function Rm(o,e,t,s){const i=d=>{t({x:d.pageX,y:d.pageY,event:d})},n=d=>{document.removeEventListener("mousemove",i),o.addEventListener("mousedown",a,{once:!0}),s?.({x:d.pageX,y:d.pageY,event:d})},a=d=>{if(d.button!==0){o.addEventListener("mousedown",a,{once:!0});return}e({x:d.pageX,y:d.pageY,event:d}),i(d),document.addEventListener("mousemove",i),document.addEventListener("mouseup",n,{once:!0})};o.addEventListener("mousedown",a,{once:!0});const r=d=>{d.preventDefault(),t({x:d.touches[0].clientX,y:d.touches[0].clientY,isTouch:!0,event:d})},l=d=>{document.removeEventListener("touchmove",r),o.addEventListener("touchstart",c,{passive:!1,once:!0});const h=d.touches[0]||d.changedTouches[0];s?.({x:h.clientX,y:h.clientY,isTouch:!0,event:d})},c=d=>{e({x:d.touches[0].clientX,y:d.touches[0].clientY,isTouch:!0,event:d}),r(d),document.addEventListener("touchmove",r,{passive:!1}),document.addEventListener("touchend",l,{passive:!1,once:!0})};return o.addEventListener("touchstart",c,{passive:!1,once:!0}),()=>{o.removeEventListener("mousedown",a),document.removeEventListener("mousemove",i),document.removeEventListener("mouseup",n),o.removeEventListener("touchstart",c),document.removeEventListener("touchmove",r),document.removeEventListener("touchend",l)}}class Td{constructor(e,t=0){this.mousedown=!1,this.events={},this.withTransition=!1,this.useTransform=!1,this.vertical=!1,this.onMouseMove=a=>{this.scrub(a)},this.onMouseDown=a=>{this.rect=this.container.getBoundingClientRect(),this.mousedown=!0,this.scrub(a),this.container.classList.add("is-focused"),this.events?.onMouseDown&&this.events.onMouseDown(a)},this.onMouseUp=a=>{this.mousedown=!1,this.container.classList.remove("is-focused"),this.events?.onMouseUp&&this.events.onMouseUp(a)},this.onInput=()=>{const a=+this.seek.value;this.setFilled(a),this.events?.onScrub&&this.events.onScrub(a)},It(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=Rm(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=Kt(t,0,1),this.useTransform?this.filled.style.transform=`scaleX(${t})`:this.filled.style.width=t*100+"%"}scrub(e){const t=this.vertical?this.rect.height:this.rect.width;let s=Kt(this.vertical?-(e.y-this.rect.bottom):e.x-this.rect.left,0,t);!this.vertical&&ke.isRTL&&(s=t-s);let i=this.min+s/t*(this.max-this.min);return i-this.min<(this.max-this.min)/2&&(i-=this.step/10),i=+i.toFixed(this.decimals),i=Kt(i,this.min,this.max),this.setProgress(i),this.events?.onScrub&&this.events.onScrub(i),i}removeListeners(){this._removeListeners&&(this._removeListeners(),this._removeListeners=null),this.seek.removeEventListener("input",this.onInput),this.events={}}}class qh{constructor(e){this.onIndex=i=>{this.onValue?.(this.steps[i][1]),this.optionsElements.forEach(({container:n},a)=>{n.classList.toggle("active",i>=a),n.classList.toggle("is-chosen",i===a)})},It(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 Td({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 a=this.createOption(i,n,s);return this.range.container.append(a.container),a}),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]}}class af extends qu{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=fe.getChat(e.chatId),i=fe.isForum(t),n=this.defaultBannedRights=s.default_banned_rights,a=this.rights=e.participant?SP(s,e.participant.banned_rights):n,r=[{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:r},{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(...r),l.forEach(d=>{const h=d.flags[0];c[h]=d,d.checked=fa(s,h,a)}),r.forEach(d=>d.nestedTo=c.send_media),c.send_media.toggleWith={unchecked:r,checked:r},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":ui(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:h}=this.createField(d);e.appendTo.append(...h)}}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 _P extends qu{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,a=s&&[{flags:["post_messages"],text:"EditAdminPostMessages"},{flags:["edit_messages"],text:"EditAdminEditMessages"},{flags:["delete_messages"],text:"EditAdminDeleteMessages"}],r=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:a},s&&{flags:[c],text:"AdminRights.ManageStories",nested:r},!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 h={};d=d.filter(Boolean),a&&d.push(...a),r&&d.push(...r),d.forEach(m=>{const g=m.flags[0];h[g]=m,m.checked??(m.checked=fa(t,g,n))}),a&&(a.forEach(m=>m.nestedTo=h[l]),h[l].toggleWith={unchecked:a,checked:a}),r&&(r.forEach(m=>m.nestedTo=h[c]),h[c].toggleWith={unchecked:r,checked:r}),this.fields=d;const u=new Set(["anonymous"]),p=e.participant?._==="channelParticipantCreator";for(const m of this.fields){const g=m.flags[0];e.canEdit?(p&&!u.has(g)||!fa(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 kP extends Xt{async init(){this.container.classList.add("edit-peer-container","group-permissions-container"),this.setTitle("ChannelPermissions"),this.participants=new Map;let e;{const t=new Pe({name:"ChannelPermissionsHeader"});e=new af({chatId:this.chatId,listenerSetter:this.listenerSetter,appendTo:t.content,forChat:!0},this.managers),this.eventListener.addEventListener("destroy",()=>{this.managers.appChatsManager.editChatDefaultBannedRights(this.chatId,e.takeOut())},{once:!0}),this.scrollable.append(t.container)}{const t=new Pe({name:"Slowmode",caption:!0}),s=await this.managers.appProfileManager.getChannelFull(this.chatId);let i;const n=new qh({generateStep:c=>{let d;if(!c)d=M("SlowmodeOff");else{const h=Math.floor(c/3600),u=Math.floor(c/60)%60,p=c%60;h?d=M("SlowmodeHours",[h]):u?d=M("SlowmodeMinutes",[u]):d=M("SlowmodeSeconds",[p])}return[d,c]},onValue:c=>{i!==c&&(i=c,c?t.caption.replaceChildren(M("SlowmodeInfoSelected",[kl(yo(c,1))])):t.caption.replaceChildren(M("SlowmodeInfoOff")))},middleware:this.middlewareHelper.get()}),a=[0,10,30,60,300,900,3600],r=n.generateSteps(a),l=s.slowmode_seconds||0;n.setSteps(r,a.indexOf(l)),t.content.append(n.container),this.eventListener.addEventListener("destroy",()=>{const{value:c}=n;c!==l&&this.managers.appChatsManager.toggleSlowMode(this.chatId,n.value)},{once:!0}),this.scrollable.append(t.container)}{const t=new Pe({name:"PrivacyExceptions"}),s=new ve({titleLangKey:"ChannelAddException",subtitleLangKey:"Loading",icon:"adduser",clickable:()=>{ee.createPopup(Es,{peerType:["channelParticipants"],onSelect:p=>{setTimeout(()=>{i(p)},0)},placeholder:"ExceptionModal.Search.Placeholder",peerId:-this.chatId,exceptSelf:!0})},listenerSetter:this.listenerSetter}),i=async p=>{let m=this.participants.get(p);if(!m)try{m=await this.managers.appProfileManager.getParticipant(this.chatId,p)}catch{zs("User is no longer participant");return}const g=this.slider.createTab(Gc);g.participant=m,g.chatId=this.chatId,g.userId=p,g.open()};t.content.append(s.container);const n=t.generateContentElement();n.classList.add("chatlist-container");const a=Xe.createChatList({new:!0});n.append(a),N(a,p=>{const m=Bi(p.target,Nl);if(!m)return;const g=m.dataset.peerId.toPeerId();i(g)},{listenerSetter:this.listenerSetter});const r=async(p,m)=>{const g=m.banned_rights,f=(await this.managers.appChatsManager.getChat(this.chatId)).default_banned_rights,y=[];e.fields.forEach(w=>{const b=w.flags[0];g.pFlags[b]&&!f.pFlags[b]&&y.push(w.exceptionText)});const v=p.lastMessageSpan;y.length?(v.replaceChildren(...pi(y.map(w=>M(w)),!1)),v.classList.toggle("hide",!y.length)):(v.replaceChildren(M("UserRestrictionsBy",[await Oe({peerId:m.kicked_by.toPeerId(!1)})])),v.classList.remove("hide"))},l=(p,m)=>{const g=at(p.peer),f=Xe.addDialogNew({peerId:g,container:a,rippleEnabled:!0,avatarSize:"abitbigger",append:m,wrapOptions:{middleware:this.middlewareHelper.get()}});this.participants.set(g,p),f.dom.listEl.dialogElement=f,r(f.dom,p)};this.listenerSetter.add(I)("chat_participant",p=>{const m=p.new_participant,g=p.prev_participant,f=p.user_id.toPeerId(!1),y=m?._==="channelParticipantBanned"&&!m.banned_rights.pFlags.view_messages;m?this.participants.set(f,m):this.participants.delete(f);const v=a.querySelector(`[data-peer-id="${f}"]`);y?(v?r(v.dialogElement.dom,m):l(m,!1),g?._!=="channelParticipantBanned"&&++d):(v&&v.dialogElement.remove(),g?._==="channelParticipantBanned"&&--d),c()});const c=()=>{const p=M(d?"Permissions.ExceptionsCount":"Permissions.NoExceptions",[d]);dt(s.subtitle,p)};let d=0,h;const u=()=>(h=new nf({scrollable:this.scrollable,getPromise:()=>this.managers.appProfileManager.getChannelParticipants({id:this.chatId,filter:{_:"channelParticipantsBanned",q:""},limit:50,offset:a.childElementCount}).then(m=>{for(const g of m.participants)l(g,!0);return d=m.count,c(),m.participants.length<50||m.count===a.childElementCount})}),h.load());this.scrollable.append(t.container),await this.managers.appChatsManager.isChannel(this.chatId)?await u():(c(),this.listenerSetter.add(I)("dialog_migrate",({migrateFrom:p,migrateTo:m})=>{this.chatId===p&&(this.chatId=m,u())}))}}onOpenAfterTimeout(){this.scrollable.onScroll()}}function rf({doc:o,row:e,size:t,managers:s}){const i=e.media,n=e.createMedia("small");i&&n.classList.add("hide");const a=i?[]:void 0,r=t==="small"?32:48,l=Rs({div:n,doc:o,width:r,height:r,loadPromises:a,managers:s}).then(({render:c})=>c);return a&&Promise.all(a).then(()=>{n.classList.remove("hide"),i.remove()}),l}class Qh extends Xt{static getInitArgs(e){return{availableReactions:I.managers.appReactionsManager.getActiveAvailableReactions(),chatFull:I.managers.appProfileManager.getChatFull(e)}}async init({chatId:e,p:t=Qh.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 a=i.available_reactions??{_:"chatReactionsNone"},r=a,l=new Set(a._==="chatReactionsSome"?a.reactions.map(w=>w.emoticon):[]);const c=w=>w.map(b=>({_:"reactionEmoji",emoticon:b})),d=()=>n?"EnableReactionsChannelInfo":r._==="chatReactionsAll"?"EnableAllReactionsInfo":r._==="chatReactionsNone"?"DisableReactionsInfo":"EnableSomeReactionsInfo",h=new Pe({name:n?void 0:"AvailableReactions",caption:d()}),u=new Pe({name:"OnlyAllowThisReactions"}),p=()=>{const w=r.reactions??[];l=new Set(w.map(({emoticon:b})=>b)),g.forEach((b,S)=>{b.setValueSilently(l.has(S))})};let m;if(n){m=new pt({toggle:!0,checked:a._==="chatReactionsSome"});const w=new ve({checkboxField:m,titleLangKey:"EnableReactions",listenerSetter:this.listenerSetter});h.content.append(w.container),this.listenerSetter.add(m.input)("change",()=>{let b=!0;m.checked?f.every(S=>!S.checked)?r={_:"chatReactionsSome",reactions:c(s.map(({reaction:S})=>S))}:r._!=="chatReactionsSome"?r={_:"chatReactionsSome",reactions:c(Array.from(l))}:b=!1:r={_:"chatReactionsNone"},b&&(p(),v())})}else{const w=[["chatReactionsAll","AllReactions"],["chatReactionsSome","SomeReactions"],["chatReactionsNone","NoReactions"]],b=()=>{u.container.classList.toggle("hide",r._!=="chatReactionsSome")};let S=a._;const C=Wh(w.map(([P,L])=>({langPackKey:L,value:P,checked:a._===P})),P=>{S=P,S==="chatReactionsAll"?r={_:S,pFlags:{allow_custom:!0}}:S==="chatReactionsNone"?r={_:S}:r={_:S,reactions:c(["👍","👎"])},dt(h.caption,M(d())),p(),v(),b()});h.content.append(C),b()}const g=new Map,f=s.map(w=>{const b=w.reaction,S=new pt({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)),v()});const C=new ve({checkboxField:S,title:w.title,havePadding:!0,listenerSetter:this.listenerSetter});return rf({row:C,doc:w.static_icon,size:"small"}),u.content.append(C.container),S}),y=async()=>{v.clearTimeout(),r._==="chatReactionsSome"&&(r.reactions=c(Array.from(l)),r.reactions.length||(r={_:"chatReactionsNone"})),this.managers.appChatsManager.setChatAvailableReactions(this.chatId,r),a=r},v=ii(y,3e3,!1,!0);this.eventListener.addEventListener("destroy",()=>{v.isDebounced()&&y()},{once:!0}),this.scrollable.append(h.container,u.container)}}function Qu(o){const{listenTo:e,appendTo:t,onOpen:s,onClose:i,slider:n,chatId:a,participants:r,middleware:l}=o;let c,d,h,u,p,m,g,f;const y=v=>{Gc.openTab(n,a,d,v)};return ln({listenTo:e,appendTo:t,middleware:l,findElement:v=>c=U(v.target,"chatlist-chat"),onOpen:async()=>(h=c.dataset.peerId.toPeerId(),d=r.get(h),[u,p,g,f]=await Promise.all([I.managers.appChatsManager.getChat(a),I.managers.appChatsManager.isBroadcast(a),I.managers.appChatsManager.hasRights(a,"change_permissions"),I.managers.appChatsManager.hasRights(a,"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:()=>{me.setInnerPeer({peerId:h})}},{icon:"adduser",text:p?"AddToChannel":"AddToGroup",onClick:()=>{m&&I.managers.appChatsManager.addToChat(a,h)},verify:()=>!!m},{icon:"promote",text:"SetAsAdmin",onClick:()=>y(!0),verify:()=>f&&d._==="channelParticipant"},{icon:"admin",text:"EditAdminRights",onClick:()=>y(!0),verify:()=>d._==="channelParticipantAdmin"&&gc(u,d,I.myId)},{icon:"restrict",text:"KickFromSupergroup",onClick:()=>y(!1),verify:()=>g&&(d._==="channelParticipant"||d._==="channelParticipantBanned"&&!d.pFlags.left)},{icon:"delete",text:"Delete",onClick:()=>{m&&I.managers.appChatsManager.editBanned(a,d,{_:"chatBannedRights",pFlags:{},until_date:0})},verify:()=>!(!m||!g||h===I.myId)},{icon:"delete",text:"KickFromGroup",onClick:()=>{I.managers.appChatsManager.kickFromChat(a,h)},verify:()=>g&&h!==I.myId&&d._!=="channelParticipantCreator"&&(d._!=="channelParticipantAdmin"||gc(u,d,I.myId))&&(d._==="channelParticipant"||!m)}]})}function TP(o){const e=Pt();return{selector:new Mi({...o,peerType:["channelParticipants"],multiSelect:!1,headerSearch:!0,placeholder:"SearchPlaceholder",meAsSaved:!1,noShadow:!1,onFirstRender:()=>{e.resolve()}}),loadPromise:e}}class Yh extends Xt{static getInitArgs(e){return{chatFull:I.managers.appProfileManager.getChatFull(e),appConfig:I.managers.apiManager.getAppConfig()}}async init({chatId:e,p:t=Yh.getInitArgs(e)}){const s=e.toPeerId(!0);this.container.classList.add("edit-peer-container","chat-administrators-container"),this.setTitle("PeerInfo.Administrators");const[i,n,a,r]=await Promise.all([this.managers.appChatsManager.getChat(e),this.managers.appChatsManager.isBroadcast(e),t.chatFull,t.appConfig]);this.addBtn=Ei({icon:"addmember_filled",className:"is-visible"}),this.content.append(this.addBtn),N(this.addBtn,()=>{const u=ee.createPopup(Es,{peerType:["channelParticipants"],peerId:s,onSelect:p=>{const m=u.selector.participants.get(p);l(m)},placeholder:"SearchPlaceholder"})},{listenerSetter:this.listenerSetter});const l=async u=>{Gc.openTab(this.slider,e,u,!0)},c=!n&&i.participants_count>=r.telegram_antispam_group_size_min,{selector:d,loadPromise:h}=TP({appendTo:this.content,managers:this.managers,middleware:this.middlewareHelper.get(),peerId:s,channelParticipantsFilter:u=>({_:"channelParticipantsAdmins",q:u}),getSubtitleForElement:async u=>{const p=this.selector.participants.get(u);if(p._==="channelParticipantCreator"||p._==="chatParticipantCreator")return M("ChannelCreator");const m=p.promoted_by.toPeerId(!1);return M("EditAdminPromotedBy",[await Oe({peerId:m})])},onSelect:u=>{const p=this.selector.participants.get(u);l(p)},channelParticipantsUpdateFilter:u=>["channelParticipantAdmin","channelParticipantCreator"].includes(u?._)});if(this.selector=d,c){const u=new Pe({noDelimiter:!0,caption:"ChannelAntiSpamInfo"}),p=!!a?.pFlags?.antispam,m=new ve({titleLangKey:"ChannelAntiSpam",checkboxField:new pt({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}),u.content.append(m.container),this.selector.scrollable.append(u.container,this.selector.scrollable.container.lastElementChild)}return Qu({chatId:e,listenTo:this.selector.scrollable.container,participants:this.selector.participants,slider:this.slider,middleware:this.middlewareHelper.get()}),h}}class Yu extends Dt{init(e){this.container.classList.add("add-members-container"),this.nextBtn=Ei({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 Mi({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=$g(this.nextBtn,"arrow_next");e.then(()=>{this.close()},()=>{t()})}}async function Nw({peerId:o,slider:e}){const t=o.toChatId(),s=await I.managers.appChatsManager.isChannel(t),i=await I.managers.appChatsManager.isBroadcast(t),n=async(r,l)=>{let c,d,h,u,p;if(r.length>1){const m=await Promise.all(r.map(async g=>{const f=document.createElement("b");return f.append(await Oe({peerId:g})),f}));c="AddMembersAlertTitle",d=[M(i?"Subscribers":"Members",[r.length])],h="AddMembersAlertCountText",u=[pi(m)],s||(p=[{text:"AddMembersForwardMessages",checked:!0}])}else{c="AddOneMemberAlertTitle",h="AddMembersAlertNamesText";const m=document.createElement("b");m.append(await Oe({peerId:r[0]})),u=[m],s||(p=[{text:"AddOneMemberForwardMessages",textArgs:[await Oe({peerId:r[0]})],checked:!0}])}u.push(await Oe({peerId:o})),ee.createPopup(Ss,"popup-add-members",{peerId:o,titleLangKey:c,titleLangArgs:d,descriptionLangKey:h,descriptionLangArgs:u,buttons:[{langKey:"Add",callback:l}],checkboxes:p}).show()},a=r=>{r.type==="USER_PRIVACY_RESTRICTED"&&Ee({langPackKey:"InviteToGroupError"})};if(s){const r=e.createTab(Yu);r.open({type:"channel",skippable:!1,takeOut:l=>(n(l,()=>{const c=I.managers.appChatsManager.inviteToChannel(t,l);c.catch(a),r.attachToPromise(c)}),!1),title:i?"ChannelAddSubscribers":"GroupAddMembers",placeholder:"SendMessageTo"})}else ee.createPopup(Es,{peerType:["contacts"],placeholder:"Search",onSelect:r=>{setTimeout(()=>{n([r],(l,c)=>{I.managers.appChatsManager.addChatUser(t,r,c.size?void 0:0).catch(a)})},0)}})}function Ow(o){const e=Pt();return{selector:new Mi({...o,multiSelect:!1,headerSearch:!0,placeholder:"SearchPlaceholder",meAsSaved:!1,noShadow:!1,onFirstRender:()=>{e.resolve()}}),loadPromise:e}}function Uw(o){return Ow({...o,peerType:["channelParticipants"]})}class xP extends Xt{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=Ei({icon:"addmember_filled",className:"is-visible"}),this.content.append(this.addBtn),N(this.addBtn,()=>{Nw({peerId:e.toPeerId(!0),slider:this.slider})},{listenerSetter:this.listenerSetter});const n=t.participants_count,a=!s&&n>=((await this.managers.apiManager.getAppConfig()).hidden_members_group_size_min||0)&&!!t.admin_rights,{selector:r,loadPromise:l}=Uw({appendTo:this.content,managers:this.managers,middleware:this.middlewareHelper.get(),peerId:e.toPeerId(!0),channelParticipantsUpdateFilter:c=>!!c});if(this.selector=r,a){const c=new Pe({noDelimiter:!0,caption:"ChannelHideMembersInfo"}),d=!!i?.pFlags?.participants_hidden,h=new ve({titleLangKey:"ChannelHideMembers",icon:"hide",checkboxField:new pt({name:"hide-members",toggle:!0,listenerSetter:this.listenerSetter,checked:d}),listenerSetter:this.listenerSetter});this.eventListener.addEventListener("destroy",()=>{const u=h.checkboxField.checked;u!==d&&this.managers.appChatsManager.toggleParticipantsHidden(e,u)},{once:!0}),c.content.append(h.container),this.selector.scrollable.append(c.container,this.selector.scrollable.container.lastElementChild)}return Qu({chatId:e,listenTo:this.selector.scrollable.container,participants:this.selector.participants,slider:this.slider,middleware:this.middlewareHelper.get()}),l}}class AP extends Xt{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=Ei({icon:"addmember_filled",className:"is-visible"}),this.content.append(this.addBtn),N(this.addBtn,()=>{const r=ee.createPopup(Es,{peerType:["channelParticipants"],peerId:e.toPeerId(!0),onSelect:l=>{const c=r.selector.participants.get(l);this.managers.appChatsManager.kickFromChat(e,c)},placeholder:"SearchPlaceholder"})},{listenerSetter:this.listenerSetter});const{selector:s,loadPromise:i}=Uw({appendTo:this.content,managers:this.managers,middleware:this.middlewareHelper.get(),peerId:e.toPeerId(!0),channelParticipantsFilter:r=>({_:"channelParticipantsKicked",q:r}),channelParticipantsUpdateFilter:r=>r?._==="channelParticipantBanned"&&r.pFlags.left,getSubtitleForElement:async r=>{const c=this.selector.participants.get(r).kicked_by.toPeerId(!1);return M("UserRemovedBy",[await Oe({peerId:c})])}});this.selector=s;const n=new Pe({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),Qu({listenTo:this.selector.scrollable.container,slider:this.slider,chatId:e,participants:this.selector.participants,middleware:this.middlewareHelper.get()}),i}}function Va(o){if(!st.isAvailable("animations"))return;const e=[{transform:"translateX(0)"},{transform:"translateX(.25rem)"},{transform:"translateX(-.25rem)"},{transform:"translateX(0)"}];o.animate([...e,...e,...e],{duration:300,iterations:1,easing:"ease-in-out"})}class Xh extends Xt{static getInitArgs(){return{animationData:_s.loadAnimationFromURLManually("UtyanDiscussion"),chats:I.managers.appChatsManager.getGroupsForDiscussion()}}async setCaption(){this.caption.replaceChildren(M(this.linkedChatId?this.isBroadcast?"DiscussionChannelGroupSetHelp2":"DiscussionGroupHelp":"DiscussionChannelHelp3",this.linkedChatId?[await Oe({peerId:this.linkedChatId.toPeerId(!0)})]:void 0))}async init({chatId:e,linkedChatId:t,p:s=Xh.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 a=this.caption=document.createElement("div");a.classList.add("caption");const r=new Pe({caption:i?"DiscussionChannelHelp2":"DiscussionGroupHelp2"}),l=Xe.createChatList();l.classList.add("chatlist"),N(l,async f=>{const y=U(f.target,"chatlist-chat");if(!y)return;const v=y.dataset.peerId.toPeerId();if(this.linkedChatId){me.setInnerPeer({peerId:v});return}if(await this.managers.appPeersManager.isForum(v)){Ee({langPackKey:"ChannelTopicsDiscussionForbidden"}),Va(y);return}const w=document.createDocumentFragment();w.append(M("Discussion.Set.Modal.Text.PublicChannelPublicGroup",[await Oe({peerId:v}),await Oe({peerId:this.chatId.toPeerId(!0)})]));const[b,S,C]=await Promise.all([this.managers.appChatsManager.isPublic(v.toChatId()),this.managers.appChatsManager.isPublic(this.chatId),this.managers.appProfileManager.getChatFull(v.toChatId())]),P=document.createElement("br");S||w.append(P.cloneNode(),P.cloneNode(),M("Discussion.Set.PrivateChannel")),b||w.append(P.cloneNode(),P.cloneNode(),M("Discussion.Set.PrivateGroup")),(C._==="chatFull"||C.pFlags.hidden_prehistory)&&w.append(P.cloneNode(),P.cloneNode(),M("DiscussionLinkGroupAlertHistory")),await Ct({peerId:this.chatId.toPeerId(!0),description:w,button:{langKey:"DiscussionLinkGroup"}}),this.managers.appChatsManager.setDiscussionGroup(this.chatId,v.toChatId())},{listenerSetter:this.listenerSetter});let c;i&&(c=ze("btn-primary btn-transparent primary",{icon:"newgroup",text:"DiscussionCreateGroup"}),N(c,async()=>{let f=await ar({peerId:this.chatId.toPeerId(!0),plainText:!0});f+=" Chat",this.slider.createTab(Ew).open({peerIds:[],onCreate:v=>{this.slider.removeTabFromHistory(this),this.managers.appChatsManager.setDiscussionGroup(this.chatId,v)},openAfter:!1,title:f,asChannel:!0})},{listenerSetter:this.listenerSetter}),r.content.append(c)),r.content.append(l);const d=new Pe({}),h=ze("btn-primary btn-transparent danger",{icon:"delete",text:i?"DiscussionUnlinkGroup":"DiscussionUnlinkChannel"});d.content.append(h),N(h,async()=>{const f=this.linkedChatId;await Ct({descriptionLangKey:i?"DiscussionUnlinkChannelAlert":"DiscussionUnlinkGroupAlert",descriptionLangArgs:[await Oe({peerId:f.toPeerId(!0)})],button:{langKey:"DiscussionUnlink"}});const y=jt([h],!0);try{await this.managers.appChatsManager.setDiscussionGroup(i?this.chatId:f,void 0)}catch{}if(!i){this.close();return}y()},{listenerSetter:this.listenerSetter}),this.scrollable.append(n,a,r.container,d.container);const u=[],p=s.animationData.then(async f=>{const y=await f({container:n,loop:!0,autoplay:!0,width:120,height:120});return _s.waitForFirstFrame(y)}),m=(i?s.chats:Promise.resolve([await this.managers.appChatsManager.getChat(this.linkedChatId)])).then(f=>{const y=f.map(v=>{const w=[],{dom:b}=Xe.addDialogNew({peerId:v.id.toPeerId(!0),container:l,rippleEnabled:!0,avatarSize:"abitbigger",loadPromises:w,wrapOptions:{middleware:this.middlewareHelper.get()}}),S=ui(v)[0];return S?b.lastMessageSpan.textContent="@"+S:b.lastMessageSpan.append(M(i?"DiscussionController.PrivateGroup":"DiscussionController.PrivateChannel")),Promise.all(w)});return Promise.all(y)}),g=async()=>{await this.setCaption(),i&&(Array.from(l.children).forEach(f=>{const y=f.dataset.peerId.toChatId();f.classList.toggle("hide",this.linkedChatId?this.linkedChatId!==y:!1)}),d.container.classList.toggle("hide",!this.linkedChatId),c.classList.toggle("hide",!!this.linkedChatId))};return this.listenerSetter.add(I)("dialog_migrate",({migrateFrom:f,migrateTo:y})=>{const v=l.querySelector(`[data-peer-id="${f}"]`);v&&(v.dataset.peerId=""+y)}),this.listenerSetter.add(I)("chat_full_update",async f=>{if(this.chatId!==f)return;const y=await this.managers.appProfileManager.getChannelFull(f);this.linkedChatId=y.linked_chat_id,g()}),u.push(p,m),Promise.all(u).then(()=>g())}}function Hw({el:o,onOpen:e,options:t,onClose:s}){(t?.listenerSetter?t.listenerSetter.add(o):o.addEventListener.bind(o))(Go,n=>{if(!o.classList.contains("btn-menu-toggle")||Ig(n))return!1;if(oe(n),o.classList.contains("menu-open"))Js.close();else{const a=e?.(n);ei(a,()=>{const l=o.querySelector(".btn-menu");l&&Js.openBtnMenu(l,s)})}})}function ai({buttonOptions:o,listenerSetter:e,container:t,direction:s,buttons:i,onOpenBefore:n,onOpen:a,onClose:r,onCloseAfter:l,noIcon:c,icon:d="more"}){o&&(o.asDiv=!0);const h=t??it(c?void 0:d,o);h.classList.add("btn-menu-toggle");const u=new Ut,p=()=>{clearTimeout(g),g=void 0};let m,g,f=0;return Hw({el:h,onOpen:async y=>{const v=++f;if(await n?.(y),v!==f)return;if(g){p();return}const b=await(C=>Zi(C,P=>P?.verify?P.verify()??!1:!0))(i);if(v!==f||!b.length)return;const S=m=await Qg({buttons:b,listenerSetter:u});v===f&&(S.classList.add(s),await a?.(y,S),v===f&&(h.append(S),await Qn(),v!==f&&S.remove()))},options:{listenerSetter:e},onClose:()=>{++f,p(),r?.(),g=window.setTimeout(()=>{l?.(),g=void 0,u.removeAll(),i.forEach(y=>y.element=void 0),m.remove()},300)}}),h}class xd{constructor({buttons:e,button:t,onButtonClick:s,listenerSetter:i,url:n,noRightButton:a,onClick:r}){this.copyLink=(u=this.url)=>{Fs(u),Ee({langPackKey:"LinkCopied"})},this.shareLink=(u=this.url)=>{Es.createSharingPicker({onSelect:p=>{I.managers.appMessagesManager.sendText({peerId:p,text:u}),me.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 h;e?h=ai({buttons:e,direction:"bottom-left",buttonOptions:{noRipple:!0},listenerSetter:i}):a||(h=it("copy",{noRipple:!0}),N(h,()=>this.copyLink(),{listenerSetter:i})),h&&h.classList.add("invite-link-menu"),!t&&t!==!1&&(t=ze("",{text:"ShareLink"}),this.buttonText=t.lastElementChild,N(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),Ni(c),c.append(...[d,h].filter(Boolean)),l.append(c,t||""),N(c,r||(()=>this.copyLink()),{listenerSetter:i})}setUrl(e){let t=e;t.includes("//")&&(t=e.split("//").slice(1).join("//")),this.textElement.replaceChildren(vo(t)),this.url=e}}class of extends Xt{constructor(){super(...arguments),this.isConfirmationNeededOnClose=()=>{if(!this.confirmBtn.classList.contains("hide"))return Ct({descriptionLangKey:"BotWebViewChangesMayNotBeSaved",button:{isDanger:!0,langKey:"BotWebViewCloseAnyway"}})},this.canSelectPeer=e=>!e||!this.chatlistInvite||e._==="user"?!1:!!ui(e).length||fa(e,"invite_links"),this.onSelectChange=e=>{if(this.updateDescription(e),!this.chatlistInvite)return;const t=[...this.selector.selected],s=this.chatlistInvite.peers.map(n=>at(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=Xe.addDialogNew({peerId:s,container:this.selector.list,rippleEnabled:!0,avatarSize:"abitbigger",meAsSaved:!1,wrapOptions:{middleware:this.middlewareHelper.get()}}),{dom:a}=n;this.elementMap.set(s,n);const r=this.selector.selected.has(s);a.containerEl.append(this.selector.checkbox(r));const l=this.canSelectPeer(i);l||a.containerEl.classList.add("cant-select");let c;i._==="user"?c=M(i.pFlags.bot?"SharedFolder.Cant.ShareBots":"SharedFolder.Cant.ShareUsers"):l?c=await da(i.id,void 0,i):c=M("SharedFolder.Cant.Share"),a.lastMessageSpan.append(c)});return Promise.all(t).then(()=>{})}}static getInitArgs(){return{animationData:_s.loadAnimationFromURLManually("Folders_Shared")}}async init(e=of.getInitArgs()){this.container.classList.add("edit-folder-container","shared-folder-container"),this.caption=document.createElement("div"),this.caption.classList.add("caption"),this.descriptionI18n=new ke.IntlElement,this.caption.append(this.descriptionI18n.element),this.stickerContainer=document.createElement("div"),this.stickerContainer.classList.add("sticker-container"),this.confirmBtn=it("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 Pe({name:"InviteLink"}),i=new xd({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 ke.IntlElement;this.selector=new Mi({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=>at(p));this.selector.addInitial(n);const a=$a(n.concat(this.filter.includePeerIds)),r=await Promise.all(a.map(p=>this.managers.appPeersManager.getPeer(p))),l=new Map,c=new Map,d=new Map;r.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)}),r.sort((p,m)=>l.get(m)-l.get(p)),this.selector.renderResultsFunc(r.map(p=>c.get(p)));const h=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 y;m.isUser()?y="SharedFolder.Toast.NoPrivate":y=d.get(m).pFlags.broadcast?"SharedFolder.Toast.NoAdminChannel":"SharedFolder.Toast.NoAdminGroup",Ee({langPackKey:y}),Va(f);return}return h(p)};const u=this.selector.remove.bind(this.selector);this.selector.remove=(...p)=>{const m=p[0].toPeerId();return this.selector.selected.size<=1?(Va(this.elementMap.get(m).container),!1):u(...p)}}return N(this.confirmBtn,()=>{const s=jt([this.confirmBtn],!0);this.managers.filtersStorage.editExportedInvite(this.filter.id,this.chatlistInvite.url,[...this.selector.selected],this.filter.title).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)),this.updateDescription(),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,_s.waitForFirstFrame(i)})])}updateDescription(e=this.chatlistInvite?this.chatlistInvite.peers.length:void 0){this.chatlistInvite?(this.descriptionI18n.update({key:"SharedFolder.Edit.Description",args:[_e(this.filter.title),M("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()})}}function Dm({chatId:o,managers:e,link:t,requested:s}){const i=[],n=new Map;let a="";return{importers:i,importersMap:n,load:async c=>{a!==c&&(i.length=0,n.clear(),a=c);const d=50,h=i[i.length-1],u=await e.appChatInvitesManager.getChatInviteImporters({chatId:o,limit:d,link:t,requested:s,offsetDate:h?.date,offsetUserId:h?.user_id,q:c});return i.push(...u.importers),{result:u.importers.map(p=>{const m=p.user_id.toPeerId(!1);return n.set(m,p),m}),isEnd:u.importers.length{i.splice(i.findIndex(d=>d.user_id.toPeerId(!1)===c),1),n.delete(c)}}}class FP extends Xt{async init(e,t,s,i){const n=await this.managers.appChatsManager.isBroadcast(e);t.title?this.title.replaceChildren(_e(t.title)):this.setTitle("InviteLink");{const r=t.expire_date&&t.expire_date>Ms(!0),l=t.usage_limit&&t.usage_limit<=(t.usage||0),c=new Pe({name:"InviteLink",caption:l?"LinkIsExpiredLimitReached":r?"InviteLinks.ExpiresCaption":t.expire_date?"LinkIsExpired":void 0,captionArgs:r?[ws(t.expire_date)]:void 0}),d=new tI({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 r=new Pe({name:"LinkCreatedeBy"}),l=document.createElement("div");l.classList.add("chatlist-container"),r.content.append(l);const c=Xe.createChatList({new:!0});l.append(c);const d=t.admin_id.toPeerId(!1),{dom:h}=Xe.addDialogNew({peerId:d,container:c,rippleEnabled:!0,avatarSize:"abitbigger",meAsSaved:!1,wrapOptions:{middleware:this.middlewareHelper.get()}});N(h.listEl,()=>{me.setInnerPeer({peerId:d})},{listenerSetter:this.listenerSetter}),h.lastMessageSpan.append(ws(t.date)),this.scrollable.append(r.container)}if(t.usage_limit&&!t.usage&&(!t.expire_date||t.expire_date>Ms(!0))){const r=new Pe({}),l=new ve({title:M("PeopleCanJoinViaLinkCount",[t.usage_limit])});r.content.append(l.container),this.scrollable.append(r.container)}const a=[];if(t.requested){const r=new Pe({name:"JoinRequests",nameArgs:[t.requested]}),{importersMap:l,load:c}=Dm({chatId:e,managers:this.managers,link:t.link,requested:!0}),d=new Map,h=async g=>{const f=[];return g.result.forEach(y=>{const v=Xe.addDialogNew({peerId:y,container:u,rippleEnabled:!0,avatarSize:"abitbigger",append:!0,loadPromises:f,wrapOptions:{middleware:this.middlewareHelper.get()}});d.set(y,v),v.dom.lastMessageSpan.append(ws(l.get(y).date))}),Promise.all(f)},u=Xe.createChatList();r.content.append(u),this.scrollable.append(r.container);let p;const m=async g=>{const f=p.dataset.peerId.toPeerId(),y=d.get(f),v=y.toggleDisability(!0);try{await this.managers.appChatsManager.hideChatJoinRequest(e,f,g),y.remove(),d.delete(f),g&&(t.usage=(t.usage||0)+1),--t.requested||(delete t.requested,r.container.remove()),i?.(t)}catch{v()}};ln({buttons:[{icon:"adduser",text:n?"AddToChannel":"AddToGroup",onClick:()=>m(!0)},{icon:"crossround",text:"Dismiss",onClick:()=>m(!1)}],listenTo:u,listenerSetter:this.listenerSetter,middleware:this.middlewareHelper.get(),findElement:g=>p=U(g.target,"chatlist-chat")}),a.push(c("",()=>!0).then(h))}if(t.usage){const{importersMap:r,load:l}=Dm({chatId:e,managers:this.managers,link:t.link,requested:!1}),c=Pt(),d=new Mi({middleware:this.middlewareHelper.get(),appendTo:this.container,onSelect:h=>{me.setInnerPeer({peerId:h})},peerType:["custom"],getMoreCustom:l,getSubtitleForElement:h=>ws(r.get(h)?.date),sectionNameLangPackKey:M("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 h=M("PeopleJoinedRemaining",[t.usage_limit-t.usage]);h.classList.add("sidebar-left-section-name-right"),d.section.title.append(h)}a.push(c)}return Promise.all(a)}}function io(o,e){return o.reduce((t,s)=>t+s,e)}let ql;function fl(o,e){return ql||(ql=document.createElement("canvas").getContext("2d",{alpha:!1})),ql.font!==e&&(ql.font=e),ql.measureText(o).width}function Zh(o){const e={},t={};return s=>{var n;const i="_"+s;return(n=typeof s=="string"?e:t)[i]??(n[i]=o(s))}}function Xu(o){return o.replace(/\D/g,"")}const By={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+)/},lf={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}},Ad=Zh((o="")=>{const e=Object.keys(By),t=Xu(o);let s,i=0;return e.forEach(n=>{const a=By[n],r=t.match(a);if(r){const l=r[0];l&&l.length>i&&(s=n,i=l.length)}}),s||"unknown"});function RP(o){return o==="diners14"?"diners":o}function $w(o=""){const e=Ad(o);return RP(e)}class Zu{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 a=n.getBoundingClientRect();if(go(n,e,void 0,a,t))i.push({element:n,rect:a});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),Pi&&bs(()=>{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:a}=i,l=n.getBoundingClientRect().bottom-a.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)}}Ws&&(Ws.ScrollSaver=Zu);function nh(o,e,t){const s=new Array(o);return s.fill(e),t?s.map(t):s}const DP=65248,BP=/[0-9]/g;function NP(o){return String.fromCharCode(o.charCodeAt(0)-DP)}function Vw(o){return o.replace(BP,NP)}function Gw(o,e){return{type:"optional",result:o,consumed:e}}function Jh(o,e,t){return{type:"required",result:o,consumed:e,partial:t}}function OP(o,e){return{type:"formatting",result:o,consumed:e}}function Ju(o,e){return t=>{const s=new RegExp("^".concat(o.source.replace(/^\^/,""))),i=t.match(s),n=e?Gw:Jh;if(i){const a=i[0];return n(a,i.index+a.length)}return n("",t.length)}}function UP(o){const e=Ju(/\w/)(o);return e.result?Jh(e.result.toUpperCase(),e.consumed):e}const HP=Ju(/1[0-2]|0?[1-9]|0/);function $P(o){return Ju(/[0-9]/)(Vw(o))}const or={digit:$P,capitalCharacter:UP,month:o=>{const e=HP(Vw(o)),t=Xu(e.result);return["0","1"].includes(e.result)&&o.length===1||e.result==="0"&&o.length>=2?Jh(e.result,o.length,!0):Jh(t.length===1?"0"+t:t,e.consumed)},formattingCharacter:o=>e=>{const t=o===e[0]?1:0;return OP(o,t)},optionalPattern:o=>e=>{const t=Ju(o,!0)(e);return t.result?t:Gw("",0)}},Qt=or.digit,Mo=or.capitalCharacter,yl=or.formattingCharacter(" "),VP=or.optionalPattern(/\d\d/),GP=[Qt,Qt,Qt,Qt,yl,Qt,Qt,Qt,Qt,Qt,Qt,yl,Qt,Qt,Qt,Qt,Qt],zP=[Qt,Qt,Qt,Qt,yl,Qt,Qt,Qt,Qt,Qt,Qt,yl,Qt,Qt,Qt,Qt],KP=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"]),WP=Zh(o=>{const e=[];for(let t=0,s=0;t[or.month,or.formattingCharacter("/"),Qt,Qt,VP],cardCvc:o=>fc.cardCvcFromBrand(Ad(o)),cardCvcFromBrand:Zh(o=>{const e=lf[o],{cvcMinLength:t,cvcMaxLength:s}=e,i=nh(t||s,Qt);if(t&&t{switch(o){case"US":return nh(5,Qt);case"CA":return gm?null:[Mo,Mo,Mo,yl,Mo,Mo,Mo];default:const e=nh(10,or.optionalPattern(/\d/));return KP.has(o)&&(e[0]=Qt),e}})};function ah(o){return io(o.map(e=>e.length),0)}function qP(o,e,t={},s){const i=o(e);if(!i)return{value:e,selection:null,autocorrectComplete:!!e};const n=i.length,a=[],r=[];let l=0,c=0,d=t.selectionStart===0?0:null,h=t.selectionEnd===0?0:null;const u=()=>{d===null&&c+1>=t.selectionStart&&(d=ah(a)+(s?r.length:0)),h===null&&c+1>=t.selectionEnd&&(h=ah(a)+(s?r.length:0))},p=m=>{m>0&&(u(),c+=m)};for(;l=e.length)break;r.push(y),++l,p(v)}}return s&&a.push(...r),{value:a.join(""),selection:{selectionStart:d===null||e.length&&t.selectionStart===e.length?ah(a):d,selectionEnd:h===null||e.length&&t.selectionEnd===e.length?ah(a):h},autocorrectComplete:l===n}}function QP(o){const{value:e,getPattern:t,deleting:s,input:i}=o,n=!s&&!!e.length,a=qP(t,e,{selectionStart:i?i.selectionStart:0,selectionEnd:i?i.selectionEnd:0},n),{value:r,selection:l}=a;return{value:r,meta:{autocorrectComplete:a.autocorrectComplete,empty:!r},selection:l}}const cf="‎",YP=new RegExp(cf,"g");function zc(o){return o?{type:"invalid",code:o}:null}function XP(o){const t=o.length%2;let s=0;for(let i=o.length-1;i>=0;--i){const n=t===i%2;let a=o.charCodeAt(i)-48;n&&(a*=2),a>9&&(a-=9),s+=a}return!(s%10)}function ZP(o,e,t){const s=t.date||new Date,i=o<100?s.getFullYear()%100:s.getFullYear(),n=s.getMonth()+1;return isNaN(o)||isNaN(e)?t?.ignoreIncomplete?null:"incomplete":o-i<0?"invalid_expiry_year_past":o-i>50?"invalid_expiry_year":!(o-i)&&e=e?XP(o)||Ad(o)==="mir"?null:zc("invalid"):t?null:zc("incomplete")}function tM(o,e={}){const{sanitized:t,minLength:s}=JP(o);return eM(t,s,e.ignoreIncomplete)}function Ny(o,e={}){const t=o.replace(YP,"").split(/ ?\/ ?/),[s,i=""]=t,[n,a]=[s,i].map(l=>+l),r=i.length===2?a%100:a;return i.length<2||i.length===3?e.ignoreIncomplete?null:zc("incomplete"):zc(ZP(r,n,e))}function sM(o,e,t={}){return o.meta.autocorrectComplete||t.ignoreIncomplete?null:zc("incomplete")}const Bm=new WeakMap;window.addEventListener("message",o=>{const e=Bm.get(o.source);e&&e(JSON.parse(o.data))});class zw extends Si{constructor({url:e,sandbox:t,allow:s,onLoad:i}){super(!1),this.onTelegramWebViewEvent=({eventType:a,eventData:r})=>{r===""&&(r=void 0),this.dispatchEvent(a,r)};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(){Bm.set(this.iframe.contentWindow,this.onTelegramWebViewEvent)}destroy(){this.cleanup(),Bm.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 Kw(o){const e=new zw({...o,sandbox:"allow-forms allow-scripts allow-same-origin allow-modals"}),{iframe:t}=e;return t.allow="payment",t.classList.add("payment-verification"),e}class iM extends ee{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=Kw({url:this.url});e.addEventListener("web_app_open_tg_link",t=>{this.dispatchEvent("finish"),this.hide(),this.openPathAfter&&me.openUrl("https://t.me"+t.path_full)}),this.body.append(e.iframe),this.show(),e.onMount()}destroy(){return this.telegramWebView.destroy(),super.destroy()}}class Dr extends _t{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=QP({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=sM(this.lastTransformed,e,t),i?.code){const n=this.options.errorKeys?.[i.code];return!s&&this.setState(gn.Error,n),!1}return!s&&this.setState(gn.Neutral),!0}}function Ww(o,e){const t=()=>{const s=o.every(i=>"validateNew"in i?i.validateNew(void 0,void 0,!0):i.isValid());e(s)};return o.forEach(s=>{if(s instanceof Dr){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 jw(o,e){let t,s;return(o||e)&&(o&&(t=new f0({noPhoneCodes:!0,onCountryChange:()=>{s?.update()},required:!0,autocomplete:"country"})),e&&(s=new Dr({label:"PaymentShippingZipPlaceholder",plainText:!0,inputMode:"numeric",autocomplete:"postal-code",formatMethod:()=>{const{country:i}=t.getSelected(),n=i?.iso2;return fc.postalCodeFromCountry(n&&n.toUpperCase())}}))),{countryInputField:t,postcodeInputField:s}}const Oy=new Set(["stripe","smartglocal"]);class nM extends ee{constructor(e,t,s){if(super("popup-payment popup-payment-card",{closable:!0,overlayClosable:!0,body:!0,scrollable:Oy.has(e.native_provider),title:"PaymentCardInfo"}),this.paymentForm=e,this.user=t,this.savedCard=s,Oy.has(e.native_provider))this.d();else{const i=this.telegramWebView=Kw({url:e.url});i.addEventListener("payment_form_submit",n=>{const a={title:n.title,save:!1};this.dispatchEvent("finish",{token:n.credentials,card:a}),this.hide(),e.pFlags.can_save_credentials&&Ct({titleLangKey:"PaymentCardSavePaymentInformation",descriptionLangKey:"PaymentCardSavePaymentInformationInfoLine1",button:{langKey:"Save"}}).then(()=>{a.save=!0},Wt)}),this.body.append(i.iframe),this.show(),i.onMount()}}destroy(){return this.telegramWebView?.destroy(),super.destroy()}d(){const e=this.savedCard,t=new Pe({name:"PaymentInfo.Card.Title",noDelimiter:!0,noShadow:!0}),s=JSON.parse(this.paymentForm.native_params.data);let i,n=0,a;const r=L=>{if(i===L)return;const E=++n;i=L;const _=JC(L);if(!_){a&&(a.remove(),a=void 0);return}const k=new Image;k.classList.add("input-field-icon"),Ki(k,_,!1).then(()=>{n===E&&(a?a.replaceWith(k):l.container.append(k),a=k)})},l=new Dr({label:"PaymentCardNumber",plainText:!0,inputMode:"numeric",autocomplete:"cc-number",formatMethod:fc.cardNumber,validateMethod:tM,errorKeys:{invalid:"PaymentCard.Error.Invalid",incomplete:"PaymentCard.Error.Incomplete"},onChange:L=>{r($w(L.value)),u.update()}});let c;s.need_cardholder_name&&(c=new _t({label:"Checkout.NewCard.CardholderNamePlaceholder",maxLength:255,required:!0,autocomplete:"cc-name"}));const d=_l(this.user.phone),h=new Dr({label:"SecureId.Identity.Placeholder.ExpiryDate",plainText:!0,inputMode:"numeric",autocomplete:"cc-exp",formatMethod:fc.cardExpiry,validateMethod:d.country.iso2==="RU"?(L,E)=>Ny(L,{...E||{},date:new Date(2022,0,1)}):Ny});h.input.addEventListener("input",()=>{let L=h.value;if(L.length<5)return;const E=L.split("/");E[1].length===4&&(L=[E[0],E[1].slice(2)].join("/"),h.setValueSilently(L))},{capture:!0});const u=new Dr({labelText:"CVC",plainText:!0,inputMode:"numeric",autocomplete:"cc-csc",name:"cvc",formatMethod:()=>fc.cardCvc(l.value)});new p0(u.container,u.input);const p=[l,h,u,c].filter(Boolean);p.forEach(L=>{const E=_=>{if(!L.value&&_.key==="Backspace"){const k=p[p.indexOf(L)-1];k&&Zs(k.input,!0)}};if(L instanceof Dr){L.options.onKeyDown=E;const _=L.options.onChange;L.options.onChange=k=>{if(_?.(k),document.activeElement===L.input&&k.meta.autocorrectComplete)for(let x=p.indexOf(L),A=p.length;xL.container)));const w=!!this.paymentForm.pFlags.can_save_credentials,b=new pt({text:"PaymentCardSavePaymentInformation",checked:!!w}),S=new ve({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(L=>L.container));const C=Cl({key:"PaymentInfo.Done",onClick:async()=>{const L={cardNumber:l.value,expiryFull:h.value,expiryMonth:h.value.split("/")[0],expiryYear:h.value.split("/")[1],cvc:u.value,cardholderName:c?.value,country:y?.value,zip:v?.value,save:b?.checked},E=this.paymentForm.native_provider;let _;if(E==="stripe"){const k=new URL("https://api.stripe.com/v1/tokens");k.search=new URLSearchParams({"card[number]":L.cardNumber,"card[exp_month]":L.expiryMonth,"card[exp_year]":L.expiryYear,"card[cvc]":L.cvc,"card[address_zip]":L.zip,"card[address_country]":L.country,"card[name]":L.cardholderName}).toString(),_=await(await fetch(k.toString(),{method:"POST",credentials:"same-origin",headers:{"Content-Type":"application/x-www-form-urlencoded",Authorization:`Bearer ${s.publishable_key}`}})).json()}else if(E==="smartglocal"){const k={card:{number:L.cardNumber.replace(/[^\d]+/g,""),expiration_month:L.expiryMonth,expiration_year:L.expiryYear,security_code:L.cvc.replace(/[^\d]+/g,"")}};_={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(k)})).json()).data.token}}this.dispatchEvent("finish",{token:_,card:L}),this.hide()}}),P=[l,c,h,u,y,v].filter(Boolean);Ww(P,L=>{C.disabled=!L}),e&&(l.value=e.cardNumber,h.value=e.expiryFull,u.value=e.cvc,c&&(c.value=e.cardholderName),y&&(y.value=e.country),v&&(v.value=e.zip)),this.body.append(this.btnConfirmOnEnter=C),this.show(),l.validateNew(void 0,void 0,!0)||Zs(l.input)}}class aM extends ee{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 Pe({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=()=>{a.disabled=!i.value,i.setState(gn.Neutral)};i.input.addEventListener("input",n);const a=Cl({key:"Checkout.PasswordEntry.Pay",onClick:async()=>{try{const r=await this.managers.passwordManager.getInputCheckPassword(i.value,t),l=await this.managers.apiManager.invokeApi("account.getTmpPassword",{password:r,period:60});this.dispatchEvent("finish",l),this.hide()}catch(r){throw r.type==="PASSWORD_HASH_INVALID"&&(r.handled=!0,i.setError("PASSWORD_HASH_INVALID")),r}}});this.body.append(this.btnConfirmOnEnter=a),n(),this.show(),Zs(i.input)}}function qw(o){return o?o.match(rL):null}class rM extends ee{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,a,r,l,c,d;if(t.pFlags.shipping_address_requested){i=new Pe({name:"PaymentShippingAddress",noDelimiter:!0,noShadow:!0}),n=new _t({label:"PaymentShippingAddress1Placeholder",maxLength:64,required:!0}),a=new _t({label:"PaymentShippingAddress2Placeholder",maxLength:64}),r=new _t({label:"PaymentShippingCityPlaceholder",maxLength:64,required:!0}),l=new _t({label:"PaymentShippingStatePlaceholder",maxLength:64});const b=jw(!0,!0);c=b.countryInputField,d=b.postcodeInputField,i.content.append(...[n,a,r,l,c,d].filter(Boolean).map(S=>S.container))}let h,u,p,m;if([t.pFlags.name_requested,t.pFlags.email_requested,t.pFlags.phone_requested].includes(!0)){h=new Pe({name:"PaymentShippingReceiver",noDelimiter:!0,noShadow:!0});const b=()=>{const C=p.value,P=qw(C);return!(!P||P[0].length!==C.length)},S=()=>!!m.value.match(/\d/);t.pFlags.name_requested&&(u=new _t({label:"PaymentShippingName",maxLength:256,required:!0})),t.pFlags.email_requested&&(p=new _t({label:"PaymentShippingEmailPlaceholder",maxLength:64,required:!0,validate:b})),t.pFlags.phone_requested&&(m=new Wb({required:!0,validate:S})),h.content.append(...[u,p,m].filter(Boolean).map(C=>C.container))}const g=new pt({text:"PaymentShippingSave",checked:!0}),f=new ve({checkboxField:g,subtitleLangKey:"PaymentShippingSaveInfo"});(h||i).content.append(f.container),this.scrollable.append(...[i,h].filter(Boolean).map(b=>b.container));const y=Cl({key:"PaymentInfo.Done",onClick:async()=>{const b=c&&c.getSelected().country,S={_:"paymentRequestedInfo",shipping_address:b&&{_:"postAddress",street_line1:n.value,street_line2:a.value,city:r.value,state:l.value,country_iso2:b?.iso2,post_code:d.value},name:u?.value,email:p?.value,phone:m?.value};try{const C=await this.managers.appPaymentsManager.validateRequestedInfo(this.inputInvoice,S,g?.checked);this.dispatchEvent("finish",{shippingAddress:S,requestedInfo:C}),this.hide()}catch(C){const L={ADDRESS_STREET_LINE1_INVALID:n,ADDRESS_STREET_LINE2_INVALID:a,ADDRESS_COUNTRY_INVALID:c,ADDRESS_CITY_INVALID:r,ADDRESS_STATE_INVALID:l,ADDRESS_POSTCODE_INVALID:d,REQ_INFO_NAME_INVALID:u,REQ_INFO_EMAIL_INVALID:p,REQ_INFO_PHONE_INVALID:m}[C.type];throw L&&(L.setError(),C.handled=!0),C}}});if(this.body.append(this.btnConfirmOnEnter=y),s){const b=s.shipping_address;b&&(n.value=b.street_line1,a.value=b.street_line2,r.value=b.city,l.value=b.state,c.selectCountryByIso2(b.country_iso2),d.value=b.post_code),s.name&&u&&(u.value=s.name),s.email&&p&&(p.value=s.email),s.phone&&m&&(m.value=s.phone)}const{validate:v}=Ww([n,a,r,l,c,d,u,p,m].filter(Boolean),b=>{y.disabled=!b});v(),this.show();let w;this.focus?w={name:u,email:p,phone:m}[this.focus]:w=n,w&&Zs(w.input)}}class oM extends ee{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 Pe({name:"PaymentCheckoutShippingMethod",noDelimiter:!0,noShadow:!0}),t=this.requestedInfo.shipping_options.map(a=>new ve({radioField:new _i({text:a.title,name:"shipping-method",value:a.id}),subtitle:In(io(a.prices.map(({amount:r})=>+r),0),this.paymentForm.invoice.currency)}));let s;const i=xl(t,a=>{s=a});this.shippingOption?t.find(a=>a.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=Cl({key:"PaymentInfo.Done",onClick:()=>{this.dispatchEvent("finish",this.requestedInfo.shipping_options.find(a=>a.id===s)),this.hide()}});this.body.append(this.btnConfirmOnEnter=n),this.show()}}function Qw(o){return o+(window.devicePixelRatio>1?"@2x":"")}const lM="_Viewer_13e91_41",cM="_isInvisible_13e91_53",dM="_isFull_13e91_60",hM="_ViewerBackground_13e91_60",uM="_isReady_13e91_63",pM="_ViewerStoryContainer_13e91_68",mM="_fromLeft_13e91_79",gM="_current_13e91_82",fM="_fromRight_13e91_90",yM="_ViewerStory_13e91_68",vM="_fadeIn_13e91_148",bM="_small_13e91_151",wM="_hideOnSmall_13e91_155",SM="_hold_13e91_158",CM="_ViewerStoryContentMediaContainer_13e91_162",IM="_ViewerStoryInfo_13e91_168",LM="_focused_13e91_174",PM="_ViewerStorySlides_13e91_177",MM="_ViewerStorySlidesSlide_13e91_186",EM="_ViewerStoryHeader_13e91_205",_M="_ViewerStoryHeaderAvatar_13e91_217",kM="_ViewerStoryHeaderName_13e91_224",TM="_ViewerStoryHeaderTime_13e91_224",xM="_ViewerStoryHeaderSecondary_13e91_232",AM="_hasRepost_13e91_242",FM="_ViewerStoryHeaderLeft_13e91_247",RM="_ViewerStoryHeaderRight_13e91_247",DM="_ViewerStoryHeaderInfo_13e91_261",BM="_ViewerStoryHeaderRow_13e91_265",NM="_ViewerStoryHeaderRepost_13e91_272",OM="_ViewerStoryHeaderRepostTitle_13e91_282",UM="_ViewerStoryPrivacy_13e91_287",HM="_ViewerStoryContent_13e91_162",$M="_ViewerStoryContentItem_13e91_310",VM="_ViewerStoryContentMedia_13e91_162",GM="_ViewerStoryFooter_13e91_323",zM="_ViewerStoryFooterLeft_13e91_342",KM="_ViewerStoryFooterRight_13e91_342",WM="_ViewerStoryFooterIcon_13e91_346",jM="_ViewerStoryFooterIconIcon_13e91_350",qM="_ViewerStoryFooterReaction_13e91_354",QM="_isReacted_13e91_363",YM="_isMe_13e91_376",XM="_isChangelog_13e91_379",ZM="_ViewerStoryShadow_13e91_383",JM="_hasCaption_13e91_389",eE="_ViewerStoryInfoAvatar_13e91_407",tE="_ViewerStoryInfoName_13e91_411",sE="_ViewerStoryCaption_13e91_424",iE="_hasReply_13e91_448",nE="_ViewerStoryCaptionText_13e91_451",aE="_ViewerStoryCaptionTextCell_13e91_460",rE="_ViewerStoryMediaArea_13e91_465",oE="_ViewerStoryMediaAreaReaction_13e91_475",lE="_ViewerStoryMediaAreaReactionBubbles_13e91_481",cE="_dark_13e91_489",dE="_ViewerStoryMediaAreaReactionBubble_13e91_481",hE="_ViewerStoryMediaAreaReactionInner_13e91_508",uE="_hasCount_13e91_519",pE="_ViewerStoryMediaAreaReactionCount_13e91_525",mE="_ViewerStoryMediaAreas_13e91_541",gE="_ViewerStoryReactions_13e91_548",fE="_ViewerStoryRepost_13e91_577",yE="_ViewerStoryRepostSmall_13e91_582",vE="_ViewerClose_13e91_775",bE="_noSound_13e91_785",Me={Viewer:lM,isInvisible:cM,isFull:dM,ViewerBackground:hM,isReady:uM,ViewerStoryContainer:pM,fromLeft:mM,current:gM,fromRight:fM,ViewerStory:yM,fadeIn:vM,small:bM,hideOnSmall:wM,hold:SM,ViewerStoryContentMediaContainer:CM,ViewerStoryInfo:IM,focused:LM,ViewerStorySlides:PM,ViewerStorySlidesSlide:MM,ViewerStoryHeader:EM,ViewerStoryHeaderAvatar:_M,ViewerStoryHeaderName:kM,ViewerStoryHeaderTime:TM,ViewerStoryHeaderSecondary:xM,hasRepost:AM,ViewerStoryHeaderLeft:FM,ViewerStoryHeaderRight:RM,ViewerStoryHeaderInfo:DM,ViewerStoryHeaderRow:BM,ViewerStoryHeaderRepost:NM,ViewerStoryHeaderRepostTitle:OM,ViewerStoryPrivacy:UM,ViewerStoryContent:HM,ViewerStoryContentItem:$M,ViewerStoryContentMedia:VM,ViewerStoryFooter:GM,ViewerStoryFooterLeft:zM,ViewerStoryFooterRight:KM,ViewerStoryFooterIcon:WM,ViewerStoryFooterIconIcon:jM,ViewerStoryFooterReaction:qM,isReacted:QM,isMe:YM,isChangelog:XM,ViewerStoryShadow:ZM,hasCaption:JM,ViewerStoryInfoAvatar:eE,ViewerStoryInfoName:tE,ViewerStoryCaption:sE,hasReply:iE,ViewerStoryCaptionText:nE,ViewerStoryCaptionTextCell:aE,ViewerStoryMediaArea:rE,ViewerStoryMediaAreaReaction:oE,ViewerStoryMediaAreaReactionBubbles:lE,dark:cE,ViewerStoryMediaAreaReactionBubble:dE,ViewerStoryMediaAreaReactionInner:hE,hasCount:uE,ViewerStoryMediaAreaReactionCount:pE,ViewerStoryMediaAreas:mE,ViewerStoryReactions:gE,ViewerStoryRepost:fE,ViewerStoryRepostSmall:yE,ViewerClose:vE,noSound:bE};function wE(o,e){return e*(--o*o*o+1)}class Yw extends _t{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 a=t?0:Math.round(50*Math.log(Math.abs(s-i)));this.input.style.transitionDuration=`${a}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),h=parseFloat(d.lineHeight),u=parseFloat(d.paddingTop),p=parseFloat(d.paddingBottom),m=(c-u-p)/h;l.classList.toggle("can-send-collapsed",m>3)}));const r="is-changing-height";bt({element:this.input,className:r,forwards:!0,duration:a,onTransitionEnd:()=>{this.input.classList.remove(r),this.input.oldHeight=this.input.newHeight}})}updateInnerHTML(e=this.input.innerHTML){e=e.replace(//,"").replace(/().+?\/custom-emoji-element>/g,"$1"),this.inputFake.innerHTML=e}setValueSilently(e,t){super.setValueSilently(e,t),this.updateInnerHTML(),t||this.onFakeInput()}}(function(o,e){typeof exports=="object"&&typeof module=="object"?module.exports=e():typeof define=="function"&&define.amd?define([],e):typeof exports=="object"?exports.Recorder=e():o.Recorder=e()})(typeof self<"u"?self:void 0,function(){return function(o){var e={};function t(s){if(e[s])return e[s].exports;var i=e[s]={i:s,l:!1,exports:{}};return o[s].call(i.exports,i,i.exports,t),i.l=!0,i.exports}return t.m=o,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 a in s)t.d(n,a,function(r){return s[r]}.bind(null,a));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(o,e,t){(function(s){var i=s.AudioContext||s.webkitAudioContext,n=function(a){if(!n.isRecordingSupported())throw new Error("Recording is not supported in this browser");a||(a={}),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},a),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(a){a.stop()}):this.stream.stop(),delete this.stream),this.audioContext&&this.closeAudioContext&&(this.audioContext.close(),delete this.audioContext)},n.prototype.encodeBuffers=function(a){if(this.state==="recording"){for(var r=[],l=0;l{this.encodeBuffers(a.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(a){return a&&a.context?s.Promise.resolve(a):s.navigator.mediaDevices.getUserMedia({audio:this.config.mediaTrackConstraints}).then(r=>(this.stream=r,this.audioContext.createMediaStreamSource(r)))},n.prototype.loadWorker=function(){this.encoder||(this.encoder=new s.Worker(this.config.encoderPath))},n.prototype.initWorker=function(){var a=(this.config.streamPages?this.streamPage:this.storePage).bind(this);return this.recordedPages=[],this.totalLength=0,this.loadWorker(),new Promise((r,l)=>{var c=d=>{switch(d.data.message){case"ready":r();break;case"page":this.encodedSamplePosition=d.data.samplePosition,a(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(a){if(this.state==="recording"){if(this.state="paused",a&&this.config.streamPages){var r=this.encoder;return new Promise((l,c)=>{var d=h=>{h.data.message==="flushed"&&(r.removeEventListener("message",d),this.onpause(),l())};r.addEventListener("message",d),r.postMessage({command:"flush"})})}return this.onpause(),Promise.resolve()}},n.prototype.resume=function(){this.state==="paused"&&(this.state="recording",this.onresume())},n.prototype.setRecordingGain=function(a){this.config.recordingGain=a,this.recordingGainNode&&this.audioContext&&this.recordingGainNode.gain.setTargetAtTime(a,this.audioContext.currentTime,.01)},n.prototype.setMonitorGain=function(a){this.config.monitorGain=a,this.monitorGainNode&&this.audioContext&&this.monitorGainNode.gain.setTargetAtTime(a,this.audioContext.currentTime,.01)},n.prototype.start=function(a){if(this.state==="inactive")return this.initAudioContext(a),this.initAudioGraph(),this.encodedSamplePosition=0,this.initWorker().then(()=>this.initSourceNode(a)).then(r=>{this.sourceNode=r,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 a=this.encoder;return new Promise(r=>{var l=c=>{c.data.message==="done"&&(a.removeEventListener("message",l),r())};a.addEventListener("message",l),a.postMessage({command:"done"}),this.config.reuseWorker||a.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(a){this.recordedPages.push(a),this.totalLength+=a.length},n.prototype.streamPage=function(a){this.ondataavailable(a)},n.prototype.finish=function(){if(!this.config.streamPages){var a=new Uint8Array(this.totalLength);this.recordedPages.reduce(function(r,l){return a.set(l,r),r+l.length},0),this.ondataavailable(a)}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(){},o.exports=n}).call(this,t(1))},function(o,e){var t;t=function(){return this}();try{t=t||new Function("return this")()}catch{typeof window=="object"&&(t=window)}o.exports=t}])});class Xw{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&&s.bottom{const t=e.filter(i=>i.boundingClientRect.topi.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 SE(o){return Yt(o,{entities:[zh(o)]})}function Zw({listenTo:o,chatInput:e,isPack:t,verifyRecent:s,appendTo:i,isEmojis:n,isGif:a,canHaveEmojiTimer:r,canViewPack:l,onOpen:c,onClose:d,onSend:h}){let u,p;const m=async v=>{const w=await(a?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 v?!b:b},g=v=>{I.managers.appUsersManager.updateEmojiStatus(v).then(()=>{Ee({langPackKey:"SetAsEmojiStatusInfo"})})},f=async v=>{g({_:"emojiStatusUntil",document_id:p.id,until:Ms(!0)+v})};let y=n?[{icon:"copy",text:"Copy",onClick:()=>{p?Fs(p.stickerEmojiRaw,u.outerHTML):Fs(iu(u).emoji)}},{icon:"stickers_face",text:"ViewPackPreview",onClick:()=>{const w=p.attributes.find(b=>b._==="documentAttributeCustomEmoji").stickerset;ee.createPopup(Cn,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(iu(u)),verify:()=>s?.(u)??!1}]:[{icon:"stickers",text:"Context.ViewStickerSet",onClick:()=>ee.createPopup(Cn,p.stickerSetInput,!1,e).show(),verify:()=>!t&&!a},{icon:a?"gifs":"favourites",text:a?"SaveToGIFs":"AddToFavorites",onClick:()=>a?I.managers.appGifsManager.saveGif(p.id,!1):I.managers.appStickersManager.faveSticker(p.id,!1),verify:()=>m(!0)},{icon:a?"crossgif":"crossstar",text:a?"Message.Context.RemoveGif":"DeleteFromFavorites",onClick:()=>a?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?.(u)??!1},{icon:"mute",text:"Chat.Send.WithoutSound",onClick:()=>(h?.(),e.emoticonsDropdown.sendDocId({document:p.id,clearDraft:!1,silent:!0,target:u})),verify:()=>!!(e&&e.chat.peerId&&e.chat.peerId!==I.myId)},{icon:"schedule",text:"Chat.Send.ScheduledMessage",onClick:()=>e.scheduleSending(()=>e.sendMessageWithDocument({document:p,target:u})),verify:()=>e&&!!e.chat.peerId}];return r&&(y=[{text:"SetEmojiStatusUntil1Hour",onClick:()=>f(3600),verify:()=>r},{text:"SetEmojiStatusUntil2Hours",onClick:()=>f(3600*2),verify:()=>r},{text:"SetEmojiStatusUntil8Hours",onClick:()=>f(3600*8),verify:()=>r},{text:"SetEmojiStatusUntil2Days",onClick:()=>f(3600*24*2),verify:()=>r}]),ln({listenTo:o,appendTo:i,findElement:v=>{if(u=v.target,n){const w=U(u,"super-emoji");w?u=w.firstElementChild:u=U(u,"emoji")||U(u,"custom-emoji")}else a?u=U(v.target,"gif"):u=U(v.target,"media-sticker-wrapper");return u},onOpen:async()=>(p=await I.managers.appDocsManager.getDoc(u.dataset.docId),c?.()),onClose:d,buttons:y})}function df(o){const e=o.thumb;return e.w=o.w,e.h=o.h,{_:"photo",access_hash:"",pFlags:{},date:0,dc_id:0,file_reference:[],id:0,sizes:[e]}}function Xs(o,e=!1,t){if(!o)return;let s;if(o.action)s=o.action.photo;else if(o.media){let i=o.media;const n=i.extended_media;if(i.webpage)i=i.webpage;else if(n){const a=Pb(n)[t??0];if(i=a.media,!i)return df(a)}s=i.document||i.photo||(e?void 0:i.game||i)}return s}const CE=(()=>{try{return Pi&&+navigator.userAgent.match(/ Version\/(\d+)/)[1]<14}catch{return!1}})(),Uy=10;class IE extends Si{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&&yi(t,Math.max(0,t.currentTime-(e.seekOffset||Uy)))},this.seekForward=(e,t=this.playingMedia)=>{t&&yi(t,Math.min(t.duration,t.currentTime+(e.seekOffset||Uy)))},this.seekTo=(e,t=this.playingMedia)=>{t&&yi(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&&CE&&this.handleSafariStreamable(e);const i=fe.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,a=this.pip;a&&a.pause();const r=this.getMessageByMedia(t);if(this.playingMedia!==t){this.stop(),this.setMedia(t,r);const c=u=>u.mid===n&&u.peerId===i,d=this.listLoader,h=d.getCurrent();if(!h||!c(h)){let u;for(const p of[!1,!0]){const m=d.getPrevious(p);let g=m.findIndex(c);if(g!==-1?u=-(m.length-g):(g=d.getNext(p).findIndex(c),g!==-1&&(u=g+1)),u!==void 0)break}u?this.go(u,!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(),yi(e,0),Sd(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,a=n.get(i);a&&(a.delete(s.mid),a.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 a of n)this.onMediaDocumentLoad(a)}),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:a=>{this[n]!==a&&(this[n]=a,this.playingMedia&&(i!=="loop"||this.playingMediaType==="audio")&&i!=="round"&&(this.playingMedia[i]=a),i==="playbackRate"&&this.playingMediaType!==void 0&&(this.playbackRates[this.playingMediaType]=a),this.dispatchPlaybackParams())}}}),Object.defineProperties(this,t),this.addEventListener("play",({doc:i})=>{i.type==="round"&>.toggleMediaPause(!1)}),this.addEventListener("pause",()=>{gt.toggleMediaPause(!0)})}dispatchPlaybackParams(){this.dispatchEvent("playbackParams",this.getPlaybackParams())}getPlaybackParams(){const{volume:e,muted:t,playbackRate:s,playbackRates:i,loop:n,round:a}=this;return{volume:e,muted:t,playbackRate:s,playbackRates:i,loop:n,round:a}}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,r=!!e.pFlags.is_scheduled?this.scheduled:this.media;let l=r.get(e.peerId);l||r.set(e.peerId,l=new Map);let c=l.get(n);if(c)return c;const d=Xs(e,!0);l.set(n,c=document.createElement(d.type==="round"||d.type==="video"?"video":"audio")),d.type==="round"&&c.setAttribute("playsinline","true");const h={peerId:i,mid:n,docId:d.id,doc:d,message:e,clean:s,isScheduled:e.pFlags.is_scheduled};this.mediaDetails.set(c,h),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 u=Pt();if(t)u.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,u)}return u.then(()=>{if(d.supportsStreaming||fe.getCacheContext(d).url)this.onMediaDocumentLoad(c);else{let p=this.waitingDocumentsForLoad[d.id];p||(p=this.waitingDocumentsForLoad[d.id]=new Set),p.add(c),cs.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",()=>{yi(e,e.duration-1),e.addEventListener("progress",()=>{yi(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 a=n.get(t);a&&(a.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 Wn(t,void 0,!1);const s=Xs(e,!0);if(!s)return;const i=[],n=s.type==="voice"||s.type==="round";let a="",r="";if(s.thumbs?.length){const c=s.thumbs[s.thumbs.length-1];if(!c.bytes){const d=fe.getCacheContext(s,c.type);d.url?i.push({src:d.url,sizes:`${c.w}x${c.h}`,type:"image/jpeg"}):cs.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),a=await ar({peerId:c,plainText:!0,onlyFirstName:!1}),r=ke.format(s.type==="voice"?"AttachAudio":"AttachRound",!0)}if(!n){const c=s.attributes.find(d=>d._==="documentAttributeAudio");a=c?.title??s.file_name,r=c?.performer}i.length||(Zr?Je?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:a,artist:r,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:Xs(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)}bindBrowserCallback(e){return s=>{e(this.pip,s)}}seekToStart(e){return e?.currentTime>5?(yi(e,0),this.toggle(!0,e),!0):!1}willBePlayed(e){this.willBePlayedMedia=e}setSearchContext(e){return Di(this.searchContext,e)?!1:(this.searchContext=Wi(e),!0)}getSearchContext(){return this.searchContext}setTargets(e,t,s){let i=this.listLoader;i?i.reset():i=this.listLoader=new zu({loadCount:10,loadWhenLeft:5,processItem:a=>(this.addMedia(a,!1),{peerId:a.peerId,mid:a.mid}),onJump:(a,r)=>{this.playItem(a)},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=Xs(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 a;return e?(a=()=>{const r=this.pip;r&&r.pause(),this.pauseMediaInOtherTabs()},e.paused||a(),e.addEventListener("play",a)):this.pauseMediaInOtherTabs(),this.willBePlayed(void 0),e?this.setMedia(e,t,s):this.playingMedia=void 0,this.toggleSwitchers(!1),this.dispatchEvent("singleMedia",e),(r=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",a),r&&this.play()}}toggleSwitchers(e){this.lockedSwitchers=!e}setPictureInPicture(e){this.pip=e;const t=new Ut;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 IE;Ws.appMediaPlaybackController=rt;const Hy="…",Kc=new Map,Wc=new Set;let Np=!1;function Jw(){Np||(Np=!0,bs(()=>{Np=!1,LE()}))}function LE(){Wc.forEach(eS),Wc.clear()}window.addEventListener("resize",()=>{for(const[o]of Kc)Wc.add(o);Jw()},{capture:!0,passive:!0});function Op(o){const e=o.getSize;if(e)return e();const t=o.dataset.sizeType;return t?$e.active[t].width:o.getBoundingClientRect().width}function eS(o){let e=Kc.get(o);const t=!e;let{text:s,textLength:i,from:n,multiplier:a,font:r,textWidth:l,elementWidth:c}=e||{};if(t){s=o.textContent,i=s.length,n=50,a=n>0&&n/100;let u=o.dataset.fontSize;u&&+u&&(u+="px"),r=`${o.dataset.fontWeight||oL} ${u||Mb} ${dl}`,l=fl(s,r),c=Op(o),e={text:s,textLength:i,from:n,multiplier:a,font:r,textWidth:l,elementWidth:c},Kc.set(o,e)}const d=Op(o),h=t||c!==d;if(!t&&h&&(e.elementWidth=c=d),h)if(l>c){o.setAttribute("title",s);let u=s,p=c;for(;u.length>3;){const m=u.length,g=a&&Kt(a*m<<0,1,m-2)||Math.max(m+n-1,1),f=u.substr(0,g).replace(/\s*$/,""),y=u.substr(g+1).replace(/^\s*/,"");if(u=f+y,p=fl(u+Hy,r),p{this.setSeekMax()},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()}}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();let i=!1;this.setSeekMax(s),this.setListeners(),this.setHandlers({onMouseDown:()=>{i=!this.media.paused,i&&this.media.pause(),this.options?.onSeekStart?.()},onMouseUp:n=>{i&&wi(this.media),this.options?.onSeekEnd?.()}})}scrub(e){const t=super.scrub(e);return yi(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 r=0;r=l&&l>=i&&(i=l,n=e.end(r))}const a=this.max?n/this.max:0;this.filledLoad.style.width=a*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)}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.progressRAF&&(window.cancelAnimationFrame(this.progressRAF),this.progressRAF=void 0)}}function Rn(o){return o&&(o.saved_from_name||o.from_name)}function tS(o){return o.fromId?{peerId:o.fromId}:{fromName:Rn(o.fwd_from)}}async function eu(o){const e=document.createElement("span");e.classList.add("sender-title");const t=o.fromId===I.myId&&o.peerId!==I.myId;if(e.append(t?M("FromYou"):await Oe({...tS(o),dialog:o.peerId===I.myId})),await I.managers.appPeersManager.isAnyGroup(o.peerId)||t){const s=await Oe({peerId:o.peerId});e.append(" ➝ ",s)}return e}function uf(o){const e=document.createElement("span");return e.classList.add("sent-time"),e.append(Md(new Date(o.date*1e3))),e}I.addEventListener("messages_media_read",({mids:o,peerId:e})=>{o.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 PE(o){o instanceof Uint8Array||(o=new Uint8Array(o));const t=o.length*8/5|0;if(!t)return new Uint8Array([]);let s;try{const i=new DataView(o.buffer);s=new Uint8Array(t);for(let n=0;n>r&31}}catch{s=new Uint8Array([])}return s}function ME(o,e){const n=($e.isMobile,23),a=$e.isMobile?152:190,r=$e.isMobile?190:256,l=Kt(e/60*r,a,r),c=Math.max(...o),d=o.length,h=Math.min(l/4|0,d);let u=0;const p=n-4;let m="";for(let y=0,v=0,w=0;y=d){w=w+h-d,w<(h+1)/2&&u`;m+=C,v+=4,w<(h+1)/2?u=0:u=b}else up._==="documentAttributeAudio").waveform||new Uint8Array([]);s=PE(s.slice(0,63));const{svg:i,container:n,availW:a}=ME(s,t.duration);let r;n&&(r=n.cloneNode(!0),r.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,r);const c=document.createElement("div");if(c.classList.add("audio-time"),o.append(l,c),o.transcriptionState!==void 0){o.classList.add("can-transcribe");const p=document.createElement("div");p.classList.add("audio-to-text-button");const m=Le("transcribe"),g=document.createElement("div");g.classList.add("loader"),g.innerHTML='',p.append(m),p.onclick=()=>{const f=(U(o,"document-wrapper")||U(o,"quote-text")).querySelector(".audio-transcribed-text");if(o.transcriptionState===0)if(f)f.classList.remove("hide"),m.classList.remove(_a("transcribe")),m.classList.add(_a("up")),o.transcriptionState=2;else{const y=o.message;if(y.pFlags.is_outgoing)return;o.transcriptionState=1,!g.parentElement&&p.append(g),Qn().then(()=>{o.transcriptionState===1&&g.classList.add("active")}),o.managers.appMessagesManager.transcribeAudio(y).catch(Wt)}else o.transcriptionState===2&&(f.classList.add("hide"),m.classList.remove(_a("up")),m.classList.add(_a("transcribe")),o.transcriptionState=0)},o.append(p)}let d=i,h;return d||(h=new ep,l.append(h.container)),()=>{let p=o.audio;const m=()=>{Ba(()=>p?(g(),!p.paused):!1,o)},g=()=>{r&&(r.style.width=p.currentTime/p.duration*100+"%")};(!p.paused||p.currentTime>0&&p.currentTime!==p.duration)&&g();const f=e0(g);return o.addAudioListener("timeupdate",f),o.addAudioListener("ended",f),o.addAudioListener("play",m),d&&o.readyPromise.then(()=>{let y=!1,v=!1;d.addEventListener("mouseleave",b=>{y&&(o.togglePlay(void 0,!0),y=!1),v=!1}),d.addEventListener("mousemove",b=>{v=!0,y&&w(b)}),d.addEventListener("mousedown",b=>{b.preventDefault(),b.button===0&&(p.paused||o.togglePlay(void 0,!1),w(b),y=!0)}),d.addEventListener("mouseup",b=>{v&&y&&(o.togglePlay(void 0,!0),y=!1)}),N(d,b=>{oe(b),p.paused||w(b)});function w(b){let S;if(b instanceof MouseEvent)S=b.offsetX;else{const P=b.target.getBoundingClientRect();S=b.targetTouches[0].pageX-P.left}const C=S/a*p.duration;yi(p,C)}},Wt),!d&&h.setMedia({media:p,streamable:t.supportsStreaming,duration:t.duration}),()=>{d?.remove(),d=null,p=null}}}async function _E(o){const e=o.withTime,t=o.message,s=Xs(t),i=s.type==="voice"||s.type==="round",n=document.createElement("div");n.classList.add("audio-description");const a=s.attributes.find(u=>u._==="documentAttributeAudio");if(!i){const u=[];a?.performer&&u.push(_e(a.performer)),e?u.push(ws(t.date)):u.length||u.push(Ta(s.size)),o.showSender&&u.push(await eu(t)),n.append(" • ",...mo(u," • "))}o.insertAdjacentHTML("beforeend",`
`);const l=o.querySelector(".audio-title"),c=new hf;c.dataset.fontWeight=o.dataset.fontWeight,c.dataset.fontSize=o.dataset.fontSize,c.dataset.sizeType=o.dataset.sizeType,c.getSize=o.getSize,i?c.append(await eu(t)):kt(c,_e(a?.title??s.file_name)),l.append(c),o.showSender&&l.append(uf(t));const d=o.querySelector(".audio-subtitle");return d.append(n),()=>{let u=!1,p=new ep;p.setMedia({media:o.audio,streamable:s.supportsStreaming,duration:s.duration}),o.addAudioListener("ended",()=>{o.classList.remove("audio-show-progress"),d.lastChild.replaceWith(n),u=!1});const m=()=>{u||(o.classList.add("audio-show-progress"),u=!0,p&&d.lastChild.replaceWith(p.container))};return o.addAudioListener("play",m),(!o.audio.paused||o.audio.currentTime>0)&&m(),()=>{p.removeListeners(),p.container.remove(),p=null}}}function Up(o=!0){const e=new tn({cancelable:!0,tryAgainOnFail:o});return e.construct(),o||(e.circle.setAttributeNS(null,"r","23"),e.totalLength=143.58203125),e}const sS=(o,e)=>{let t,s;const i=!o.classList.contains("search-super-item"),n=U(o,i?"bubbles-inner":"tabs-tab");if(n){const a=':not([data-is-outgoing="1"])',r=`.audio:not(.is-voice)${a}`;let l;if(o.matches(r)?l=[r]:l=[`.audio.is-voice${a}`,`.media-round${a}`],i){const p=".bubble:not(.webpage) ";l=l.map(m=>p+m)}const c=l.join(", "),d=Array.from(n.querySelectorAll(c)),h=d.indexOf(o),u=d.map(p=>({peerId:p.dataset.peerId.toPeerId(),mid:+p.dataset.mid}));t=u.slice(0,h),s=u.slice(h+1)}return(s.length&&s[0].mide)&&([t,s]=[s.reverse(),t.reverse()]),[t,s]};class pf extends HTMLElement{constructor(){super(...arguments),this.withTime=!1,this.voiceAsMusic=!1,this.showSender=!1,this.listenerSetter=new Ut}async render(){this.classList.add("audio"),this.managers=I.managers,this.dataset.mid=""+this.message.mid,this.dataset.peerId=""+this.message.peerId;const e=Xs(this.message),t=e.type==="voice",s=!this.voiceAsMusic&&t,i=this.message.pFlags.is_outgoing,n=this.uploadingFileName??this.message?.uploadingFileName?.[0],a=()=>{const p=this.audio&&this.audio.readyState>=this.audio.HAVE_CURRENT_DATA?this.audio.duration:e.duration;return Fi(p|0)};this.innerHTML=`
`;const r=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?EE(this):_E(this)),h=this.querySelector(".audio-time");h.textContent=a();const u=this.onLoad=p=>{this.onLoad=void 0;const m=this.audio=rt.addMedia(this.message,p),g=this.readyPromise=Pt();this.audio.readyState>=this.audio.HAVE_CURRENT_DATA?g.resolve():this.addAudioListener("canplay",()=>g.resolve(),{once:!0}),this.onTypeDisconnect=d();const f=()=>Fi(m.currentTime|0)+(s?" / "+a():""),y=()=>{h.innerText=f(),r.classList.toggle("playing",!m.paused)};(!m.paused||m.currentTime>0&&m.currentTime!==m.duration)&&y();const v=w=>{this.togglePlay(w)};r.addEventListener("click",v),this.addAudioListener("ended",()=>{r.classList.remove("playing"),h.innerText=a()}),this.addAudioListener("timeupdate",()=>{!m.currentTime&&m.paused||rt.isSafariBuffering(m)||(h.innerText=f())}),this.addAudioListener("pause",()=>{r.classList.remove("playing")}),this.addAudioListener("play",y)};if(e.thumbs?.length){const p=[],m=await Ks({photo:e,message:null,container:r,boxWidth:48,boxHeight:48,loadPromises:this.loadPromises,withoutPreloader:!0,lazyLoadQueue:this.lazyLoadQueue});r.style.width=r.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=Up(!1);const p=cs.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";u(m);const g=this.load=(f,y)=>{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 v;const w=()=>{const S=Up(!1),C=Pt();C.notifyAll({done:75,total:100}),C.catch(()=>{this.audio.pause(),rt.willBePlayed(void 0)}),C.cancel=()=>{C.cancel=Wt;const P=new Error;P.type="CANCELED",C.reject(P)},S.attach(l,!1,C),v=this.addAudioListener("pause",()=>{C.cancel()},{once:!0}),this.onDownloadInit(f)},b=this.addAudioListener("play",w);this.readyPromise.then(()=>{this.listenerSetter.remove(b),v&&this.listenerSetter.remove(v)})}else{p=Up(),f||(this.readyPromise=Pt());const v=()=>{this.onDownloadInit(f);const w=cs.downloadMediaURL({media:e});return f||w.then(()=>{this.readyPromise.resolve()}),p.attach(l,!1,w),{download:w}};p.setDownloadFunction(v),v()}this.classList.contains("corner-download")?r.append(l):this.append(l),this.classList.add("downloading"),this.readyPromise.then(()=>{this.classList.remove("downloading"),l.classList.add("downloaded"),setTimeout(()=>{l.remove()},200),!y&&rt.willBePlayedMedia===this.audio&&(wi(this.audio),rt.willBePlayed(void 0))})}};this.audio?.src||(m?g(!1):N(r,()=>{g(!0)},{once:!0,listenerSetter:this.listenerSetter}))}}onDownloadInit(e){e&&(rt.willBePlayed(this.audio),Pi&&!this.audio.autoplay&&(this.audio.autoplay=!0))}togglePlay(e,t=this.audio.paused){e&&oe(e),t?(this.setTargetsIfNeeded(),wi(this.audio)):this.audio.pause()}setTargetsIfNeeded(){const e=!!this.searchContext;if(rt.setSearchContext(this.searchContext||{peerId:Tt,inputFilter:{_:"inputMessagesFilterEmpty"},useSearch:!1})){const[t,s]=e?sS(this,this.message.mid):[];rt.setTargets({peerId:this.message.peerId,mid:this.message.mid},t,s)}}playWithTimestamp(e){this.load?.(!0),yi(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",pf);class mf extends Si{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.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){It(this,e);const{listenerSetter:t,element:s}=this;Je?t.add(s)("click",i=>{this.ignoreClickClassName&&U(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&&U(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 Hp="player-volume",Pu=class Pu extends Td{constructor(e){super({step:.01,min:0,max:1,vertical:e.vertical},1),this.setVolume=({volume:s,muted:i,eventType:n})=>{let a;!s||i?a=0:s>.5?a=3:s>0&&s<.25?a=1:a=2,po(this.btn,Pu.ICONS[a]).classList.add(Hp+"__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})},It(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",Hp),N(t,s=>{U(s.target,Hp+"__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&&oe(e),this.useGlobalVolume&&this.modifyGlobal(()=>{rt.muted=!rt.muted}),this.setVolume({volume:this.media.volume,muted:!this.media.muted,eventType:"click"})}};Pu.ICONS=["volume_off","volume_mute","volume_down","volume_up"];let tu=Pu;function kE({width:o=0,height:e=0,image:t}={}){const s=document.createElement("canvas");s.width=o,s.height=e;const i=s.captureStream();i.getVideoTracks()[0].enabled=!0;const n=s.getContext("2d");return t&&(n.drawImage(t,0,0,o,e),n.globalAlpha=.5,n.fillStyle="#000"),n.fillRect(0,0,o,e),i}const iS=o=>{const e=[.5,1,1.5,2],t=["playback_05","playback_1x","playback_15","playback_2x"],s=it(" btn-menu-toggle",{noRipple:!0}),i=()=>{const l=s;let c=e.indexOf(rt.playbackRate);c===-1&&(c=e.indexOf(1));const d=Le(t[c]);l.firstElementChild?l.firstElementChild.replaceWith(d):l.append(d)},n=()=>{const l=e.map((d,h)=>({regularText:d+"x",onClick:()=>{rt.playbackRate=d}})),c=jn({buttons:l});c.classList.add(o.direction,"playback-rate-menu"),Hw({el:s,onOpen:o.onPlaybackRateMenuToggle?()=>{o.onPlaybackRateMenuToggle(!0)}:void 0,onClose:o.onPlaybackRateMenuToggle?()=>{o.onPlaybackRateMenuToggle(!1)}:void 0}),i(),s.append(c)},a=l=>{const c=rt.playbackRate,h=e.indexOf(c)+l;h>=0&&hs.classList.contains("menu-open");return n(),{element:s,setIcon:i,addRate:a,isMenuOpen:r}};class nS extends mf{constructor({video:e,container:t,play:s=!1,streamable:i=!1,duration:n,live:a,width:r,height:l,onPlaybackRateMenuToggle:c,onPip:d,onPipClose:h,listenKeyboardEvents:u,useGlobalVolume:p,onVolumeChange:m,onFullScreen:g,onFullScreenToPip:f,shouldEnableSoundOnClick:y}){if(super(),this._inPip=!1,this._onPip=v=>{this._inPip=v,this.wrapper.style.visibility=v?"hidden":"",this.onPip?.(v)},this.onEnterPictureInPictureLeave=v=>{const w=()=>{clearTimeout(S),this.onPipClose?.()},b=this.listenerSetter.add(v.target)("pause",w,{once:!0}),S=setTimeout(()=>{this.listenerSetter.remove(b)},this.debouncePipTime)},this.onEnterPictureInPicture=v=>{this.debouncedPip(!0),this.listenerSetter.add(v.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:v,height:w}=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=kE({width:v,height:w,image:this.emptyPipVideoSource}),this.addPipListeners(this.emptyPipVideo)}await Wn(this.emptyPipVideo),this.emptyPipVideo.requestPictureInPicture(),Wn(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=a,this.canPause=!a,this.canSeek=!a,this._width=r,this._height=l,this.onPlaybackRateMenuToggle=c,this.onPip=d,this.onPipClose=h,this.onVolumeChange=m,this.onFullScreen=g,this.onFullScreenToPip=f,this.listenKeyboardEvents=u,this.hadContainer=!!t,this.useGlobalVolume=p,this.shouldEnableSoundOnClick=y,this.listenerSetter=new Ut,this.setup({element:this.wrapper,listenerSetter:this.listenerSetter,canHideControls:()=>!this.video.paused&&(!this.playbackRateButton||!this.playbackRateButton.isMenuOpen()),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"&&!a){const v=this.controls=this.wrapper.querySelector(".default__controls.ckin__controls");this.gradient=this.controls.previousElementSibling,this.progress=new ep({onSeekStart:()=>{this.wrapper.classList.add("is-seeking")},onSeekEnd:()=>{this.wrapper.classList.remove("is-seeking")}}),this.progress.setMedia({media:e,streamable:i,duration:n}),v.prepend(this.progress.container)}s?e.play().catch(v=>{v.name==="NotAllowedError"&&(e.muted=!0,e.autoplay=!0,wi(e))}).finally(()=>{this.setIsPlaing(!this.video.paused)}):this.setIsPlaing(!this.video.paused)}get width(){return this.video.videoWidth||this._width}get height(){return this.video.videoHeight||this._height}setIsPlaing(e){this.isPlaying!==e&&(this.isPlaying=e,!(this.live&&!e)&&(this.wrapper.classList.toggle("is-playing",e),this.toggles.forEach(t=>{t.replaceChildren(Le(e?"pause":"play"))})))}stylePlayer(e){const{wrapper:t,video:s,skin:i,listenerSetter:n,live:a}=this;t.classList.add(i),a&&t.classList.add(`${i}-live`);const r=this.buildControls();t.insertAdjacentHTML("beforeend",r);let l;const c=[],d=[];if(i==="default"){if(this.canPause){const y=this.mainToggle=ze(`${i}__button--big toggle`,{noRipple:!0,icon:"play"});t.firstElementChild.after(y)}const h=t.querySelector(".left-controls");if(a)this.toggles=[];else{const y=it(` ${i}__button toggle`,{noRipple:!0});h.prepend(y),this.toggles=[y]}const u=t.querySelector(".right-controls");a||(this.playbackRateButton=iS({direction:"top-left",onPlaybackRateMenuToggle:this.onPlaybackRateMenuToggle}),this.playbackRateButton.element.classList.add(`${i}__button`)),!Oi&&document.pictureInPictureEnabled&&(this.pipButton=it(`pip ${i}__button`,{noRipple:!0}));const p=it(` ${i}__button`,{noRipple:!0});u.append(...[this.playbackRateButton?.element,this.pipButton,p].filter(Boolean));const m=t.querySelector(".ckin__time-elapsed");l=t.querySelector(".ckin__time-duration");const g=this.volumeSelector=new tu({listenerSetter:n,vertical:!1,media:s,useGlobalVolume:this.useGlobalVolume,onVolumeChange:this.onVolumeChange});g.btn.classList.remove("btn-icon"),m?m.parentElement.before(g.btn):h.lastElementChild.before(g.btn),this.toggles.forEach(y=>{N(y,()=>{this.togglePlay()},{listenerSetter:this.listenerSetter})}),this.pipButton&&(N(this.pipButton,this.requestPictureInPicture,{listenerSetter:this.listenerSetter}),this.debouncePipTime=20,this.debouncedPip=ii(this._onPip,this.debouncePipTime,!1,!0),this.addPipListeners(s)),Je||(this.canPause&&N(s,()=>{this.checkInteraction()||this.togglePlay()},{listenerSetter:this.listenerSetter}),this.listenKeyboardEvents&&n.add(document)("keydown",y=>{if(Li.overlaysActive>1||document.pictureInPictureElement===s||this.listenKeyboardEvents==="fullscreen"&&!this.isFullScreen())return;const{key:v,code:w}=y;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(y.altKey&&(w==="Equal"||w==="Minus")&&this.canSeek){const S=w==="Equal"?1:-1;this.playbackRateButton.addRate(S)}else t.classList.contains("ckin__fullscreen")&&(v==="ArrowLeft"||v==="ArrowRight")&&this.canSeek?v==="ArrowLeft"?rt.seekBackward({action:"seekbackward"}):rt.seekForward({action:"seekforward"}):b=!1;if(b)return oe(y),!1})),n.add(s)("dblclick",()=>{Je||this.toggleFullScreen()}),N(p,()=>{this.toggleFullScreen()},{listenerSetter:this.listenerSetter}),Eu(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"),Sd(s,"play")),m.textContent=Fi(s.currentTime|0)});const f=()=>{t.classList.add("played"),!Je&&!a&&c.push(()=>{this.hideControls(!0)}),us(c,f)};this.hadContainer&&f(),c.push(f),d.push(()=>{this.showControls(!1)}),n.add(rt)("playbackParams",()=>{this.playbackRateButton.setIcon()}),a&&(this.liveEl=M("Rtmp.MediaViewer.Live"),this.liveEl.classList.add("controls-live"),h.prepend(this.liveEl))}n.add(s)("play",()=>{this.setIsPlaing(!0),c.forEach(h=>h())}),n.add(s)("pause",()=>{this.setIsPlaing(!1),d.forEach(h=>h())}),l&&(s.duration||e?l.textContent=Fi(Math.round(s.duration||e)):Wn(s).then(()=>{l.textContent=Fi(Math.round(s.duration))}))}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?` `:` / `;return`
${t}
`}}cancelFullScreen(){ZI()===this.wrapper&&this.toggleFullScreen()}toggleFullScreen(){const e=this.wrapper;if(Dg){const t=this.video;t.webkitEnterFullscreen(),t.enterFullscreen();return}wn()?kc():(Sg(e),this.checkInteraction())}isFullScreen(){return wn()}_onFullScreen(e,t){const s=wn();this.wrapper.classList.toggle("ckin__fullscreen",s),s?(e.replaceChildren(Le("smallscreen")),e.setAttribute("title","Exit Full Screen")):(e.replaceChildren(Le("fullscreen")),e.setAttribute("title","Full Screen")),!t&&this.onFullScreen?.(s)}dimBackground(){this.wrapper.classList.add("dim-background")}setTimestamp(e){yi(this.video,e),this.togglePlay(!0)}cleanup(){super.cleanup(),this.listenerSetter.removeAll(),this.progress?.removeListeners(),this.volumeSelector?.removeListeners(),this.onPlaybackRateMenuToggle=this.onPip=this.onVolumeChange=this.onFullScreen=this.onFullScreenToPip=this.shouldEnableSoundOnClick=void 0}unmount(){[this.mainToggle,this.gradient,this.controls].forEach(e=>{e.remove()})}setupLiveMenu(e){this.liveMenuButton=ai({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(M("Rtmp.Watching",[Xg(Math.max(1,e))]))}get inPip(){return this._inPip}}const TE=50*1024*1024,xE=!1;let $n=0;$e.addEventListener("changeScreen",(o,e)=>{if(e===hi.mobile||o===hi.mobile){const t=Array.from(document.querySelectorAll(".media-round .progress-ring")),s=$e.active.round.width,i=s/2,n=i-7;$n=2*Math.PI*n,t.forEach(a=>{a.setAttributeNS(null,"width",""+s),a.setAttributeNS(null,"height",""+s);const r=a.firstElementChild;r.setAttributeNS(null,"cx",""+i),r.setAttributeNS(null,"cy",""+i),r.setAttributeNS(null,"r",""+n),r.style.strokeDasharray=$n+" "+$n,r.style.strokeDashoffset=""+$n})}});let Ql=!1;async function qn({doc:o,altDoc:e,container:t,message:s,boxWidth:i,boxHeight:n,withTail:a,isOut:r,middleware:l,lazyLoadQueue:c,noInfo:d,group:h,onlyPreview:u,noPreview:p,withoutPreloader:m,loadPromises:g,noPlayButton:f,photoSize:y,videoSize:v,searchContext:w,autoDownload:b,managers:S=I.managers,noAutoplayAttribute:C,ignoreStreaming:P,canAutoplay:L,useBlur:E,observer:_,setShowControlsOn:k,uploadingFileName:x}){const A=o.supportsStreaming&&!P;!A&&e&&!u&&!lL&&(o=e,e=void 0),o.type==="gif"&&t&&(t.classList.add("media-gif-wrapper"),t.dataset.docId=""+o.id);const T=b?.video;let B=T===0;const R=!(i&&n);L??(L=(o.type!=="video"||o.size<=TE&&!R)&&(o.type==="gif"?st.isAvailable("gif"):st.isAvailable("video")));let O,X,F=!1,H,G;if(!d&&t){O=document.createElement("span"),O.classList.add("video-time"),t.append(O);let de=!1;o.type!=="gif"?(O.innerText=Fi(o.duration,!1),!f&&o.type!=="round"&&(L&&!B?(_&&xE&&(F=!0,G=l,H=xt(),l=H.get()),O.append(Le("nosound","video-time-icon"))):de=!0)):(O.innerText="GIF",!L&&!f&&(de=!0,B=void 0)),de&&(X=ze("btn-circle video-play position-center",{icon:"largeplay",noRipple:!0}),t.append(X))}const z={};if(o.mime_type==="image/gif"){const de=await Ks({photo:o,message:s,container:t,boxWidth:i,boxHeight:n,withTail:a,isOut:r,lazyLoadQueue:c,middleware:l,withoutPreloader:m,loadPromises:g,autoDownloadSize:T,size:y,managers:S,useBlur:E,uploadingFileName:x});return z.thumb=de,z.loadPromise=de.loadPromises.full,z}let q;const $=hl({middleware:l,pip:F});if($.classList.add("media-video"),$.muted=!0,o.type==="round"){const de=document.createElement("div");de.classList.add("media-round","z-depth-1"),de.dataset.mid=""+s.mid,de.dataset.peerId=""+s.peerId,de.message=s;const Ze=$e.active.round,Ne=Ze.width/2,pe=3.5,Be=Ne-pe*2;de.innerHTML=` `;const He=de.firstElementChild.firstElementChild;$n||($n=2*Math.PI*Be),He.style.strokeDasharray=$n+" "+$n,He.style.strokeDashoffset=""+$n,s.pFlags.media_unread&&de.classList.add("is-unread");const Ae=document.createElement("canvas");Ae.classList.add("video-round-canvas"),Ae.width=Ae.height=o.w,de.prepend(Ae,O),de.append($),t?.append(de);const Ke=Ae.getContext("2d"),We=()=>{const Fe=de.message,Ue=rt.addMedia(Fe,!B),nt=()=>{(me.chat.setPeerPromise||Promise.resolve()).finally(()=>{ca(Ue)||(Ue.removeEventListener("play",js),Ue.removeEventListener("timeupdate",rs),Ue.removeEventListener("pause",mi),Ue.removeEventListener("ended",oi))})},Lt=()=>{Ke.drawImage(Ue,0,0);const si=$n-Ue.currentTime/Ue.duration*$n;return He.style.strokeDashoffset=""+si,!Ue.paused},At=()=>{if(Ue.duration){if(!ca(Ue)){nt();return}Ue.paused&&Lt(),O.firstChild.nodeValue=Fi(Ue.duration-Ue.currentTime,!1)}},rs=ma(()=>{bs(At)},1e3,!1),Cs=Le("nosound","video-time-icon"),os=si=>{de.classList.toggle("is-paused",si),si?O.append(Cs):Cs.remove()},js=()=>{$.classList.add("hide"),os(!1),Ba(Lt,Ae),q?.preloader&&q.preloader.classList.contains("manual")&&q.onClick()},mi=()=>{if(!ca(Ue)){nt();return}os(!0)},oi=()=>{$.classList.remove("hide"),os(!0),yi($,0),O.firstChild.nodeValue=Fi(Ue.duration,!1),Ue.currentTime&&yi(Ue,0)};Ue.addEventListener("play",js),Ue.addEventListener("timeupdate",rs),Ue.addEventListener("pause",mi),Ue.addEventListener("ended",oi),N(Ae,si=>{if(oe(si),q&&!q.detached&&q.onClick(),Ue.paused){const cn=!!w;if(rt.setSearchContext(w||{peerId:Tt,inputFilter:{_:"inputMessagesFilterEmpty"},useSearch:!1})){const[gi,J]=cn?sS(de,Fe.mid):[];rt.setTargets({peerId:Fe.peerId,mid:Fe.mid},gi,J)}wi(Ue)}else Ue.pause()}),Ue.paused?Ue.duration&&Ue.currentTime!==Ue.duration&&Ue.currentTime>0?(Lt(),At(),$.classList.add("hide")):mi():js()};s.pFlags.is_outgoing?(de.onLoad=We,de.dataset.isOutgoing="1"):We()}else C||($.autoplay=!0);let se;if(s||u){if(se=await Ks({photo:o,message:s,container:t,boxWidth:i,boxHeight:n,withTail:a,isOut:r,lazyLoadQueue:c,middleware:l,withoutPreloader:!0,loadPromises:g,autoDownloadSize:b?.photo,size:y,managers:S,useBlur:E,canHaveVideoPlayer:F,uploadingFileName:x}),z.thumb=se,!L&&o.type!=="gif"||u)return z.loadPromise=se.loadPromises.full,z;if(a){const de=(se.images.thumb||se.images.full).parentElement;$.width=+de.getAttributeNS(null,"width"),$.height=+de.getAttributeNS(null,"height"),de.append($)}}else if(!p){const de=Oc({photo:o,cacheContext:{},useBlur:E||!0});if(de){const Ze=de.image;Ze.classList.add("media-poster"),t?.append(Ze),z.thumb={loadPromises:{thumb:de.loadPromise,full:Promise.resolve()},images:{thumb:Ze,full:null},preloader:null,aspecter:null},g?.push(de.loadPromise),z.loadPromise=de.loadPromise}}if(u)return z;const Y=()=>{(se?.aspecter||t).append($)};!$.parentElement&&t&&$.poster&&Y();let Q,he;const le=()=>{Q=fe.getCacheContext(o,v?.type),e&&(he=fe.getCacheContext(e,v?.type))};le(),x??(x=s?.uploadingFileName?.[0]),x?(q=new tn({attachMethod:"prepend",isUpload:!0}),q.attachPromise(cs.getUpload(x)),q.attach(t,!1),B=void 0):!Q.downloaded&&!A&&!m?q=new tn({attachMethod:"prepend"}):A&&!m&&(q=new tn({cancelable:!1,attachMethod:"prepend"}));const re=Pt();if($.addEventListener("error",de=>{Ob(de)||($.error.code!==4&&console.error("Error "+$.error.code+"; details: "+$.error.message),q&&!x&&q.detach(),re.isFulfilled||re.resolve())},{once:!0}),o.type==="video"&&O){const de=()=>{$.duration&&(O.firstChild.nodeValue=Fi($.duration-$.currentTime,!1))},Ze=ma(()=>{bs(de)},1e3,!1);$.addEventListener("timeupdate",Ze),X&&$.addEventListener("timeupdate",()=>{Dh.mutateElement(X,()=>{X.remove()})},{once:!0})}$.muted=!0,$.loop=!0,C||($.autoplay=!0);let ge=B&&se?.preloader?.loadFunc;const be=async()=>{q&&B&&!m&&(q.construct(),q.setManual()),le();let de=Promise.resolve();if(q&&!x||m)if(!Q.downloaded&&!A){const Ze=de=cs.downloadMediaURL({media:o,queueId:c?.queueId,onlyCache:B,thumb:v});q&&q.attach(t,!1,Ze)}else A&&(B?de=Promise.reject(Ld("NO_AUTO_DOWNLOAD")):!Q.downloaded&&q&&(q.attach(t,!1,null),$.addEventListener(Pi?"timeupdate":"canplay",()=>{q.detach()},{once:!0})));return!B&&ge&&(ge(),ge=null),B=void 0,de.then(async()=>{if(l&&!l()){re.resolve();return}o.type==="round"&&rt.resolveWaitingForLoadMedia(s.peerId,s.mid,s.pFlags.is_scheduled),le();const Ze=Be=>{if(console.error("video load error",$,Be),O){O.classList.add("is-error");const He=O.querySelector(".video-time-icon"),De=Le("sendingerror","video-time-icon");He?He.replaceWith(De):O.append(De)}re.reject(Be)},Ne=Wn($),pe=Bg($,Ne);if(pe.catch(Ze),Ne.then(()=>{h&>.addAnimation({animation:$,group:h,observeElement:$,type:"video",locked:F}),q&&!x&&q.detach(),!$.parentElement&&t&&!$.poster&&Y(),e?(pe.then(()=>{$.pause(),re.resolve()}),yi($,1e-4)):re.resolve(),Z?.()},Ze),e&&he){const Be=[{context:Q,type:'video/mp4; codecs="hev1"',width:o.w},{context:he,type:'video/mp4; codecs="avc1.64001E"',width:e.w}].map(({context:He,type:De,width:Ae})=>{const Ke=document.createElement("source");return Ke.src=He.url,Ke.width=Ae,Ke});$.append(...Be),$.load()}else Kn($,Q.url)},Wt),{download:de,render:Promise.all([de,re])}};q&&!x&&q.setDownloadFunction(be),t&&(t.preloader=q),o.type==="gif"&&!L?N(t,de=>{oe(de),X.remove(),be()},{capture:!0,once:!0}):z.loadPromise=c?(c.push({div:t,load:()=>be().then(({render:de})=>de)}),Promise.resolve()):(await be()).render,z.thumb&&await z.thumb.loadPromises.thumb,$&&(z.video=$);const Z=F?()=>{$.mini=!0,$.pause();const de=Ae=>{Ae.isIntersecting||Ze(),!Ae.isIntersecting&&$.muted};t.classList.add("media-video-container","media-video-mini"),_.observe($,de);const Ze=()=>{Ne.clearTimeout(),!(!pe||!l()||wn()||pe.inPip)&&(pe.unmount(),pe.cleanup(),pe=void 0,k.classList.remove("show-controls"))},Ne=ii(Ze,1e3,!1,!0);let pe,Be;t.onMouseMove=Ae=>{if(pe)return;const Ke=Ue=>{Ue?Be=Pt():Be?.resolve()},We=Ue=>{if(Fe&&Fe--)return;const nt=gt.getAnimations($)[0];gt.toggleItemLock(nt,Ue),Ke(Ue)};let Fe=0;pe=new nS({video:$,container:t,duration:$.duration,streamable:!0,listenKeyboardEvents:"fullscreen",useGlobalVolume:"no-init",onVolumeChange:Ue=>{const nt=!$.volume||$.muted;let Lt;nt?Lt=Ql=!1:Ue==="click"&&(Lt=Ql=!0),Lt!==Ql&&Lt!==void 0&&rt.dispatchEvent("toggleVideoAutoplaySound",Lt)},onFullScreen:Ue=>{We(Ue),Li.isDarkOverlayActive=Ue},onFullScreenToPip:()=>{Fe=2},onPip:We}),pe.volumeSelector.setVolume({muted:!Ql,volume:$.volume}),pe.addEventListener("toggleControls",Ue=>{k.classList.toggle("show-controls",Ue),Ue?Ne.clearTimeout():Ne()})};const He=Ae=>{pe||($.muted=rt.muted,$.volume=rt.volume)},De=Ae=>{pe||($.muted=Ql?Ae.muted:!0,$.playbackRate=Ae.playbackRate,$.volume=Ae.volume)};rt.addEventListener("toggleVideoAutoplaySound",He),rt.addEventListener("playbackParams",De),l.onClean(()=>{_.unobserve($,de),delete t.onMouseMove,rt.removeEventListener("toggleVideoAutoplaySound",He),rt.removeEventListener("playbackParams",De)}),G.onClean(async()=>{await Be,H.destroy()})}:void 0;return z}let $p=!1;function Al({listenTo:o,listenerSetter:e,selector:t,findTarget:s,getTextColor:i}){if(Je)return;const n=(r,l)=>{let c;if(s)c=s(r);else{const d=t||".media-sticker-wrapper, .media-gif-wrapper";c=r.target.closest(d)}return c&&(!l||Ns(c,o))?c:void 0},a=I.managers;e.add(o)("mousedown",r=>{if($p||r.buttons>1||r.button!==0)return;let l=n(r);if(!l)return;const c=l.dataset.docId;if(!c)return;const d="sticker-viewer",h="STICKER-VIEWER",u=200,p=200,m=gt.getOnlyOnePlayableGroup(),g=xt();let f,y,v=!1;const w=async({mediaContainer:L,doc:E,middleware:_,lockGroups:k,isSwitching:x})=>{const A=E.type==="gif",T=A?void 0:fo(E),B=L.getBoundingClientRect(),R=vs(E.w,E.h),O=T?280:A?Math.min(480,lt.height-200):360,X=vs(O,O),F=B.width===B.height?X:R.aspectFitted(X),H=U(L,"bubble"),G=H?H.classList.contains("is-out"):!0,z=document.createElement("div");z.classList.add(d+"-transformer"),z.middlewareHelper=_.create(),_=z.middlewareHelper.get();const q=document.createElement("div");q.classList.add(d+"-sticker"),q.style.width=F.width+"px",q.style.height=F.height+"px";const $=document.createElement("div");if($.classList.add(d+"-emoji"),$.append(_e(E.stickerEmojiRaw)),T){const Ne=(O*Ub-O)/3*(G?1:-1);z.classList.add("has-effect"),z.style.setProperty("--translateX",`${Ne}px`),$.style.setProperty("--translateX",`${-Ne}px`)}const se=U(L,"scrollable"),Y=go(L,se,!0,B);(Y.overflow.vertical||Y.overflow.horizontal)&&q.classList.add("is-overflow");const Q=L.getBoundingClientRect(),he=Q.width/F.width,le=Q.height/F.height,re=Q.left-(lt.width-Q.width)/2,ge=Q.top-(lt.height-Q.height)/2;z.style.transform=`translate(${re}px, ${ge}px) scale(${he}, ${le})`,x&&z.classList.add("is-switching"),z.append(q,$),f.append(z);const be=E.attributes.find(Ne=>Ne._==="documentAttributeCustomEmoji"),Z=A?await qn({doc:E,container:q,group:h,boxWidth:F.width,boxHeight:F.height,canAutoplay:!0,middleware:_,noInfo:!0}).then(async Ne=>(await Ne.loadPromise,Ne.video)):await Rs({doc:E,div:q,group:h,width:F.width,height:F.height,play:!1,loop:!0,middleware:_,managers:a,needFadeIn:!1,isOut:G,withThumb:!1,relativeEffect:!0,loopEffect:!0,textColor:be&&be.pFlags.text_color?i?.()||jc:void 0}).then(({render:Ne})=>Ne);if(!_())return;f.parentElement||document.body.append(f);const de=Array.isArray(Z)?Z[0]:Z,Ze=de instanceof Ih?new Promise(Ne=>de.addEventListener("firstFrame",Ne,{once:!0})):Promise.resolve();if(await Promise.all([Ze,Qn()]),await Hs(0),!!_()){if(k&&(gt.setOnlyOnePlayableGroup(h),gt.checkAnimations2(!0)),de instanceof Ih){const Ne=L instanceof Ng?L.player:_s.getAnimation(L);if(Ne){if(de.curFrame=Ne.curFrame,de.play(),await new Promise(pe=>{let Be=0;const He=()=>{++Be===2&&(pe(),de.removeEventListener("enterFrame",He))};de.addEventListener("enterFrame",He)}),!_())return;de.pause()}}else if(de instanceof HTMLVideoElement){const Ne=L.querySelector("video");Ne&&(de.currentTime=Ne.currentTime)}return{ready:()=>{(de instanceof Ih||de instanceof HTMLVideoElement)&&wi(de),T&&fs(q)},transformer:z}}},b=window.setTimeout(async()=>{document.removeEventListener("mousemove",C),f=document.createElement("div"),f.classList.add(d),$p=!0;const L=g.get(),E=await a.appDocsManager.getDoc(c);if(!L())return;let _;try{if(_=await w({doc:E,mediaContainer:l,middleware:L,lockGroups:!0}),!_)return}catch{return}if(v)return;const{ready:k,transformer:x}=_;y=x,bt({element:f,className:"is-visible",forwards:!0,duration:u,onTransitionEnd:()=>{L()&&k()}}),document.addEventListener("mousemove",S)},125),S=async L=>{const E=n(L,!0);if(!E||l===E)return;const _=E.dataset.docId;if(!_)return;l=E,g.clean();const k=g.get(),x=await a.appDocsManager.getDoc(_);if(!k())return;let A;try{if(A=await w({doc:x,mediaContainer:l,middleware:k,isSwitching:!0}),!A)return}catch(O){console.error("sticker viewer error",O);return}const{ready:T,transformer:B}=A,R=y;bt({element:R,className:"is-switching",forwards:!0,duration:p,onTransitionEnd:()=>{R.remove(),R.middlewareHelper.destroy()}}),y=B,bt({element:B,className:"is-switching",forwards:!1,duration:p,onTransitionEnd:()=>{k()&&T()}})},C=L=>{Ns(L.target,l)||P()},P=()=>{v=!0,clearTimeout(b),f&&(bt({element:f,className:"is-visible",forwards:!1,duration:u,onTransitionEnd:()=>{f.remove(),gt.setOnlyOnePlayableGroup(m),gt.checkAnimations2(!1),g.destroy(),$p=!1}}),N(document.body,oe,{capture:!0,once:!0})),document.removeEventListener("mousemove",C),document.removeEventListener("mousemove",S),document.removeEventListener("mouseup",P,{capture:!0})};document.addEventListener("mousemove",C),document.addEventListener("mouseup",P,{once:!0,capture:!0})})}const Vp="STICKERS-POPUP";class Cn extends ee{constructor(e,t,s=me.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 r=>{if(!this.chatInput.chat.peerId)return;const l=U(r.target,"sticker-set-sticker")||U(r.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 me.chat.input.sendMessageWithDocument({document:c,target:l}))&&this.hide()},this.title.append(M("Loading")),this.updateAdded={},Ji.setIgnoreMouseOut("popup",!0),this.addEventListener("close",()=>{Ji.setIgnoreMouseOut("popup",!1),gt.setOnlyOnePlayableGroup()}),this.appendTo=this.scrollable.container,this.appendTo.classList.add("is-loading"),rn(this.appendTo,!0);const i=ze("btn-primary btn-primary-transparent disable-hover",{noRipple:!0,text:"Loading"});this.footer.append(i),Al({listenTo:this.appendTo,listenerSetter:this.listenerSetter});const n=r=>{const l=this.sets.findIndex(d=>d.id===r.id);if(l===-1)return;this.sets[l]=r;const c=this.updateAdded[r.id];c?.(!!r.installed_date),this.updateButton()};this.listenerSetter.add(I)("stickers_installed",n),this.listenerSetter.add(I)("stickers_deleted",n);const a=r=>{const l=Ud(this.container,r);if(l)return this.addEventListener("closeAfterTimeout",l),this.hide(),!1};this.container.addEventListener("click",a,{capture:!0}),this.middlewareHelper.onDestroy(()=>{this.container.removeEventListener("click",a,{capture:!0})}),this.loadStickerSet()}createStickerSetElements(e){const t=document.createElement("div");t.classList.add("sticker-set");let s,i;e&&(s=new ve({title:Yt(e.title),subtitle:M(e.pFlags.emojis?"EmojiCount":"Stickers",[e.count]),buttonRight:!0}),i=a=>{dt(s.buttonRight,M(a?"Stickers.SearchAdded":"Stickers.SearchAdd")),s.buttonRight.classList.toggle("active",a)},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=Pb(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){Ee({langPackKey:this.isEmojis?"AddEmojiNotFound":"StickerSet.DontExist"}),this.hide();return}i=i.filter(Boolean),n=i[0],this.sets=i.map(g=>g.set);const a=this.isEmojis??(this.isEmojis=!!n.set.pFlags.emojis);N(this.appendTo,this.onStickersClick,{listenerSetter:this.listenerSetter});const{destroy:r}=Zw({listenTo:this.appendTo,chatInput:this.chatInput,isPack:!0,isEmojis:a,onSend:()=>this.hide()});this.addEventListener("close",r),gt.setOnlyOnePlayableGroup(Vp);const l=new Ga,c=[],d=i.map(async g=>{const{container:f,itemsContainer:y,headerRow:v,updateAdded:w}=this.createStickerSetElements(i.length>1?g.set:void 0);v&&N(v.buttonRight,()=>{this.managers.appStickersManager.toggleStickerSet(g.set)},{listenerSetter:this.listenerSetter}),this.updateAdded[g.set.id]=w;let b;const S=g.documents.filter(C=>C?._==="document");if(a){const C=Kg({docIds:S.map(P=>P.id),loadPromises:c,animationGroup:Vp,customEmojiSize:$e.active.esgCustomEmoji,middleware:e});Array.from(C.children).slice(1).forEach(P=>{const L=document.createElement("span");L.classList.add("super-emoji","super-emoji-custom"),P.replaceWith(L),L.append(P)}),b=[C],y.classList.replace("sticker-set-stickers","super-emojis"),y.classList.add("is-emojis")}else b=await Promise.all(S.map(async C=>{const P=document.createElement("div");P.classList.add("sticker-set-sticker");const L=$e.active.popupSticker.width;return await Rs({doc:C,div:P,lazyLoadQueue:l,group:Vp,play:!0,loop:!0,width:L,height:L,withLock:!0,loadPromises:c,middleware:e}),P}));return y.append(...b.filter(Boolean)),f}),h=await Promise.all(d);await Promise.all(c);const u=this.button=ze("",{noRipple:!0});this.updateButton(),N(u,()=>{const g=jt([u],!0);this.managers.appStickersManager.toggleStickerSets(i.map(f=>f.set)).then(()=>{this.hide()}).catch(()=>{g()})},{listenerSetter:this.listenerSetter}),i.length===1?kt(this.title,Yt(n.set.title)):kt(this.title,M("Emoji"));const p=[{icon:"copy",text:"CopyLink",onClick:()=>{const g=`https://t.me/${this.isEmojis?"addemoji":"addstickers"}/`,f=i.map(y=>g+y.set.short_name).join(` `);Fs(f)}}];$i&&p.push({icon:"download",text:"MediaViewer.Context.Download",onClick:async()=>{for(const g of i)for(const f of g.documents)cs.downloadToDisc({media:f}),await Hs(100)}});const m=ai({listenerSetter:this.listenerSetter,buttons:p,direction:"bottom-left"});this.title.after(m),this.footer.textContent="",this.footer.append(u),this.appendTo.classList.remove("is-loading"),this.appendTo.textContent="",this.appendTo.append(...h),this.scrollable.onAdditionalScroll()}updateButton(){const{sets:e,isEmojis:t}=this;let s,i;if(e.length===1){const n=e[0];i=M(t?"EmojiCount":"Stickers",[n.count]),s=!n.installed_date}else{const n=e.filter(r=>r.installed_date);let a;e.length===n.length?(s=!1,a=e.length):(s=!0,a=e.length-n.length),i=M("EmojiPackCount",[a])}this.button.className=s?"btn-primary btn-color-primary":"btn-primary btn-primary-transparent danger",dt(this.button,M(s?"AddStickersCount":"RemoveStickersCount",[i]))}}const Ma={Stickers:{getElementMediaSize:()=>$e.active.esgSticker,padding:3*2,gapX:4,gapY:4,itemsClassName:"super-stickers"},Emoji:{getElementMediaSize:()=>$E,padding:16,gapX:4,gapY:0,itemsClassName:"super-emojis"},GIF:{getElementMediaSize:()=>vs(124,124),padding:4,gapX:2,gapY:2,itemsClassName:"emoticons-gifs"}};class AE{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,a;e.noMenuTab||(n=it(void 0,{noRipple:!0}),n.classList.add("menu-horizontal-div-item"),a=document.createElement("div"),a.classList.add("menu-horizontal-div-item-padding"),n.append(a)),i&&t.append(i),t.append(s),this.elements={container:t,title:i,items:s,menuTab:n,menuTabPadding:a},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():xt()}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 a=n*s;this.gapY&&(a+=(n-1)*this.gapY),this.elements.items.style.minHeight=a+"px"}}function gf(o,e){const t=Et(o),{onChange:s}=e;let i=new Set(e.appear?void 0:t);const n=new WeakSet,[a,r]=ne([],{equals:!1}),[l]=Eb(),c=e.exitMethod==="remove"?Wt:u=>{r(p=>(p.push(...u),p));for(const p of u)n.delete(p)};let d;return e.exitMethod==="remove"?d=Wt:e.exitMethod==="keep-index"?d=u=>u.elements.splice(u.previousIndex,0,u.element):e.exitMethod==="keep-relative"?d=u=>{let p;u.side==="start"?p=u.previousIndex:p=u.elements.length,u.elements.splice(p,0,u.element)}:d=u=>u.elements.push(u.element),K(u=>{const p=a(),m=o();if(m[cL],Et(l))return l(),u;if(p.length){const g=u.filter(f=>!p.includes(f));return p.length=0,s({list:g,added:[],removed:[],unchanged:g,finishRemoved:c}),g}return Et(()=>{const g=new Set(m),f=m.slice(),y=[],v=[],w=[];for(const C of m)(i.has(C)?w:y).push(C);const b={elements:f,previousElements:u,side:"start"};let S=!y.length;for(let C=0;Co instanceof Element;function Nm(o,e){if(e(o))return o;if(typeof o=="function"&&!o.length)return Nm(o(),e);if(Array.isArray(o)){const t=[];for(const s of o){const i=Nm(s,e);i&&(Array.isArray(i)?t.push.apply(t,i):t.push(i))}return t.length?t:null}return null}function ff(o,e=su,t=su){const s=K(o),i=K(()=>Nm(s(),e));return i.toArray=()=>{const n=i();return Array.isArray(n)?n:n?[n]:[]},i}function Om(o,e){if(e(o))return o;if(typeof o=="function"&&!o.length)return Om(o(),e);if(Array.isArray(o))for(const t of o){const s=Om(t,e);if(s)return s}return null}function yf(o,e=su,t=su){const s=K(o);return K(()=>Om(s(),e))}function FE(o){const e=ff(()=>o.children).toArray,t=o.itemClassName?i=>{i.forEach(n=>{n.classList.add(o.itemClassName)})}:void 0;return t?.(e()),gf(e,{exitMethod:"keep-index",appear:o.appear,onChange:({added:i,removed:n,finishRemoved:a})=>{const r=o.animationOptions;st.isAvailable("animations")||(r.duration=0),t?.(i);const l=o.keyframes;queueMicrotask(()=>{if(!o.animateOnlyReplacement||n.length)for(const h of i)h.animate(l,r);if(o.animateOnlyReplacement&&!i.length){a(n);return}const c=l.slice().reverse(),d=[];for(const h of n){const u=h.animate(c,r);d.push(u.finished)}Promise.all(d).then(()=>a(n))})}})}function RE(o){return j(FE,{animationOptions:{duration:200,easing:"ease-in-out"},keyframes:[{opacity:0},{opacity:1}],animateOnlyReplacement:!0,itemClassName:"animated-item",get children(){return o.children}})}const DE={"cross-fade":RE};function tp(o){return j(Cg,{get component(){return DE[o.type]},get children(){return o.children}})}const BE=ce("
"),NE=ce("
");function OE(o){const{inputSearch:e}=o,[t,s]=ne([]),[i,n]=ne(),[a,r]=ne(!1),l=(p,m)=>{n(p),Lg({container:d,element:m.target,position:"center",axis:"x"})},c=({group:p,document:m})=>{if(o.type!=="stickers"&&p._==="emojiGroupPremium")return;let g,f;const y=(()=>{const v=BE(),w=v.firstChild;v.$$click=l,v.$$clickData=p;const b=g;typeof b=="function"?wt(b,v):g=v;const S=f;return typeof S=="function"?wt(S,w):f=w,Ve(C=>{const P=i()===p,L=p.title;return P!==C._v$&&v.classList.toggle("active",C._v$=P),L!==C._v$2&&Ti(v,"title",C._v$2=L),C},{_v$:void 0,_v$2:void 0}),v})();return Rs({doc:m,div:f,width:24,height:24,group:"emoticons-dropdown",play:!0,middleware:Ys().get()}),y};let d;j(td,{ref(p){const m=d;typeof m=="function"?m(p):d=p},class:"emoticons-search-input-scrollable",get classList(){return{"is-searching":o.searching(),"is-scrolled":a()}},onClick:p=>{p.target===e.currentPlaceholder&&Zs(e.input,!0,!0)},onAdditionalScroll:()=>{r(d.scrollLeft>0)},get children(){return[K(()=>e.currentPlaceholder),(()=>{const p=NE();return D(p,j(ti,{get each(){return t()},children:c})),p})()]}}),e.input.after(d),e.currentPlaceholder.classList.remove("will-animate");const h=e.createButtonIcon("arrow_prev","will-animate","emoticons-search-input-arrow");e.searchIcon.classList.add("will-animate"),e.searchIcon.after(h);const u=N(h,()=>{n()});ut(u),ye(()=>{h.classList.toggle("is-hiding",!i()),e.searchIcon.classList.toggle("is-hiding",!!i())}),ye(()=>{o.searching()&&n()}),ye($s(i,p=>{o.onGroup(p),p||vb(d)},{defer:!0})),I.managers.appEmojiManager.getEmojiGroups(o.type==="stickers"?"stickers":"esg").then(s)}function UE(o){const[e,t]=ne(!1),[s,i]=ne(!1),n=new wo({placeholder:o.placeholder||"Search",onChange:a=>{a=a.trim(),t(!!a),o.onValue(a)},onFocusChange:o.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"),ut(()=>{n.remove()}),o.loading&&ye(()=>{n.toggleLoading(s()||o.loading())}),o.onGroup&&OE({type:o.type,searching:e,inputSearch:n,onGroup:o.onGroup}),K(()=>n.container)}Ui(["click"]);async function aS({set:o,lazyLoadQueue:e,container:t,group:s,autoplay:i,width:n,height:a,managers:r=I.managers,middleware:l,textColor:c}){if(o.thumbs?.length){t.classList.add("media-sticker-wrapper"),e.push({div:t,load:async()=>{const p=await r.appStickersManager.getStickerSetThumbDownloadOptions(o),m=cs.download(p);if(p.mimeType==="application/x-tgsticker")return m.then(f=>{_s.loadAnimationWorker({container:t,loop:!0,autoplay:i,animationData:f,width:n,height:a,needUpscale:!0,name:"setThumb"+o.id,group:s,middleware:l})});{const f=o.thumbs?.some(v=>v.type==="v");let y;return f?(y=hl({middleware:l}),y.autoplay=!0,y.muted=!0,y.loop=!0):y=new Image,y.classList.add("media-sticker"),m.then(v=>{Kn(y,URL.createObjectURL(v),()=>{t.append(y),f&>.addAnimation({animation:y,group:s,observeElement:y,type:"video"})})})}}});return}let d;o.thumb_document_id?d=r.appEmojiManager.getCustomEmojiDocument(o.thumb_document_id):d=r.appStickersManager.getStickerSet(o).then(p=>p.documents[0]);const h=await d;if(!h)return;const u=h.attributes.find(p=>p._==="documentAttributeCustomEmoji");Rs({doc:h,div:t,group:s,lazyLoadQueue:e,managers:r,width:n,height:a,middleware:l,textColor:u?.pFlags?.text_color?c||jc:void 0})}class HE extends Hb{constructor(e,t,s){super(e),this.onVisibilityChange=t,this.elementsMap=new Map,this.intersector=new xu(i=>{const{target:n,visible:a}=i,r=this.elementsMap.get(n);r.visible=a,a?(r.wasSeen=!0,this.queue.includes(r)||this.queue.push(r)):us(this.queue,r),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 sp{constructor(e){this.animated=new Set,this.checkAnimationContainer=(t,s)=>{gt.getAnimations(t).forEach(n=>{s?gt.checkAnimation(n,!1):gt.removeAnimation(n)})},this.processVisible=async t=>{const s=t.dataset.docId,i=await this.managers.appDocsManager.getDoc(s),n=$e.active.esgSticker.width;t.middlewareHelper??(t.middlewareHelper=xt()),t.middlewareHelper.clean();const a=Rs({doc:i,div:t,width:n,height:n,lazyLoadQueue:null,group:this.group,onlyThumb:!1,play:!0,loop:!0,withLock:!0,middleware:t.middlewareHelper.get(),...this.visibleRenderOptions||{}}).then(({render:r})=>r);return a.then(()=>{this.checkAnimationContainer(t,this.lazyLoadQueue.intersector.isVisible(t))},Wt),a},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)},It(this,e),this.lazyLoadQueue=new HE(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():xt()),Rs({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)}}class vf{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)},It(this,e),this.categories={},this.categoriesMap=new Map,this.categoriesByMenuTabMap=new Map,this.localCategories=[],this.postponedEvents=[],this.listenerSetter=new Ut,this.middlewareHelper=xt(),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 vi(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 yr(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=Hi(()=>{const[t,s]=ne(""),[i,n]=ne(),[a,r]=ne(!1),l=K(()=>!!t()),[c,d]=ne(),[h]=zo(t,this.searchFetcher),[u]=this.groupFetcher?zo(i,this.groupFetcher):[],[p]=zo(()=>({data:c(),grouping:!!Et(i),searching:Et(l)}),this.processSearchResult),m=this.searchNoLoader?void 0:K(()=>l()&&p.loading),g=K(()=>a()||l()||!!i()),f=K(()=>p()||this.categoriesContainer);return _u({mount:this.scrollable.container,children:tp({type:"cross-fade",get children(){return f()}})}),ye(()=>{const y=i()?u:h;y.loading||d(()=>y())}),ye(()=>{this.container.classList.toggle("is-searching",g())}),UE({type:this.searchType,placeholder:this.searchPlaceholder,loading:m,onValue:s,onFocusChange:r,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 a=new AE({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(),h=d.style.getPropertyValue("--width");l=h?parseInt(h):d.offsetWidth}return{width:l-n.padding,height:c}},styles:n,noMenuTab:i,middleware:this.middlewareHelper.get()});n.itemsClassName&&a.elements.items.classList.add(n.itemsClassName);const r=a.elements.container;return r.classList.add("hide"),e&&(a.set=e,this.categories[e.id]=a,this.categoriesMap.set(r,a),this.categoriesIntersector.observe(r)),i||(this.categoriesByMenuTabMap.set(a.elements.menuTab,a),this.menuOnClickResult.stickyIntersector.observeStickyHeaderChanges(r),!s&&a.elements.menuTab.classList.add("not-local")),a}positionCategory(e,t){const{menuTab:s,container:i}=e.elements,n=t?this.localCategories.filter(l=>l.mounted).length:65535;let a=!1;const r=t?this.localCategories.filter(l=>l.menuScroll&&!a?(a=!0,!0):l.mounted&&!l.menuScroll&&l.elements.menuTab).length:65535;Ps(i,this.categoriesContainer,n),Ps(s,this.menu,r)}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,a=0;i.forEach(c=>{c.mounted?(!c.elements.menuTab||c.menuScroll)&&++a:(++n,++a)});const r=s-n,l=s-a;e.elements.menuTab&&Ps(e.elements.menuTab,this.menu,l),Ps(e.elements.container,this.categoriesContainer,r)}e.mounted=t}createLocalCategory({id:e,title:t,icon:s,noMenuTab:i,styles:n}){this.noMenu&&(i=!0);const a=e!==void 0,r=this.createCategory({stickerSet:a?{id:e}:void 0,title:t&&M(t),isLocal:!0,noMenuTab:i,styles:n});return r.local=!0,a&&this.localCategories.push(r),r.elements.title&&r.elements.title.classList.add("disable-hover"),r.elements.menuTab&&(s&&r.elements.menuTab.append(Le(s)),r.elements.menuTabPadding.remove()),this.toggleLocalCategory(r,!1),r}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}={}){Al({listenTo:this.content,listenerSetter:this.listenerSetter,getTextColor:e});const n="menu";Zw({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}){aS({set:e,container:t,group:Vn,lazyLoadQueue:this.emoticonsDropdown?.lazyLoadQueue,width:32,height:32,autoplay:!1,textColor:i,middleware:s})}createStickerRenderer(){const e=new sp({regularLazyLoadQueue:this.emoticonsDropdown.lazyLoadQueue,group:Vn,managers:this.managers,intersectionObserverInit:this.emoticonsDropdown.intersectionOptions}),t=e.lazyLoadQueue;return this.emoticonsDropdown.addLazyLoadQueueRepeat(t,e.processInvisible,this.middlewareHelper.get()),e}}const tr=class tr extends vf{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=M("NoStickersFound");return c.classList.add("emoticons-not-found"),c}const n=this.categoriesContainer.cloneNode(!1),a=this.createCategory({styles:Ma.Stickers}),r=tr.categoryAppendStickers(this,this.stickerRenderer,t.length,a,t);n.append(a.elements.container);let l=!1;return ut(()=>{l=!0,a.middlewareHelper.destroy(),this.clearCategoryItems(a,!0)}),await r,l||tr._onCategoryVisibility(a,!0),n},searchPlaceholder:"SearchStickers",searchType:"stickers"}),this.onCategoryVisibility=({target:t,visible:s})=>{const i=this.categoriesMap.get(t);tr._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 xu(this.onCategoryVisibility,e),this.scrollable.container.addEventListener("click",l=>{const c=l.target;if(U(c,"category-title")){const d=U(c,"emoji-category"),h=this.categoriesMap.get(d);if(h.local)return;ee.createPopup(Cn,{id:h.set.id,access_hash:h.set.access_hash},!1,this.emoticonsDropdown.chatInput).show();return}this.emoticonsDropdown.onMediaClick(l)}),this.menuOnClickResult=no.menuOnClick(this,this.menu,this.scrollable,this.menuScroll);const t=rn(this.content,!0),s=(l,c)=>{l.limit&&(c=c.slice(0,l.limit));const d=new Set(c.map(h=>h.id));bi(l.items,h=>{d.has(h.document.id)||this.deleteSticker(l,h.document,!0)}),this.toggleLocalCategory(l,!!c.length),bi(c,(h,u)=>{this.unshiftSticker(l,h,!0,u)}),this.spliceExceed(l),l.elements.container.classList.remove("hide")},i=this.createLocalCategory({id:"faved",title:"FavoriteStickers",icon:"savedmessages",styles:Ma.Stickers}),n=this.createLocalCategory({id:"recent",title:"Stickers.Recent",icon:"recent",styles:Ma.Stickers});n.limit=20;const a=it("close",{noRipple:!0});n.elements.title.append(a),N(a,()=>{Ct({titleLangKey:"ClearRecentStickersAlertTitle",descriptionLangKey:"ClearRecentStickersAlertMessage",button:{langKey:"Clear"}}).then(()=>{this.managers.appStickersManager.clearRecentStickers()},Wt)});const r=[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)tr.renderStickerSet(this,this.stickerRenderer,c,!1)})];Promise.race(r).finally(()=>{t.remove()}),Promise.all(r).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]||tr.renderStickerSet(this,this.stickerRenderer,d,!0)})}),this.stickerRenderer=this.createStickerRenderer(),I.addEventListener("sticker_updated",({type:l,document:c,faved:d})=>{const h=this.categories[l==="faved"?"faved":"recent"];h&&(d?this.unshiftSticker(h,c):this.deleteSticker(h,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 h=this.categories[d];h&&this.positionCategory(h,!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)})}),$e.addEventListener("resize",this.resizeCategories),this.attachHelpers({verifyRecent:l=>!!Ns(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=ga(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 a=e.items[i];if(a&&a.document.id===t.id)return}let n=ga(e.items,a=>a.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:a}=i.elements;return i.setCategoryItemsHeight(s),a.classList.remove("hide"),Promise.all([n,fe.isPremiumFeaturesHidden()]).then(([r,l])=>{const c=e.isCategoryVisible(i),d=r.map(h=>{if(l&&fo(h))return;const u=t.renderSticker(h,void 0,void 0,i.middlewareHelper.get());return i.items.push({document:h,element:u}),u}).filter(Boolean);c&&i.elements.items.append(...d)})}static async renderStickerSet(e,t,s,i){const n=e.createCategory({stickerSet:s,title:_e(s.title),styles:Ma.Stickers}),{menuTabPadding:a}=n.elements,r=e.managers.appStickersManager.getStickerSet(s);this.categoryAppendStickers(e,t,s.count,n,r.then(l=>l.documents)),i!==void 0&&e.positionCategory(n,i),e.renderStickerSetThumb({set:s,menuTabPadding:a,middleware:n.middlewareHelper.get()})}};tr._onCategoryVisibility=(e,t)=>{e.elements.items.replaceChildren(...t?e.items.map(({element:s})=>s):[])};let Ea=tr;const $y=new Set;function rS(o,e=!1){if(o.docId){const n=Ng.create(o.docId),a=document.createElement("span");return a.classList.add("super-emoji","super-emoji-custom"),a.append(n),a}let{emoji:t}=o;const s=document.createElement("span");s.classList.add("super-emoji","super-emoji-regular");let i;if(e&&!dL?i=SE(t):(t=Wg(t),i=_e(t)),s.append(i),s.children.length>1){const n=s.firstElementChild;s.replaceChildren(n)}if(s.firstElementChild?.tagName==="IMG"){const n=s.firstElementChild,a=n.src;if(!$y.has(a)){n.setAttribute("loading","lazy");const r=document.createElement("span");r.classList.add("emoji-placeholder"),st.isAvailable("animations")&&(n.style.opacity="0",r.style.opacity="1"),n.addEventListener("load",()=>{bs(()=>{st.isAvailable("animations")&&(n.style.opacity="",r.style.opacity=""),s.classList.remove("empty"),$y.add(a)})},{once:!0}),s.append(r)}}return s}function iu(o){const e=U(o,"super-emoji");if(!e)return;const t=e.firstElementChild;return t&&t.classList.contains("custom-emoji")?{emoji:t.dataset.stickerEmoji,docId:t.dataset.docId}:o.nodeType===o.TEXT_NODE?{emoji:o.nodeValue}:(o.tagName==="SPAN"&&!o.classList.contains("emoji")&&o.firstElementChild&&(o=o.firstElementChild),{emoji:o.getAttribute("alt")||o.innerText})}const Tr="Emoji.Recent",Um=[Tr,"recent"],sa="",Hm=[sa,""],cc=[["Emoji.SmilesAndPeople","smile"],["Emoji.AnimalsAndNature","animals"],["Emoji.FoodAndDrink","eats"],["Emoji.TravelAndPlaces","car"],["Emoji.ActivityAndSport","sport"],["Emoji.Objects","lamp"],["Emoji.Flags","flag"],["Skin Tones",""]];let wa;function Vy(){if(wa)return wa;const o=[[Hm,[]],[Um,[]]];wa=new Map(o);for(const s in gy){const n=""+gy[s],a=cc[+n[0]-1];if(!a)continue;let r=wa.get(a);r||(r=[],wa.set(a,r)),r[+n.slice(1)||0]=s}wa.delete(cc.pop()),cc.unshift(Hm,Um);const e=cc.map(([s])=>s),t=[...wa.entries()].sort((s,i)=>e.indexOf(s[0][0])-e.indexOf(i[0][0]));return wa=new Map(t),wa}const $E=vs(42,42),Gp=32;class Un extends vf{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:a}=t||{};if(!n||!s&&!i)return;if(!n.length&&!a){const d=M("NoEmojiFound");return d.classList.add("emoticons-not-found"),d}const r=this.categoriesContainer.cloneNode(!1),l=this.createCategory({styles:Ma.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(a){const d=this.renderLocalStickerSet(a);c.push(d)}return r.append(...c.map(d=>d.elements.container)),ut(()=>{c.forEach(d=>{d.middlewareHelper.destroy()})}),r},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=U(s,"emoji-category");if(!i)return;oe(t);const n=this.categoriesMap.get(i);if(!n){const r=U(s,"super-sticker");if(r){this.onClick({emoji:"",docId:r.dataset.docId,element:r});return}}if(U(s,"category-title")){if(n.local)return;ee.createPopup(Cn,{id:n.set.id,access_hash:n.set.access_hash},!0,this.emoticonsDropdown.chatInput).show();return}const a=iu(s);!a||!this.canUseEmoji(a,n,!0)||(this.onClick?this.onClick({...a,element:U(s,"super-emoji").firstElementChild}):this.emoticonsDropdown.chatInput.onEmojiSelected(a,!1),Je&&Dn())},It(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:a,element:r})=>{if(!a)return r;const l=r.firstElementChild;return l.clear(!1),n.set(l.docId,new Set([l])),r})),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:a,element:r})=>{if(!a)return;const l=r.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 xu(this.onCategoryVisibility,e),this.menu&&(this.menuOnClickResult=no.menuOnClick(this,this.menu,this.scrollable,this.menuScroll,void 0,this.listenerSetter));const t=rn(this.content,!0);let s;if(!this.isStandalone&&this.menu){const c=this.menuInnerScroll=new yr(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;Vy(),this.noRegularEmoji?(i=new Map([[[Hm[0],"recent"],[]]]),this.menu&&i.set([Um[0],""],[])):i=Vy(),i.forEach((c,[d,h])=>{const u=this.createLocalCategory({id:d,title:d,icon:h,noMenuTab:!h,styles:Ma.Emoji});u.elements.container.classList.remove("hide"),c.forEach(p=>{const m=Og(p);this.addEmojiToCategory({category:u,emoji:{emoji:m},batch:!0})})});const n=this.mainSets?.(),a=Promise.all([this.preloaderDelay?Hs(this.preloaderDelay):void 0,!this.noRegularEmoji&&this.managers.appEmojiManager.getRecentEmojis("native"),!this.isStandalone&&this.managers.appEmojiManager.getRecentEmojis("custom"),!this.noPacks&&Promise.resolve(fe.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,h,u,p,m,g])=>{t.remove();const f=S=>S.map(C=>({emoji:"",docId:C}));let y,v;p&&(v=f(p[0]),p[1]&&(y=f(p[1]))),!y&&d&&(y=d.map(S=>({emoji:S}))),!v&&h&&(v=f(h));const w=this.categories[Tr],b=this.categories[sa];if(this.noRegularEmoji||[w&&[w,d],b&&[b,h]].filter(Boolean).forEach(([C,P])=>{C.limit=Gp,P.splice(Gp,P.length-Gp)}),w&&(this.createEmojiRendererForCategory(w),y?.length))for(const S of y)this.addEmojiToCategory({category:w,emoji:S,batch:!0});if(b){if(this.createEmojiRendererForCategory(b),v?.length)for(const S of v)this.addEmojiToCategory({category:b,emoji:S,batch:!0});b.elements.container.style.paddingTop=".5rem",this.noMenu&&(b.elements.container.style.paddingBottom=".5rem")}if(cc.forEach(([S])=>{const C=this.categories[S];C&&(this.toggleLocalCategory(C,!!C.items.length),S!==Tr&&S!==sa&&(C.menuScroll=this.menuInnerScroll,this.menuInnerScroll.append(C.elements.menuTab)))}),this.resizeCategories(),w&&s&&w.elements.menuTab&&w.elements.menuTab.after(s),Ln([u?.sets,m].filter(Boolean)).forEach(S=>{this.renderEmojiSet(S)}),g){const S=this.renderLocalStickerSet(g);this.categoriesContainer.append(S.elements.container)}this.continueInit()});N(this.content,this.onContentClick,{listenerSetter:this.listenerSetter});const r=this.categories[Tr],l=this.categories[sa];return this.attachHelpers({getTextColor:()=>this.textColor,verifyRecent:c=>!!(Ns(c,l.elements.items)||Ns(c,r.elements.items)),canHaveEmojiTimer:this.canHaveEmojiTimer}),this.initPromise=a}renderLocalStickerSet(e){this.stickerRenderer??(this.stickerRenderer=this.createStickerRenderer());const t=this.createLocalCategory({title:e.title,styles:Ma.Stickers,noMenuTab:!0});return Ea.categoryAppendStickers(this,this.stickerRenderer,e.stickers.length,t,e.stickers).then(()=>{Ea._onCategoryVisibility(t,!0)}),t.elements.container.style.paddingBottom=Ma.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 a=this.categories[i].elements.renderer;a&&(a.ignoreSettingDimensions=s,s||a.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?sa:Tr];if(!n)return;const a=s.docId?l=>l.docId===s.docId:l=>l.emoji===s.emoji,r=ga(n.items,a);if(i){if(ga(this.postponedEvents,l=>l.cb===t&&l.args[0].deleted),!r)return;r.element.remove(),this.isCategoryVisible(n)&&this.onLocalCategoryUpdate(n)}else if(r){if(n.items.unshift(r),this.isCategoryVisible(n)){const{renderer:l}=n.elements;Ps(r.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[Tr]: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[Tr],this.categories[sa]].find(s=>!!s.elements.menuTab)),this.onReady?.()}get peerId(){return this.emoticonsDropdown?this.emoticonsDropdown.chatInput.chat.peerId:Tt}getCustomCategory(){return this.categories[sa]}toggleCustomCategory(){const e=this.categories[sa],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===sa){this.toggleCustomCategory();return}super.toggleLocalCategory(e,t)}setTextColor(e=jc){this.categoriesMap.forEach(t=>{t.elements.renderer?.setTextColor(e)})}get textColor(){return this.emoticonsDropdown?.textColor||jc}renderEmojiSet(e,t){const s=this.createCategory({stickerSet:e,title:_e(e.title),styles:Ma.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(Le("premium_lock","category-title-lock")),this.createEmojiRendererForCategory(s),s.setCategoryItemsHeight(e.count),i.classList.remove("hide"),this.managers.appStickersManager.getStickerSet(e).then(({documents:r})=>{r.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=Ug.create({animationGroup:Vn,customEmojiSize:$e.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 a=e.element;if(a){const l=document.createElement("span");l.classList.add("super-emoji"),l.append(a),a=l}else a=rS(s),this.showLocks&&!this.canUseEmoji(s,t)&&a.append(Le("premium_lock","premium-sticker-lock"));const r={...s||{emoji:void 0},element:a};(e.active||this.activeEmoji&&(r.docId?this.activeEmoji.docId===r.docId:this.activeEmoji.emoji===r.emoji))&&(this.activeEmoji,this.activeElements.push(r),a.classList.add("active")),t.items[n?"unshift":"push"](r),!i&&!this.spliceExceed(t)&&this.onLocalCategoryUpdate(t)}canUseEmoji(e,t,s){if(e.docId&&!I.premium&&(this.isStandalone&&t?t.id!==sa:this.peerId!==I.myId)&&!this.freeCustomEmoji.has(e.docId)){if(s){const i=ni(()=>{bo(),me.openPremiumBot()});Ee({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 VE extends Hb{constructor(e,t){super(e),this.onVisibilityChange=t,this.intersector=new xu(s=>{const{target:i,visible:n}=s,a=$b(this.queue,r=>r.div===i);n&&a.length&&a.forEach(r=>{this.queue.unshift(r)}),this.onVisibilityChange&&this.onVisibilityChange(s),this.setProcessQueueTimeout()})}observe(e){super.observe(e)}}class bf{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=Pt(),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 a=n.querySelector("img, canvas");a&&(a.classList.remove("hide"),await Qn()),!this.lazyLoadQueue.intersector.isVisible(n)&&n.middlewareHelper.clean()}),this.managers=I.managers,this.middlewareHelper=xt(),this.map=new Map,this.lazyLoadQueue=new VE(void 0,({target:n,visible:a})=>{a?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([a])=>{if(!this.lazyLoadQueue.intersector.isVisible(e)){this.processInvisibleDiv(e);return}e.middlewareHelper.clean();const r=e.middlewareHelper.get().create().get(),l=await qn({doc:a,container:e,lazyLoadQueue:null,group:this.group,noInfo:!0,noPreview:!0,middleware:r}),c=l.loadPromise;return c.finally(()=>{if(r.onDestroy(()=>{l.video?.remove()}),!r()||!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;tt?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 h=M("NoGIFsFound");return h.classList.add("emoticons-not-found"),h}const a=Ys().get(),r=this.categoriesContainer.cloneNode(!1),{masonry:l,container:c}=this.createMasonry(a);t.forEach(h=>l.add(h)),r.append(c);const d=this.scrollable.onAdditionalScroll;return this.scrollable.onAdditionalScroll=()=>{d?.(),s&&(this.managers.appGifsManager.searchGifs(this.query,s).then(({documents:h,nextOffset:u})=>{a()&&(h.forEach(p=>l.add(p)),s=u)}),s=void 0)},ut(()=>{this.scrollable.onAdditionalScroll=d}),r},searchNoLoader:!0,searchPlaceholder:"SearchGIFs",searchType:"gifs"}),It(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=N(t,this.emoticonsDropdown.onMediaClick),i=new bf(t,Vn,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=rn(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 Gy="GIFS-SEARCH";class zy extends Dt{constructor(){super(...arguments),this.nextOffset="",this.loadedAll=!1,this.onGifsClick=async e=>{const t=U(e.target,"gif");if(!t)return;const s=t.dataset.docId;await me.chat.input.sendMessageWithDocument({document:s,target:t})?$e.isMobile&&ls.onCloseBtnClick():console.warn("got no doc by id:",s)}}init(){this.container.id="search-gifs-container",this.inputSearch=new wo({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"),N(this.gifsDiv,this.onGifsClick,{listenerSetter:this.listenerSetter}),this.scrollable.append(this.gifsDiv),this.masonry=new bf(this.gifsDiv,Gy,this.scrollable),ls.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(),gt.checkAnimations(void 0,Gy),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(Tt,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 Ky extends Dt{init(){this.container.id="stickers-container",this.container.classList.add("chatlist-container"),this.lazyLoadQueue=new Ga,this.inputSearch=new wo({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),Al({listenTo:this.setsDiv,listenerSetter:this.listenerSetter}),N(this.setsDiv,e=>{const t=U(e.target,"sticker-set-sticker");if(t){const r=t.dataset.docId;me.chat.input.sendMessageWithDocument({document:r,target:t});return}const s=U(e.target,"sticker-set");if(!s)return;const i=s.dataset.stickerSet,n=s.dataset.access_hash,a=U(e.target,"sticker-set-button");a?(e.preventDefault(),e.cancelBubble=!0,a.setAttribute("disabled","true"),this.managers.appStickersManager.getStickerSet({id:i,access_hash:n}).then(r=>{this.managers.appStickersManager.toggleStickerSet(r.set).then(l=>{l&&(a.textContent="",a.append(M(r.set.installed_date?"Stickers.SearchAdded":"Stickers.SearchAdd")),a.classList.toggle("gray",!!r.set.installed_date))}).finally(()=>{a.removeAttribute("disabled")})})):this.managers.appStickersManager.getStickerSet({id:i,access_hash:n}).then(r=>{ee.createPopup(Cn,r.set).show()})},{listenerSetter:this.listenerSetter}),ls.toggleSidebar(!0).then(()=>{this.renderFeatured()})}onCloseAfterTimeout(){return this.setsDiv.replaceChildren(),gt.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='
',kt(i.firstElementChild,_e(e.title));const n=document.createElement("div");n.classList.add("sticker-set-count"),n.append(M("Stickers",[e.count])),i.append(n);const a=document.createElement("button");a.classList.add("btn-primary","btn-color-primary","sticker-set-button"),a.append(M(e.installed_date?"Stickers.SearchAdded":"Stickers.SearchAdd")),e.installed_date&&a.classList.add("gray"),s.append(i,a);const r=document.createElement("div");r.classList.add("sticker-set-stickers");const l=Math.min(5,e.count);for(let c=0;c{for(let d=0;d{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 bi(s,i=>{const n=i.dataset.stickerSet,a=t.findIndex(r=>r.set.id===n);a!==-1?t.splice(a,1):(!e||!i.dataset.title.toLowerCase().includes(e.toLowerCase()))&&i.remove()}),gt.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 Wy=200,GE=200;class yc extends Si{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=N(window,this.onClickOut,{capture:!0})},0)),this.setIgnoreMouseOut(i,n),this.toggle(n)},this.onClickOut=t=>{const s=t.target;t.isTrusted&&!Ns(s,this.element)&&!Array.from(this.ignoreButtons).some(i=>Ns(s,i)||s===i)&&this.ignoreMouseOut.size<=1&&(!this.ignoreOutClickClassName||!U(s,this.ignoreOutClickClassName))&&this.toggle(!1)},this.onMouseOut=t=>{if(!this.isActive()||(this.clearTimeout("toggle"),this.ignoreMouseOut.size))return;const s=t.toElement;s&&Ns(s,this.element)||this.setTimeout("toggle",()=>{this.toggle(!1)},Wy)},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=Je||!st.isAvailable("animations")?0:GE;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"),ft.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"),ft.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)},It(this,e),this.forceClose=!1,this.inited=!1,this.ignoreMouseOut=new Set,this.ignoreButtons=new Set,this.timeouts={}}attachButtonListener(e,t){let s=!0;Je?N(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)},Wy)}),N(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(){Je||(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)}}var zE=4,KE=.001,WE=1e-7,jE=10,dc=11,rh=1/(dc-1),qE=typeof Float32Array=="function";function oS(o,e){return 1-3*e+3*o}function lS(o,e){return 3*e-6*o}function cS(o){return 3*o}function nu(o,e,t){return((oS(e,t)*o+lS(e,t))*o+cS(e))*o}function dS(o,e,t){return 3*oS(e,t)*o*o+2*lS(e,t)*o+cS(e)}function QE(o,e,t,s,i){var n,a,r=0;do a=e+(t-e)/2,n=nu(a,s,i)-o,n>0?t=a:e=a;while(Math.abs(n)>WE&&++r=KE?YE(r,u,o,t):p===0?u:QE(r,l,l+rh,o,t)}return function(l){return l===0||l===1?l:nu(a(l),e,s)}}const Vn="emoticons-dropdown",ZE=_h(.42,0,.58,1),Yl={forceDuration:150,transitionFunction:ZE,maxDistance:150},JE=()=>{const o=document.createElement("div");o.innerHTML=``;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=o.firstElementChild;return t.lastElementChild.append(...e.map(([s,i,n])=>{const a=it(`${i} menu-horizontal-div-item emoji-tabs-${s}`,{noRipple:!0});return a.dataset.tab=""+n,a})),t},jc="primary-text-color",Zf=class Zf extends yc{constructor(e={}){super({element:JE(),ignoreOutClickClassName:"input-message-input"}),this.lazyLoadQueue=new Ga(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(Ea)&&{[this.getTab(Ea).tabId]:"send_stickers"},...this.getTab(zp)&&{[this.getTab(zp).tabId]:"send_gifs"}}[t];if(i&&!this.rights[i])return Ee({langPackKey:Or[i]}),!1;gt.checkAnimations(!0,Vn),this.tabId=t,this.searchButton.classList.toggle("hide",this.tabId===this.getTab(Un)?.tabId),this.deleteBtn.classList.toggle("hide",this.tabId!==this.getTab(Un)?.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 a=this.getTab(Un),r=this.tabsEl.querySelector(".active");r&&Ri(r)!==a?.tabId+1&&(!this.rights.send_stickers||!this.rights.send_gifs)&&this.selectTab(a.tabId,!1),a?.toggleCustomCategory()},this.onMediaClick=async(t,s=!1,i,n)=>{const a=Bi(t.target,"DIV");if(!a)return!1;const r=a.dataset.docId;return r?this.sendDocId({document:r,clearDraft:s,silent:i,target:a,ignoreNoPremium:n}):!1},It(this,e),this.listenerSetter=new Ut,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(Je&&Dn()&&await Hs(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(),gt.lockIntersectionGroup(Vn),this.tab.onOpen?.()}),this.addEventListener("opened",()=>{gt.unlockIntersectionGroup(Vn),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(),gt.lockIntersectionGroup(Vn),gt.checkAnimations(!0,Vn),this.tab.onClose?.()}),this.addEventListener("closed",()=>{gt.unlockIntersectionGroup(Vn),this.lazyLoadQueue.unlock(),this.lazyLoadQueue.refresh(),this.savedRange=void 0,this.tab.onClosed?.()})}canUseEmoji(e,t){return this.init?.(),this.getTab(Un).canUseEmoji(e,void 0,t)}get tab(){return this.tabs[this.tabId]}get chatInput(){return this._chatInput||me.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=jc){this.textColor=e,this.getTab(Un)?.setTextColor(e)}getTab(e){return this.tabsToRender.find(t=>t instanceof e)}init(){this.managers=I.managers,this.tabsToRender.length||(this.tabsToRender=[new Un({managers:this.managers,preloaderDelay:200}),new Ea(this.managers),new zp({managers:this.managers})]),this.tabs={},this.tabsToRender.forEach((a,r)=>{a.emoticonsDropdown=this,a.tabId=r,this.tabs[r]=a}),this.container=this.element.querySelector(".emoji-container .tabs-container"),this.container.prepend(...this.tabsToRender.map(a=>a.container)),this.tabsEl=this.element.querySelector(".emoji-tabs"),this.selectTab=Ml(this.tabsEl,this.container,this.onSelectTabClick,()=>{const{tab:a}=this;a.init?.(),gt.checkAnimations(!1,Vn)}),this.searchButton=this.element.querySelector(".emoji-tabs-search"),this.listenerSetter.add(this.searchButton)("click",()=>{this.tabId===this.getTab(Ea)?.tabId?ls.isTabExists(Ky)||ls.createTab(Ky).open():ls.isTabExists(zy)||ls.createTab(zy).open()}),this.deleteBtn=this.element.querySelector(".emoji-tabs-delete"),N(this.deleteBtn,a=>{oe(a);const r=this.chatInput.messageInput;let l=Hg.getInstance().getSavedRange(r);l||(l=document.createRange(),l.setStartAfter(r.lastChild));const c=l.cloneRange();if(l.collapsed){const{node:d,offset:h}=t0(r,l.endContainer,l.endOffset);let u;if(h)u=d;else{if(u=d.previousSibling,!u)return;for(;u.nodeType===u.TEXT_NODE&&!u.nodeValue&&(u=u.previousSibling););if(u.nodeType===u.ELEMENT_NODE&&!u.isContentEditable)return}if(u.nodeType===u.ELEMENT_NODE&&u.tagName==="IMG")c.selectNode(u);else{const p=[...u.textContent];let m;if(h){let f=0;m=p.find(y=>(f+=y.length,f>=h))}else m=p.pop()||"";const g=h?h-m.length:u.textContent.length-m.length;c.setStart(u,g)}}c.deleteContents(),this.chatInput.messageInputField.simulateInputEvent()},{listenerSetter:this.listenerSetter});const e=Dg&&!1,t=e?this.getTab(Ea).tabId:this.getTab(Un).tabId;if(e&&this.tabsEl.children[1].classList.add("hide"),fs(this.tabsEl.children[t+1]),this.tabsToRender.length<=1&&this.tabsEl.classList.add("hide"),this.tabs[t].init?.(),!Je){let a,r=!1;const l=c=>{a=c};this.listenerSetter.add(Li)("change",c=>{c?r||(this.listenerSetter.add(document.body)("mousemove",l),r=!0):r&&(this.listenerSetter.removeManual(document.body,"mousemove",l),a&&this.onMouseOut(a))})}const s=()=>{this._chatInput||this.isStandalone||this.toggle(!1)},i=()=>{this._chatInput||this.isStandalone||this.checkRights()};this.listenerSetter.add(me)("peer_changing",s),this.listenerSetter.add(me)("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,...Yl})}async sendDocId(e){return await this.chatInput.sendMessageWithDocument(e)?(vc.container&&(vc.forceClose=!0,vc.toggle(!1)),!0):(console.warn("got no doc by id:",document),!1)}addLazyLoadQueueRepeat(e,t,s){const i=new Ut;i.add(this)("close",()=>{e.lock()}),i.add(this)("closed",()=>{const n=e.intersector.getVisible();for(const a of n)t(a);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())}};Zf.menuOnClick=(e,t,s,i,n,a)=>{let r=-1;const l=(m,g)=>{const f=m.menuScroll||i;f&&f.scrollIntoViewNew({element:m.elements.menuTab,position:"center",axis:"x",getElementPosition:g?({elementPosition:y})=>y-106:void 0,...Yl})},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:Rh.Static,position:"center",axis:"x",...Yl}))),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",...Yl})),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 h=!1;const u=new Xw(s.container,(m,g)=>{if(h||Math.abs(r-s.scrollPosition)<=1)return;r=-1;const f=e.getCategoryByContainer(g);if(!f.elements.menuTab)return;const y=Ri(g);!m&&(y||f.menuScroll)||c(f)});N(t,m=>{oe(m);let g=U(m.target,"menu-horizontal-div-item");if(!g){if(g=U(m.target,"menu-horizontal-inner"),!g||g.classList.contains("active"))return;g=g.firstElementChild.firstElementChild}const f=Ri(g),y=e.getCategoryByMenuTab(g);c(y);let v=0,w=0;if(f>0||y.menuScroll){const b=y.elements.container;w=1,v=b.offsetTop+w}r=v,h=!0,s.scrollIntoViewNew({element:v?y.elements.container:s.firstElementChild,position:"start",axis:"y",getElementPosition:v?({elementPosition:b})=>b+w:void 0,startCallback:()=>{e instanceof Un&&!e.isCategoryVisible(y)&&e._onCategoryVisibility(y,!0)},...Yl}).finally(()=>{c(y),h=!1})},{listenerSetter:a});const p=s.onAdditionalScroll?s.onAdditionalScroll.bind(s):Wt;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:u,setActive:c,setActiveStatic:d}};let no=Zf;const vc=new no;Ws.emoticonsDropdown=vc;const Ji=vc;function ha(o,e){let t;const s=o.reply_to,i=o.saved_peer_id&&at(o.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&&(o._==="messageService"&&o.action?._==="messageActionTopicCreate"?t=o.mid:t=Id),t}function $m(o,e,t,s){return t?Yr(o,e,t):(us(o,e),(s?o.push(e):o.unshift(e))-1)}class e_{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=Rn(t),n=e.from_id&&e.from_id._==="peerChannel"&&e.fromId===s,a=this.chat.peerId,r=(t&&a===cr&&!i||n?s:e.fromId)||Tt;return{peerId:r,peerTitle:r===Tt?i:void 0}}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=es({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,a=t-1;n{this.mountItem(n,i-1-a,t)}),e&&this.updateClassNames(),this.onItemMount()}mountItem(e,t=this.items.indexOf(e),s=this.offset){e.mounted||(Ps(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(a=>a.dateTimestamp===this.dateTimestamp),s=t.length,i=t.indexOf(this),n=t.slice(i+1).reduce((a,r)=>a+(r.mounted?0:1),0);Ps(this.container,e.container,QS+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 t_{constructor(e){this.chat=e,this.itemsArr=[],this.itemsMap=new Map,this.groups=[],this.newGroupDiff=121,e.type!==te.Search&&(this.sortItemsKey=e.type===te.Scheduled?"timestamp":"mid",this.sortGroupsKey=e.type===te.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),a=t.group;this.removeItem(t);const r=new Set;a&&(a.unmountItem(t),r.add(a));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(),r.add(l.group),this.groupUngrouped()}return this.mountUnmountGroups(Array.from(r)),!0}mountUnmountGroups(e){const[t,s]=ul(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{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){us(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===te.Scheduled?+`${(i*1e3-t)/1e3}.${+(""+s).replace(".","")}`:s}createItem(e,t,s){const i=!(t._==="message"||t.action&&Pf.has(t.action._)),{mid:n,date:a}=t,{dateTimestamp:r}=this.chat.bubbles.getDateForDateContainer(a);return{mid:n,groupMid:this.generateGroupMid(t,r),fromId:this.getMessageFromId(t),bubble:e,timestamp:a,dateTimestamp:r,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,a=n.indexOf(t)+1,r=n.length;if(a===r)return;const l=[i];return this.f(n,a,r),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;is.add(u))}}return s}cleanup(){this.itemsArr=[],this.groups=[],this.itemsMap.clear()}}class ip extends ee{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 a=n.target;if(!a.dataset.timestamp)return;if(this.selectedEl){if(this.selectedEl===a)return;this.selectedEl.classList.remove("active")}this.selectedEl=a,a.classList.add("active");const r=+a.dataset.timestamp;this.selectedDate=new Date(r),this.setTitle(),this.setTimeTitle()},this.minDate=s.minDate||new Date("2013-08-01T00:00:00"),e{const h=""+r;this.listenerSetter.add(l.input)("input",u=>{let p=l.value.replace(/\D/g,"");p.length>2?p=p.slice(0,2):(p.length===1&&+p[0]>+h[0]||p.length===2&&+p>r)&&(p.length===2&&d&&d(+p[1]),p="0"+p[0]),l.setValueSilently(p),c(p.length)})};this.hoursInputField=new _t({plainText:!0}),this.minutesInputField=new _t({plainText:!0}),a(23,this.hoursInputField,r=>{r===2&&this.minutesInputField.input.focus(),this.setTimeTitle()},r=>{this.minutesInputField.value=(r+this.minutesInputField.value).slice(0,2)}),a(59,this.minutesInputField,r=>{r||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),N(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 ke.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&&$e.isMobile?"short":"long"};this.monthTitle.replaceChildren(new ke.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 ke.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 a=new Date(e.getTime());a.setDate(a.getDate()-n-1);for(let c=0;cthis.maxDate||e{if(t){const r=t(n);r instanceof Promise&&await r}if(n===I.myId){let r=0;for(const l in e){const c=e[l];r+=c.length,this.managers.appMessagesManager.forwardMessages({peerId:n,fromPeerId:l.toPeerId(),mids:c})}Ee({langPackKey:r>0?"FwdMessagesToSavedMessages":"FwdMessageToSavedMessages"});return}await me.setInnerPeer({peerId:n,threadId:a}),me.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(a=>t[a].map(l=>I.managers.appMessagesManager.getMessageByPeer(a.toPeerId(),l))),i=await Promise.all(Ln(s)),n=new Set;i.forEach(a=>{if(!a)return;const r=Xs(a);let l;if(!r)a.viaBotId?l="send_inline":l="send_plain";else if(r._==="webPage")l="embed_links";else if(r._==="photo")l="send_photos";else if(r._==="game")l="send_games";else switch(r.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)}),ee.createPopup(va,e[0],e[1],Array.from(n))}}function on(o,e=2){if(o===0)return"0";const t=1e3,s=e<0?0:e,i=["","K","M","B","T"],n=Math.floor(Math.log(o)/Math.log(t));return parseFloat((o/Math.pow(t,n)).toFixed(s))+i[n]}class np{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"),Oa(this.title),this.subtitle=document.createElement("div"),this.subtitle.classList.add(e+"-subtitle"),Oa(this.subtitle),this.content.append(this.title,this.subtitle),this.container.append(this.border,this.content)}}const ja=32;async function wf(o){o.loadPromises||(o.loadPromises=[]);const{titleEl:e,subtitleEl:t,mediaEl:s,message:i,loadPromises:n,animationGroup:a,middleware:r,lazyLoadQueue:l,replyHeader:c}=o;let{storyItem:d,quote:h}=o,u=o.title;if(u!==void 0)typeof u=="string"&&(u=Aa(u,140),u=_e(u)),dt(e,u);else if(o.isStoryExpired){const v=Le("bomb","expired-story-icon");e.append(v,M("ExpiredStory"))}const p=c?._==="messageReplyHeader";p&&c.quote_text&&(h??(h={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 y=s?Array.from(s.children).slice():[];if(m&&s){m=m.webpage||m;const v=m.photo,w=m.document;if(v||w&&w.thumbs?.length)if(w?.type==="sticker")await Rs({doc:w,div:s,lazyLoadQueue:l||void 0,group:a,width:ja,height:ja,middleware:r,loadPromises:n}),g=!0;else if(w?.type==="gif"&&w.video_thumbs)g=!0,await qn({doc:w,container:s,boxWidth:ja,boxHeight:ja,lazyLoadQueue:l||void 0,noPlayButton:!0,noInfo:!0,middleware:r,loadPromises:n,withoutPreloader:!0,videoSize:w.video_thumbs[0],group:a});else{const b=v||w;f=w?.type==="round";try{await Ks({photo:b,container:s,boxWidth:ja,boxHeight:ja,size:Sn(b,ja,ja),middleware:r,lazyLoadQueue:l,noBlur:!0,withoutPreloader:!0,loadPromises:n}),g=!0}catch{}}}if(o.subtitle!==void 0){let v=o.subtitle;typeof v=="string"&&(v=Aa(v,140),v=_e(v)),dt(t,v||"")}else if(d&&o.storyItem)t.replaceChildren(M("Story"));else if(o.isStoryExpired){const v=Le("bomb","expired-story-icon");t.replaceChildren(v,M("ExpiredStory"))}else if(h){const v=Yt(Aa(h.text,200),{...o,noLinebreaks:!0,entities:h.entities,noLinks:!0});t.replaceChildren(v)}else if(i){const v=await hr(o);t.replaceChildren(v)}return Promise.all(n).then(()=>{r&&!r()||(y.forEach(v=>v.remove()),s&&s.classList.toggle("is-round",f))}),g}class hS extends np{constructor(e){super(e,async t=>{this.mediaEl||(this.mediaEl=document.createElement("div"),this.mediaEl.classList.add(this.className+"-media"));const s=await wf({...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 uS({docId:o,middleware:e,useHighlightingColor:t,colorAsOut:s,container:i,color:n,positions:a,canvasWidth:r,canvasHeight:l,emojiSize:c,onCacheStatus:d}){const h=await I.managers.acknowledged.appEmojiManager.getCustomEmojiDocument(o);h.cached||d?.(!1);const u=await h.result,p=document.createElement("div");return Rs({doc:u,div:p,middleware:e,width:c,height:c,static:!0,withThumb:!1,exportLoad:2,useCache:!1}).then(({load:m,downloaded:g})=>(d?.(g),m())).then(m=>{const g=m[0];return g.naturalWidth?g:(console.warn("should wait for image size",g),Hs(100).then(()=>g))}).then(m=>{const g=document.createElement("canvas");g.classList.add("emoji-pattern-canvas"),g.style.width=`${r}px`,g.style.height=`${l}px`;const f=g.getContext("2d"),y=g.dpr=window.devicePixelRatio;return g.width=r*y,g.height=l*y,a.forEach(([v,w,b,S])=>{f.globalAlpha=S,f.drawImage(m,v*y,w*y,b*y,b*y)}),f.globalAlpha=1,t?n="#ffffff":s&&(n=Ls.getProperty("message-out-primary-color")),Vb(f,n,0,0,g.width,g.height),i&&i.prepend(g),g}).catch(Wt)}function Fd(o){const e=new hS("reply"),t=e.fill(o);e.container.classList.add("quote-like","quote-like-hoverable","quote-like-border"),Oa(e.container),e.border.remove(),Ni(e.container,void 0,void 0,!0),o.isQuote&&(e.container.classList.add("quote-like-icon"),e.container.classList.add("reply-multiline")),o.noBorder&&e.container.classList.remove("quote-like-border");const{setColorPeerId:s}=o;if(s!==void 0){me.setPeerColorToElement({peerId:s,element:e.container,messageHighlighting:o.useHighlightingColor,colorAsOut:o.colorAsOut});const i=fe.getPeer(s),n=i?.color?.background_emoji_id;n&&uS({docId:n,container:e.container,middleware:o.middleware,color:jg(i)[0],colorAsOut:o.colorAsOut,useHighlightingColor:o.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(a=>{o.middleware&&!o.middleware()||a.classList.add("reply-background-canvas")})}return{container:e.container,fillPromise:t}}const pS="stacked-avatars",mS=pS+"-avatar",s_=mS+"-container";class Co{constructor(e){this.lazyLoadQueue=e.lazyLoadQueue,this.avatarSize=e.avatarSize,this.middlewareHelper=e.middleware.create(),this.container=document.createElement("div"),this.container.classList.add(pS),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 a=s[n];a?a.middlewareHelper.clean():(a=document.createElement("div"),a.classList.add(s_),a.middlewareHelper=this.middlewareHelper.get().create());const r=es({middleware:a.middlewareHelper.get(),size:this.avatarSize,isDialog:!1,lazyLoadQueue:this.lazyLoadQueue,peerId:i});r.node.classList.add(mS),t?.push(r.readyThumbPromise),a.replaceChildren(r.node),a.parentNode||this.container.append(a),a.classList.toggle("is-first",n===0)}),Array.from(s).slice(e.length).forEach(i=>{i.middlewareHelper.destroy(),i.remove()}),Promise.all(t)}}const gS="replies-element";I.addEventListener("replies_updated",o=>{Array.from(document.querySelectorAll(gS+`[data-post-key="${o.peerId}_${o.mid}"]`)).forEach(e=>{e.message=o,e.render()})});class fS 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 Co({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=>at(n)),this.loadPromises)):(t&&!t.classList.contains(_a("comments"))&&(t.remove(),t=null),t||(t=Le("comments","replies-footer-icon","replies-footer-icon-comments"))),t.parentElement||this.prepend(t),this.text||(this.text=new ke.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?.replies?on(e.replies,0):""}`,this.prepend(Le("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(gS,fS);const i_=" ",jy=()=>{const o=document.createElement("i");return o.classList.add("time-edited","time-part"),Zt(o,"EditedMessage"),o},qy=(o,e)=>e?Ib(o.getTime()/1e3|0,{combined:!0}).dateEl:Ag(o),Qy=o=>{const e=document.createElement("span");if(e.classList.add("time-effect"),o.onlyElement)return e;const t=Pt();return e.dataset.effectId=""+o.docId,I.managers.acknowledged.appReactionsManager.getAvailableEffect(o.docId).then(async s=>{s.cached||t.resolve();const i=await s.result;if(!i){t.resolve();return}const n=[];Rs({doc:await I.managers.appDocsManager.getDoc(i.static_icon_id),div:e,middleware:o.middleware,loadPromises:n,width:12,height:12}),Promise.all(n).then(async()=>{s.cached&&t.resolve();const{doc:a,thumb:r}=await yS(i);cs.downloadMedia({media:a,thumb:r})})}),o.loadPromises?.push(t),e},yS=async o=>{const e=!o.effect_animation_id,t=await I.managers.appDocsManager.getDoc(e?o.effect_sticker_id:o.effect_animation_id);return{isPremiumEffect:e,doc:t,thumb:fo(t)}},vS=({e:o,isOut:e,element:t,middleware:s,scrollable:i,effectId:n})=>{if(t.dataset.playing){o&&oe(o);return}t.dataset.playing="1",I.managers.appReactionsManager.getAvailableEffect(n).then(async a=>{const{doc:r,thumb:l}=await yS(a);if(!s())return;const{animationDiv:c}=Dc({doc:r,middleware:s,side:e?"right":"left",size:240,target:t,play:!0,scrollable:i,fullThumb:fo(r),addOffsetX:40,onUnmount:()=>{delete t.dataset.playing}});e===!1&&c.classList.add("reflect-x")}),o&&oe(o)},n_=({timeEffect:o,bubble:e,e:t,scrollable:s})=>{const i=o.dataset.effectId;return vS({element:o,isOut:e.classList.contains("is-out"),e:t,scrollable:s,effectId:i,middleware:e.middlewareHelper.get()})};var Uo;(o=>{o.setTime=e=>{const{chatType:t,message:s}=e,i=!("action"in s),n=s.peerId===I.myId&&!e.isOut,a=[];let r=s.date;n&&i&&s.fwd_from&&(r=s.fwd_from.saved_date||s.fwd_from.date||r);const l=new Date(r*1e3);let c,d;const h=i&&s.fwd_from,u=qy(l,n);if(i){if(s.views){const v=document.createElement("span");v.classList.add("post-views"),v.textContent=on(s.views,1);const w=Le("channelviews","time-icon","time-part","time-icon-views");a.push(v,w)}const y=e.chat.getPostAuthor(s);if(y){const v=document.createElement("span");v.classList.add("time-post-author"),kt(v,_e(y)),v.insertAdjacentHTML("beforeend",'"),a.push(v)}if(s.edit_date&&t!==te.Scheduled&&!s.pFlags.edit_hide&&a.unshift(c=jy()),t!==te.Pinned&&s.pFlags.pinned){const v=Le("pinnedchat","time-icon","time-pinned","time-part");a.unshift(v)}s.effect&&(d=Qy({onlyElement:!0}),a.push(d))}u&&a.push(u);let p=Mp(new Date(s.date*1e3));i&&(p+=(s.edit_date&&!s.pFlags.edit_hide?` Edited: ${Mp(new Date(s.edit_date*1e3))}`:"")+(h?` Original: ${Mp(new Date(h.saved_date||h.date*1e3))}`:""));const m=document.createElement("span");m.classList.add("time"),m.append(...a);const g=document.createElement("div");g.classList.add("time-inner"),p&&(g.title=p);let f=a;return c&&(f[f.indexOf(c)]=jy()),d&&(f[f.indexOf(d)]=Qy({docId:s.effect,middleware:e.middleware,loadPromises:e.loadPromises})),f=f.map(y=>y instanceof HTMLElement&&!y.classList.contains("i18n")&&!y.classList.contains("reactions")&&!y.classList.contains("time-effect")?y.cloneNode(!0):y),u&&(f[f.length-1]=qy(l,n)),g.append(...f),m.append(g),m},o.renderReplies=({bubble:e,bubbleContainer:t,message:s,messageDiv:i,loadPromises:n,lazyLoadQueue:a,middleware:r})=>{const l=!e.classList.contains("sticker")&&!e.classList.contains("emoji-big")&&!e.classList.contains("round"),c=new fS;return c.message=s,c.type=l?"footer":"beside",c.loadPromises=n,c.lazyLoadQueue=a,c.middlewareHelper=r.create(),c.init(),t.append(c),l},o.setReply=async({chat:e,bubble:t,bubbleContainer:s,message:i,appendCallback:n,middleware:a,lazyLoadQueue:r,needUpdate:l,isStandaloneMedia:c,isOut:d})=>{const h=!s;h&&(s=t.querySelector(".bubble-content"));const u=h?s.querySelector(".reply"):null,p=i.reply_to;if(!p){u?.remove(),t.classList.remove("is-reply");return}const m=p._==="messageReplyStoryHeader",g=m?at(p.peer):p.reply_to_peer_id?at(p.reply_to_peer_id):i.peerId,f=!m&&fe.getMessageByPeer(g,i.reply_to_mid),y=m&&await I.managers.acknowledged.appStoriesManager.getStoryById(g,p.story_id);let v,w=!1,b,S;if(m)y.cached?(b=g,v=new Rt({peerId:b,dialog:!1,onlyFirstName:!1,plainText:!1}).element):(l.push({replyToPeerId:g,replyStoryId:p.story_id,mid:i.mid,peerId:i.peerId}),I.managers.appMessagesManager.fetchMessageReplyTo(i),v=M("Loading"));else if(!f)p.reply_from?(w=!0,b=at(p.reply_from?.from_id||p.reply_to_peer_id),v=new Rt({peerId:b||void 0,dialog:!1,onlyFirstName:!1,plainText:!1,fromName:Rn(p.reply_from)}).element):(l.push({replyToPeerId:g,replyMid:i.reply_to_mid,mid:i.mid,peerId:i.peerId}),I.managers.appMessagesManager.fetchMessageReplyTo(i),v=M("Loading"));else{w=!!p.reply_from;const E=f.fwdFromId;b=i.fwdFromId&&i.fwdFromId===E?i.fwdFromId:E||f.fromId,S=i.fwdFromId&&i.fwdFromId===E?void 0:f.fromId,v=new Rt({peerId:b,dialog:!1,onlyFirstName:!1,plainText:!1,fromName:b?void 0:Rn(f.fwd_from)}).element}if(!m&&p.reply_from){const E=document.createDocumentFragment();let _;if(p.reply_from.channel_post)E.append(_=Le("newchannel_filled","with-margin"),v);else if(p.reply_to_peer_id){const k=new Rt({peerId:at(p.reply_to_peer_id),dialog:!1,onlyFirstName:!1,plainText:!1}).element;E.append(v," ",_=Le("group_filled")," ",k)}else E.append(_=Le("newprivate_filled","with-margin"),v);_&&(_.classList.add("inline-icon","reply-title-icon"),v=E)}const C=m&&y.cached&&!await y.result,{container:P,fillPromise:L}=Fd({title:v,animationGroup:e.animationGroup,message:f||(w?{_:"message",pFlags:{},id:0,date:0,message:"",peer_id:void 0,media:p.reply_media}:void 0),isStoryExpired:C,storyItem:y?.cached&&await y.result,setColorPeerId:S||b,textColor:"primary-text-color",isQuote:m?void 0:p.pFlags.quote,middleware:a,lazyLoadQueue:r,replyHeader:p,useHighlightingColor:c,colorAsOut:d,canTranslate:f&&!w?!f.pFlags.out:void 0});if(await L,u){const E=["floating-part","mb-shorter"],_=u.classList;E.forEach(k=>{_.contains(k)&&P.classList.add(k)}),u.replaceWith(P)}else n(P);return t.classList.add("is-reply"),P}})(Uo||(Uo={}));class Yy extends Dt{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=Bc(t.poll.question);kt(s,Yt(i.text,{entities:i.entities,middleware:this.middlewareHelper.get()}));const n=t.results.results.map(r=>r.voters/t.results.total_voters*100);wS(n);const a=document.createDocumentFragment();t.results.results.forEach((r,l)=>{if(!r.voters)return;const c=document.createElement("hr"),d=t.poll.answers[l],h=document.createElement("div");h.classList.add("poll-results-answer");const u=document.createElement("div"),p=Bc(d.text);kt(u,Yt(p.text,{entities:p.entities,middleware:this.middlewareHelper.get()}));const m=document.createElement("div");m.innerText=Math.round(n[l])+"%",h.append(u,m);const g=Xe.createChatList();g.classList.add("poll-results-voters"),Xe.setListClickListener({list:g,onFound:()=>{ls.onCloseBtnClick()},withContext:void 0,autonomous:!0}),g.style.minHeight=Math.min(r.voters,4)*48+"px",a.append(c,h,g);let f,y=4,v=!1,w=Math.max(0,r.voters-4);const b=()=>{v||(v=!0,this.managers.appPollsManager.getVotes(e,d.option,f,y).then(C=>{C.votes.forEach(P=>{const{dom:L}=Xe.addDialogNew({peerId:at(P.peer),container:g,rippleEnabled:!1,meAsSaved:!1,avatarSize:"small",withStories:!1,wrapOptions:{middleware:this.middlewareHelper.get()}});L.lastMessageSpan.parentElement.remove()}),f&&(w=Math.max(0,w-C.votes.length),w&&S.lastElementChild.replaceWith(M("PollResults.LoadMore",[Math.min(20,w)]))),f=C.next_offset,y=20,(!w||!C.votes.length)&&S.remove()}).finally(()=>{v=!1}))},S=ze("poll-results-more btn btn-primary btn-transparent",{icon:"down"});S.addEventListener("click",b),S.append(M("PollResults.LoadMore",[Math.min(20,w)])),a.append(S),b()}),this.resultsDiv.append(s,a),ls.toggleSidebar(!0).then(()=>{})}}let Xy=0;const a_=9,Fo=10,bS=340,Zy=bS/Fo,wS=o=>{const e=o.reduce((t,s)=>t+Math.round(s),0);if(e>100){const t=e-100,s=o.length;for(let i=0;i=.5&&la&&(a=l,n=r)}if(n===-1)return;o[n]+=1-a}}};I.addEventListener("poll_update",({poll:o,results:e})=>{Array.from(document.querySelectorAll(`poll-element[poll-id="${o.id}"]`)).forEach(s=>{s.isClosed=!!o.pFlags.closed,s.performResults(e,o.chosenIndexes)})});$e.addEventListener("resize",()=>{ao.setMaxLength(),ao.resizePolls()});$e.addEventListener("changeScreen",()=>{ao.setMaxLength()});const Kp=(o,e,t)=>{o.classList.remove("active"),clearTimeout(t),setTimeout(()=>{e?.(),o.remove(),Br===o&&bc===e&&wc===t&&(Br=bc=null,wc=0)},200)};let Br,bc,wc,Jy=!1;const ap=o=>{Br&&Kp(Br,bc,wc);const e=document.createElement("div");e.classList.add("quiz-hint","from-"+o.from);const t=document.createElement("div");t.classList.add("quiz-hint-container");let s;o.title&&(s=document.createElement("div"),s.classList.add("quiz-hint-title"),s.append(o.title),t.classList.add("has-title"));const i=document.createElement("div");i.classList.add("quiz-hint-text");let n;o.textRight&&(n=document.createElement("div"),n.classList.add("quiz-hint-text-right"),n.append(o.textRight),t.classList.add("has-right-text")),t.append(...[o.icon&&Le(o.icon,"quiz-hint-icon"),s,i,n].filter(Boolean)),e.append(t),kt(i,o.textElement),o.appendTo.append(e),e.offsetLeft,e.classList.add("active");const a=()=>{Kp(e,o.onHide,r)};Br=e,bc=o.onHide;const r=wc=window.setTimeout(a,o.duration);return Jy||(Jy=!0,me.addEventListener("peer_changed",()=>{Br&&Kp(Br,bc,wc)})),{hide:a}},Hr=class Hr 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=U(e.target,"poll-answer");if(!t)return;oe(e);const s=+t.dataset.index;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=lt.width<=360?lt.width-120:$e.active.poll.width;this.MAX_LENGTH=e+a_+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(){Xy||(Xy=document.getElementById("poll-line").getTotalLength(),Hr.setMaxLength());const{poll:e,results:t}=this.message.media;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((r,l)=>{const c=`
`,d=Ed(c);if(this.isMultiple){const u=document.createElement("span");u.classList.add("poll-answer-selected"),u.append(Le("check")),d.firstElementChild.firstElementChild.append(u)}const h=document.createElement("span");return h.classList.add("poll-answer-selected"),d.firstElementChild.append(h),d});if(this.innerHTML=`
`,this.append(...i),kt(this.firstElementChild,this.wrapSomeText(e.question)),Array.from(this.querySelectorAll(".poll-answer-text")).forEach((r,l)=>{const c=this.wrapSomeText(e.answers[l].text);kt(r,c)}),this.descDiv=this.firstElementChild.nextElementSibling,this.typeDiv=this.descDiv.firstElementChild,this.avatarsDiv=this.descDiv.lastElementChild,s&&this.typeDiv.append(M(s)),this.isQuiz&&(this.classList.add("is-quiz"),e.close_period&&e.close_date)){const r=document.createElement("div");r.classList.add("poll-time"),this.descDiv.append(r);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,h=2*Math.PI*d,u=document.createElementNS("http://www.w3.org/2000/svg","circle");u.classList.add("poll-quiz-timer-circle"),u.setAttributeNS(null,"cx","16"),u.setAttributeNS(null,"cy","16"),u.setAttributeNS(null,"r",""+d),u.setAttributeNS(null,"stroke-width",""+c),l.append(u),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,y=(m-g)/1e3+1|0;r.textContent=Fi(y),y<=5&&(r.style.color="#ee545c",u.style.stroke="#ee545c"),u.style.strokeDashoffset=h+f*h,u.style.strokeDasharray=`${h} ${h}`,g>=m&&(clearInterval(this.quizInterval),r.replaceChildren(),u.style.strokeDashoffset=h,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(M("Chat.Poll.ViewResults")),this.votersCountDiv=document.createElement("div"),this.votersCountDiv.className="poll-votes-count",n.append(this.viewResults,this.votersCountDiv),this.append(n),this.viewResults.addEventListener("click",r=>{oe(r),ls.isTabExists(Yy)||ls.createTab(Yy).open(this.message)}),Ni(this.viewResults),this.isMultiple&&(this.sendVoteBtn=document.createElement("div"),this.sendVoteBtn.classList.add("poll-footer-button","poll-send-vote"),this.sendVoteBtn.append(M("Chat.Poll.SubmitVote")),Ni(this.sendVoteBtn),e.chosenIndexes.length||this.votersCountDiv.classList.add("hide"),N(this.sendVoteBtn,r=>{oe(r),this.chosingIndexes.length&&this.sendVotes(this.chosingIndexes).then(()=>{this.chosingIndexes.length=0,this.answerDivs.forEach(l=>{l.classList.remove("is-chosing")})})}),n.append(this.sendVoteBtn));const a=!(e.chosenIndexes.length||this.isClosed);(!a||this.isPublic)&&this.performResults(t,e.chosenIndexes,!1),a&&(this.setVotersCount(t),this.detachClickEvent=N(this,this.clickHandler))}wrapSomeText(e,t,s=this.middlewareHelper.get()){return typeof e!="string"&&(t=e.entities,e=e.text),this.translatableParams?_d({...this.translatableParams,middleware:s,textWithEntities:{_:"textWithEntities",text:e,entities:t}}):Yt(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(Le("tip")),this.descDiv.append(t),N(t,s=>{oe(s),t.classList.add("active");const i=xt();ap({textElement:this.wrapSomeText(e.solution,e.solution_entities,i.get()),appendTo:me.chat.bubbles.container,from:"top",duration:Je?5e3:7e3,icon:"info2",onHide:()=>{i.destroy(),t.classList.remove("active")}})}),this.sentVote){const s=e.results.find(i=>i.pFlags.correct);s&&!s.pFlags.chosen&&fs(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(st.isAvailable("animations")||(s=!1),this.isQuiz&&(e.results?.length||this.isClosed)&&(this.answerDivs.forEach((n,a)=>{const l=!!e.results[a].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"),dt(this.typeDiv,M("Chat.Poll.Type.Closed"))),(this.chosenIndexes.length!==t.length||this.isClosed)&&(this.isRetracted=this.chosenIndexes.length&&!t.length,this.chosenIndexes=t.slice(),this.isRetracted?this.detachClickEvent=N(this,this.clickHandler):(this.detachClickEvent?.(),this.detachClickEvent=void 0)),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&&bt({element:this,className:"",forwards:!this.isRetracted,duration:340}),bs(()=>{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(a=>at(a)),n=new Co({avatarSize:16,middleware:this.middlewareHelper.get()});n.render(i),dt(this.avatarsDiv,n.container)}if(this.isMultiple){const i=!!this.chosenIndexes.length,n=this.isClosed||i,a=!this.isPublic||!e.total_voters||!i&&!this.isClosed;this.sendVoteBtn.classList.toggle("hide",n),this.viewResults.classList.toggle("hide",a),this.votersCountDiv.classList.toggle("hide",!n||!a)}}setResults(e,t,s){this.svgLines.forEach(r=>r.style.display=""),this.answerDivs.forEach((r,l)=>{const c=t.includes(l);r.classList.toggle("is-chosen",c);const d=r.lastElementChild;let h;r.classList.contains("is-correct")||!this.isQuiz&&c?h=Le("check"):c&&(h=Le("close")),d.replaceChildren(h)});const i=Math.max(...e);if(this.maxPercents=e.map(r=>r/i),this.isRetracted)this.svgLines.forEach((r,l)=>{this.setLineProgress(l,-1)});else{const r=()=>{this.svgLines.forEach((l,c)=>{this.setLineProgress(c,1)})};s?bs(r):r()}e=e.slice(),wS(e);let n;const a=r=>{e.forEach((l,c)=>{const d=n(l,r);this.numberDivs[c].innerText=d+"%"})};if(this.isRetracted)if(n=(r,l)=>Math.round(r/Fo*l),s)for(let r=Fo-1,l=0;r>=0;--r,++l)setTimeout(()=>{a(r)},Zy*l);else a(0);else if(n=(r,l)=>Math.round(r/Fo*(l+1)),s)for(let r=0;r{a(r)},Zy*r);else a(Fo-1);if(this.isRetracted){s&&this.classList.add("is-retracting"),this.classList.remove("is-voted");const r=()=>{this.svgLines.forEach(l=>l.style.display="none")};s?setTimeout(()=>{this.classList.remove("is-retracting"),r()},bS):r()}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",dt(this.votersCountDiv,M(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]*Hr.MAX_LENGTH+", 485.9",s.style.strokeDashoffset=""+t*Hr.MAX_OFFSET)}};Hr.MAX_OFFSET=-46.5,Hr.MAX_LENGTH=0;let ao=Hr;customElements.define("poll-element",ao);function r_(o,e){const t=o.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;i0?1:0}return r_(o,e)}var Ro=(o=>(o[o.None=0]="None",o[o.Top=1]="Top",o[o.Bottom=2]="Bottom",o[o.Both=3]="Both",o))(Ro||{});class vl{constructor(){this.sliceConstructor=vl.getSliceConstructor(this),this.compareValue??(this.compareValue=o_);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 a=super.splice(s,i,...n);if(!this.length){const r=e.slices,l=r.indexOf(this);l!==-1&&(r.length===1?this.unsetEnd(3):r.splice(l,1))}return a}}}constructSlice(...e){const t=new this.sliceConstructor(e.length);for(let s=0,i=e.length;s=2)for(let t=0,s=this.slices.length;t=0)return{slice:t,offset:e===t[s]?s+1:s}}findSliceOffset(e){let t;for(let s=0;s=d||(i.isEnd(1)?(c.setEnd(1),!0):!1),p=a-h>=0||(i.isEnd(2)?(c.setEnd(2),!0):!1);return{slice:c,offsetIdOffset:n,fulfilled:0|(u&&p?3:(u?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){us(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 vl;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}}Ws&&(Ws.SlicedArray=vl);function l_(o){o.style.display="none",o.offsetLeft,o.style.display=""}function SS(o){let e=!1,t=!1;return new So({...o,verifyTouchTarget:s=>!U(s.target,"progress-line")&&!Lb(s)&&(o.verifyTouchTarget?o.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))oe(n),e=!0;else if(!e&&Math.abs(i)>Math.abs(s))return!0;return t=!0,o.onSwipe(s,i,n)},onReset:()=>{t&&o.onReset?.(),e=t=!1},cancelEvent:!1})}var vt=(o=>(o[o.MESSAGE=0]="MESSAGE",o[o.PRIVATE_POST=1]="PRIVATE_POST",o[o.STICKER_SET=2]="STICKER_SET",o[o.JOIN_CHAT=3]="JOIN_CHAT",o[o.VOICE_CHAT=4]="VOICE_CHAT",o[o.USER_PHONE_NUMBER=5]="USER_PHONE_NUMBER",o[o.INVOICE=6]="INVOICE",o[o.EMOJI_SET=7]="EMOJI_SET",o[o.ATTACH_MENU_BOT=8]="ATTACH_MENU_BOT",o[o.WEB_APP=9]="WEB_APP",o[o.ADD_LIST=10]="ADD_LIST",o[o.STORY=11]="STORY",o[o.BOOST=12]="BOOST",o[o.PREMIUM_FEATURES=13]="PREMIUM_FEATURES",o[o.GIFT_CODE=14]="GIFT_CODE",o[o.BUSINESS_CHAT=15]="BUSINESS_CHAT",o))(vt||{});function rp(o,e){return o.some(t=>t instanceof Promise)?Promise.all(o).then(e):e(o)}function c_(o){return{_:"reactionEmoji",emoticon:o.reaction}}function en(o,e){return typeof o!=typeof e?!1:([o,e]=[o,e].map(t=>t._==="availableReaction"?c_(t):t),Di(o,e))}const Za="reaction",d_=Za+"-element";var vn=(o=>(o.Inline="inline",o.Block="block",o.Tag="tag",o))(vn||{});const Vm={inline:14,block:22,tag:22},Gm={inline:2,block:4},h_=o=>o;class Wp{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,a)=>n+(this.nextKeyframe.s[a]-n)*(i?this.beziers[a](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=_h(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)=>_h(this.keyframe.o.x[s],this.keyframe.o.y[s],this.keyframe.i.x[s],this.keyframe.i.y[s])):this.beziers=_h(this.keyframe.o.x,this.keyframe.o.y,this.keyframe.i.x,this.keyframe.i.y):this.beziers=h_,!this.nextKeyframe||e===this.nextKeyframe.t?this.keyframe.s:this.withProgress(e)):this.keyframe?this.withProgress(e):this.nextKeyframe.s}}function u_(o){const e=o.ks,t=e.a,s=o.op,i=new Array(s-1),n=e.o&&new Wp(e.o),a=e.p&&new Wp(e.p),r=e.s&&new Wp(e.s);for(let l=0;l{const s=t.layers.filter(n=>n.nm.startsWith("placeholder_")),i=[];for(const n of s)i.push(u_(n));return{layersPositions:i,op:t.op}})}class wr extends HTMLElement{constructor(){super(),this.classList.add(Za),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(Za+"-"+e),this.classList.toggle(Za+"-like-block",e==="block"||e==="tag"),this.middleware=t,e==="tag"&&this.insertAdjacentHTML("beforeend",`
`)}setCanRenderAvatars(e){this.canRenderAvatars=e}render(e){const t=!!this.stickerContainer;if(!t)this.stickerContainer=document.createElement("div"),this.stickerContainer.classList.add(Za+"-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=fe.getReaction(i.emoticon);return ei(n,a=>{a.center_icon?this.stickerContainer.classList.add("is-regular"):this.stickerContainer.classList.add("is-static"),a.pFlags.inactive&&this.classList.add("is-inactive");const r=a.center_icon??a.static_icon;this.renderDoc(r)})}else if(i._==="reactionCustomEmoji"){if(this.stickerContainer.classList.add("is-custom"),!this.customEmojiElement){this.customEmojiElement=Ng.create();const n=this.wrapStickerPromise=this.customEmojiElement.readyPromise=Pt();this.wrapStickerPromise.finally(()=>{this.wrapStickerPromise===n&&(this.wrapStickerPromise=void 0)}),this.stickerContainer.append(this.customEmojiElement)}return this.customEmojiElement.docId=i.document_id,this.customEmojiElement}}renderDoc(e){const t=Vm[this.type],s=this.wrapStickerPromise=Rs({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=qc.find(s=>en(s.reaction,this.reactionCount.reaction))?.title),e}renderCounter(e,t=this.findTitle()){const s=Gm[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(Za+"-counter"));const a=on(i.count);if(t){const r=document.createElement("span");r.classList.add(Za+"-counter-title"),r.append(typeof t=="string"?_e(t):t),this.counter.replaceChildren(r),n=!0,e&&this.counter.append(" ",a)}else this.counter.textContent!==a&&(this.counter.textContent=a);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>=Gm[this.type]||!this.canRenderAvatars){this.stackedAvatars&&(this.stackedAvatars.container.remove(),this.stackedAvatars=void 0);return}this.stackedAvatars||(this.stackedAvatars=new Co({avatarSize:24,middleware:this.middleware}),this.append(this.stackedAvatars.container)),this.stackedAvatars.render(e.map(t=>at(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&&bt({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),wr?.fireAroundAnimation({waitPromise:e,cache:this,middleware:this.middleware,reaction:this.reactionCount?.reaction,stickerContainer:this.stickerContainer,managers:this.managers,sizes:{genericEffect:26,genericEffectSize:100,size:Vm[this.type]+t,effectSize:80},scrollable:me.chat.bubbles.scrollable})}static fireAroundAnimation(e){if(e.cache.hasAroundAnimation||!st.isAvailable("effects_reactions"))return;e.managers??(e.managers=I.managers);const t=e.reaction;if(t._==="reactionEmpty")return;const s=({availableReaction:a,genericEffect:r,sticker:l,onlyAround:c})=>{const d=r?e.sizes.genericEffect:e.sizes.size,h=r?void 0:document.createElement("div");h&&h.classList.add(Za+"-sticker-activate");const u=e.sizes.genericEffectSize,p=r&&l.sticker!==2,m=e.textColor||"primary-text-color",g={doc:r||a.around_animation,size:r?u:e.sizes.effectSize,target:e.stickerContainer,side:"center",skipRatio:1,play:!1,managers:e.managers,middleware:e.middleware,scrollable:e.scrollable},f=Dc(g),y=r&&Dc({...g,doc:p?g.doc:l,size:u,stickerSize:d,loopEffect:!0,textColor:m}),v=(!r||p)&&!c&&Rs({div:h||document.createElement("div"),doc:l||a.center_icon,width:d,height:d,withThumb:!1,needUpscale:!0,play:!1,skipRatio:1,group:"none",needFadeIn:!1,managers:e.managers,middleware:e.middleware,textColor:m,loop:p}).then(({render:w})=>w);return Promise.all([r?y.stickerPromise:v,f.stickerPromise,v,r&&p_(),e.waitPromise]).then(([w,b,S,C,P])=>{c&&(w=b);const L=Pt(),E=()=>{L.resolve(),w?.remove(),h?.remove(),e.stickerContainer.classList.remove("has-animation")};if(r){const k=w.canvas[0];k.classList.add("hide");const x=w.contexts[0],A=k.dpr,T=u*A,B=k.width;y.animationDiv.append(k),y.animationDiv.style.transform="scaleX(-1)";const R=S?.[0],O=R instanceof HTMLVideoElement;w.addEventListener("firstFrame",()=>{w.setSize(T,T),k.classList.remove("hide"),O&&wi(R)},{once:!0});let X=0;const F=T/512,{layersPositions:H,op:G}=C;w.overrideRender=z=>{p&&(z=R);const q=z instanceof ImageData;x.clearRect(0,0,T,T);for(let $=0;$=G&&_()}}if(!w||!b)return E(),L;const _=()=>{bs(E)};return e.middleware.onDestroy(_),!r&&w.addEventListener("enterFrame",k=>{k===w.maxFrame&&(e.cache.wrapStickerPromise?e.cache.wrapStickerPromise.then(()=>{setTimeout(_,1e3)}):_())}),w.addEventListener("firstFrame",()=>{h&&e.stickerContainer.append(h),e.stickerContainer.classList.add("has-animation"),w.play(),b.play()},{once:!0}),L})},i=(a,r=a.stickerEmojiRaw)=>rp([fe.getReaction(r),a?e.managers.appReactionsManager.getRandomGenericAnimation():void 0],([l,c])=>s(l?{availableReaction:l,onlyAround:!!a}:{genericEffect:c,sticker:a}));let n;t._==="reactionEmoji"?n=i(void 0,t.emoticon):n=ei(e.managers.appEmojiManager.getCustomEmojiDocument(t.document_id),a=>i(a)),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(d_,wr);const xr="reactions",m_=xr+"-element",Ho=new Map,qc=[];I.addEventListener("saved_tags",({savedPeerId:o,tags:e})=>{o||(qc.splice(0,qc.length,...e),Ho.forEach(t=>{t.forEach(s=>{s.getContext().peerId===I.myId&&s.getType()===vn.Tag&&s.render()})}))});class op extends HTMLElement{constructor(){super(),this.classList.add(xr),this.sorted=[],this.middlewareHelpers=new Map,this.managers=I.managers}connectedCallback(){let e=Ho.get(this.key);e||Ho.set(this.key,e=new Set),e.add(this),this.onConnectCallback&&this.isConnected&&(this.onConnectCallback(),this.onConnectCallback=void 0)}disconnectedCallback(){const e=Ho.get(this.key);e.delete(this),e.size||Ho.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:a,forceCounter:r}){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=a,this.forceCounter=r,this.setType(t),this.connectedCallback()}setType(e){if(e===vn.Block&&this.shouldUseTagsForContext(this.context)&&(e=vn.Tag),this.type!==e){this.type=e;for(const t in vn)this.classList.remove(xr+"-"+t);this.classList.add(xr+"-"+e),this.classList.toggle(xr+"-like-block",e===vn.Block||e===vn.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:[];n.sort((d,h)=>h.count-d.count||(d.chosen_order??0)-(h.chosen_order??0)),bi(this.sorted,(d,h,u)=>{const p=d.reactionCount.reaction;n.some(g=>en(g.reaction,p))||(this.middlewareHelpers.get(d).destroy(),this.middlewareHelpers.delete(d),u.splice(h,1),d.remove())});let a=!1;const r=n.reduce((d,h)=>d+h.count,0),l=s&&(!!s.pFlags.can_see_list||this.context.peerId.isUser())&&r{let p=this.sorted.find(v=>en(v.reactionCount.reaction,d.reaction));if(!p){const v=this.middleware.create();p=new wr,p.init(this.type,v.get()),this.middlewareHelpers.set(p,v)}p.classList.toggle("is-last",h===u.length-1),Ps(p,this,h);const m=s.recent_reactions?s.recent_reactions.filter(v=>en(v.reaction,d.reaction)):[],g=p.isUnread,f=m.some(v=>v.pFlags.unread);p.reactionCount={...d},p.setCanRenderAvatars(l);const y=p.render(this.isPlaceholder);return p.renderCounter(this.forceCounter),p.renderAvatars(m),p.isUnread=f,p.setIsChosen(),g&&!f&&!e?.includes(d)&&((e??(e=[])).push(d),a=!0),c[h]=y,p}),rp(c,d=>{const h=new Map;if(d.forEach(u=>{u&&h.set(u.docId,new Set([u]))}),!h.size){this.customEmojiRenderer&&(this.customEmojiRendererMiddlewareHelper.destroy(),this.customEmojiRenderer.remove(),this.customEmojiRenderer=this.customEmojiRendererMiddlewareHelper=void 0);return}if(!this.customEmojiRenderer){const u=Vm[this.type];this.customEmojiRendererMiddlewareHelper=this.middleware.create(),this.customEmojiRenderer=Ug.create({animationGroup:this.animationGroup,customEmojiSize:vs(u,u),middleware:this.customEmojiRendererMiddlewareHelper.get(),lazyLoadQueue:this.lazyLoadQueue,observeResizeElement:this}),this.customEmojiRenderer.classList.add(xr+"-renderer"),this.customEmojiRenderer.canvas.classList.add(xr+"-renderer-canvas"),this.prepend(this.customEmojiRenderer)}this.customEmojiRenderer.add({addCustomEmojis:h,lazyLoadQueue:this.lazyLoadQueue})}),!this.isPlaceholder&&e?.length&&(this.isConnected?this.handleChangedResults(e,t,a):this.onConnectCallback=()=>{this.handleChangedResults(e,t,a)})}async handleChangedResults(e,t,s){await As(),this.context.peerId===me.chat.peerId&&(s&&(t=(t||Promise.resolve()).then(()=>Hs(150))),e.forEach(i=>{this.sorted.find(a=>en(a.reactionCount.reaction,i.reaction))?.fireAroundAnimation(t)}))}}customElements.define(m_,op);class g_{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;i1)break;t=s}return e>1&&(t=void 0),t}const Ye={None:0,Top:1,Right:2,Bottom:4,Left:8};class au{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=au.countRatios(e),this.proportions=au.countProportions(this.ratios),this.averageRatio=io(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 Sf(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:Ye.Left|Ye.Top|Ye.Right|Ye.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:Ye.Left|Ye.Top|Ye.Right},{geometry:{x:0,y:t+this.spacing,width:e,height:t},sides:Ye.Left|Ye.Bottom|Ye.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:Ye.Top|Ye.Left|Ye.Bottom},{geometry:{x:e+this.spacing,y:0,width:e,height:t},sides:Ye.Top|Ye.Right|Ye.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:Ye.Top|Ye.Left|Ye.Bottom},{geometry:{x:s+this.spacing,y:0,width:t,height:i},sides:Ye.Top|Ye.Right|Ye.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:Ye.Top|Ye.Left|Ye.Bottom},{geometry:{x:n+this.spacing,y:0,width:i,height:s},sides:Ye.Top|Ye.Right},{geometry:{x:n+this.spacing,y:s+this.spacing,width:i,height:t},sides:Ye.Bottom|Ye.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:Ye.Left|Ye.Top|Ye.Right},{geometry:{x:0,y:t+this.spacing,width:s,height:i},sides:Ye.Bottom|Ye.Left},{geometry:{x:s+this.spacing,y:t+this.spacing,width:n,height:i},sides:Ye.Bottom|Ye.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])),a=e-i-n-2*this.spacing,r=Math.min(this.maxHeight-t-this.spacing,s);return[{geometry:{x:0,y:0,width:e,height:t},sides:Ye.Left|Ye.Top|Ye.Right},{geometry:{x:0,y:t+this.spacing,width:i,height:r},sides:Ye.Bottom|Ye.Left},{geometry:{x:i+this.spacing,y:t+this.spacing,width:a,height:r},sides:Ye.Bottom},{geometry:{x:i+this.spacing+a+this.spacing,y:t+this.spacing,width:n,height:r},sides:Ye.Right|Ye.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]),a=e-i-n-2*this.spacing,r=Math.max(this.minWidth,Math.min(this.maxWidth-t-this.spacing,s));return[{geometry:{x:0,y:0,width:t,height:e},sides:Ye.Top|Ye.Left|Ye.Bottom},{geometry:{x:t+this.spacing,y:0,width:r,height:i},sides:Ye.Top|Ye.Right},{geometry:{x:t+this.spacing,y:i+this.spacing,width:r,height:n},sides:Ye.Right},{geometry:{x:t+this.spacing,y:i+n+2*this.spacing,width:r,height:a},sides:Ye.Bottom|Ye.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 Sf{constructor(e,t,s,i,n,a=s*4/3){this.averageRatio=t,this.maxWidth=s,this.minWidth=i,this.spacing=n,this.maxHeight=a,this.ratios=Sf.cropRatios(e,t),this.count=e.length}static cropRatios(e,t){return e.map(n=>t>1.1?Kt(n,1,2.75):Kt(n,.6667,1))}layout(){const e=new Array(this.count),t=[],s=(u,p)=>{const m=this.ratios.slice(u,u+p),g=io(m,0);return(this.maxWidth-(p-1)*this.spacing)/g},i=u=>{const p=[];let m=0;for(const g of u)p.push(s(m,g)),m+=g;t.push({lineCounts:u,heights:p})};for(let u=1;u!==this.count;++u){const p=this.count-u;u>3||p>3||i([u,p])}for(let u=1;u!==this.count-1;++u)for(let p=1;p!==this.count-u;++p){const m=this.count-u-p;u>3||p>(this.averageRatio<.85?4:3)||m>3||i([u,p,m])}for(let u=1;u!==this.count-1;++u)for(let p=1;p!==this.count-u;++p)for(let m=1;m!==this.count-u-p;++m){const g=this.count-u-p-m;u>3||p>3||m>3||g>3||i([u,p,m,g])}let n=null,a=0;for(const u of t){const{heights:p,lineCounts:m}=u,g=m.length,f=io(p,0)+this.spacing*(g-1),y=Math.min(...p);Math.max(...p);const v=y{for(let S=1;S!==g;++S)if(m[S-1]>m[S])return 1.5;return 1})(),b=Math.abs(f-this.maxHeight)*v*w;(!n||bc.sides&Ye.Right),i=s.geometry.width+s.geometry.x,n=t.find(c=>c.sides&Ye.Bottom),a=n.geometry.height+n.geometry.y,r=o.container;r.style.width=i+"px",r.style.height=a+"px";const l=r.children;t.forEach(({geometry:c,sides:d},h)=>{let u;if(u=l[h],u||(u=document.createElement("div"),r.append(u)),u.classList.add("album-item"),o.noGroupedItem||u.classList.add("grouped-item"),u.style.width=c.width/i*100+"%",u.style.height=c.height/a*100+"%",u.style.top=c.y/a*100+"%",u.style.left=c.x/i*100+"%",d&Ye.Left&&d&Ye.Top&&(u.style.borderStartStartRadius=`calc(var(--border-start-start-radius) - ${o.spacing}px)`),d&Ye.Left&&d&Ye.Bottom&&(u.style.borderEndStartRadius=`calc(var(--border-end-start-radius) - ${o.spacing}px)`),d&Ye.Right&&d&Ye.Top&&(u.style.borderStartEndRadius=`calc(var(--border-start-end-radius) - ${o.spacing}px)`),d&Ye.Right&&d&Ye.Bottom&&(u.style.borderEndEndRadius=`calc(var(--border-end-end-radius) - ${o.spacing}px)`),o.forMedia){const p=document.createElement("div");p.classList.add("album-item-media"),u.append(p)}})}function zm(o,e){return o=Math.ceil(o),e=Math.floor(e),Math.floor(Math.random()*(e-o+1))+o}class y_{constructor(e){this.options=e,this.autoplay=!0,this.loop=!0,this.paused=!0}remove(){this.pause(),this.options.onDestroy?.()}play(){this.paused&&(this.paused=!1,this.options.onPlay())}pause(){this.paused||(this.paused=!0,this.options.onPause())}}const ia=class ia{constructor(){this.reset=!0,this.loop=!0;const e=this.canvas=document.createElement("canvas");this.dpr=window.devicePixelRatio,e.classList.add("canvas-thumbnail","canvas-dots"),this.paused=!0,this.autoplay=!0,this.tempId=0,this.time=0,this.bufferIndex=0,this.context=e.getContext("webgl2")}resize(e,t,s,i={}){this.width=e,this.height=t,this.multiply=s,this.canvas.width=e*this.dpr,this.canvas.height=t*this.dpr,this.config={particlesCount:Kt(e*t/(500*500)*1e3*(Oi?5:10),500,1e4),radius:this.dpr*1.6,seed:Math.random()*10,noiseScale:6,noiseSpeed:.6,forceMult:.6,velocityMult:1,dampingMult:.9999,maxVelocity:6,longevity:1.4,noiseMovement:4,timeScale:.65,color:16777215,...i},this.inited&&this.draw()}genBuffer(){this.buffer&&(this.context.deleteBuffer(this.buffer[0]),this.context.deleteBuffer(this.buffer[1])),this.buffer=[];for(let e=0;e<2;++e)this.buffer[e]=this.context.createBuffer(),this.context.bindBuffer(this.context.ARRAY_BUFFER,this.buffer[e]),this.context.bufferData(this.context.ARRAY_BUFFER,(this.bufferParticlesCount=Math.ceil(this.config.particlesCount))*6*4,this.context.DYNAMIC_DRAW)}compileShader(e,t){var n;const s=this.context.createShader(e),i=(n=ia.shaderTexts)[t]??(n[t]=fetch(t).then(a=>a.text()).then(a=>ia.shaderTexts[t]=a+` //`+Math.random()));return ei(i,a=>{if(this.context.shaderSource(s,a),this.context.compileShader(s),!this.context.getShaderParameter(s,this.context.COMPILE_STATUS))throw`compile shader error: `+this.context.getShaderInfoLog(s);return s})}compileShaders(){return rp([this.compileShader(this.context.VERTEX_SHADER,"assets/img/spoiler_vertex.glsl"),this.compileShader(this.context.FRAGMENT_SHADER,"assets/img/spoiler_fragment.glsl")],e=>e)}draw(){if(!this.inited)return;const e=this.context,t=this.config,s=Date.now(),i=Math.min((s-this.lastDrawTime)/1e3,1)*t.timeScale;this.lastDrawTime=s,this.time+=i,this.bufferParticlesCount>16&255)/255,(t.color>>8&255)/255,(t.color&255)/255),e.bindBuffer(e.ARRAY_BUFFER,this.buffer[this.bufferIndex]),e.vertexAttribPointer(0,2,e.FLOAT,!1,24,0),e.enableVertexAttribArray(0),e.vertexAttribPointer(1,2,e.FLOAT,!1,24,8),e.enableVertexAttribArray(1),e.vertexAttribPointer(2,1,e.FLOAT,!1,24,16),e.enableVertexAttribArray(2),e.vertexAttribPointer(3,1,e.FLOAT,!1,24,20),e.enableVertexAttribArray(3),e.bindBufferBase(e.TRANSFORM_FEEDBACK_BUFFER,0,this.buffer[1-this.bufferIndex]),e.vertexAttribPointer(0,2,e.FLOAT,!1,24,0),e.enableVertexAttribArray(0),e.vertexAttribPointer(1,2,e.FLOAT,!1,24,8),e.enableVertexAttribArray(1),e.vertexAttribPointer(2,1,e.FLOAT,!1,24,16),e.enableVertexAttribArray(2),e.vertexAttribPointer(3,1,e.FLOAT,!1,24,20),e.enableVertexAttribArray(3),e.beginTransformFeedback(e.POINTS),e.drawArrays(e.POINTS,0,t.particlesCount),e.endTransformFeedback(),e.bindBuffer(e.ARRAY_BUFFER,null),e.bindBufferBase(e.TRANSFORM_FEEDBACK_BUFFER,0,null),this.bufferIndex=1-this.bufferIndex,ia.drawCallbacks.forEach(n=>n())}remove(){this.pause(),this.destroy()}pause(){this.paused||(this.paused=!0,++this.tempId)}play(){if(!this.paused)return;this.paused=!1;const e=++this.tempId;this.lastDrawTime=Date.now(),ll(()=>this.tempId!==e||this.paused?!1:(this.draw(),!0))}_init(e,t){this.genBuffer();const s=this.context,i=this.program=s.createProgram();if(s.attachShader(i,e),s.attachShader(i,t),s.transformFeedbackVaryings(i,["outPosition","outVelocity","outTime","outDuration"],s.INTERLEAVED_ATTRIBS),s.linkProgram(i),!s.getProgramParameter(i,s.LINK_STATUS))throw`program link error: `+s.getProgramInfoLog(i);s.deleteShader(e),s.deleteShader(t),this.timeHandle=s.getUniformLocation(i,"time"),this.deltaTimeHandle=s.getUniformLocation(i,"deltaTime"),this.sizeHandle=s.getUniformLocation(i,"size"),this.resetHandle=s.getUniformLocation(i,"reset"),this.radiusHandle=s.getUniformLocation(i,"r"),this.seedHandle=s.getUniformLocation(i,"seed"),this.noiseScaleHandle=s.getUniformLocation(i,"noiseScale"),this.noiseSpeedHandle=s.getUniformLocation(i,"noiseSpeed"),this.dampingMultHandle=s.getUniformLocation(i,"dampingMult"),this.velocityMultHandle=s.getUniformLocation(i,"velocityMult"),this.forceMultHandle=s.getUniformLocation(i,"forceMult"),this.longevityHandle=s.getUniformLocation(i,"longevity"),this.maxVelocityHandle=s.getUniformLocation(i,"maxVelocity"),this.noiseMovementHandle=s.getUniformLocation(i,"noiseMovement"),this.colorHandle=s.getUniformLocation(i,"color"),s.clearColor(0,0,0,0),s.viewport(0,0,this.canvas.width,this.canvas.height),s.enable(s.BLEND),s.blendFunc(s.SRC_ALPHA,s.ONE_MINUS_SRC_ALPHA),this.inited=!0,this.lastDrawTime=Date.now()}init(){return this.initPromise??(this.initPromise=ei(this.compileShaders(),e=>(this._init(...e),this.draw(),!0)))}destroy(){this.buffer&&(this.context.deleteBuffer(this.buffer[0]),this.context.deleteBuffer(this.buffer[1])),this.buffer=null,this.context.deleteProgram(this.program),this.program=null}static create({width:e,height:t,middleware:s,animationGroup:i,multiply:n,config:a}){const r=++this.createdIndex;let{instance:l}=this;l||(l=this.instance=new ia,l.resize(480,480),window.dotRenderer=l);const c=document.createElement("canvas");c.classList.add("canvas-thumbnail","canvas-dots");const d=window.devicePixelRatio;e&&(c.width=e*d,c.height=t*d);const h=c.getContext("2d"),u=r%4===1,p=r%4===2,m=r%4===3,g=[u&&"rotate(180deg)",p&&"scaleX(-1)",m&&"scaleY(-1)"].filter(Boolean);g.length&&(c.style.transform=g.join(" "));const f=zm(0,l.canvas.width-c.width),y=zm(0,l.canvas.height-c.height),v=()=>{const{width:b,height:S}=c;h.clearRect(0,0,b,S),h.drawImage(l.canvas,f,y,b,S,0,0,b,S),a?.color&&Vb(h,"#"+a.color.toString(16),0,0,b,S)};++this.counter;const w=new y_({onPlay:()=>{this.drawCallbacks.set(c,v),l.play()},onPause:()=>{this.drawCallbacks.delete(c),this.drawCallbacks.size||l.pause()},onDestroy:()=>{--this.counter||(l.remove(),this.instance=void 0)}});return gt.addAnimation({animation:w,group:i,observeElement:c,controlled:s,type:"dots"}),{canvas:c,readyResult:e&&l.init()}}};ia.shaderTexts={},ia.createdIndex=-1,ia.drawCallbacks=new Map,ia.counter=0;let Qc=ia;function Km(o){const{mediaSpoiler:e,reveal:t,destroyAfter:s}=o;bt({element:e,forwards:t,className:"is-revealing",duration:250,onTransitionEnd:()=>{t&&s&&(e.remove(),e.middlewareHelper.destroy())}})}function MS(o){const{mediaSpoiler:e,event:t}=o;if(oe(t),e.classList.contains("is-revealing"))return;const s=e.parentElement.querySelector("video");s&&!e.parentElement.querySelector(".video-play")&&(s.autoplay=!0,wi(s)),Km({mediaSpoiler:e,reveal:!0,destroyAfter:!0})}function v_(o){const{middleware:e,image:t}=o;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}=Qc.create({...o,middleware:s.middlewareHelper.get()});return s.append(t,i),{container:s,readyResult:n}}async function Rd(o){const{media:e}=o,s=(e.sizes||e.thumbs).find(l=>l._==="photoStrippedSize");if(!s)return;const{image:i,loadPromise:n}=Im(e,s,!0);await n;const{container:a,readyResult:r}=v_({...o,image:i});return r instanceof Promise&&await r,a}function qp({messages:o,media:e,attachmentDiv:t,middleware:s,uploading:i,lazyLoadQueue:n,isOut:a,chat:r,loadPromises:l,autoDownload:c,managers:d=I.managers,animationGroup:h,spoilered:u,videoTimes:p,uploadingFileName:m}){const g=[];for(const b of e||o){const S=!!o,C=S?Xs(b,!0):b,P=C._==="photo"?Sn(C,480,480):{w:C.w,h:C.h};g.push({size:P,media:C,message:S?b:void 0})}PS({container:t,items:g.map(b=>({w:b.size.w,h:b.size.h})),maxWidth:$e.active.album.width,minWidth:100,spacing:1,forMedia:!0,noGroupedItem:!o});const{width:f,height:y}=t.style,v=parseInt(f),w=parseInt(y);g.forEach((b,S)=>{const{size:C,media:P,message:L}=b,E=L?.media,_=u||!!E?.pFlags?.spoiler,k=t.children[S];L?(k.dataset.mid=""+L.mid,k.dataset.peerId=""+L.peerId):k.dataset.index=""+S;const x=k.firstElementChild,A=P._==="photo";let T;if(A?T=Ks({photo:P,message:L,container:x,boxWidth:0,boxHeight:0,isOut:a,lazyLoadQueue:n,middleware:s,size:C,loadPromises:l,autoDownloadSize:c.photo,managers:d,uploadingFileName:m?.[S]}):T=qn({doc:P,container:x,message:L,boxWidth:0,boxHeight:0,withTail:!1,isOut:a,lazyLoadQueue:n,middleware:s,loadPromises:l,autoDownload:c,managers:d,noAutoplayAttribute:!0,uploadingFileName:m?.[S]}),T&&l?.push(T),_){const R=(T||Promise.resolve()).then(async()=>{if(!s())return;const{width:O,height:X}=k.style,F=+O.slice(0,-1)/100*v,H=+X.slice(0,-1)/100*w,G=await Rd({media:P,animationGroup:h,middleware:s,width:F,height:H});s()&&x.append(G)});l?.push(R)}const B=p?.[S];B&&x.append(B)})}const b_={Á:"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"},w_=/[`~!@#$%^&*()\-_=+\[\]\\|{}'";:\/?.>,<]+/g,S_=/^\s+|\s$/g,C_={й:"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 ES(o){return o.replace(w_,"").replace(S_,"")}function I_(o){return o.toLowerCase().replace(/[\wа-я]/g,e=>C_[e]??e)}function L_(o){return o.replace(/[^A-Za-z0-9]/g,e=>b_[e]??e)}function P_(o="",e={}){const t=e.includeTag&&o.charAt(0)==="%",s=o;return e.clearBadChars&&(o=ES(o)),e.latinize&&(o=L_(o)),e.ignoreCase&&(o=o.toLowerCase()),t&&(o="%"+o),e.latinize&&(o+=""+I_(s)),o}I.addEventListener("document_downloading",o=>{Array.from(document.querySelectorAll(`.document[data-doc-id="${o}"]`)).forEach(t=>{t.querySelector(".preloader-container.manual")&&fs(t)})});async function Yc({message:o,withTime:e,fontWeight:t,voiceAsMusic:s,showSender:i,searchContext:n,loadPromises:a,autoDownloadSize:r,lazyLoadQueue:l,sizeType:c,managers:d=I.managers,cacheContext:h,fontSize:u,getSize:p,canTranscribeVoice:m,isOut:g,uploadingFileName:f}){t??(t=500),c??(c=""),u??(u=16);const y=r===0,v=o.media.document||o.media.webpage.document;if(f??(f=o?.uploadingFileName?.[0]),v.type==="audio"||v.type==="voice"||v.type==="round"){const Q=new pf;return Q.withTime=e,Q.message=o,Q.noAutoDownload=y,Q.lazyLoadQueue=l,Q.loadPromises=a,Q.uploadingFileName=f,m&&v.type==="voice"&&(Q.transcriptionState=0),Q.getSize=p,s&&(Q.voiceAsMusic=s),n&&(Q.searchContext=n),i&&(Q.showSender=i),Q.dataset.fontWeight=""+t,Q.dataset.fontSize=""+u,Q.dataset.sizeType=c,g&&Q.classList.add("is-out"),await Q.render(),Q}const w=v.file_name?v.file_name.split("."):"";let b="";b=w.length>1&&Array.isArray(w)?ES(w.pop().split(" ",1)[0].toLowerCase()):"file";const S=document.createElement("div");S.classList.add("document",`ext-${b}`),S.dataset.docId=""+v.id,S.doc=v;const C=document.createElement("div");C.classList.add("document-ico");let P;const L=!!h;h=L?h:fe.getCacheContext(v);let _=!1;if(v.thumbs?.length||o.pFlags.is_outgoing&&h.url&&v.type==="photo"){S.classList.add("document-with-thumb"),_=!0;const Q=[];if(o.pFlags.is_outgoing&&["photo","video"].includes(v.type)&&h.url)C.innerHTML=``,Q.push(C.firstElementChild);else{performance.now();const he=await Ks({photo:v,message:null,container:C,boxWidth:54,boxHeight:54,loadPromises:a,withoutPreloader:!0,lazyLoadQueue:l,size:Sn(v,54,54,!0),managers:d});C.style.width=C.style.height="",he.images.thumb&&Q.push(he.images.thumb),he.images.full&&Q.push(he.images.full)}Q.forEach(he=>he.classList.add("document-thumb"))}else P=document.createElement("span"),P.classList.add("document-ico-text"),P.innerText=b,C.append(P);const k=v.file_name?vo(v.file_name):"Unknown.file";document.createElement("div").classList.add("document-description");const A=document.createElement("span"),T=Ta(v.size),B=" / ",R=[T];if(e&&R.push(ws(o.date)),i&&R.push(await eu(o)),!e&&!i){const Q=document.createElement("span"),he=Ta(v.size);Q.append(B,he),Q.style.visibility="hidden",R.push(Q)}S.innerHTML=` ${h.downloaded&&!f||!o.mid||!_?"":'
'}
`;const O=S.querySelector(".document-name"),X=new hf;X.dataset.fontWeight=""+t,X.dataset.fontSize=""+u,X.dataset.sizeType=c,X.getSize=p,X.textContent=k,o.mid||S.classList.add("downloaded"),O.append(X),i&&O.append(uf(o));const F=S.querySelector(".document-size");if(A.append(...mo(R," · ")),F.append(A),S.prepend(C),!f&&o.pFlags.is_outgoing&&!o.mid)return S;const H=v.size<=fm;let G,z=null;const q=()=>{if(S.classList.remove("downloading"),v.size>fm&&!f){z.setManual(),z.attach(G),z.preloader.classList.add("manual"),z.setDownloadFunction(se);return}if(H&&S.classList.add("downloaded"),G){if(G!==C){const Q=G;setTimeout(()=>{Q.remove()},200)}G=null}z&&(z=null)},$=Q=>{S.classList.add("downloading");const he=document.createElement("span"),le=Ta(v.size);he.style.position="absolute",he.style.left="0",Q.then(q,Wt).finally(()=>{A.style.visibility="",he.remove()});const re=be=>Ta(be);let ge=re(0);A.style.visibility="hidden",he.append(ge,B,le),A.parentElement.append(he),Q.addNotifyListener(be=>{const Z=re(be.done);ge.replaceWith(Z),ge=Z})},se=Q=>{const he=!Q||Q.isTrusted,le=S.doc;let re;const ge=me.chat.bubbles?me.chat.bubbles.lazyLoadQueue.queueId:void 0;he?(le.type,ka.has(le.mime_type)&&le.thumbs?.length&&H?re=cs.downloadMediaURL({media:le,queueId:ge}):(re=cs.downloadToDisc({media:le,queueId:ge}),le.mime_type==="image/svg+xml"&&Ct({descriptionLangKey:"Chat.File.QuickLook.Svg",button:{langKey:"OK",isCancel:!0}}))):re=cs.downloadToDisc({media:le,queueId:ge},!0),re.catch(()=>{S.classList.remove("downloading")}),G&&(z.attach(G,!0,re),$(re))},{fileName:Y}=s0({media:v,downloadId:"1"});if(await d.apiFileManager.isDownloading(Y)){G=S.querySelector(".document-download")||C;const Q=cs.downloadToDisc({media:v},!0);z=new tn,z.attach(G,!1,Q),z.setDownloadFunction(se),$(Q)}else if(!h.downloaded||f)if(G=S.querySelector(".document-download")||C,z=new tn({isUpload:!!f}),!f)z.construct(),z.setManual(),z.attach(G),z.setDownloadFunction(se),r!==void 0&&r>=v.size&&fs(z.preloader);else{const Q=cs.getUpload(f);z.attachPromise(Q),z.attach(G),$(Q)}return N(S,Q=>{U(Q.target,"time")||(z?z.onClick(Q):se(Q))}),S}function Sc(o){if(!o)return;const e=o.media?.document;return["voice","audio","video"].includes(e?.type)&&e.duration||void 0}async function M_({albumMustBeRenderedFull:o,message:e,bubble:t,messageDiv:s,chat:i,loadPromises:n,autoDownloadSize:a,lazyLoadQueue:r,searchContext:l,useSearch:c,sizeType:d,managers:h,fontWeight:u,fontSize:p,richTextFragment:m,richTextOptions:g,canTranscribeVoice:f,translatableParams:y,factCheckBox:v,isOut:w}){let b;const{peerId:S}=e,C=o?await i.getMidsByMid(e.peerId,e.mid):[e.mid],P=C.map(async(E,_,k)=>{const x=i.getMessageByPeer(S,E),A=await Yc({message:x,loadPromises:n,autoDownloadSize:a,lazyLoadQueue:r,searchContext:l,sizeType:d,managers:h,fontWeight:u,fontSize:p,canTranscribeVoice:f,isOut:w}),T=document.createElement("div");T.classList.add("document-container"),T.dataset.mid=""+E,T.dataset.peerId=""+x.peerId;const B=document.createElement("div");B.classList.add("document-wrapper");const R=_===0,O=_===k.length-1;R&&T.classList.add("is-first"),O&&T.classList.add("is-last");let X;if((x.message||O&&v)&&(X=document.createElement("div"),X.classList.add("document-message")),x.message){let F=m;F||(y?F=_d({...y,message:x,richTextOptions:{...y.richTextOptions,maxMediaTimestamp:Sc(x)}}):F=Yt(x.message,{...g,entities:x.totalEntities,maxMediaTimestamp:Sc(x)})),kt(X,F)}if(v&&X&&O&&X.append(v),C.length>1){const F=document.createElement("div");F.classList.add("document-selection"),T.append(F),T.classList.add("grouped-item"),_===0&&(b=B)}return B.append(...[A,X].filter(Boolean)),T.append(B),T}),L=await Promise.all(P);return s.append(...L),C.length>1&&t.classList.add("is-multiple-documents","is-grouped"),b}function E_({message:o,managers:e=I.managers,middleware:t,translatableParams:s,richTextOptions:i}){const n=new ao;return n.message=o,n.managers=e,n.translatableParams=s,n.richTextOptions=i,n.setAttribute("peer-id",""+o.peerId),n.setAttribute("poll-id",""+o.media.poll.id),n.setAttribute("message-id",""+o.mid),n.middlewareHelper=t.create(),n.render(),n}const __="֑-߿יִ-﷽ﹰ-ﻼ",_S=new RegExp("["+__+"]");function k_(o,e){return _S.test(o)}function T_(o){return _S.test(o?.slice(-1))}async function kS(o){const{peerId:e,threadId:t,lastMsgId:s}=o;let i=Promise.resolve(),n;if(o.noLink){n=document.createElement("span"),n.dataset.savedFrom=`${o.peerId}_${o.lastMsgId}`,n.classList.add("has-avatar");const a=es({peerId:o.peerId,isDialog:!0,middleware:o.wrapOptions.middleware,size:30});a.node.classList.add("topic-name-button-avatar"),n.append(a.node,Le("next","topic-name-button-arrow")),i=a.readyThumbPromise,o.withIcons=!1}else n=Gb("t.me/c/"+e.toChatId()+(t?"/"+yn(t):"")+(s?"/"+yn(s):""));return n.classList.add("topic-name","topic-name-button"),n.append(await Oe(o)),{cached:!0,element:n,loadPromise:i}}const oh="popup-chatlist-invite";class Cf extends ee{constructor(e){super("popup-forward "+oh,{closable:!0,overlayClosable:!0,body:!0,footer:!0,title:!0,withConfirm:!0}),It(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,a=s?._==="chatlists.chatlistInviteAlready",r=a&&!!s.missing_peers.length,l=this.filter??(this.filter=a?await this.managers.filtersStorage.getFilter(s.filter_id):void 0);this.title.append(M(i?"SharedFolder.Link.TitleRemove":r?"SharedFolder.Link.TitleAdd":"SharedFolder.Link.Title"));let c;i&&(c=(await this.managers.filtersStorage.getLeaveChatlistSuggestions(this.filter.id)).map(_=>at(_)));const d=()=>{const E=document.createElement("div");E.classList.add("menu-horizontal-div-item");const _=document.createElement("span");return _.classList.add("menu-horizontal-div-item-span"),E.append(_),t.append(E),_};d().append(M("FilterAllChats"));const h=d();h.parentElement.classList.add("active"),h.append(_e(l?l.title:s.title),document.createElement("i")),d().append(M("FilterPersonal"));const u=document.createElement("div");u.classList.add("inner-shadow","inner-shadow-inset"),e.append(t,u);const p=document.createElement("div");p.classList.add(oh+"-description","subtitle");let m;i?Zt(p,"SharedFolder.Link.DescriptionRemove",[_e(l.title)]):r?m=new ke.IntlElement:Zt(p,a?"SharedFolder.Link.DescriptionAlready":"SharedFolder.Link.Description");const g=new ke.IntlElement,f=E=>{b&&r&&(E=Math.max(0,E-b.length)),g.update({key:i?"SharedFolder.Link.ChatsRemove":r?"SharedFolder.Link.ChatsAdd":a?"SharedFolder.Link.ChatsAlready":"SharedFolder.Link.Chats",args:[M("Chats",[E])]}),v?.update({key:(y=E===w.length)?"DeselectAll":"SelectAll"}),m?.update({key:"SharedFolder.Link.DescriptionAdd",args:[M("Chats",[E]),_e(l.title)]}),v&&(E&&(C.dataset.badge=""+E),C.classList.toggle("has-badge",!!E)),i&&S.update({key:E?"SharedFolder.Link.Remove":"SharedFolder.Link.TitleRemove"}),i||jt([this.btnConfirm],!E)};let y;this.selector=new Mi({middleware:this.middlewareHelper.get(),appendTo:this.body,onChange:f,onFirstRender:()=>{this.show(),this.selector.checkForTriggers()},multiSelect:!0,noSearch:!0,sectionNameLangPackKey:g.element,avatarSize:"abitbigger",managers:this.managers,peerType:[],getSubtitleForElement:async E=>{if(b?.includes(E)){const _=await this.managers.appPeersManager.isBroadcast(E);return M(_?"SharedFolder.Link.ChannelAlready":"SharedFolder.Link.ChatAlready")}},processElementAfter:(E,_)=>{b?.includes(E)&&_.dom.containerEl.classList.add("already")}});let v;(!a||r)&&(v=new ke.IntlElement,v.element.classList.add("sidebar-left-section-name-right"),this.selector.section.title.append(v.element),N(v.element,()=>{y?this.selector.removeBatch(w):this.selector.addBatch(w)},{listenerSetter:this.listenerSetter}));let w;s?w=(r?s.missing_peers:a?s.already_peers:s.peers).map(_=>at(_)):w=l.includePeerIds;let b;if(a&&(b=s.already_peers.map(E=>at(E))),b){const E=this.selector.remove.bind(this.selector);this.selector.remove=(..._)=>{const k=_[0].toPeerId();if(b.includes(k)){const x=this.selector.getElementByPeerId(k);return Va(x),!1}return E(..._)}}this.scrollable=this.selector.scrollable,this.attachScrollableListeners(),this.scrollable.prepend(e,p),this.btnConfirm.classList.add(`${oh}-button`);const S=new ke.IntlElement({key:i?"SharedFolder.Link.Remove":r?"SharedFolder.Link.Join":a?"OK":"SharedFolder.Link.Title"}),C=S.element;C.classList.add(`${oh}-button-text`),this.btnConfirm.append(C),this.footer.append(this.btnConfirm),N(this.btnConfirm,()=>{if(a&&!r){this.hide();return}let E;const _=jt([this.btnConfirm],!0),k=[...this.selector.selected];n?E=this.managers.filtersStorage.joinChatlistUpdates(this.filter.id,k):s?E=this.managers.filtersStorage.joinChatlistInvite(this.slug,k).catch(x=>{if(x.type==="DIALOG_FILTERS_TOO_MUCH")ua("folders"),this.hide();else throw x}):E=this.managers.filtersStorage.leaveChatlist(this.filter.id,k),E.then(()=>{this.hide()},x=>{throw _(),x})},{listenerSetter:this.listenerSetter});const P=b?w.concat(b):w,L=i?c:P;this.selector.addInitial(L),this.selector.renderResultsFunc(i?$a(c.concat(P)):P),L.length||f(0),this.body.after(this.footer)}}const x_=o=>o._==="chatInvitePeek"?o.chat.pFlags.broadcast?"JoinByPeekChannelTitle":"JoinByPeekGroupTitle":o.pFlags.request_needed?"RequestJoin.Button":o.pFlags.broadcast?"JoinByPeekChannelTitle":"JoinByPeekGroupTitle";class ru extends Ss{constructor(e,t){super("popup-join-chat-invite",{closable:!0,overlayClosable:!0,body:!0,buttons:fr([{langKey:x_(t),callback:()=>{ru.import(e)}}]),description:!0}),this.hash=e,this.chatInvite=t,this.construct()}static openChat(e){const t=e.toPeerId(!0);me.setInnerPeer({peerId:t})}static import(e){I.managers.appChatInvitesManager.importChatInvite(e).then(t=>{this.openChat(t)},t=>{t.type==="INVITE_REQUEST_SENT"&&Ee({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):ee.createPopup(ru,e,t)}async construct(){this.header.remove();const{chatInvite:e}=this,t=es({middleware:this.middlewareHelper.get(),size:100,isDialog:!1});e.photo?._==="photo"?await fw(t,e.photo):(t.render({peerTitle:e.title}),await t.readyThumbPromise);const s=document.createElement("div");s.classList.add("peer-title","chat-title");const i=await Mm({peerId:Tt,noVerifiedIcon:!1,noFakeIcon:!1,noPremiumIcon:!1,peer:{_:"channel",pFlags:{verified:e.pFlags.verified,scam:e.pFlags.scam,fake:e.pFlags.fake},date:0,id:0,photo:void 0,title:""},wrapOptions:{middleware:this.middlewareHelper.get()}}),n=_e(e.title);if(i.length){s.classList.add("with-icons");const l=document.createElement("span");l.classList.add("peer-title-inner"),l.append(n),s.append(l,...i)}else kt(s,n);e.about?this.description.replaceChildren(_e(e.about)):(this.description.remove(),this.description=void 0);const a=e.pFlags.broadcast,r=M(a?"Subscribers":"Members",[Ha(e.participants_count)]);if(r.classList.add("chat-participants-count"),this.body.append(...[t.node,s,r,this.description].filter(Boolean)),e.pFlags.request_needed){const l=document.createElement("div");Zt(l,a?"RequestToJoinChannelDescription":"RequestToJoinGroupDescription"),l.classList.add("chat-participants-count","request-caption"),this.body.append(l)}this.show()}}const A_=new Set(["showMaskedAlert","execBotCommand"]);function Us(o){window[(o.protocol?o.protocol+"_":"")+o.name]=(e,t)=>{!o.noCancelEvent&&oe(null);let s=e.href;if(!s)return;let i,n;const a=new URL(s),r=a.host.match(/(.+?)\.t(?:elegram)?\.me/);r&&!hL.has(r[1])&&(a.pathname=r[1]+(a.pathname==="/"?"":a.pathname),s=a.toString()),o.noPathnameParams||(i=new URL(s).pathname.split("/").slice(1)),o.noUriParams||(n=_b(s));const l=e.href!==e.textContent&&e.getAttribute("safe")===null,c=o.callback({pathnameParams:i,uriParams:n},e,l);if(!t?.isTrusted)return c}}function bl(o,e,t){const s=document.createElement(o);return s.className=`badge badge-${e} badge-${t} is-badge-empty`,s}const TS=ce("
"),F_=ce("
"),R_=ce("
"),D_=ce("